BlueGit

ict rusty-teams

Files

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

rows.rs

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