BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / rows.rs

rows.rs

rows.rs 44.0 KiB Download Raw
1use std::collections::{BTreeMap, HashMap};
2use std::ops::Range;
3use std::sync::Arc;
4
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
7use store::MessageRecord;
8use teams_core::{
9 AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,
10 card_texts, files, images, link_preview, message_spans, reactions,
11};
12
13use crate::card_state::CardOverride;
14use crate::format;
15use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
16use crate::render::blocks::{Inline, strip_image_placeholders};
17use crate::render::{Block, layout_blocks};
18
19const POST_VISIBLE_REPLIES: usize = 3;
20
21pub const LOAD_OLDER_KEY: &str = "load-older";
22const UNKNOWN_AUTHOR: &str = "Unknown";
23const DELETED_TEXT: &str = "Message deleted";
24const SERIES_GAP_MINUTES: i64 = 5;
25const CORNER_RADIUS: f32 = 14.;
26const CORNER_SERIES: f32 = 4.;
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct ReactionChip {
30 pub reaction_type: String,
31 pub label: String,
32 pub count: usize,
33 pub mine: bool,
34 pub reactors: Vec<Reactor>,
35}
36
37impl ReactionChip {
38 pub fn glyph(&self) -> String {
39 reaction_glyph(&self.reaction_type)
40 }
41}
42
43#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
44pub struct Series {
45 pub has_prev: bool,
46 pub has_next: bool,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct Corners {
51 pub top_left: f32,
52 pub top_right: f32,
53 pub bottom_right: f32,
54 pub bottom_left: f32,
55}
56
57pub fn bubble_corners(own: bool, series: Series) -> Corners {
58 if own {
59 let top_right = if series.has_prev || !series.has_next {
60 CORNER_SERIES
61 } else {
62 CORNER_RADIUS
63 };
64 let bottom_right = if series.has_next || !series.has_prev {
65 CORNER_SERIES
66 } else {
67 CORNER_RADIUS
68 };
69 Corners {
70 top_left: CORNER_RADIUS,
71 top_right,
72 bottom_right,
73 bottom_left: CORNER_RADIUS,
74 }
75 } else {
76 Corners {
77 top_left: CORNER_SERIES,
78 top_right: CORNER_RADIUS,
79 bottom_right: CORNER_RADIUS,
80 bottom_left: if series.has_next {
81 CORNER_SERIES
82 } else {
83 CORNER_RADIUS
84 },
85 }
86 }
87}
88
89#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
90pub enum Receipt {
91 #[default]
92 Hidden,
93 Pending,
94 Sent,
95 Read,
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum ScheduledState {
100 Waiting,
101 DeliveryFailed,
102 ChangeFailed,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub enum Delivery {
107 Delivered,
108 Sending,
109 Failed(String),
110 Scheduled(ScheduledState),
111}
112
113/// An image of a message that is still being sent, shown from its local bytes.
114#[derive(Debug, Clone, PartialEq)]
115pub struct LocalImage {
116 pub image: Arc<Image>,
117 pub size: Option<(u32, u32)>,
118}
119
120#[derive(Debug, Clone, PartialEq)]
121pub struct MessageRow {
122 pub key: String,
123 pub conversation_id: String,
124 pub author: String,
125 pub sender_id: Option<String>,
126 pub application_id: Option<String>,
127 pub created_at: DateTime<Utc>,
128 pub series: Series,
129 pub time: String,
130 pub day_header: Option<String>,
131 pub blocks: Vec<Block>,
132 pub edited: bool,
133 pub deleted: bool,
134 pub reactions: Vec<ReactionChip>,
135 pub images: Vec<ImageRef>,
136 pub local_images: Vec<LocalImage>,
137 pub files: Vec<FileCard>,
138 pub link_preview: Option<LinkPreview>,
139 pub adaptive_cards: Vec<AdaptiveCard>,
140 pub subject: Option<String>,
141 pub new_marker: bool,
142 pub reply_root: Option<String>,
143 pub delivery: Delivery,
144 pub own: bool,
145 pub receipt: Receipt,
146 pub forwarded: bool,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct StartInfo {
151 pub title: String,
152 pub user_id: Option<String>,
153}
154
155pub const START_KEY: &str = "conversation-start";
156
157#[derive(Debug, Clone, PartialEq)]
158pub enum Row {
159 LoadOlder,
160 Start(StartInfo),
161 Skeleton(Skeleton),
162 Message(Box<MessageRow>),
163 Post(Box<PostRow>),
164}
165
166#[derive(Debug, Clone, Copy, PartialEq)]
167pub struct Skeleton {
168 pub key: &'static str,
169 pub own: bool,
170 pub width_ratio: f32,
171 pub lines: u8,
172}
173
174const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [
175 Skeleton {
176 key: "skeleton-0",
177 own: false,
178 width_ratio: 0.42,
179 lines: 1,
180 },
181 Skeleton {
182 key: "skeleton-1",
183 own: true,
184 width_ratio: 0.3,
185 lines: 1,
186 },
187 Skeleton {
188 key: "skeleton-2",
189 own: true,
190 width_ratio: 0.48,
191 lines: 2,
192 },
193 Skeleton {
194 key: "skeleton-3",
195 own: false,
196 width_ratio: 0.26,
197 lines: 1,
198 },
199];
200
201pub fn placeholder_rows() -> Vec<Row> {
202 SKELETON_PLACEHOLDERS
203 .into_iter()
204 .map(Row::Skeleton)
205 .collect()
206}
207
208fn sender_key(row: &MessageRow) -> &str {
209 row.sender_id.as_deref().unwrap_or(&row.author)
210}
211
212fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
213 next.day_header.is_none()
214 && !next.new_marker
215 && sender_key(previous) == sender_key(next)
216 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
217 && next.created_at >= previous.created_at
218}
219
220pub fn assign_series(rows: &mut [Row]) {
221 let mut previous: Option<usize> = None;
222 for index in 0..rows.len() {
223 let Row::Message(_) = &rows[index] else {
224 previous = None;
225 continue;
226 };
227 if let Some(before) = previous {
228 let joined = match (&rows[before], &rows[index]) {
229 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
230 _ => false,
231 };
232 if joined {
233 if let Row::Message(a) = &mut rows[before] {
234 a.series.has_next = true;
235 }
236 if let Row::Message(b) = &mut rows[index] {
237 b.series.has_prev = true;
238 }
239 }
240 }
241 previous = Some(index);
242 }
243}
244
245impl Row {
246 pub fn key(&self) -> &str {
247 match self {
248 Row::LoadOlder => LOAD_OLDER_KEY,
249 Row::Start(_) => START_KEY,
250 Row::Skeleton(skeleton) => skeleton.key,
251 Row::Message(message) => &message.key,
252 Row::Post(post) => &post.root.key,
253 }
254 }
255
256 pub fn messages(&self) -> Box<dyn Iterator<Item = &MessageRow> + '_> {
257 match self {
258 Row::Message(message) => Box::new(std::iter::once(message.as_ref())),
259 Row::Post(post) => Box::new(post.messages()),
260 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => Box::new(std::iter::empty()),
261 }
262 }
263}
264
265#[derive(Debug, Clone, PartialEq)]
266pub struct PostRow {
267 pub root: MessageRow,
268 pub replies: Vec<MessageRow>,
269 pub hidden_reply_count: usize,
270 pub hidden_repliers: Vec<String>,
271}
272
273impl PostRow {
274 pub fn local(root: MessageRow) -> Self {
275 PostRow {
276 root,
277 replies: Vec::new(),
278 hidden_reply_count: 0,
279 hidden_repliers: Vec::new(),
280 }
281 }
282
283 pub fn messages(&self) -> impl Iterator<Item = &MessageRow> {
284 std::iter::once(&self.root).chain(&self.replies)
285 }
286
287 pub fn hidden_replies_label(&self) -> Option<String> {
288 (self.hidden_reply_count > 0)
289 .then(|| replies_label(self.hidden_reply_count, &self.hidden_repliers))
290 }
291}
292
293fn first_name(name: &str) -> &str {
294 name.split_whitespace().next().unwrap_or(name)
295}
296
297pub fn replies_label(count: usize, repliers: &[String]) -> String {
298 let noun = if count == 1 { "reply" } else { "replies" };
299 let mut names: Vec<&str> = Vec::new();
300 for name in repliers.iter().map(|name| first_name(name)) {
301 if !names.contains(&name) {
302 names.push(name);
303 }
304 }
305 let people = match names.as_slice() {
306 [] => return format!("{count} {noun}"),
307 [only] => (*only).to_owned(),
308 [first, second] => format!("{first} and {second}"),
309 [first, second, third] => format!("{first}, {second} and {third}"),
310 [first, second, rest @ ..] => format!("{first}, {second} and {} others", rest.len()),
311 };
312 format!("{count} {noun} from {people}")
313}
314
315#[derive(Debug, Clone, PartialEq, Eq)]
316pub struct Thread {
317 pub root_id: String,
318 pub reply_ids: Vec<String>,
319}
320
321pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String {
322 time.with_timezone(&offset).format("%H:%M").to_string()
323}
324
325pub fn reaction_label(reaction_type: &str) -> String {
326 match reaction_type {
327 "like" => "\u{1F44D}".to_owned(),
328 "heart" => "\u{2764}".to_owned(),
329 "laugh" => "\u{1F606}".to_owned(),
330 "surprised" => "\u{1F62E}".to_owned(),
331 "sad" => "\u{1F641}".to_owned(),
332 "angry" => "\u{1F620}".to_owned(),
333 other => other.to_owned(),
334 }
335}
336
337pub fn reaction_glyph(reaction_type: &str) -> String {
338 reaction_label(reaction_type)
339 .trim_end_matches('\u{FE0F}')
340 .to_owned()
341}
342
343/// Graph rejects the legacy names ("Unicode 'like' in the payload is not supported").
344pub fn api_reaction(glyph: &str) -> String {
345 match glyph {
346 "\u{2764}" => "\u{2764}\u{FE0F}".to_owned(),
347 other => other.to_owned(),
348 }
349}
350
351/// The reaction type Teams uses for a glyph: the legacy name for the six classic ones.
352pub fn reaction_type_for(glyph: &str) -> String {
353 let bare = glyph.trim_end_matches('\u{FE0F}');
354 ["like", "heart", "laugh", "surprised", "sad", "angry"]
355 .into_iter()
356 .find(|name| reaction_label(name) == bare)
357 .map_or_else(|| bare.to_owned(), str::to_owned)
358}
359
360pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;
361
362fn is_own_reaction(reaction: &ReactionInfo, wanted: &str, my_user_id: Option<&str>) -> bool {
363 my_user_id.is_some()
364 && reaction.user_id.as_deref() == my_user_id
365 && reaction_glyph(&reaction.reaction_type) == wanted
366}
367
368pub fn has_own_reaction(reactions: &[ReactionInfo], glyph: &str, my_user_id: Option<&str>) -> bool {
369 let wanted = reaction_glyph(glyph);
370 reactions
371 .iter()
372 .any(|reaction| is_own_reaction(reaction, &wanted, my_user_id))
373}
374
375pub fn set_own_reaction(
376 reactions: &mut Vec<ReactionInfo>,
377 glyph: &str,
378 my_user_id: Option<&str>,
379 present: bool,
380 now: DateTime<Utc>,
381) {
382 let wanted = reaction_glyph(glyph);
383 if !present {
384 reactions.retain(|reaction| !is_own_reaction(reaction, &wanted, my_user_id));
385 } else if !has_own_reaction(reactions, glyph, my_user_id) {
386 reactions.push(ReactionInfo {
387 reaction_type: reaction_type_for(glyph),
388 user_id: my_user_id.map(str::to_owned),
389 user_name: Some("You".to_owned()),
390 created_at: Some(now),
391 });
392 }
393}
394
395pub fn apply_pending_reactions(
396 reactions: &mut Vec<ReactionInfo>,
397 pending: Option<&Vec<(String, bool)>>,
398 my_user_id: Option<&str>,
399 now: DateTime<Utc>,
400) {
401 for (glyph, present) in pending.into_iter().flatten() {
402 set_own_reaction(reactions, glyph, my_user_id, *present, now);
403 }
404}
405
406pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
407 let my_user_id = context.my_user_id.as_deref();
408 let mut chips: Vec<ReactionChip> = Vec::new();
409 for reaction in reactions {
410 let glyph = reaction_glyph(&reaction.reaction_type);
411 let position = match chips.iter().position(|chip| chip.glyph() == glyph) {
412 Some(position) => position,
413 None => {
414 chips.push(ReactionChip {
415 reaction_type: reaction.reaction_type.clone(),
416 label: reaction_label(&reaction.reaction_type),
417 count: 0,
418 mine: false,
419 reactors: Vec::new(),
420 });
421 chips.len() - 1
422 }
423 };
424 let chip = &mut chips[position];
425 chip.count += 1;
426 chip.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id;
427 chip.reactors.push(Reactor {
428 user_id: reaction.user_id.clone(),
429 name: reactor_name(reaction, context),
430 created_at: reaction.created_at,
431 });
432 }
433 chips
434}
435
436fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String {
437 reaction
438 .user_name
439 .clone()
440 .or_else(|| {
441 reaction
442 .user_id
443 .as_ref()
444 .and_then(|user_id| context.names.get(user_id).cloned())
445 })
446 .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned())
447}
448
449const REPLY_EXCERPT_CHARS: usize = 90;
450const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";
451
452pub fn message_text(record: &MessageRecord) -> String {
453 let own_spans: Vec<Span> = message_spans(record)
454 .into_iter()
455 .filter(|span| !matches!(span, Span::Quote(_)))
456 .collect();
457 strip_image_placeholders(layout_blocks(&own_spans))
458 .into_iter()
459 .filter_map(|block| block.markdown())
460 .collect::<Vec<_>>()
461 .join("\n")
462}
463
464/// The message as the composer edits it, formatting kept.
465pub fn message_draft(record: &MessageRecord) -> Draft {
466 let own_spans: Vec<Span> = message_spans(record)
467 .into_iter()
468 .filter(|span| !matches!(span, Span::Quote(_)))
469 .collect();
470 Draft::from_spans(&own_spans).trimmed()
471}
472
473pub fn reply_excerpt(record: &MessageRecord) -> String {
474 let own_spans: Vec<Span> = message_spans(record)
475 .into_iter()
476 .filter(|span| !matches!(span, Span::Quote(_)))
477 .collect();
478 let text = strip_image_placeholders(layout_blocks(&own_spans))
479 .into_iter()
480 .find_map(|block| block.first_line())
481 .unwrap_or_default();
482 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
483 let excerpt = match first_line {
484 Some(line) => line.to_owned(),
485 None if !images(record).is_empty() => "Image".to_owned(),
486 None if let Some(line) = card_texts(record)
487 .iter()
488 .flat_map(|text| text.lines())
489 .next() =>
490 {
491 line.to_owned()
492 }
493 None => files(record)
494 .into_iter()
495 .next()
496 .map_or_else(|| "Message".to_owned(), |card| card.name),
497 };
498 if excerpt.chars().count() > REPLY_EXCERPT_CHARS {
499 let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect();
500 format!("{}...", cut.trim_end())
501 } else {
502 excerpt
503 }
504}
505
506pub struct RowContext {
507 pub offset: FixedOffset,
508 pub today: NaiveDate,
509 pub my_user_id: Option<String>,
510 pub names: HashMap<String, String>,
511 pub pending_reactions: PendingReactions,
512 pub card_overrides: HashMap<String, CardOverride>,
513}
514
515fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
516 let mut visible = reactions(record);
517 apply_pending_reactions(
518 &mut visible,
519 context.pending_reactions.get(&record.message_id),
520 context.my_user_id.as_deref(),
521 Utc::now(),
522 );
523 visible
524}
525
526pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
527 let local = record.created_at.with_timezone(&context.offset);
528 let images = images(record);
529 let blocks = if record.deleted {
530 vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
531 } else {
532 layout_blocks(&message_spans(record))
533 };
534 let blocks = if images.is_empty() {
535 blocks
536 } else {
537 strip_image_placeholders(blocks)
538 };
539 MessageRow {
540 key: record.message_id.clone(),
541 conversation_id: record.conversation_id.clone(),
542 sender_id: record.sender_id.clone(),
543 application_id: record.sender_application_id.clone(),
544 created_at: record.created_at,
545 series: Series::default(),
546 author: record
547 .sender_name
548 .clone()
549 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
550 time: clock_label(record.created_at, context.offset),
551 day_header: Some(format::day_label(local.date_naive(), context.today)),
552 blocks,
553 edited: record.edited_at.is_some() && !record.deleted,
554 deleted: record.deleted,
555 reactions: reaction_chips(&visible_reactions(record, context), context),
556 images,
557 local_images: Vec::new(),
558 files: files(record),
559 link_preview: link_preview(record),
560 adaptive_cards: match context.card_overrides.get(&record.message_id) {
561 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
562 _ => adaptive_cards(record),
563 },
564 subject: record.subject.clone(),
565 new_marker: false,
566 reply_root: record.reply_to_id.clone(),
567 delivery: Delivery::Delivered,
568 receipt: Receipt::Hidden,
569 own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
570 forwarded: !record.deleted && is_forwarded(&record.body_html),
571 }
572}
573
574pub fn is_forwarded(body_html: &str) -> bool {
575 body_html.contains(FORWARD_ITEMTYPE)
576}
577
578pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
579 let mut rows = Vec::with_capacity(records.len() + 1);
580 if has_older {
581 rows.push(Row::LoadOlder);
582 }
583 let mut previous_day: Option<NaiveDate> = None;
584 for record in records {
585 let mut row = message_row(record, context);
586 let day = record
587 .created_at
588 .with_timezone(&context.offset)
589 .date_naive();
590 if previous_day == Some(day) {
591 row.day_header = None;
592 }
593 previous_day = Some(day);
594 rows.push(Row::Message(Box::new(row)));
595 }
596 assign_series(&mut rows);
597 rows
598}
599
600pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> {
601 let mut threads: Vec<Thread> = Vec::new();
602 let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new();
603 for record in records.iter().filter(|record| record.reply_to_id.is_none()) {
604 index_by_root.insert(record.message_id.as_str(), threads.len());
605 threads.push(Thread {
606 root_id: record.message_id.clone(),
607 reply_ids: Vec::new(),
608 });
609 }
610 for record in records {
611 let Some(root_id) = record.reply_to_id.as_deref() else {
612 continue;
613 };
614 if let Some(&index) = index_by_root.get(root_id) {
615 threads[index].reply_ids.push(record.message_id.clone());
616 }
617 }
618 threads
619}
620
621fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> {
622 thread
623 .reply_ids
624 .iter()
625 .chain(std::iter::once(&thread.root_id))
626 .filter_map(|id| by_id.get(id.as_str()))
627 .map(|record| record.created_at)
628 .max()
629 .unwrap_or_default()
630}
631
632fn post_message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
633 let mut row = message_row(record, context);
634 row.day_header = None;
635 row.time = format::post_time_label(record.created_at, context.today, context.offset);
636 row
637}
638
639fn distinct_names<'a>(records: impl Iterator<Item = &'a MessageRecord>) -> Vec<String> {
640 let mut names: Vec<String> = Vec::new();
641 for record in records {
642 let name = record
643 .sender_name
644 .clone()
645 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
646 if !names.contains(&name) {
647 names.push(name);
648 }
649 }
650 names
651}
652
653fn post_row(
654 root: &MessageRecord,
655 mut replies: Vec<&MessageRecord>,
656 context: &RowContext,
657) -> PostRow {
658 replies.sort_by_key(|reply| reply.created_at);
659 let hidden = replies.len().saturating_sub(POST_VISIBLE_REPLIES);
660 PostRow {
661 root: post_message_row(root, context),
662 hidden_reply_count: hidden,
663 hidden_repliers: distinct_names(replies[..hidden].iter().copied()),
664 replies: replies[hidden..]
665 .iter()
666 .map(|reply| post_message_row(reply, context))
667 .collect(),
668 }
669}
670
671pub fn thread_list_rows(
672 records: &[MessageRecord],
673 context: &RowContext,
674 has_older: bool,
675) -> Vec<Row> {
676 let by_id: BTreeMap<&str, &MessageRecord> = records
677 .iter()
678 .map(|record| (record.message_id.as_str(), record))
679 .collect();
680 let mut threads = group_threads(records);
681 threads.sort_by_key(|thread| std::cmp::Reverse(last_activity(thread, &by_id)));
682 let mut rows: Vec<Row> = threads
683 .iter()
684 .filter_map(|thread| {
685 let root = by_id.get(thread.root_id.as_str())?;
686 let replies = thread
687 .reply_ids
688 .iter()
689 .filter_map(|id| by_id.get(id.as_str()).copied())
690 .collect();
691 Some(Row::Post(Box::new(post_row(root, replies, context))))
692 })
693 .collect();
694 if has_older {
695 rows.push(Row::LoadOlder);
696 }
697 rows
698}
699
700pub fn place_local_rows(rows: &mut Vec<Row>, local: Vec<MessageRow>) {
701 for message in local {
702 let Some(root_id) = message.reply_root.clone() else {
703 rows.insert(0, Row::Post(Box::new(PostRow::local(message))));
704 continue;
705 };
706 let position = rows
707 .iter()
708 .position(|row| matches!(row, Row::Post(post) if post.root.key == root_id));
709 if let Some(position) = position {
710 let mut row = rows.remove(position);
711 if let Row::Post(post) = &mut row {
712 post.replies.push(message);
713 }
714 rows.insert(0, row);
715 }
716 }
717}
718
719pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
720 let members: Vec<MessageRecord> = records
721 .iter()
722 .filter(|record| {
723 record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id)
724 })
725 .cloned()
726 .collect();
727 flat_rows(&members, context, false)
728}
729
730#[derive(Debug, Clone, PartialEq, Eq)]
731pub struct Splice {
732 pub range: Range<usize>,
733 pub count: usize,
734}
735
736pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> {
737 if old == new {
738 return None;
739 }
740 let prefix = old
741 .iter()
742 .zip(new)
743 .take_while(|(left, right)| left == right)
744 .count();
745 let suffix = old[prefix..]
746 .iter()
747 .rev()
748 .zip(new[prefix..].iter().rev())
749 .take_while(|(left, right)| left == right)
750 .count();
751 Some(Splice {
752 range: prefix..old.len() - suffix,
753 count: new.len() - prefix - suffix,
754 })
755}
756
757pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> {
758 let prefix = old
759 .iter()
760 .zip(new)
761 .take_while(|(left, right)| left.key() == right.key())
762 .count();
763 let suffix = old[prefix..]
764 .iter()
765 .rev()
766 .zip(new[prefix..].iter().rev())
767 .take_while(|(left, right)| left.key() == right.key())
768 .count();
769 let mut changed: Vec<usize> = (0..prefix)
770 .filter(|&index| old[index] != new[index])
771 .collect();
772 changed.extend((0..suffix).filter_map(|offset| {
773 let old_index = old.len() - 1 - offset;
774 let new_index = new.len() - 1 - offset;
775 (old[old_index] != new[new_index]).then_some(new_index)
776 }));
777 changed
778}
779
780#[cfg(test)]
781mod tests {
782 use chrono::TimeZone;
783
784 use super::*;
785
786 fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord {
787 MessageRecord {
788 conversation_id: "c".into(),
789 message_id: id.into(),
790 reply_to_id: reply_to.map(str::to_owned),
791 sender_id: Some("u".into()),
792 sender_name: Some("Author".into()),
793 sender_application_id: None,
794 links_json: "[]".to_owned(),
795 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
796 edited_at: None,
797 deleted: false,
798 body_html: format!("<p>text {id}</p>"),
799 attachments_json: "[]".into(),
800 reactions_json: "[]".into(),
801 mentions_json: "[]".into(),
802 subject: None,
803 }
804 }
805
806 fn own_reaction(reaction_type: &str) -> ReactionInfo {
807 ReactionInfo {
808 reaction_type: reaction_type.into(),
809 user_id: Some("me".into()),
810 user_name: None,
811 created_at: None,
812 }
813 }
814
815 #[test]
816 fn setting_a_reaction_is_idempotent_and_only_touches_mine() {
817 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
818 let other = ReactionInfo {
819 user_id: Some("them".into()),
820 ..own_reaction("like")
821 };
822 let mut reactions = vec![other.clone()];
823 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
824 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
825 assert_eq!(reactions.len(), 2);
826 assert_eq!(reactions[1].reaction_type, "like");
827 assert_eq!(reactions[1].user_id.as_deref(), Some("me"));
828 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
829 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
830 assert_eq!(reactions, vec![other]);
831 }
832
833 #[test]
834 fn setting_matches_legacy_names_and_variation_selectors() {
835 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
836 let mut reactions = vec![own_reaction("heart")];
837 assert!(has_own_reaction(&reactions, "\u{2764}\u{FE0F}", Some("me")));
838 set_own_reaction(&mut reactions, "\u{2764}\u{FE0F}", Some("me"), false, now);
839 assert!(reactions.is_empty());
840 set_own_reaction(&mut reactions, "\u{1F389}", Some("me"), true, now);
841 assert_eq!(reactions[0].reaction_type, "\u{1F389}");
842 }
843
844 #[test]
845 fn setting_without_a_known_user_never_matches() {
846 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
847 let mut reactions = Vec::new();
848 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
849 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
850 assert_eq!(reactions.len(), 2);
851 }
852
853 #[test]
854 fn pending_reactions_overlay_the_stored_ones() {
855 let mut stored = record("a", None, 8, 6);
856 stored.reactions_json = serde_json::to_string(&[own_reaction("like")]).unwrap();
857 let mut context = context();
858 context.my_user_id = Some("me".into());
859 context.pending_reactions.insert(
860 "a".into(),
861 vec![("\u{1F44D}".into(), false), ("\u{1F389}".into(), true)],
862 );
863 let chips = message_row(&stored, &context).reactions;
864 assert_eq!(chips.len(), 1);
865 assert_eq!(chips[0].reaction_type, "\u{1F389}");
866 assert!(chips[0].mine);
867 }
868
869 #[test]
870 fn reaction_type_maps_classic_glyphs_to_names() {
871 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
872 assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart");
873 assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}");
874 assert_eq!(reaction_glyph("like"), reaction_glyph("\u{1F44D}"));
875 assert_eq!(reaction_glyph("heart"), reaction_glyph("\u{2764}\u{FE0F}"));
876 assert_eq!(api_reaction(&reaction_glyph("heart")), "\u{2764}\u{FE0F}");
877 assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
878 }
879
880 #[test]
881 fn forwarded_messages_are_detected_by_the_forward_blockquote() {
882 assert!(is_forwarded(
883 r#"<p>fyi</p><blockquote itemscope="" itemtype="http://schema.skype.com/Forward" itemid="1">text</blockquote>"#
884 ));
885 assert!(!is_forwarded(
886 r#"<blockquote itemtype="http://schema.skype.com/Reply">text</blockquote>"#
887 ));
888 assert!(!is_forwarded("<p>plain</p>"));
889 let mut forwarded = record("f", None, 8, 6);
890 forwarded.body_html =
891 r#"<blockquote itemtype="http://schema.skype.com/Forward">text</blockquote>"#.into();
892 assert!(message_row(&forwarded, &context()).forwarded);
893 forwarded.deleted = true;
894 assert!(!message_row(&forwarded, &context()).forwarded);
895 }
896
897 #[test]
898 fn editing_loads_the_message_formatted_without_its_reply_quote() {
899 let mut edited = record("a", None, 8, 6);
900 edited.body_html =
901 "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\
902 <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\
903 <ol><li>one</li><li>two</li></ol>"
904 .into();
905 let draft = message_draft(&edited);
906 assert_eq!(draft.text(), "Plan for today\n1. one\n2. two");
907 assert_eq!(
908 draft.to_html(),
909 "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>"
910 );
911 }
912
913 #[test]
914 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
915 let mut text = record("a", None, 8, 6);
916 text.body_html = "<p>first line</p><p>second</p>".into();
917 assert_eq!(reply_excerpt(&text), "first line");
918 let mut quoted = record("q", None, 8, 6);
919 quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into();
920 assert_eq!(reply_excerpt(&quoted), "my answer");
921 let mut image = record("b", None, 8, 6);
922 image.body_html = "<img src=\"u\">".into();
923 assert_eq!(reply_excerpt(&image), "Image");
924 let mut long = record("c", None, 8, 6);
925 long.body_html = format!("<p>{}</p>", "x".repeat(200));
926 assert!(reply_excerpt(&long).ends_with("..."));
927 assert_eq!(
928 reply_excerpt(&long).chars().count(),
929 REPLY_EXCERPT_CHARS + 3
930 );
931 }
932
933 fn context() -> RowContext {
934 RowContext {
935 offset: FixedOffset::east_opt(0).unwrap(),
936 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
937 my_user_id: None,
938 names: HashMap::new(),
939 pending_reactions: HashMap::new(),
940 card_overrides: HashMap::new(),
941 }
942 }
943
944 fn keys(rows: &[Row]) -> Vec<String> {
945 rows.iter().map(|row| row.key().to_owned()).collect()
946 }
947
948 #[test]
949 fn day_header_only_on_first_message_of_a_day() {
950 let records = vec![
951 record("a", None, 8, 6),
952 record("b", None, 9, 6),
953 record("c", None, 9, 7),
954 ];
955 let rows = flat_rows(&records, &context(), false);
956 let headers: Vec<Option<String>> = rows
957 .iter()
958 .map(|row| match row {
959 Row::Message(message) => message.day_header.clone(),
960 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
961 })
962 .collect();
963 assert_eq!(
964 headers,
965 vec![Some("Yesterday".into()), None, Some("Today".into())]
966 );
967 }
968
969 #[test]
970 fn load_older_row_only_when_more_exists() {
971 let records = vec![record("a", None, 8, 6)];
972 assert_eq!(
973 keys(&flat_rows(&records, &context(), true))[0],
974 LOAD_OLDER_KEY
975 );
976 assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]);
977 }
978
979 #[test]
980 fn threads_group_replies_by_root() {
981 let records = vec![
982 record("r1", None, 8, 6),
983 record("r2", None, 9, 6),
984 record("x1", Some("r1"), 10, 6),
985 record("x2", Some("r1"), 11, 6),
986 record("orphan", Some("missing"), 12, 6),
987 ];
988 let threads = group_threads(&records);
989 assert_eq!(threads.len(), 2);
990 assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]);
991 assert!(threads[1].reply_ids.is_empty());
992 }
993
994 fn post_of(row: &Row) -> &PostRow {
995 let Row::Post(post) = row else {
996 panic!("post expected")
997 };
998 post
999 }
1000
1001 fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord {
1002 let mut reply = record(id, Some(root), hour, 6);
1003 reply.sender_name = Some(sender.into());
1004 reply
1005 }
1006
1007 #[test]
1008 fn feed_orders_posts_by_last_activity_newest_first() {
1009 let records = vec![
1010 record("r1", None, 8, 6),
1011 record("r2", None, 9, 6),
1012 record("r3", None, 10, 6),
1013 record("x1", Some("r1"), 11, 6),
1014 ];
1015 let rows = thread_list_rows(&records, &context(), false);
1016 assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]);
1017 }
1018
1019 #[test]
1020 fn feed_puts_load_older_at_the_bottom() {
1021 let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)];
1022 let rows = thread_list_rows(&records, &context(), true);
1023 assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]);
1024 }
1025
1026 #[test]
1027 fn post_shows_the_last_three_replies_oldest_first() {
1028 let mut records = vec![record("r1", None, 1, 6)];
1029 for hour in 2..=6 {
1030 records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour));
1031 }
1032 records.reverse();
1033 let rows = thread_list_rows(&records, &context(), false);
1034 let post = post_of(&rows[0]);
1035 let shown: Vec<&str> = post
1036 .replies
1037 .iter()
1038 .map(|reply| reply.key.as_str())
1039 .collect();
1040 assert_eq!(shown, vec!["x4", "x5", "x6"]);
1041 assert_eq!(post.hidden_reply_count, 2);
1042 assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]);
1043 }
1044
1045 #[test]
1046 fn post_without_hidden_replies_has_no_link() {
1047 let records = vec![
1048 record("r1", None, 1, 6),
1049 reply_by("x1", "r1", "Ada", 2),
1050 reply_by("x2", "r1", "Ben", 3),
1051 reply_by("x3", "r1", "Cy", 4),
1052 ];
1053 let rows = thread_list_rows(&records, &context(), false);
1054 assert_eq!(post_of(&rows[0]).hidden_replies_label(), None);
1055 assert_eq!(post_of(&rows[0]).replies.len(), 3);
1056 }
1057
1058 fn label_for(repliers: &[&str]) -> String {
1059 let mut records = vec![record("r1", None, 1, 6)];
1060 for (index, name) in repliers.iter().enumerate() {
1061 records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32));
1062 }
1063 for index in 0..POST_VISIBLE_REPLIES {
1064 records.push(reply_by(
1065 &format!("v{index}"),
1066 "r1",
1067 "Shown",
1068 20 + index as u32,
1069 ));
1070 }
1071 let rows = thread_list_rows(&records, &context(), false);
1072 post_of(&rows[0]).hidden_replies_label().unwrap()
1073 }
1074
1075 #[test]
1076 fn replies_label_names_one_to_three_people() {
1077 assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna");
1078 assert_eq!(
1079 label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]),
1080 "3 replies from Anna and Ben"
1081 );
1082 assert_eq!(
1083 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]),
1084 "4 replies from Anna, Ben and Clara"
1085 );
1086 }
1087
1088 #[test]
1089 fn replies_label_counts_the_others_beyond_three_people() {
1090 assert_eq!(
1091 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]),
1092 "5 replies from Anna, Ben and 3 others"
1093 );
1094 assert_eq!(
1095 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]),
1096 "4 replies from Anna, Ben and 2 others"
1097 );
1098 }
1099
1100 #[test]
1101 fn local_reply_lands_in_its_post_and_local_post_on_top() {
1102 let records = vec![
1103 record("r1", None, 8, 6),
1104 record("r2", None, 9, 6),
1105 reply_by("x1", "r1", "Ada", 10),
1106 ];
1107 let mut rows = thread_list_rows(&records, &context(), true);
1108 let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context());
1109 pending_reply.reply_root = Some("r2".into());
1110 let pending_post = message_row(&record("pending-2", None, 12, 6), &context());
1111 place_local_rows(&mut rows, vec![pending_reply, pending_post]);
1112 assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]);
1113 let replies: Vec<&str> = post_of(&rows[1])
1114 .replies
1115 .iter()
1116 .map(|reply| reply.key.as_str())
1117 .collect();
1118 assert_eq!(replies, vec!["pending-1"]);
1119 }
1120
1121 #[test]
1122 fn local_reply_to_an_unloaded_post_is_not_shown() {
1123 let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false);
1124 let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context());
1125 orphan.reply_root = Some("gone".into());
1126 place_local_rows(&mut rows, vec![orphan]);
1127 assert_eq!(keys(&rows), vec!["r1"]);
1128 }
1129
1130 #[test]
1131 fn subject_reaches_the_post_root() {
1132 let mut with_subject = record("r1", None, 8, 6);
1133 with_subject.subject = Some("Release plan".into());
1134 let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false);
1135 assert_eq!(
1136 post_of(&rows[0]).root.subject.as_deref(),
1137 Some("Release plan")
1138 );
1139 assert_eq!(post_of(&rows[1]).root.subject, None);
1140 }
1141
1142 #[test]
1143 fn thread_view_has_root_then_replies() {
1144 let records = vec![
1145 record("r1", None, 8, 6),
1146 record("r2", None, 9, 6),
1147 record("x1", Some("r1"), 10, 6),
1148 ];
1149 assert_eq!(
1150 keys(&thread_rows(&records, "r1", &context())),
1151 vec!["r1", "x1"]
1152 );
1153 }
1154
1155 #[test]
1156 fn reactions_are_counted_in_first_seen_order() {
1157 let reaction = |kind: &str| ReactionInfo {
1158 reaction_type: kind.into(),
1159 user_id: None,
1160 user_name: None,
1161 created_at: None,
1162 };
1163 let chips = reaction_chips(
1164 &[reaction("heart"), reaction("like"), reaction("heart")],
1165 &context(),
1166 );
1167 assert_eq!(chips.len(), 2);
1168 assert_eq!(chips[0].count, 2);
1169 assert_eq!(chips[1].label, reaction_label("like"));
1170 }
1171
1172 #[test]
1173 fn legacy_laugh_and_sad_use_the_teams_glyphs() {
1174 assert_eq!(reaction_label("laugh"), "\u{1F606}");
1175 assert_eq!(reaction_label("sad"), "\u{1F641}");
1176 assert_eq!(reaction_type_for("\u{1F606}"), "laugh");
1177 assert_eq!(reaction_type_for("\u{1F641}"), "sad");
1178 }
1179
1180 #[test]
1181 fn legacy_and_emoji_reactions_share_a_chip() {
1182 let reaction = |kind: &str| ReactionInfo {
1183 reaction_type: kind.into(),
1184 user_id: None,
1185 user_name: Some("Lea".into()),
1186 created_at: None,
1187 };
1188 let chips = reaction_chips(&[reaction("like"), reaction("\u{1F44D}")], &context());
1189 assert_eq!(chips.len(), 1);
1190 assert_eq!(chips[0].count, 2);
1191 }
1192
1193 #[test]
1194 fn reactor_name_falls_back_to_directory_then_unknown() {
1195 let reaction = |user: &str| ReactionInfo {
1196 reaction_type: "like".into(),
1197 user_id: Some(user.into()),
1198 user_name: None,
1199 created_at: None,
1200 };
1201 let mut context = context();
1202 context.names.insert("known".into(), "Priya Nair".into());
1203 let chips = reaction_chips(&[reaction("known"), reaction("other")], &context);
1204 assert_eq!(chips[0].reactors[0].name, "Priya Nair");
1205 assert_eq!(chips[0].reactors[1].name, "Unknown");
1206 }
1207
1208 fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord {
1209 let mut record = record(id, None, hour, day);
1210 record.sender_id = Some(sender.into());
1211 record.created_at = Utc
1212 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
1213 .unwrap();
1214 record
1215 }
1216
1217 fn series_of(rows: &[Row]) -> Vec<(bool, bool)> {
1218 rows.iter()
1219 .filter_map(|row| match row {
1220 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1221 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
1222 })
1223 .collect()
1224 }
1225
1226 #[test]
1227 fn series_joins_same_sender_within_five_minutes() {
1228 let records = vec![
1229 record_by("a", "ada", 9, 0, 7),
1230 record_by("b", "ada", 9, 4, 7),
1231 record_by("c", "ada", 9, 20, 7),
1232 record_by("d", "bob", 9, 21, 7),
1233 record_by("e", "ada", 9, 22, 7),
1234 ];
1235 let rows = flat_rows(&records, &context(), false);
1236 assert_eq!(
1237 series_of(&rows),
1238 vec![
1239 (false, true),
1240 (true, false),
1241 (false, false),
1242 (false, false),
1243 (false, false)
1244 ]
1245 );
1246 }
1247
1248 #[test]
1249 fn series_window_ends_exactly_at_the_gap_constant() {
1250 let gap = SERIES_GAP_MINUTES as u32;
1251 let records = vec![
1252 record_by("a", "ada", 9, 0, 7),
1253 record_by("b", "ada", 9, gap - 1, 7),
1254 record_by("c", "ada", 9, 2 * gap - 1 + gap, 7),
1255 ];
1256 let rows = flat_rows(&records, &context(), false);
1257 assert_eq!(
1258 series_of(&rows),
1259 vec![(false, true), (true, false), (false, false)]
1260 );
1261 }
1262
1263 #[test]
1264 fn series_breaks_at_a_new_day() {
1265 let records = vec![
1266 record_by("a", "ada", 23, 58, 6),
1267 record_by("b", "ada", 0, 1, 7),
1268 ];
1269 let rows = flat_rows(&records, &context(), false);
1270 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1271 }
1272
1273 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
1274 let corners = bubble_corners(own, Series { has_prev, has_next });
1275 [
1276 corners.top_left,
1277 corners.top_right,
1278 corners.bottom_right,
1279 corners.bottom_left,
1280 ]
1281 }
1282
1283 #[test]
1284 fn corners_match_the_mockup_for_other_senders() {
1285 assert_eq!(corners(false, false, false), [4., 14., 14., 14.]);
1286 assert_eq!(corners(false, false, true), [4., 14., 14., 4.]);
1287 assert_eq!(corners(false, true, true), [4., 14., 14., 4.]);
1288 assert_eq!(corners(false, true, false), [4., 14., 14., 14.]);
1289 }
1290
1291 #[test]
1292 fn corners_match_the_mockup_for_own_messages() {
1293 assert_eq!(corners(true, false, false), [14., 4., 4., 14.]);
1294 assert_eq!(corners(true, false, true), [14., 14., 4., 14.]);
1295 assert_eq!(corners(true, true, true), [14., 4., 4., 14.]);
1296 assert_eq!(corners(true, true, false), [14., 4., 14., 14.]);
1297 }
1298
1299 #[test]
1300 fn own_reaction_is_marked() {
1301 let reaction = |user: &str| ReactionInfo {
1302 reaction_type: "like".into(),
1303 user_id: Some(user.into()),
1304 user_name: None,
1305 created_at: None,
1306 };
1307 let mut context = context();
1308 context.my_user_id = Some("me".into());
1309 let chips = reaction_chips(&[reaction("x"), reaction("me")], &context);
1310 assert!(chips[0].mine);
1311 assert!(!reaction_chips(&[reaction("x")], &context)[0].mine);
1312 }
1313
1314 fn strings(values: &[&str]) -> Vec<String> {
1315 values.iter().map(|value| (*value).to_owned()).collect()
1316 }
1317
1318 #[test]
1319 fn diff_detects_append_prepend_and_replace() {
1320 let base = strings(&["a", "b"]);
1321 assert_eq!(diff_keys(&base, &base), None);
1322 assert_eq!(
1323 diff_keys(&base, &strings(&["a", "b", "c"])),
1324 Some(Splice {
1325 range: 2..2,
1326 count: 1
1327 })
1328 );
1329 assert_eq!(
1330 diff_keys(&base, &strings(&["x", "a", "b"])),
1331 Some(Splice {
1332 range: 0..0,
1333 count: 1
1334 })
1335 );
1336 assert_eq!(
1337 diff_keys(
1338 &strings(&["load-older", "a"]),
1339 &strings(&["load-older", "x", "y", "a"])
1340 ),
1341 Some(Splice {
1342 range: 1..1,
1343 count: 2
1344 })
1345 );
1346 assert_eq!(
1347 diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])),
1348 Some(Splice {
1349 range: 0..1,
1350 count: 0
1351 })
1352 );
1353 assert_eq!(
1354 diff_keys(&base, &strings(&["x"])),
1355 Some(Splice {
1356 range: 0..2,
1357 count: 1
1358 })
1359 );
1360 }
1361
1362 #[test]
1363 fn changed_indices_find_edited_rows() {
1364 let old = flat_rows(
1365 &[record("a", None, 8, 6), record("b", None, 9, 6)],
1366 &context(),
1367 false,
1368 );
1369 let mut edited = record("b", None, 9, 6);
1370 edited.body_html = "<p>changed</p>".into();
1371 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
1372 assert_eq!(changed_indices(&old, &new), vec![1]);
1373 }
1374}