BlueGit

ict rusty-teams

Files

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

rows.rs

rows.rs 26.8 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| block.markdown())
304 .collect::<Vec<_>>()
305 .join("\n")
306}
307
308pub fn reply_excerpt(record: &MessageRecord) -> String {
309 let own_spans: Vec<Span> = message_spans(record)
310 .into_iter()
311 .filter(|span| !matches!(span, Span::Quote(_)))
312 .collect();
313 let text = strip_image_placeholders(layout_blocks(&own_spans))
314 .into_iter()
315 .find_map(|block| block.first_line())
316 .unwrap_or_default();
317 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
318 let excerpt = match first_line {
319 Some(line) => line.to_owned(),
320 None if !images(record).is_empty() => "Image".to_owned(),
321 None => files(record)
322 .into_iter()
323 .next()
324 .map_or_else(|| "Message".to_owned(), |card| card.name),
325 };
326 if excerpt.chars().count() > REPLY_EXCERPT_CHARS {
327 let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect();
328 format!("{}...", cut.trim_end())
329 } else {
330 excerpt
331 }
332}
333
334pub struct RowContext {
335 pub offset: FixedOffset,
336 pub today: NaiveDate,
337 pub my_user_id: Option<String>,
338}
339
340pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
341 let local = record.created_at.with_timezone(&context.offset);
342 let images = images(record);
343 let blocks = if record.deleted {
344 vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
345 } else {
346 layout_blocks(&message_spans(record))
347 };
348 let blocks = if images.is_empty() {
349 blocks
350 } else {
351 strip_image_placeholders(blocks)
352 };
353 MessageRow {
354 key: record.message_id.clone(),
355 sender_id: record.sender_id.clone(),
356 created_at: record.created_at,
357 series: Series::default(),
358 card: false,
359 author: record
360 .sender_name
361 .clone()
362 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
363 time: clock_label(record.created_at, context.offset),
364 day_header: Some(format::day_label(local.date_naive(), context.today)),
365 blocks,
366 edited: record.edited_at.is_some() && !record.deleted,
367 deleted: record.deleted,
368 reactions: reaction_chips(&reactions(record), context.my_user_id.as_deref()),
369 images,
370 files: files(record),
371 reply_count: None,
372 new_marker: false,
373 reply_faces: Vec::new(),
374 last_reply_time: None,
375 open_thread: None,
376 is_reply: record.reply_to_id.is_some(),
377 delivery: Delivery::Delivered,
378 receipt: Receipt::Hidden,
379 own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
380 }
381}
382
383pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
384 let mut rows = Vec::with_capacity(records.len() + 1);
385 if has_older {
386 rows.push(Row::LoadOlder);
387 }
388 let mut previous_day: Option<NaiveDate> = None;
389 for record in records {
390 let mut row = message_row(record, context);
391 let day = record
392 .created_at
393 .with_timezone(&context.offset)
394 .date_naive();
395 if previous_day == Some(day) {
396 row.day_header = None;
397 }
398 previous_day = Some(day);
399 rows.push(Row::Message(Box::new(row)));
400 }
401 assign_series(&mut rows);
402 rows
403}
404
405pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> {
406 let mut threads: Vec<Thread> = Vec::new();
407 let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new();
408 for record in records.iter().filter(|record| record.reply_to_id.is_none()) {
409 index_by_root.insert(record.message_id.as_str(), threads.len());
410 threads.push(Thread {
411 root_id: record.message_id.clone(),
412 reply_ids: Vec::new(),
413 });
414 }
415 for record in records {
416 let Some(root_id) = record.reply_to_id.as_deref() else {
417 continue;
418 };
419 if let Some(&index) = index_by_root.get(root_id) {
420 threads[index].reply_ids.push(record.message_id.clone());
421 }
422 }
423 threads
424}
425
426fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> {
427 thread
428 .reply_ids
429 .iter()
430 .chain(std::iter::once(&thread.root_id))
431 .filter_map(|id| by_id.get(id.as_str()))
432 .map(|record| record.created_at)
433 .max()
434 .unwrap_or_default()
435}
436
437pub fn thread_list_rows(
438 records: &[MessageRecord],
439 context: &RowContext,
440 has_older: bool,
441) -> Vec<Row> {
442 let by_id: BTreeMap<&str, &MessageRecord> = records
443 .iter()
444 .map(|record| (record.message_id.as_str(), record))
445 .collect();
446 let mut threads = group_threads(records);
447 threads.sort_by_key(|thread| last_activity(thread, &by_id));
448 let mut rows = Vec::with_capacity(threads.len() + 1);
449 if has_older {
450 rows.push(Row::LoadOlder);
451 }
452 let mut previous_day: Option<NaiveDate> = None;
453 for thread in threads {
454 let Some(root) = by_id.get(thread.root_id.as_str()) else {
455 continue;
456 };
457 let mut row = message_row(root, context);
458 let day = last_activity(&thread, &by_id)
459 .with_timezone(&context.offset)
460 .date_naive();
461 row.day_header = (previous_day != Some(day)).then(|| format::day_label(day, context.today));
462 previous_day = Some(day);
463 row.card = true;
464 row.time = format::post_time_label(root.created_at, context.today, context.offset);
465 row.reply_count = Some(thread.reply_ids.len());
466 let replies: Vec<&&MessageRecord> = thread
467 .reply_ids
468 .iter()
469 .filter_map(|id| by_id.get(id.as_str()))
470 .collect();
471 for reply in &replies {
472 let face = Face {
473 user_id: reply.sender_id.clone(),
474 name: reply
475 .sender_name
476 .clone()
477 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
478 };
479 if row.reply_faces.len() < REPLY_FACE_LIMIT && !row.reply_faces.contains(&face) {
480 row.reply_faces.push(face);
481 }
482 }
483 row.last_reply_time = replies
484 .iter()
485 .map(|reply| reply.created_at)
486 .max()
487 .map(|time| {
488 let local = time.with_timezone(&context.offset);
489 format!(
490 "{} {}",
491 format::day_label(local.date_naive(), context.today),
492 clock_label(time, context.offset)
493 )
494 });
495 row.open_thread = Some(thread.root_id.clone());
496 rows.push(Row::Message(Box::new(row)));
497 }
498 rows
499}
500
501pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
502 let members: Vec<MessageRecord> = records
503 .iter()
504 .filter(|record| {
505 record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id)
506 })
507 .cloned()
508 .collect();
509 flat_rows(&members, context, false)
510}
511
512#[derive(Debug, Clone, PartialEq, Eq)]
513pub struct Splice {
514 pub range: Range<usize>,
515 pub count: usize,
516}
517
518pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> {
519 if old == new {
520 return None;
521 }
522 let prefix = old
523 .iter()
524 .zip(new)
525 .take_while(|(left, right)| left == right)
526 .count();
527 let suffix = old[prefix..]
528 .iter()
529 .rev()
530 .zip(new[prefix..].iter().rev())
531 .take_while(|(left, right)| left == right)
532 .count();
533 Some(Splice {
534 range: prefix..old.len() - suffix,
535 count: new.len() - prefix - suffix,
536 })
537}
538
539pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> {
540 let prefix = old
541 .iter()
542 .zip(new)
543 .take_while(|(left, right)| left.key() == right.key())
544 .count();
545 let suffix = old[prefix..]
546 .iter()
547 .rev()
548 .zip(new[prefix..].iter().rev())
549 .take_while(|(left, right)| left.key() == right.key())
550 .count();
551 let mut changed: Vec<usize> = (0..prefix)
552 .filter(|&index| old[index] != new[index])
553 .collect();
554 changed.extend((0..suffix).filter_map(|offset| {
555 let old_index = old.len() - 1 - offset;
556 let new_index = new.len() - 1 - offset;
557 (old[old_index] != new[new_index]).then_some(new_index)
558 }));
559 changed
560}
561
562#[cfg(test)]
563mod tests {
564 use chrono::TimeZone;
565
566 use super::*;
567
568 fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord {
569 MessageRecord {
570 conversation_id: "c".into(),
571 message_id: id.into(),
572 reply_to_id: reply_to.map(str::to_owned),
573 sender_id: Some("u".into()),
574 sender_name: Some("Author".into()),
575 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
576 edited_at: None,
577 deleted: false,
578 body_html: format!("<p>text {id}</p>"),
579 attachments_json: "[]".into(),
580 reactions_json: "[]".into(),
581 mentions_json: "[]".into(),
582 }
583 }
584
585 #[test]
586 fn reaction_type_maps_classic_glyphs_to_names() {
587 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
588 assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart");
589 assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}");
590 }
591
592 #[test]
593 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
594 let mut text = record("a", None, 8, 6);
595 text.body_html = "<p>first line</p><p>second</p>".into();
596 assert_eq!(reply_excerpt(&text), "first line");
597 let mut quoted = record("q", None, 8, 6);
598 quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into();
599 assert_eq!(reply_excerpt(&quoted), "my answer");
600 let mut image = record("b", None, 8, 6);
601 image.body_html = "<img src=\"u\">".into();
602 assert_eq!(reply_excerpt(&image), "Image");
603 let mut long = record("c", None, 8, 6);
604 long.body_html = format!("<p>{}</p>", "x".repeat(200));
605 assert!(reply_excerpt(&long).ends_with("..."));
606 assert_eq!(
607 reply_excerpt(&long).chars().count(),
608 REPLY_EXCERPT_CHARS + 3
609 );
610 }
611
612 fn context() -> RowContext {
613 RowContext {
614 offset: FixedOffset::east_opt(0).unwrap(),
615 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
616 my_user_id: None,
617 }
618 }
619
620 fn keys(rows: &[Row]) -> Vec<String> {
621 rows.iter().map(|row| row.key().to_owned()).collect()
622 }
623
624 #[test]
625 fn day_header_only_on_first_message_of_a_day() {
626 let records = vec![
627 record("a", None, 8, 6),
628 record("b", None, 9, 6),
629 record("c", None, 9, 7),
630 ];
631 let rows = flat_rows(&records, &context(), false);
632 let headers: Vec<Option<String>> = rows
633 .iter()
634 .map(|row| match row {
635 Row::Message(message) => message.day_header.clone(),
636 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
637 })
638 .collect();
639 assert_eq!(
640 headers,
641 vec![Some("Yesterday".into()), None, Some("Today".into())]
642 );
643 }
644
645 #[test]
646 fn load_older_row_only_when_more_exists() {
647 let records = vec![record("a", None, 8, 6)];
648 assert_eq!(
649 keys(&flat_rows(&records, &context(), true))[0],
650 LOAD_OLDER_KEY
651 );
652 assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]);
653 }
654
655 #[test]
656 fn threads_group_replies_by_root() {
657 let records = vec![
658 record("r1", None, 8, 6),
659 record("r2", None, 9, 6),
660 record("x1", Some("r1"), 10, 6),
661 record("x2", Some("r1"), 11, 6),
662 record("orphan", Some("missing"), 12, 6),
663 ];
664 let threads = group_threads(&records);
665 assert_eq!(threads.len(), 2);
666 assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]);
667 assert!(threads[1].reply_ids.is_empty());
668 }
669
670 #[test]
671 fn thread_list_orders_by_last_activity_with_reply_count() {
672 let records = vec![
673 record("r1", None, 8, 6),
674 record("r2", None, 9, 6),
675 record("x1", Some("r1"), 10, 6),
676 ];
677 let rows = thread_list_rows(&records, &context(), false);
678 assert_eq!(keys(&rows), vec!["r2", "r1"]);
679 let Row::Message(last) = &rows[1] else {
680 panic!("message expected")
681 };
682 assert_eq!(last.reply_count, Some(1));
683 assert_eq!(last.open_thread.as_deref(), Some("r1"));
684 }
685
686 #[test]
687 fn thread_view_has_root_then_replies() {
688 let records = vec![
689 record("r1", None, 8, 6),
690 record("r2", None, 9, 6),
691 record("x1", Some("r1"), 10, 6),
692 ];
693 assert_eq!(
694 keys(&thread_rows(&records, "r1", &context())),
695 vec!["r1", "x1"]
696 );
697 }
698
699 #[test]
700 fn reactions_are_counted_in_first_seen_order() {
701 let reaction = |kind: &str| ReactionInfo {
702 reaction_type: kind.into(),
703 user_id: None,
704 user_name: None,
705 };
706 let chips = reaction_chips(
707 &[reaction("heart"), reaction("like"), reaction("heart")],
708 None,
709 );
710 assert_eq!(chips.len(), 2);
711 assert_eq!(chips[0].count, 2);
712 assert_eq!(chips[1].label, reaction_label("like"));
713 }
714
715 fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord {
716 let mut record = record(id, None, hour, day);
717 record.sender_id = Some(sender.into());
718 record.created_at = Utc
719 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
720 .unwrap();
721 record
722 }
723
724 fn series_of(rows: &[Row]) -> Vec<(bool, bool)> {
725 rows.iter()
726 .filter_map(|row| match row {
727 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
728 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
729 })
730 .collect()
731 }
732
733 #[test]
734 fn series_joins_same_sender_within_five_minutes() {
735 let records = vec![
736 record_by("a", "ada", 9, 0, 7),
737 record_by("b", "ada", 9, 4, 7),
738 record_by("c", "ada", 9, 20, 7),
739 record_by("d", "bob", 9, 21, 7),
740 record_by("e", "ada", 9, 22, 7),
741 ];
742 let rows = flat_rows(&records, &context(), false);
743 assert_eq!(
744 series_of(&rows),
745 vec![
746 (false, true),
747 (true, false),
748 (false, false),
749 (false, false),
750 (false, false)
751 ]
752 );
753 }
754
755 #[test]
756 fn series_window_ends_exactly_at_the_gap_constant() {
757 let gap = SERIES_GAP_MINUTES as u32;
758 let records = vec![
759 record_by("a", "ada", 9, 0, 7),
760 record_by("b", "ada", 9, gap - 1, 7),
761 record_by("c", "ada", 9, 2 * gap - 1 + gap, 7),
762 ];
763 let rows = flat_rows(&records, &context(), false);
764 assert_eq!(
765 series_of(&rows),
766 vec![(false, true), (true, false), (false, false)]
767 );
768 }
769
770 #[test]
771 fn series_breaks_at_a_new_day() {
772 let records = vec![
773 record_by("a", "ada", 23, 58, 6),
774 record_by("b", "ada", 0, 1, 7),
775 ];
776 let rows = flat_rows(&records, &context(), false);
777 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
778 }
779
780 #[test]
781 fn thread_list_rows_never_join() {
782 let records = vec![
783 record_by("a", "ada", 9, 0, 7),
784 record_by("b", "ada", 9, 1, 7),
785 ];
786 let rows = thread_list_rows(&records, &context(), false);
787 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
788 }
789
790 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
791 let corners = bubble_corners(own, Series { has_prev, has_next });
792 [
793 corners.top_left,
794 corners.top_right,
795 corners.bottom_right,
796 corners.bottom_left,
797 ]
798 }
799
800 #[test]
801 fn corners_match_the_mockup_for_other_senders() {
802 assert_eq!(corners(false, false, false), [4., 14., 14., 14.]);
803 assert_eq!(corners(false, false, true), [4., 14., 14., 4.]);
804 assert_eq!(corners(false, true, true), [4., 14., 14., 4.]);
805 assert_eq!(corners(false, true, false), [4., 14., 14., 14.]);
806 }
807
808 #[test]
809 fn corners_match_the_mockup_for_own_messages() {
810 assert_eq!(corners(true, false, false), [14., 4., 4., 14.]);
811 assert_eq!(corners(true, false, true), [14., 14., 4., 14.]);
812 assert_eq!(corners(true, true, true), [14., 4., 4., 14.]);
813 assert_eq!(corners(true, true, false), [14., 4., 14., 14.]);
814 }
815
816 #[test]
817 fn own_reaction_is_marked() {
818 let reaction = |user: &str| ReactionInfo {
819 reaction_type: "like".into(),
820 user_id: Some(user.into()),
821 user_name: None,
822 };
823 let chips = reaction_chips(&[reaction("x"), reaction("me")], Some("me"));
824 assert!(chips[0].mine);
825 assert!(!reaction_chips(&[reaction("x")], Some("me"))[0].mine);
826 }
827
828 fn strings(values: &[&str]) -> Vec<String> {
829 values.iter().map(|value| (*value).to_owned()).collect()
830 }
831
832 #[test]
833 fn diff_detects_append_prepend_and_replace() {
834 let base = strings(&["a", "b"]);
835 assert_eq!(diff_keys(&base, &base), None);
836 assert_eq!(
837 diff_keys(&base, &strings(&["a", "b", "c"])),
838 Some(Splice {
839 range: 2..2,
840 count: 1
841 })
842 );
843 assert_eq!(
844 diff_keys(&base, &strings(&["x", "a", "b"])),
845 Some(Splice {
846 range: 0..0,
847 count: 1
848 })
849 );
850 assert_eq!(
851 diff_keys(
852 &strings(&["load-older", "a"]),
853 &strings(&["load-older", "x", "y", "a"])
854 ),
855 Some(Splice {
856 range: 1..1,
857 count: 2
858 })
859 );
860 assert_eq!(
861 diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])),
862 Some(Splice {
863 range: 0..1,
864 count: 0
865 })
866 );
867 assert_eq!(
868 diff_keys(&base, &strings(&["x"])),
869 Some(Splice {
870 range: 0..2,
871 count: 1
872 })
873 );
874 }
875
876 #[test]
877 fn changed_indices_find_edited_rows() {
878 let old = flat_rows(
879 &[record("a", None, 8, 6), record("b", None, 9, 6)],
880 &context(),
881 false,
882 );
883 let mut edited = record("b", None, 9, 6);
884 edited.body_html = "<p>changed</p>".into();
885 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
886 assert_eq!(changed_indices(&old, &new), vec![1]);
887 }
888}