BlueGit

ict rusty-teams

Files

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

rows.rs

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