BlueGit

ict rusty-teams

Files

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

rows.rs

rows.rs 31.1 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, ReactionInfo, Span, adaptive_cards, card_texts, files,
10 images, message_spans, reactions,
11};
12
13use crate::format;
14use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
15use crate::render::blocks::{Inline, strip_image_placeholders};
16use crate::render::{Block, layout_blocks};
17use crate::sidebar_model::Face;
18
19const REPLY_FACE_LIMIT: 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, PartialEq, Eq)]
99pub enum Delivery {
100 Delivered,
101 Sending,
102 Failed(String),
103}
104
105/// An image of a message that is still being sent, shown from its local bytes.
106#[derive(Debug, Clone, PartialEq)]
107pub struct LocalImage {
108 pub image: Arc<Image>,
109 pub size: Option<(u32, u32)>,
110}
111
112#[derive(Debug, Clone, PartialEq)]
113pub struct MessageRow {
114 pub key: String,
115 pub author: String,
116 pub sender_id: Option<String>,
117 pub created_at: DateTime<Utc>,
118 pub series: Series,
119 pub card: bool,
120 pub time: String,
121 pub day_header: Option<String>,
122 pub blocks: Vec<Block>,
123 pub edited: bool,
124 pub deleted: bool,
125 pub reactions: Vec<ReactionChip>,
126 pub images: Vec<ImageRef>,
127 pub local_images: Vec<LocalImage>,
128 pub files: Vec<FileCard>,
129 pub adaptive_cards: Vec<AdaptiveCard>,
130 pub reply_count: Option<usize>,
131 pub new_marker: bool,
132 pub reply_faces: Vec<Face>,
133 pub last_reply_time: Option<String>,
134 pub open_thread: Option<String>,
135 pub is_reply: bool,
136 pub delivery: Delivery,
137 pub own: bool,
138 pub receipt: Receipt,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct StartInfo {
143 pub title: String,
144 pub user_id: Option<String>,
145}
146
147pub const START_KEY: &str = "conversation-start";
148
149#[derive(Debug, Clone, PartialEq)]
150pub enum Row {
151 LoadOlder,
152 Start(StartInfo),
153 Skeleton(Skeleton),
154 Message(Box<MessageRow>),
155}
156
157#[derive(Debug, Clone, Copy, PartialEq)]
158pub struct Skeleton {
159 pub key: &'static str,
160 pub own: bool,
161 pub width_ratio: f32,
162 pub lines: u8,
163}
164
165const SKELETON_TRAILING: Skeleton = Skeleton {
166 key: "skeleton-trailing",
167 own: false,
168 width_ratio: 0.32,
169 lines: 1,
170};
171
172const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [
173 Skeleton {
174 key: "skeleton-0",
175 own: false,
176 width_ratio: 0.42,
177 lines: 1,
178 },
179 Skeleton {
180 key: "skeleton-1",
181 own: true,
182 width_ratio: 0.3,
183 lines: 1,
184 },
185 Skeleton {
186 key: "skeleton-2",
187 own: true,
188 width_ratio: 0.48,
189 lines: 2,
190 },
191 Skeleton {
192 key: "skeleton-3",
193 own: false,
194 width_ratio: 0.26,
195 lines: 1,
196 },
197];
198
199pub fn placeholder_rows() -> Vec<Row> {
200 SKELETON_PLACEHOLDERS
201 .into_iter()
202 .map(Row::Skeleton)
203 .collect()
204}
205
206pub fn trailing_skeleton() -> Row {
207 Row::Skeleton(SKELETON_TRAILING)
208}
209
210fn sender_key(row: &MessageRow) -> &str {
211 row.sender_id.as_deref().unwrap_or(&row.author)
212}
213
214fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
215 !previous.card
216 && !next.card
217 && next.day_header.is_none()
218 && !next.new_marker
219 && sender_key(previous) == sender_key(next)
220 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
221 && next.created_at >= previous.created_at
222}
223
224pub fn assign_series(rows: &mut [Row]) {
225 let mut previous: Option<usize> = None;
226 for index in 0..rows.len() {
227 let Row::Message(_) = &rows[index] else {
228 previous = None;
229 continue;
230 };
231 if let Some(before) = previous {
232 let joined = match (&rows[before], &rows[index]) {
233 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
234 _ => false,
235 };
236 if joined {
237 if let Row::Message(a) = &mut rows[before] {
238 a.series.has_next = true;
239 }
240 if let Row::Message(b) = &mut rows[index] {
241 b.series.has_prev = true;
242 }
243 }
244 }
245 previous = Some(index);
246 }
247}
248
249impl Row {
250 pub fn key(&self) -> &str {
251 match self {
252 Row::LoadOlder => LOAD_OLDER_KEY,
253 Row::Start(_) => START_KEY,
254 Row::Skeleton(skeleton) => skeleton.key,
255 Row::Message(message) => &message.key,
256 }
257 }
258}
259
260#[derive(Debug, Clone, PartialEq, Eq)]
261pub struct Thread {
262 pub root_id: String,
263 pub reply_ids: Vec<String>,
264}
265
266pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String {
267 time.with_timezone(&offset).format("%H:%M").to_string()
268}
269
270pub fn reaction_label(reaction_type: &str) -> String {
271 match reaction_type {
272 "like" => "\u{1F44D}".to_owned(),
273 "heart" => "\u{2764}".to_owned(),
274 "laugh" => "\u{1F602}".to_owned(),
275 "surprised" => "\u{1F62E}".to_owned(),
276 "sad" => "\u{1F622}".to_owned(),
277 "angry" => "\u{1F620}".to_owned(),
278 other => other.to_owned(),
279 }
280}
281
282pub fn reaction_glyph(reaction_type: &str) -> String {
283 reaction_label(reaction_type)
284 .trim_end_matches('\u{FE0F}')
285 .to_owned()
286}
287
288/// Graph rejects the legacy names ("Unicode 'like' in the payload is not supported").
289pub fn api_reaction(glyph: &str) -> String {
290 match glyph {
291 "\u{2764}" => "\u{2764}\u{FE0F}".to_owned(),
292 other => other.to_owned(),
293 }
294}
295
296/// The reaction type Teams uses for a glyph: the legacy name for the six classic ones.
297pub fn reaction_type_for(glyph: &str) -> String {
298 let bare = glyph.trim_end_matches('\u{FE0F}');
299 ["like", "heart", "laugh", "surprised", "sad", "angry"]
300 .into_iter()
301 .find(|name| reaction_label(name) == bare)
302 .map_or_else(|| bare.to_owned(), str::to_owned)
303}
304
305pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
306 let my_user_id = context.my_user_id.as_deref();
307 let mut chips: Vec<ReactionChip> = Vec::new();
308 for reaction in reactions {
309 let glyph = reaction_glyph(&reaction.reaction_type);
310 let position = match chips.iter().position(|chip| chip.glyph() == glyph) {
311 Some(position) => position,
312 None => {
313 chips.push(ReactionChip {
314 reaction_type: reaction.reaction_type.clone(),
315 label: reaction_label(&reaction.reaction_type),
316 count: 0,
317 mine: false,
318 reactors: Vec::new(),
319 });
320 chips.len() - 1
321 }
322 };
323 let chip = &mut chips[position];
324 chip.count += 1;
325 chip.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id;
326 chip.reactors.push(Reactor {
327 user_id: reaction.user_id.clone(),
328 name: reactor_name(reaction, context),
329 created_at: reaction.created_at,
330 });
331 }
332 chips
333}
334
335fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String {
336 reaction
337 .user_name
338 .clone()
339 .or_else(|| {
340 reaction
341 .user_id
342 .as_ref()
343 .and_then(|user_id| context.names.get(user_id).cloned())
344 })
345 .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned())
346}
347
348const REPLY_EXCERPT_CHARS: usize = 90;
349
350pub fn message_text(record: &MessageRecord) -> String {
351 let own_spans: Vec<Span> = message_spans(record)
352 .into_iter()
353 .filter(|span| !matches!(span, Span::Quote(_)))
354 .collect();
355 strip_image_placeholders(layout_blocks(&own_spans))
356 .into_iter()
357 .filter_map(|block| block.markdown())
358 .collect::<Vec<_>>()
359 .join("\n")
360}
361
362/// The message as the composer edits it, formatting kept.
363pub fn message_draft(record: &MessageRecord) -> Draft {
364 let own_spans: Vec<Span> = message_spans(record)
365 .into_iter()
366 .filter(|span| !matches!(span, Span::Quote(_)))
367 .collect();
368 Draft::from_spans(&own_spans).trimmed()
369}
370
371pub fn reply_excerpt(record: &MessageRecord) -> String {
372 let own_spans: Vec<Span> = message_spans(record)
373 .into_iter()
374 .filter(|span| !matches!(span, Span::Quote(_)))
375 .collect();
376 let text = strip_image_placeholders(layout_blocks(&own_spans))
377 .into_iter()
378 .find_map(|block| block.first_line())
379 .unwrap_or_default();
380 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
381 let excerpt = match first_line {
382 Some(line) => line.to_owned(),
383 None if !images(record).is_empty() => "Image".to_owned(),
384 None if let Some(line) = card_texts(record)
385 .iter()
386 .flat_map(|text| text.lines())
387 .next() =>
388 {
389 line.to_owned()
390 }
391 None => files(record)
392 .into_iter()
393 .next()
394 .map_or_else(|| "Message".to_owned(), |card| card.name),
395 };
396 if excerpt.chars().count() > REPLY_EXCERPT_CHARS {
397 let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect();
398 format!("{}...", cut.trim_end())
399 } else {
400 excerpt
401 }
402}
403
404pub struct RowContext {
405 pub offset: FixedOffset,
406 pub today: NaiveDate,
407 pub my_user_id: Option<String>,
408 pub names: HashMap<String, String>,
409}
410
411pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
412 let local = record.created_at.with_timezone(&context.offset);
413 let images = images(record);
414 let blocks = if record.deleted {
415 vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
416 } else {
417 layout_blocks(&message_spans(record))
418 };
419 let blocks = if images.is_empty() {
420 blocks
421 } else {
422 strip_image_placeholders(blocks)
423 };
424 MessageRow {
425 key: record.message_id.clone(),
426 sender_id: record.sender_id.clone(),
427 created_at: record.created_at,
428 series: Series::default(),
429 card: false,
430 author: record
431 .sender_name
432 .clone()
433 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
434 time: clock_label(record.created_at, context.offset),
435 day_header: Some(format::day_label(local.date_naive(), context.today)),
436 blocks,
437 edited: record.edited_at.is_some() && !record.deleted,
438 deleted: record.deleted,
439 reactions: reaction_chips(&reactions(record), context),
440 images,
441 local_images: Vec::new(),
442 files: files(record),
443 adaptive_cards: adaptive_cards(record),
444 reply_count: None,
445 new_marker: false,
446 reply_faces: Vec::new(),
447 last_reply_time: None,
448 open_thread: None,
449 is_reply: record.reply_to_id.is_some(),
450 delivery: Delivery::Delivered,
451 receipt: Receipt::Hidden,
452 own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
453 }
454}
455
456pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
457 let mut rows = Vec::with_capacity(records.len() + 1);
458 if has_older {
459 rows.push(Row::LoadOlder);
460 }
461 let mut previous_day: Option<NaiveDate> = None;
462 for record in records {
463 let mut row = message_row(record, context);
464 let day = record
465 .created_at
466 .with_timezone(&context.offset)
467 .date_naive();
468 if previous_day == Some(day) {
469 row.day_header = None;
470 }
471 previous_day = Some(day);
472 rows.push(Row::Message(Box::new(row)));
473 }
474 assign_series(&mut rows);
475 rows
476}
477
478pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> {
479 let mut threads: Vec<Thread> = Vec::new();
480 let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new();
481 for record in records.iter().filter(|record| record.reply_to_id.is_none()) {
482 index_by_root.insert(record.message_id.as_str(), threads.len());
483 threads.push(Thread {
484 root_id: record.message_id.clone(),
485 reply_ids: Vec::new(),
486 });
487 }
488 for record in records {
489 let Some(root_id) = record.reply_to_id.as_deref() else {
490 continue;
491 };
492 if let Some(&index) = index_by_root.get(root_id) {
493 threads[index].reply_ids.push(record.message_id.clone());
494 }
495 }
496 threads
497}
498
499fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> {
500 thread
501 .reply_ids
502 .iter()
503 .chain(std::iter::once(&thread.root_id))
504 .filter_map(|id| by_id.get(id.as_str()))
505 .map(|record| record.created_at)
506 .max()
507 .unwrap_or_default()
508}
509
510pub fn thread_list_rows(
511 records: &[MessageRecord],
512 context: &RowContext,
513 has_older: bool,
514) -> Vec<Row> {
515 let by_id: BTreeMap<&str, &MessageRecord> = records
516 .iter()
517 .map(|record| (record.message_id.as_str(), record))
518 .collect();
519 let mut threads = group_threads(records);
520 threads.sort_by_key(|thread| last_activity(thread, &by_id));
521 let mut rows = Vec::with_capacity(threads.len() + 1);
522 if has_older {
523 rows.push(Row::LoadOlder);
524 }
525 let mut previous_day: Option<NaiveDate> = None;
526 for thread in threads {
527 let Some(root) = by_id.get(thread.root_id.as_str()) else {
528 continue;
529 };
530 let mut row = message_row(root, context);
531 let day = last_activity(&thread, &by_id)
532 .with_timezone(&context.offset)
533 .date_naive();
534 row.day_header = (previous_day != Some(day)).then(|| format::day_label(day, context.today));
535 previous_day = Some(day);
536 row.card = true;
537 row.time = format::post_time_label(root.created_at, context.today, context.offset);
538 row.reply_count = Some(thread.reply_ids.len());
539 let replies: Vec<&&MessageRecord> = thread
540 .reply_ids
541 .iter()
542 .filter_map(|id| by_id.get(id.as_str()))
543 .collect();
544 for reply in &replies {
545 let face = Face {
546 user_id: reply.sender_id.clone(),
547 name: reply
548 .sender_name
549 .clone()
550 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
551 };
552 if row.reply_faces.len() < REPLY_FACE_LIMIT && !row.reply_faces.contains(&face) {
553 row.reply_faces.push(face);
554 }
555 }
556 row.last_reply_time = replies
557 .iter()
558 .map(|reply| reply.created_at)
559 .max()
560 .map(|time| {
561 let local = time.with_timezone(&context.offset);
562 format!(
563 "{} {}",
564 format::day_label(local.date_naive(), context.today),
565 clock_label(time, context.offset)
566 )
567 });
568 row.open_thread = Some(thread.root_id.clone());
569 rows.push(Row::Message(Box::new(row)));
570 }
571 rows
572}
573
574pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
575 let members: Vec<MessageRecord> = records
576 .iter()
577 .filter(|record| {
578 record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id)
579 })
580 .cloned()
581 .collect();
582 flat_rows(&members, context, false)
583}
584
585#[derive(Debug, Clone, PartialEq, Eq)]
586pub struct Splice {
587 pub range: Range<usize>,
588 pub count: usize,
589}
590
591pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> {
592 if old == new {
593 return None;
594 }
595 let prefix = old
596 .iter()
597 .zip(new)
598 .take_while(|(left, right)| left == right)
599 .count();
600 let suffix = old[prefix..]
601 .iter()
602 .rev()
603 .zip(new[prefix..].iter().rev())
604 .take_while(|(left, right)| left == right)
605 .count();
606 Some(Splice {
607 range: prefix..old.len() - suffix,
608 count: new.len() - prefix - suffix,
609 })
610}
611
612pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> {
613 let prefix = old
614 .iter()
615 .zip(new)
616 .take_while(|(left, right)| left.key() == right.key())
617 .count();
618 let suffix = old[prefix..]
619 .iter()
620 .rev()
621 .zip(new[prefix..].iter().rev())
622 .take_while(|(left, right)| left.key() == right.key())
623 .count();
624 let mut changed: Vec<usize> = (0..prefix)
625 .filter(|&index| old[index] != new[index])
626 .collect();
627 changed.extend((0..suffix).filter_map(|offset| {
628 let old_index = old.len() - 1 - offset;
629 let new_index = new.len() - 1 - offset;
630 (old[old_index] != new[new_index]).then_some(new_index)
631 }));
632 changed
633}
634
635#[cfg(test)]
636mod tests {
637 use chrono::TimeZone;
638
639 use super::*;
640
641 fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord {
642 MessageRecord {
643 conversation_id: "c".into(),
644 message_id: id.into(),
645 reply_to_id: reply_to.map(str::to_owned),
646 sender_id: Some("u".into()),
647 sender_name: Some("Author".into()),
648 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
649 edited_at: None,
650 deleted: false,
651 body_html: format!("<p>text {id}</p>"),
652 attachments_json: "[]".into(),
653 reactions_json: "[]".into(),
654 mentions_json: "[]".into(),
655 }
656 }
657
658 #[test]
659 fn reaction_type_maps_classic_glyphs_to_names() {
660 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
661 assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart");
662 assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}");
663 assert_eq!(reaction_glyph("like"), reaction_glyph("\u{1F44D}"));
664 assert_eq!(reaction_glyph("heart"), reaction_glyph("\u{2764}\u{FE0F}"));
665 assert_eq!(api_reaction(&reaction_glyph("heart")), "\u{2764}\u{FE0F}");
666 assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
667 }
668
669 #[test]
670 fn editing_loads_the_message_formatted_without_its_reply_quote() {
671 let mut edited = record("a", None, 8, 6);
672 edited.body_html =
673 "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\
674 <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\
675 <ol><li>one</li><li>two</li></ol>"
676 .into();
677 let draft = message_draft(&edited);
678 assert_eq!(draft.text(), "Plan for today\n1. one\n2. two");
679 assert_eq!(
680 draft.to_html(),
681 "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>"
682 );
683 }
684
685 #[test]
686 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
687 let mut text = record("a", None, 8, 6);
688 text.body_html = "<p>first line</p><p>second</p>".into();
689 assert_eq!(reply_excerpt(&text), "first line");
690 let mut quoted = record("q", None, 8, 6);
691 quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into();
692 assert_eq!(reply_excerpt(&quoted), "my answer");
693 let mut image = record("b", None, 8, 6);
694 image.body_html = "<img src=\"u\">".into();
695 assert_eq!(reply_excerpt(&image), "Image");
696 let mut long = record("c", None, 8, 6);
697 long.body_html = format!("<p>{}</p>", "x".repeat(200));
698 assert!(reply_excerpt(&long).ends_with("..."));
699 assert_eq!(
700 reply_excerpt(&long).chars().count(),
701 REPLY_EXCERPT_CHARS + 3
702 );
703 }
704
705 fn context() -> RowContext {
706 RowContext {
707 offset: FixedOffset::east_opt(0).unwrap(),
708 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
709 my_user_id: None,
710 names: HashMap::new(),
711 }
712 }
713
714 fn keys(rows: &[Row]) -> Vec<String> {
715 rows.iter().map(|row| row.key().to_owned()).collect()
716 }
717
718 #[test]
719 fn day_header_only_on_first_message_of_a_day() {
720 let records = vec![
721 record("a", None, 8, 6),
722 record("b", None, 9, 6),
723 record("c", None, 9, 7),
724 ];
725 let rows = flat_rows(&records, &context(), false);
726 let headers: Vec<Option<String>> = rows
727 .iter()
728 .map(|row| match row {
729 Row::Message(message) => message.day_header.clone(),
730 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
731 })
732 .collect();
733 assert_eq!(
734 headers,
735 vec![Some("Yesterday".into()), None, Some("Today".into())]
736 );
737 }
738
739 #[test]
740 fn load_older_row_only_when_more_exists() {
741 let records = vec![record("a", None, 8, 6)];
742 assert_eq!(
743 keys(&flat_rows(&records, &context(), true))[0],
744 LOAD_OLDER_KEY
745 );
746 assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]);
747 }
748
749 #[test]
750 fn threads_group_replies_by_root() {
751 let records = vec![
752 record("r1", None, 8, 6),
753 record("r2", None, 9, 6),
754 record("x1", Some("r1"), 10, 6),
755 record("x2", Some("r1"), 11, 6),
756 record("orphan", Some("missing"), 12, 6),
757 ];
758 let threads = group_threads(&records);
759 assert_eq!(threads.len(), 2);
760 assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]);
761 assert!(threads[1].reply_ids.is_empty());
762 }
763
764 #[test]
765 fn thread_list_orders_by_last_activity_with_reply_count() {
766 let records = vec![
767 record("r1", None, 8, 6),
768 record("r2", None, 9, 6),
769 record("x1", Some("r1"), 10, 6),
770 ];
771 let rows = thread_list_rows(&records, &context(), false);
772 assert_eq!(keys(&rows), vec!["r2", "r1"]);
773 let Row::Message(last) = &rows[1] else {
774 panic!("message expected")
775 };
776 assert_eq!(last.reply_count, Some(1));
777 assert_eq!(last.open_thread.as_deref(), Some("r1"));
778 }
779
780 #[test]
781 fn thread_view_has_root_then_replies() {
782 let records = vec![
783 record("r1", None, 8, 6),
784 record("r2", None, 9, 6),
785 record("x1", Some("r1"), 10, 6),
786 ];
787 assert_eq!(
788 keys(&thread_rows(&records, "r1", &context())),
789 vec!["r1", "x1"]
790 );
791 }
792
793 #[test]
794 fn reactions_are_counted_in_first_seen_order() {
795 let reaction = |kind: &str| ReactionInfo {
796 reaction_type: kind.into(),
797 user_id: None,
798 user_name: None,
799 created_at: None,
800 };
801 let chips = reaction_chips(
802 &[reaction("heart"), reaction("like"), reaction("heart")],
803 &context(),
804 );
805 assert_eq!(chips.len(), 2);
806 assert_eq!(chips[0].count, 2);
807 assert_eq!(chips[1].label, reaction_label("like"));
808 }
809
810 #[test]
811 fn legacy_and_emoji_reactions_share_a_chip() {
812 let reaction = |kind: &str| ReactionInfo {
813 reaction_type: kind.into(),
814 user_id: None,
815 user_name: Some("Lea".into()),
816 created_at: None,
817 };
818 let chips = reaction_chips(&[reaction("like"), reaction("\u{1F44D}")], &context());
819 assert_eq!(chips.len(), 1);
820 assert_eq!(chips[0].count, 2);
821 }
822
823 #[test]
824 fn reactor_name_falls_back_to_directory_then_unknown() {
825 let reaction = |user: &str| ReactionInfo {
826 reaction_type: "like".into(),
827 user_id: Some(user.into()),
828 user_name: None,
829 created_at: None,
830 };
831 let mut context = context();
832 context.names.insert("known".into(), "Priya Nair".into());
833 let chips = reaction_chips(&[reaction("known"), reaction("other")], &context);
834 assert_eq!(chips[0].reactors[0].name, "Priya Nair");
835 assert_eq!(chips[0].reactors[1].name, "Unknown");
836 }
837
838 fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord {
839 let mut record = record(id, None, hour, day);
840 record.sender_id = Some(sender.into());
841 record.created_at = Utc
842 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
843 .unwrap();
844 record
845 }
846
847 fn series_of(rows: &[Row]) -> Vec<(bool, bool)> {
848 rows.iter()
849 .filter_map(|row| match row {
850 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
851 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
852 })
853 .collect()
854 }
855
856 #[test]
857 fn series_joins_same_sender_within_five_minutes() {
858 let records = vec![
859 record_by("a", "ada", 9, 0, 7),
860 record_by("b", "ada", 9, 4, 7),
861 record_by("c", "ada", 9, 20, 7),
862 record_by("d", "bob", 9, 21, 7),
863 record_by("e", "ada", 9, 22, 7),
864 ];
865 let rows = flat_rows(&records, &context(), false);
866 assert_eq!(
867 series_of(&rows),
868 vec![
869 (false, true),
870 (true, false),
871 (false, false),
872 (false, false),
873 (false, false)
874 ]
875 );
876 }
877
878 #[test]
879 fn series_window_ends_exactly_at_the_gap_constant() {
880 let gap = SERIES_GAP_MINUTES as u32;
881 let records = vec![
882 record_by("a", "ada", 9, 0, 7),
883 record_by("b", "ada", 9, gap - 1, 7),
884 record_by("c", "ada", 9, 2 * gap - 1 + gap, 7),
885 ];
886 let rows = flat_rows(&records, &context(), false);
887 assert_eq!(
888 series_of(&rows),
889 vec![(false, true), (true, false), (false, false)]
890 );
891 }
892
893 #[test]
894 fn series_breaks_at_a_new_day() {
895 let records = vec![
896 record_by("a", "ada", 23, 58, 6),
897 record_by("b", "ada", 0, 1, 7),
898 ];
899 let rows = flat_rows(&records, &context(), false);
900 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
901 }
902
903 #[test]
904 fn thread_list_rows_never_join() {
905 let records = vec![
906 record_by("a", "ada", 9, 0, 7),
907 record_by("b", "ada", 9, 1, 7),
908 ];
909 let rows = thread_list_rows(&records, &context(), false);
910 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
911 }
912
913 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
914 let corners = bubble_corners(own, Series { has_prev, has_next });
915 [
916 corners.top_left,
917 corners.top_right,
918 corners.bottom_right,
919 corners.bottom_left,
920 ]
921 }
922
923 #[test]
924 fn corners_match_the_mockup_for_other_senders() {
925 assert_eq!(corners(false, false, false), [4., 14., 14., 14.]);
926 assert_eq!(corners(false, false, true), [4., 14., 14., 4.]);
927 assert_eq!(corners(false, true, true), [4., 14., 14., 4.]);
928 assert_eq!(corners(false, true, false), [4., 14., 14., 14.]);
929 }
930
931 #[test]
932 fn corners_match_the_mockup_for_own_messages() {
933 assert_eq!(corners(true, false, false), [14., 4., 4., 14.]);
934 assert_eq!(corners(true, false, true), [14., 14., 4., 14.]);
935 assert_eq!(corners(true, true, true), [14., 4., 4., 14.]);
936 assert_eq!(corners(true, true, false), [14., 4., 14., 14.]);
937 }
938
939 #[test]
940 fn own_reaction_is_marked() {
941 let reaction = |user: &str| ReactionInfo {
942 reaction_type: "like".into(),
943 user_id: Some(user.into()),
944 user_name: None,
945 created_at: None,
946 };
947 let mut context = context();
948 context.my_user_id = Some("me".into());
949 let chips = reaction_chips(&[reaction("x"), reaction("me")], &context);
950 assert!(chips[0].mine);
951 assert!(!reaction_chips(&[reaction("x")], &context)[0].mine);
952 }
953
954 fn strings(values: &[&str]) -> Vec<String> {
955 values.iter().map(|value| (*value).to_owned()).collect()
956 }
957
958 #[test]
959 fn diff_detects_append_prepend_and_replace() {
960 let base = strings(&["a", "b"]);
961 assert_eq!(diff_keys(&base, &base), None);
962 assert_eq!(
963 diff_keys(&base, &strings(&["a", "b", "c"])),
964 Some(Splice {
965 range: 2..2,
966 count: 1
967 })
968 );
969 assert_eq!(
970 diff_keys(&base, &strings(&["x", "a", "b"])),
971 Some(Splice {
972 range: 0..0,
973 count: 1
974 })
975 );
976 assert_eq!(
977 diff_keys(
978 &strings(&["load-older", "a"]),
979 &strings(&["load-older", "x", "y", "a"])
980 ),
981 Some(Splice {
982 range: 1..1,
983 count: 2
984 })
985 );
986 assert_eq!(
987 diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])),
988 Some(Splice {
989 range: 0..1,
990 count: 0
991 })
992 );
993 assert_eq!(
994 diff_keys(&base, &strings(&["x"])),
995 Some(Splice {
996 range: 0..2,
997 count: 1
998 })
999 );
1000 }
1001
1002 #[test]
1003 fn changed_indices_find_edited_rows() {
1004 let old = flat_rows(
1005 &[record("a", None, 8, 6), record("b", None, 9, 6)],
1006 &context(),
1007 false,
1008 );
1009 let mut edited = record("b", None, 9, 6);
1010 edited.body_html = "<p>changed</p>".into();
1011 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
1012 assert_eq!(changed_indices(&old, &new), vec![1]);
1013 }
1014}