BlueGit

ict rusty-teams

Files

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

rows.rs

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