BlueGit

ict rusty-teams

Files

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

rows.rs

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