BlueGit

ict rusty-teams

Files

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

rows.rs

rows.rs 36.4 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, Copy, PartialEq, Eq)]
100pub enum ScheduledState {
101 Waiting,
102 DeliveryFailed,
103 ChangeFailed,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub enum Delivery {
108 Delivered,
109 Sending,
110 Failed(String),
111 Scheduled(ScheduledState),
112}
113
114/// An image of a message that is still being sent, shown from its local bytes.
115#[derive(Debug, Clone, PartialEq)]
116pub struct LocalImage {
117 pub image: Arc<Image>,
118 pub size: Option<(u32, u32)>,
119}
120
121#[derive(Debug, Clone, PartialEq)]
122pub struct MessageRow {
123 pub key: String,
124 pub conversation_id: String,
125 pub author: String,
126 pub sender_id: Option<String>,
127 pub application_id: Option<String>,
128 pub created_at: DateTime<Utc>,
129 pub series: Series,
130 pub card: bool,
131 pub time: String,
132 pub day_header: Option<String>,
133 pub blocks: Vec<Block>,
134 pub edited: bool,
135 pub deleted: bool,
136 pub reactions: Vec<ReactionChip>,
137 pub images: Vec<ImageRef>,
138 pub local_images: Vec<LocalImage>,
139 pub files: Vec<FileCard>,
140 pub link_preview: Option<LinkPreview>,
141 pub adaptive_cards: Vec<AdaptiveCard>,
142 pub reply_count: Option<usize>,
143 pub new_marker: bool,
144 pub reply_faces: Vec<Face>,
145 pub last_reply_time: Option<String>,
146 pub open_thread: Option<String>,
147 pub is_reply: bool,
148 pub delivery: Delivery,
149 pub own: bool,
150 pub receipt: Receipt,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct StartInfo {
155 pub title: String,
156 pub user_id: Option<String>,
157}
158
159pub const START_KEY: &str = "conversation-start";
160
161#[derive(Debug, Clone, PartialEq)]
162pub enum Row {
163 LoadOlder,
164 Start(StartInfo),
165 Skeleton(Skeleton),
166 Message(Box<MessageRow>),
167}
168
169#[derive(Debug, Clone, Copy, PartialEq)]
170pub struct Skeleton {
171 pub key: &'static str,
172 pub own: bool,
173 pub width_ratio: f32,
174 pub lines: u8,
175}
176
177const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [
178 Skeleton {
179 key: "skeleton-0",
180 own: false,
181 width_ratio: 0.42,
182 lines: 1,
183 },
184 Skeleton {
185 key: "skeleton-1",
186 own: true,
187 width_ratio: 0.3,
188 lines: 1,
189 },
190 Skeleton {
191 key: "skeleton-2",
192 own: true,
193 width_ratio: 0.48,
194 lines: 2,
195 },
196 Skeleton {
197 key: "skeleton-3",
198 own: false,
199 width_ratio: 0.26,
200 lines: 1,
201 },
202];
203
204pub fn placeholder_rows() -> Vec<Row> {
205 SKELETON_PLACEHOLDERS
206 .into_iter()
207 .map(Row::Skeleton)
208 .collect()
209}
210
211fn sender_key(row: &MessageRow) -> &str {
212 row.sender_id.as_deref().unwrap_or(&row.author)
213}
214
215fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
216 !previous.card
217 && !next.card
218 && next.day_header.is_none()
219 && !next.new_marker
220 && sender_key(previous) == sender_key(next)
221 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
222 && next.created_at >= previous.created_at
223}
224
225pub fn assign_series(rows: &mut [Row]) {
226 let mut previous: Option<usize> = None;
227 for index in 0..rows.len() {
228 let Row::Message(_) = &rows[index] else {
229 previous = None;
230 continue;
231 };
232 if let Some(before) = previous {
233 let joined = match (&rows[before], &rows[index]) {
234 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
235 _ => false,
236 };
237 if joined {
238 if let Row::Message(a) = &mut rows[before] {
239 a.series.has_next = true;
240 }
241 if let Row::Message(b) = &mut rows[index] {
242 b.series.has_prev = true;
243 }
244 }
245 }
246 previous = Some(index);
247 }
248}
249
250impl Row {
251 pub fn key(&self) -> &str {
252 match self {
253 Row::LoadOlder => LOAD_OLDER_KEY,
254 Row::Start(_) => START_KEY,
255 Row::Skeleton(skeleton) => skeleton.key,
256 Row::Message(message) => &message.key,
257 }
258 }
259}
260
261#[derive(Debug, Clone, PartialEq, Eq)]
262pub struct Thread {
263 pub root_id: String,
264 pub reply_ids: Vec<String>,
265}
266
267pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String {
268 time.with_timezone(&offset).format("%H:%M").to_string()
269}
270
271pub fn reaction_label(reaction_type: &str) -> String {
272 match reaction_type {
273 "like" => "\u{1F44D}".to_owned(),
274 "heart" => "\u{2764}".to_owned(),
275 "laugh" => "\u{1F606}".to_owned(),
276 "surprised" => "\u{1F62E}".to_owned(),
277 "sad" => "\u{1F641}".to_owned(),
278 "angry" => "\u{1F620}".to_owned(),
279 other => other.to_owned(),
280 }
281}
282
283pub fn reaction_glyph(reaction_type: &str) -> String {
284 reaction_label(reaction_type)
285 .trim_end_matches('\u{FE0F}')
286 .to_owned()
287}
288
289/// Graph rejects the legacy names ("Unicode 'like' in the payload is not supported").
290pub fn api_reaction(glyph: &str) -> String {
291 match glyph {
292 "\u{2764}" => "\u{2764}\u{FE0F}".to_owned(),
293 other => other.to_owned(),
294 }
295}
296
297/// The reaction type Teams uses for a glyph: the legacy name for the six classic ones.
298pub fn reaction_type_for(glyph: &str) -> String {
299 let bare = glyph.trim_end_matches('\u{FE0F}');
300 ["like", "heart", "laugh", "surprised", "sad", "angry"]
301 .into_iter()
302 .find(|name| reaction_label(name) == bare)
303 .map_or_else(|| bare.to_owned(), str::to_owned)
304}
305
306pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;
307
308fn is_own_reaction(reaction: &ReactionInfo, wanted: &str, my_user_id: Option<&str>) -> bool {
309 my_user_id.is_some()
310 && reaction.user_id.as_deref() == my_user_id
311 && reaction_glyph(&reaction.reaction_type) == wanted
312}
313
314pub fn has_own_reaction(reactions: &[ReactionInfo], glyph: &str, my_user_id: Option<&str>) -> bool {
315 let wanted = reaction_glyph(glyph);
316 reactions
317 .iter()
318 .any(|reaction| is_own_reaction(reaction, &wanted, my_user_id))
319}
320
321pub fn set_own_reaction(
322 reactions: &mut Vec<ReactionInfo>,
323 glyph: &str,
324 my_user_id: Option<&str>,
325 present: bool,
326 now: DateTime<Utc>,
327) {
328 let wanted = reaction_glyph(glyph);
329 if !present {
330 reactions.retain(|reaction| !is_own_reaction(reaction, &wanted, my_user_id));
331 } else if !has_own_reaction(reactions, glyph, my_user_id) {
332 reactions.push(ReactionInfo {
333 reaction_type: reaction_type_for(glyph),
334 user_id: my_user_id.map(str::to_owned),
335 user_name: Some("You".to_owned()),
336 created_at: Some(now),
337 });
338 }
339}
340
341pub fn apply_pending_reactions(
342 reactions: &mut Vec<ReactionInfo>,
343 pending: Option<&Vec<(String, bool)>>,
344 my_user_id: Option<&str>,
345 now: DateTime<Utc>,
346) {
347 for (glyph, present) in pending.into_iter().flatten() {
348 set_own_reaction(reactions, glyph, my_user_id, *present, now);
349 }
350}
351
352pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
353 let my_user_id = context.my_user_id.as_deref();
354 let mut chips: Vec<ReactionChip> = Vec::new();
355 for reaction in reactions {
356 let glyph = reaction_glyph(&reaction.reaction_type);
357 let position = match chips.iter().position(|chip| chip.glyph() == glyph) {
358 Some(position) => position,
359 None => {
360 chips.push(ReactionChip {
361 reaction_type: reaction.reaction_type.clone(),
362 label: reaction_label(&reaction.reaction_type),
363 count: 0,
364 mine: false,
365 reactors: Vec::new(),
366 });
367 chips.len() - 1
368 }
369 };
370 let chip = &mut chips[position];
371 chip.count += 1;
372 chip.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id;
373 chip.reactors.push(Reactor {
374 user_id: reaction.user_id.clone(),
375 name: reactor_name(reaction, context),
376 created_at: reaction.created_at,
377 });
378 }
379 chips
380}
381
382fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String {
383 reaction
384 .user_name
385 .clone()
386 .or_else(|| {
387 reaction
388 .user_id
389 .as_ref()
390 .and_then(|user_id| context.names.get(user_id).cloned())
391 })
392 .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned())
393}
394
395const REPLY_EXCERPT_CHARS: usize = 90;
396
397pub fn message_text(record: &MessageRecord) -> String {
398 let own_spans: Vec<Span> = message_spans(record)
399 .into_iter()
400 .filter(|span| !matches!(span, Span::Quote(_)))
401 .collect();
402 strip_image_placeholders(layout_blocks(&own_spans))
403 .into_iter()
404 .filter_map(|block| block.markdown())
405 .collect::<Vec<_>>()
406 .join("\n")
407}
408
409/// The message as the composer edits it, formatting kept.
410pub fn message_draft(record: &MessageRecord) -> Draft {
411 let own_spans: Vec<Span> = message_spans(record)
412 .into_iter()
413 .filter(|span| !matches!(span, Span::Quote(_)))
414 .collect();
415 Draft::from_spans(&own_spans).trimmed()
416}
417
418pub fn reply_excerpt(record: &MessageRecord) -> String {
419 let own_spans: Vec<Span> = message_spans(record)
420 .into_iter()
421 .filter(|span| !matches!(span, Span::Quote(_)))
422 .collect();
423 let text = strip_image_placeholders(layout_blocks(&own_spans))
424 .into_iter()
425 .find_map(|block| block.first_line())
426 .unwrap_or_default();
427 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
428 let excerpt = match first_line {
429 Some(line) => line.to_owned(),
430 None if !images(record).is_empty() => "Image".to_owned(),
431 None if let Some(line) = card_texts(record)
432 .iter()
433 .flat_map(|text| text.lines())
434 .next() =>
435 {
436 line.to_owned()
437 }
438 None => files(record)
439 .into_iter()
440 .next()
441 .map_or_else(|| "Message".to_owned(), |card| card.name),
442 };
443 if excerpt.chars().count() > REPLY_EXCERPT_CHARS {
444 let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect();
445 format!("{}...", cut.trim_end())
446 } else {
447 excerpt
448 }
449}
450
451pub struct RowContext {
452 pub offset: FixedOffset,
453 pub today: NaiveDate,
454 pub my_user_id: Option<String>,
455 pub names: HashMap<String, String>,
456 pub pending_reactions: PendingReactions,
457 pub card_overrides: HashMap<String, CardOverride>,
458}
459
460fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
461 let mut visible = reactions(record);
462 apply_pending_reactions(
463 &mut visible,
464 context.pending_reactions.get(&record.message_id),
465 context.my_user_id.as_deref(),
466 Utc::now(),
467 );
468 visible
469}
470
471pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
472 let local = record.created_at.with_timezone(&context.offset);
473 let images = images(record);
474 let blocks = if record.deleted {
475 vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
476 } else {
477 layout_blocks(&message_spans(record))
478 };
479 let blocks = if images.is_empty() {
480 blocks
481 } else {
482 strip_image_placeholders(blocks)
483 };
484 MessageRow {
485 key: record.message_id.clone(),
486 conversation_id: record.conversation_id.clone(),
487 sender_id: record.sender_id.clone(),
488 application_id: record.sender_application_id.clone(),
489 created_at: record.created_at,
490 series: Series::default(),
491 card: false,
492 author: record
493 .sender_name
494 .clone()
495 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
496 time: clock_label(record.created_at, context.offset),
497 day_header: Some(format::day_label(local.date_naive(), context.today)),
498 blocks,
499 edited: record.edited_at.is_some() && !record.deleted,
500 deleted: record.deleted,
501 reactions: reaction_chips(&visible_reactions(record, context), context),
502 images,
503 local_images: Vec::new(),
504 files: files(record),
505 link_preview: link_preview(record),
506 adaptive_cards: match context.card_overrides.get(&record.message_id) {
507 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
508 _ => adaptive_cards(record),
509 },
510 reply_count: None,
511 new_marker: false,
512 reply_faces: Vec::new(),
513 last_reply_time: None,
514 open_thread: None,
515 is_reply: record.reply_to_id.is_some(),
516 delivery: Delivery::Delivered,
517 receipt: Receipt::Hidden,
518 own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
519 }
520}
521
522pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
523 let mut rows = Vec::with_capacity(records.len() + 1);
524 if has_older {
525 rows.push(Row::LoadOlder);
526 }
527 let mut previous_day: Option<NaiveDate> = None;
528 for record in records {
529 let mut row = message_row(record, context);
530 let day = record
531 .created_at
532 .with_timezone(&context.offset)
533 .date_naive();
534 if previous_day == Some(day) {
535 row.day_header = None;
536 }
537 previous_day = Some(day);
538 rows.push(Row::Message(Box::new(row)));
539 }
540 assign_series(&mut rows);
541 rows
542}
543
544pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> {
545 let mut threads: Vec<Thread> = Vec::new();
546 let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new();
547 for record in records.iter().filter(|record| record.reply_to_id.is_none()) {
548 index_by_root.insert(record.message_id.as_str(), threads.len());
549 threads.push(Thread {
550 root_id: record.message_id.clone(),
551 reply_ids: Vec::new(),
552 });
553 }
554 for record in records {
555 let Some(root_id) = record.reply_to_id.as_deref() else {
556 continue;
557 };
558 if let Some(&index) = index_by_root.get(root_id) {
559 threads[index].reply_ids.push(record.message_id.clone());
560 }
561 }
562 threads
563}
564
565fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> {
566 thread
567 .reply_ids
568 .iter()
569 .chain(std::iter::once(&thread.root_id))
570 .filter_map(|id| by_id.get(id.as_str()))
571 .map(|record| record.created_at)
572 .max()
573 .unwrap_or_default()
574}
575
576pub fn thread_list_rows(
577 records: &[MessageRecord],
578 context: &RowContext,
579 has_older: bool,
580) -> Vec<Row> {
581 let by_id: BTreeMap<&str, &MessageRecord> = records
582 .iter()
583 .map(|record| (record.message_id.as_str(), record))
584 .collect();
585 let mut threads = group_threads(records);
586 threads.sort_by_key(|thread| last_activity(thread, &by_id));
587 let mut rows = Vec::with_capacity(threads.len() + 1);
588 if has_older {
589 rows.push(Row::LoadOlder);
590 }
591 let mut previous_day: Option<NaiveDate> = None;
592 for thread in threads {
593 let Some(root) = by_id.get(thread.root_id.as_str()) else {
594 continue;
595 };
596 let mut row = message_row(root, context);
597 let day = last_activity(&thread, &by_id)
598 .with_timezone(&context.offset)
599 .date_naive();
600 row.day_header = (previous_day != Some(day)).then(|| format::day_label(day, context.today));
601 previous_day = Some(day);
602 row.card = true;
603 row.time = format::post_time_label(root.created_at, context.today, context.offset);
604 row.reply_count = Some(thread.reply_ids.len());
605 let replies: Vec<&&MessageRecord> = thread
606 .reply_ids
607 .iter()
608 .filter_map(|id| by_id.get(id.as_str()))
609 .collect();
610 for reply in &replies {
611 let face = Face {
612 user_id: reply.sender_id.clone(),
613 name: reply
614 .sender_name
615 .clone()
616 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
617 };
618 if row.reply_faces.len() < REPLY_FACE_LIMIT && !row.reply_faces.contains(&face) {
619 row.reply_faces.push(face);
620 }
621 }
622 row.last_reply_time = replies
623 .iter()
624 .map(|reply| reply.created_at)
625 .max()
626 .map(|time| {
627 let local = time.with_timezone(&context.offset);
628 format!(
629 "{} {}",
630 format::day_label(local.date_naive(), context.today),
631 clock_label(time, context.offset)
632 )
633 });
634 row.open_thread = Some(thread.root_id.clone());
635 rows.push(Row::Message(Box::new(row)));
636 }
637 rows
638}
639
640pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
641 let members: Vec<MessageRecord> = records
642 .iter()
643 .filter(|record| {
644 record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id)
645 })
646 .cloned()
647 .collect();
648 flat_rows(&members, context, false)
649}
650
651#[derive(Debug, Clone, PartialEq, Eq)]
652pub struct Splice {
653 pub range: Range<usize>,
654 pub count: usize,
655}
656
657pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> {
658 if old == new {
659 return None;
660 }
661 let prefix = old
662 .iter()
663 .zip(new)
664 .take_while(|(left, right)| left == right)
665 .count();
666 let suffix = old[prefix..]
667 .iter()
668 .rev()
669 .zip(new[prefix..].iter().rev())
670 .take_while(|(left, right)| left == right)
671 .count();
672 Some(Splice {
673 range: prefix..old.len() - suffix,
674 count: new.len() - prefix - suffix,
675 })
676}
677
678pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> {
679 let prefix = old
680 .iter()
681 .zip(new)
682 .take_while(|(left, right)| left.key() == right.key())
683 .count();
684 let suffix = old[prefix..]
685 .iter()
686 .rev()
687 .zip(new[prefix..].iter().rev())
688 .take_while(|(left, right)| left.key() == right.key())
689 .count();
690 let mut changed: Vec<usize> = (0..prefix)
691 .filter(|&index| old[index] != new[index])
692 .collect();
693 changed.extend((0..suffix).filter_map(|offset| {
694 let old_index = old.len() - 1 - offset;
695 let new_index = new.len() - 1 - offset;
696 (old[old_index] != new[new_index]).then_some(new_index)
697 }));
698 changed
699}
700
701#[cfg(test)]
702mod tests {
703 use chrono::TimeZone;
704
705 use super::*;
706
707 fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord {
708 MessageRecord {
709 conversation_id: "c".into(),
710 message_id: id.into(),
711 reply_to_id: reply_to.map(str::to_owned),
712 sender_id: Some("u".into()),
713 sender_name: Some("Author".into()),
714 sender_application_id: None,
715 links_json: "[]".to_owned(),
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}