BlueGit

ict rusty-teams

Files

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

rows.rs

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