BlueGit

ict rusty-teams

Files

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

rows.rs

cdded127 History
rows.rs 46.9 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, linked_message_spans, message_spans, reactions,
11 translated_spans,
12};
13
14use crate::card_state::CardOverride;
15use crate::format;
16use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
17use crate::render::blocks::{Inline, strip_image_placeholders};
18use crate::render::{Block, layout_blocks};
19use crate::translation::{TranslationContext, TranslationLine};
20
21const POST_VISIBLE_REPLIES: usize = 3;
22
23pub const LOAD_OLDER_KEY: &str = "load-older";
24const UNKNOWN_AUTHOR: &str = "Unknown";
25const DELETED_TEXT: &str = "Message deleted";
26const SERIES_GAP_MINUTES: i64 = 5;
27const CORNER_RADIUS: f32 = 14.;
28const CORNER_SERIES: f32 = 4.;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct ReactionChip {
32 pub reaction_type: String,
33 pub label: String,
34 pub count: usize,
35 pub mine: bool,
36 pub reactors: Vec<Reactor>,
37}
38
39impl ReactionChip {
40 pub fn glyph(&self) -> String {
41 reaction_glyph(&self.reaction_type)
42 }
43}
44
45#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
46pub struct Series {
47 pub has_prev: bool,
48 pub has_next: bool,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct Corners {
53 pub top_left: f32,
54 pub top_right: f32,
55 pub bottom_right: f32,
56 pub bottom_left: f32,
57}
58
59pub fn bubble_corners(own: bool, series: Series) -> Corners {
60 if own {
61 let top_right = if series.has_prev || !series.has_next {
62 CORNER_SERIES
63 } else {
64 CORNER_RADIUS
65 };
66 let bottom_right = if series.has_next || !series.has_prev {
67 CORNER_SERIES
68 } else {
69 CORNER_RADIUS
70 };
71 Corners {
72 top_left: CORNER_RADIUS,
73 top_right,
74 bottom_right,
75 bottom_left: CORNER_RADIUS,
76 }
77 } else {
78 Corners {
79 top_left: CORNER_SERIES,
80 top_right: CORNER_RADIUS,
81 bottom_right: CORNER_RADIUS,
82 bottom_left: if series.has_next {
83 CORNER_SERIES
84 } else {
85 CORNER_RADIUS
86 },
87 }
88 }
89}
90
91#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
92pub enum Receipt {
93 #[default]
94 Hidden,
95 Pending,
96 Sent,
97 Read,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum ScheduledState {
102 Waiting,
103 DeliveryFailed,
104 ChangeFailed,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum Delivery {
109 Delivered,
110 Sending,
111 Failed(String),
112 Scheduled(ScheduledState),
113}
114
115/// An image of a message that is still being sent, shown from its local bytes.
116#[derive(Debug, Clone, PartialEq)]
117pub struct LocalImage {
118 pub image: Arc<Image>,
119 pub size: Option<(u32, u32)>,
120}
121
122#[derive(Debug, Clone, PartialEq)]
123pub struct MessageRow {
124 pub key: String,
125 pub conversation_id: String,
126 pub author: String,
127 pub sender_id: Option<String>,
128 pub application_id: Option<String>,
129 pub created_at: DateTime<Utc>,
130 pub series: Series,
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 subject: Option<String>,
143 pub new_marker: bool,
144 pub reply_root: Option<String>,
145 pub delivery: Delivery,
146 pub own: bool,
147 pub receipt: Receipt,
148 pub forwarded: bool,
149 pub translation: Option<TranslationLine>,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct StartInfo {
154 pub title: String,
155 pub user_id: Option<String>,
156}
157
158pub const START_KEY: &str = "conversation-start";
159
160#[derive(Debug, Clone, PartialEq)]
161pub enum Row {
162 LoadOlder,
163 Start(StartInfo),
164 Skeleton(Skeleton),
165 Message(Box<MessageRow>),
166 Post(Box<PostRow>),
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 next.day_header.is_none()
217 && !next.new_marker
218 && sender_key(previous) == sender_key(next)
219 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
220 && next.created_at >= previous.created_at
221}
222
223pub fn assign_series(rows: &mut [Row]) {
224 let mut previous: Option<usize> = None;
225 for index in 0..rows.len() {
226 let Row::Message(_) = &rows[index] else {
227 previous = None;
228 continue;
229 };
230 if let Some(before) = previous {
231 let joined = match (&rows[before], &rows[index]) {
232 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
233 _ => false,
234 };
235 if joined {
236 if let Row::Message(a) = &mut rows[before] {
237 a.series.has_next = true;
238 }
239 if let Row::Message(b) = &mut rows[index] {
240 b.series.has_prev = true;
241 }
242 }
243 }
244 previous = Some(index);
245 }
246}
247
248impl Row {
249 pub fn key(&self) -> &str {
250 match self {
251 Row::LoadOlder => LOAD_OLDER_KEY,
252 Row::Start(_) => START_KEY,
253 Row::Skeleton(skeleton) => skeleton.key,
254 Row::Message(message) => &message.key,
255 Row::Post(post) => &post.root.key,
256 }
257 }
258
259 pub fn messages(&self) -> Box<dyn Iterator<Item = &MessageRow> + '_> {
260 match self {
261 Row::Message(message) => Box::new(std::iter::once(message.as_ref())),
262 Row::Post(post) => Box::new(post.messages()),
263 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => Box::new(std::iter::empty()),
264 }
265 }
266}
267
268#[derive(Debug, Clone, PartialEq)]
269pub struct PostRow {
270 pub root: MessageRow,
271 pub replies: Vec<MessageRow>,
272 pub hidden_reply_count: usize,
273 pub hidden_repliers: Vec<String>,
274}
275
276impl PostRow {
277 pub fn local(root: MessageRow) -> Self {
278 PostRow {
279 root,
280 replies: Vec::new(),
281 hidden_reply_count: 0,
282 hidden_repliers: Vec::new(),
283 }
284 }
285
286 pub fn messages(&self) -> impl Iterator<Item = &MessageRow> {
287 std::iter::once(&self.root).chain(&self.replies)
288 }
289
290 pub fn hidden_replies_label(&self) -> Option<String> {
291 (self.hidden_reply_count > 0)
292 .then(|| replies_label(self.hidden_reply_count, &self.hidden_repliers))
293 }
294}
295
296fn first_name(name: &str) -> &str {
297 name.split_whitespace().next().unwrap_or(name)
298}
299
300pub fn replies_label(count: usize, repliers: &[String]) -> String {
301 let noun = if count == 1 { "reply" } else { "replies" };
302 let mut names: Vec<&str> = Vec::new();
303 for name in repliers.iter().map(|name| first_name(name)) {
304 if !names.contains(&name) {
305 names.push(name);
306 }
307 }
308 let people = match names.as_slice() {
309 [] => return format!("{count} {noun}"),
310 [only] => (*only).to_owned(),
311 [first, second] => format!("{first} and {second}"),
312 [first, second, third] => format!("{first}, {second} and {third}"),
313 [first, second, rest @ ..] => format!("{first}, {second} and {} others", rest.len()),
314 };
315 format!("{count} {noun} from {people}")
316}
317
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct Thread {
320 pub root_id: String,
321 pub reply_ids: Vec<String>,
322}
323
324pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String {
325 time.with_timezone(&offset).format("%H:%M").to_string()
326}
327
328pub fn reaction_label(reaction_type: &str) -> String {
329 match reaction_type {
330 "like" => "\u{1F44D}".to_owned(),
331 "heart" => "\u{2764}".to_owned(),
332 "laugh" => "\u{1F606}".to_owned(),
333 "surprised" => "\u{1F62E}".to_owned(),
334 "sad" => "\u{1F641}".to_owned(),
335 "angry" => "\u{1F620}".to_owned(),
336 other => other.to_owned(),
337 }
338}
339
340pub fn reaction_glyph(reaction_type: &str) -> String {
341 reaction_label(reaction_type)
342 .trim_end_matches('\u{FE0F}')
343 .to_owned()
344}
345
346/// Graph rejects the legacy names ("Unicode 'like' in the payload is not supported").
347pub fn api_reaction(glyph: &str) -> String {
348 match glyph {
349 "\u{2764}" => "\u{2764}\u{FE0F}".to_owned(),
350 other => other.to_owned(),
351 }
352}
353
354/// The reaction type Teams uses for a glyph: the legacy name for the six classic ones.
355pub fn reaction_type_for(glyph: &str) -> String {
356 let bare = glyph.trim_end_matches('\u{FE0F}');
357 ["like", "heart", "laugh", "surprised", "sad", "angry"]
358 .into_iter()
359 .find(|name| reaction_label(name) == bare)
360 .map_or_else(|| bare.to_owned(), str::to_owned)
361}
362
363pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;
364
365fn is_own_reaction(reaction: &ReactionInfo, wanted: &str, my_user_id: Option<&str>) -> bool {
366 my_user_id.is_some()
367 && reaction.user_id.as_deref() == my_user_id
368 && reaction_glyph(&reaction.reaction_type) == wanted
369}
370
371pub fn has_own_reaction(reactions: &[ReactionInfo], glyph: &str, my_user_id: Option<&str>) -> bool {
372 let wanted = reaction_glyph(glyph);
373 reactions
374 .iter()
375 .any(|reaction| is_own_reaction(reaction, &wanted, my_user_id))
376}
377
378pub fn set_own_reaction(
379 reactions: &mut Vec<ReactionInfo>,
380 glyph: &str,
381 my_user_id: Option<&str>,
382 present: bool,
383 now: DateTime<Utc>,
384) {
385 let wanted = reaction_glyph(glyph);
386 if !present {
387 reactions.retain(|reaction| !is_own_reaction(reaction, &wanted, my_user_id));
388 } else if !has_own_reaction(reactions, glyph, my_user_id) {
389 reactions.push(ReactionInfo {
390 reaction_type: reaction_type_for(glyph),
391 user_id: my_user_id.map(str::to_owned),
392 user_name: Some("You".to_owned()),
393 created_at: Some(now),
394 });
395 }
396}
397
398pub fn apply_pending_reactions(
399 reactions: &mut Vec<ReactionInfo>,
400 pending: Option<&Vec<(String, bool)>>,
401 my_user_id: Option<&str>,
402 now: DateTime<Utc>,
403) {
404 for (glyph, present) in pending.into_iter().flatten() {
405 set_own_reaction(reactions, glyph, my_user_id, *present, now);
406 }
407}
408
409pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
410 let my_user_id = context.my_user_id.as_deref();
411 let mut chips: Vec<ReactionChip> = Vec::new();
412 for reaction in reactions {
413 let glyph = reaction_glyph(&reaction.reaction_type);
414 let position = match chips.iter().position(|chip| chip.glyph() == glyph) {
415 Some(position) => position,
416 None => {
417 chips.push(ReactionChip {
418 reaction_type: reaction.reaction_type.clone(),
419 label: reaction_label(&reaction.reaction_type),
420 count: 0,
421 mine: false,
422 reactors: Vec::new(),
423 });
424 chips.len() - 1
425 }
426 };
427 let chip = &mut chips[position];
428 chip.count += 1;
429 chip.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id;
430 chip.reactors.push(Reactor {
431 user_id: reaction.user_id.clone(),
432 name: reactor_name(reaction, context),
433 created_at: reaction.created_at,
434 });
435 }
436 chips
437}
438
439fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String {
440 reaction
441 .user_name
442 .clone()
443 .or_else(|| {
444 reaction
445 .user_id
446 .as_ref()
447 .and_then(|user_id| context.names.get(user_id).cloned())
448 })
449 .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned())
450}
451
452const REPLY_EXCERPT_CHARS: usize = 90;
453const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";
454
455pub fn message_text(record: &MessageRecord) -> String {
456 let own_spans: Vec<Span> = message_spans(record)
457 .into_iter()
458 .filter(|span| !matches!(span, Span::Quote(_)))
459 .collect();
460 strip_image_placeholders(layout_blocks(&own_spans))
461 .into_iter()
462 .filter_map(|block| block.markdown())
463 .collect::<Vec<_>>()
464 .join("\n")
465}
466
467/// The message as the composer edits it, formatting kept.
468pub fn message_draft(record: &MessageRecord) -> Draft {
469 let own_spans: Vec<Span> = message_spans(record)
470 .into_iter()
471 .filter(|span| !matches!(span, Span::Quote(_)))
472 .collect();
473 Draft::from_spans(&own_spans).trimmed()
474}
475
476pub fn reply_excerpt(record: &MessageRecord) -> String {
477 let own_spans: Vec<Span> = message_spans(record)
478 .into_iter()
479 .filter(|span| !matches!(span, Span::Quote(_)))
480 .collect();
481 let text = strip_image_placeholders(layout_blocks(&own_spans))
482 .into_iter()
483 .find_map(|block| block.first_line())
484 .unwrap_or_default();
485 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
486 let excerpt = match first_line {
487 Some(line) => line.to_owned(),
488 None if !images(record).is_empty() => "Image".to_owned(),
489 None if let Some(line) = card_texts(record)
490 .iter()
491 .flat_map(|text| text.lines())
492 .next() =>
493 {
494 line.to_owned()
495 }
496 None => files(record)
497 .into_iter()
498 .next()
499 .map_or_else(|| "Message".to_owned(), |card| card.name),
500 };
501 if excerpt.chars().count() > REPLY_EXCERPT_CHARS {
502 let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect();
503 format!("{}...", cut.trim_end())
504 } else {
505 excerpt
506 }
507}
508
509pub struct RowContext {
510 pub offset: FixedOffset,
511 pub today: NaiveDate,
512 pub my_user_id: Option<String>,
513 pub names: HashMap<String, String>,
514 pub pending_reactions: PendingReactions,
515 pub card_overrides: HashMap<String, CardOverride>,
516 pub translation: TranslationContext,
517}
518
519fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
520 let mut visible = reactions(record);
521 apply_pending_reactions(
522 &mut visible,
523 context.pending_reactions.get(&record.message_id),
524 context.my_user_id.as_deref(),
525 Utc::now(),
526 );
527 visible
528}
529
530pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
531 let local = record.created_at.with_timezone(&context.offset);
532 let images = images(record);
533 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
534 let translation = context.translation.resolve(record, own);
535 let blocks = if record.deleted {
536 vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
537 } else if let Some(html) = &translation.translated_html {
538 layout_blocks(&translated_spans(record, html))
539 } else {
540 layout_blocks(&linked_message_spans(record))
541 };
542 let blocks = if images.is_empty() {
543 blocks
544 } else {
545 strip_image_placeholders(blocks)
546 };
547 MessageRow {
548 key: record.message_id.clone(),
549 conversation_id: record.conversation_id.clone(),
550 sender_id: record.sender_id.clone(),
551 application_id: record.sender_application_id.clone(),
552 created_at: record.created_at,
553 series: Series::default(),
554 author: record
555 .sender_name
556 .clone()
557 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
558 time: clock_label(record.created_at, context.offset),
559 day_header: Some(format::day_label(local.date_naive(), context.today)),
560 blocks,
561 edited: record.edited_at.is_some() && !record.deleted,
562 deleted: record.deleted,
563 reactions: reaction_chips(&visible_reactions(record, context), context),
564 images,
565 local_images: Vec::new(),
566 files: files(record),
567 link_preview: link_preview(record),
568 adaptive_cards: match context.card_overrides.get(&record.message_id) {
569 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
570 _ => adaptive_cards(record),
571 },
572 subject: record.subject.clone(),
573 new_marker: false,
574 reply_root: record.reply_to_id.clone(),
575 delivery: Delivery::Delivered,
576 receipt: Receipt::Hidden,
577 own,
578 forwarded: !record.deleted && is_forwarded(&record.body_html),
579 translation: translation.line,
580 }
581}
582
583pub fn is_forwarded(body_html: &str) -> bool {
584 body_html.contains(FORWARD_ITEMTYPE)
585}
586
587pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
588 let mut rows = Vec::with_capacity(records.len() + 1);
589 if has_older {
590 rows.push(Row::LoadOlder);
591 }
592 let mut previous_day: Option<NaiveDate> = None;
593 for record in records {
594 let mut row = message_row(record, context);
595 let day = record
596 .created_at
597 .with_timezone(&context.offset)
598 .date_naive();
599 if previous_day == Some(day) {
600 row.day_header = None;
601 }
602 previous_day = Some(day);
603 rows.push(Row::Message(Box::new(row)));
604 }
605 assign_series(&mut rows);
606 rows
607}
608
609pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> {
610 let mut threads: Vec<Thread> = Vec::new();
611 let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new();
612 for record in records.iter().filter(|record| record.reply_to_id.is_none()) {
613 index_by_root.insert(record.message_id.as_str(), threads.len());
614 threads.push(Thread {
615 root_id: record.message_id.clone(),
616 reply_ids: Vec::new(),
617 });
618 }
619 for record in records {
620 let Some(root_id) = record.reply_to_id.as_deref() else {
621 continue;
622 };
623 if let Some(&index) = index_by_root.get(root_id) {
624 threads[index].reply_ids.push(record.message_id.clone());
625 }
626 }
627 threads
628}
629
630fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> {
631 thread
632 .reply_ids
633 .iter()
634 .chain(std::iter::once(&thread.root_id))
635 .filter_map(|id| by_id.get(id.as_str()))
636 .map(|record| record.created_at)
637 .max()
638 .unwrap_or_default()
639}
640
641fn post_message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
642 let mut row = message_row(record, context);
643 row.day_header = None;
644 row.time = format::post_time_label(record.created_at, context.today, context.offset);
645 row
646}
647
648fn distinct_names<'a>(records: impl Iterator<Item = &'a MessageRecord>) -> Vec<String> {
649 let mut names: Vec<String> = Vec::new();
650 for record in records {
651 let name = record
652 .sender_name
653 .clone()
654 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
655 if !names.contains(&name) {
656 names.push(name);
657 }
658 }
659 names
660}
661
662fn post_row(
663 root: &MessageRecord,
664 mut replies: Vec<&MessageRecord>,
665 context: &RowContext,
666) -> PostRow {
667 replies.sort_by_key(|reply| reply.created_at);
668 let hidden = replies.len().saturating_sub(POST_VISIBLE_REPLIES);
669 PostRow {
670 root: post_message_row(root, context),
671 hidden_reply_count: hidden,
672 hidden_repliers: distinct_names(replies[..hidden].iter().copied()),
673 replies: replies[hidden..]
674 .iter()
675 .map(|reply| post_message_row(reply, context))
676 .collect(),
677 }
678}
679
680pub fn thread_list_rows(
681 records: &[MessageRecord],
682 context: &RowContext,
683 has_older: bool,
684) -> Vec<Row> {
685 let by_id: BTreeMap<&str, &MessageRecord> = records
686 .iter()
687 .map(|record| (record.message_id.as_str(), record))
688 .collect();
689 let mut threads = group_threads(records);
690 threads.sort_by_key(|thread| std::cmp::Reverse(last_activity(thread, &by_id)));
691 let mut rows: Vec<Row> = threads
692 .iter()
693 .filter_map(|thread| {
694 let root = by_id.get(thread.root_id.as_str())?;
695 let replies = thread
696 .reply_ids
697 .iter()
698 .filter_map(|id| by_id.get(id.as_str()).copied())
699 .collect();
700 Some(Row::Post(Box::new(post_row(root, replies, context))))
701 })
702 .collect();
703 if has_older {
704 rows.push(Row::LoadOlder);
705 }
706 rows
707}
708
709pub fn place_local_rows(rows: &mut Vec<Row>, local: Vec<MessageRow>) {
710 for message in local {
711 let Some(root_id) = message.reply_root.clone() else {
712 rows.insert(0, Row::Post(Box::new(PostRow::local(message))));
713 continue;
714 };
715 let position = rows
716 .iter()
717 .position(|row| matches!(row, Row::Post(post) if post.root.key == root_id));
718 if let Some(position) = position {
719 let mut row = rows.remove(position);
720 if let Row::Post(post) = &mut row {
721 post.replies.push(message);
722 }
723 rows.insert(0, row);
724 }
725 }
726}
727
728pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
729 let members: Vec<MessageRecord> = records
730 .iter()
731 .filter(|record| {
732 record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id)
733 })
734 .cloned()
735 .collect();
736 flat_rows(&members, context, false)
737}
738
739#[derive(Debug, Clone, PartialEq, Eq)]
740pub struct Splice {
741 pub range: Range<usize>,
742 pub count: usize,
743}
744
745pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> {
746 if old == new {
747 return None;
748 }
749 let prefix = old
750 .iter()
751 .zip(new)
752 .take_while(|(left, right)| left == right)
753 .count();
754 let suffix = old[prefix..]
755 .iter()
756 .rev()
757 .zip(new[prefix..].iter().rev())
758 .take_while(|(left, right)| left == right)
759 .count();
760 Some(Splice {
761 range: prefix..old.len() - suffix,
762 count: new.len() - prefix - suffix,
763 })
764}
765
766pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> {
767 let prefix = old
768 .iter()
769 .zip(new)
770 .take_while(|(left, right)| left.key() == right.key())
771 .count();
772 let suffix = old[prefix..]
773 .iter()
774 .rev()
775 .zip(new[prefix..].iter().rev())
776 .take_while(|(left, right)| left.key() == right.key())
777 .count();
778 let mut changed: Vec<usize> = (0..prefix)
779 .filter(|&index| old[index] != new[index])
780 .collect();
781 changed.extend((0..suffix).filter_map(|offset| {
782 let old_index = old.len() - 1 - offset;
783 let new_index = new.len() - 1 - offset;
784 (old[old_index] != new[new_index]).then_some(new_index)
785 }));
786 changed
787}
788
789#[cfg(test)]
790mod tests {
791 use chrono::TimeZone;
792
793 use super::*;
794
795 fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord {
796 MessageRecord {
797 conversation_id: "c".into(),
798 message_id: id.into(),
799 reply_to_id: reply_to.map(str::to_owned),
800 sender_id: Some("u".into()),
801 sender_name: Some("Author".into()),
802 sender_application_id: None,
803 links_json: "[]".to_owned(),
804 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
805 edited_at: None,
806 deleted: false,
807 body_html: format!("<p>text {id}</p>"),
808 attachments_json: "[]".into(),
809 reactions_json: "[]".into(),
810 mentions_json: "[]".into(),
811 subject: None,
812 }
813 }
814
815 fn own_reaction(reaction_type: &str) -> ReactionInfo {
816 ReactionInfo {
817 reaction_type: reaction_type.into(),
818 user_id: Some("me".into()),
819 user_name: None,
820 created_at: None,
821 }
822 }
823
824 #[test]
825 fn setting_a_reaction_is_idempotent_and_only_touches_mine() {
826 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
827 let other = ReactionInfo {
828 user_id: Some("them".into()),
829 ..own_reaction("like")
830 };
831 let mut reactions = vec![other.clone()];
832 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
833 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
834 assert_eq!(reactions.len(), 2);
835 assert_eq!(reactions[1].reaction_type, "like");
836 assert_eq!(reactions[1].user_id.as_deref(), Some("me"));
837 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
838 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
839 assert_eq!(reactions, vec![other]);
840 }
841
842 #[test]
843 fn setting_matches_legacy_names_and_variation_selectors() {
844 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
845 let mut reactions = vec![own_reaction("heart")];
846 assert!(has_own_reaction(&reactions, "\u{2764}\u{FE0F}", Some("me")));
847 set_own_reaction(&mut reactions, "\u{2764}\u{FE0F}", Some("me"), false, now);
848 assert!(reactions.is_empty());
849 set_own_reaction(&mut reactions, "\u{1F389}", Some("me"), true, now);
850 assert_eq!(reactions[0].reaction_type, "\u{1F389}");
851 }
852
853 #[test]
854 fn setting_without_a_known_user_never_matches() {
855 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
856 let mut reactions = Vec::new();
857 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
858 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
859 assert_eq!(reactions.len(), 2);
860 }
861
862 #[test]
863 fn pending_reactions_overlay_the_stored_ones() {
864 let mut stored = record("a", None, 8, 6);
865 stored.reactions_json = serde_json::to_string(&[own_reaction("like")]).unwrap();
866 let mut context = context();
867 context.my_user_id = Some("me".into());
868 context.pending_reactions.insert(
869 "a".into(),
870 vec![("\u{1F44D}".into(), false), ("\u{1F389}".into(), true)],
871 );
872 let chips = message_row(&stored, &context).reactions;
873 assert_eq!(chips.len(), 1);
874 assert_eq!(chips[0].reaction_type, "\u{1F389}");
875 assert!(chips[0].mine);
876 }
877
878 #[test]
879 fn reaction_type_maps_classic_glyphs_to_names() {
880 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
881 assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart");
882 assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}");
883 assert_eq!(reaction_glyph("like"), reaction_glyph("\u{1F44D}"));
884 assert_eq!(reaction_glyph("heart"), reaction_glyph("\u{2764}\u{FE0F}"));
885 assert_eq!(api_reaction(&reaction_glyph("heart")), "\u{2764}\u{FE0F}");
886 assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
887 }
888
889 #[test]
890 fn forwarded_messages_are_detected_by_the_forward_blockquote() {
891 assert!(is_forwarded(
892 r#"<p>fyi</p><blockquote itemscope="" itemtype="http://schema.skype.com/Forward" itemid="1">text</blockquote>"#
893 ));
894 assert!(!is_forwarded(
895 r#"<blockquote itemtype="http://schema.skype.com/Reply">text</blockquote>"#
896 ));
897 assert!(!is_forwarded("<p>plain</p>"));
898 let mut forwarded = record("f", None, 8, 6);
899 forwarded.body_html =
900 r#"<blockquote itemtype="http://schema.skype.com/Forward">text</blockquote>"#.into();
901 assert!(message_row(&forwarded, &context()).forwarded);
902 forwarded.deleted = true;
903 assert!(!message_row(&forwarded, &context()).forwarded);
904 }
905
906 #[test]
907 fn editing_loads_the_message_formatted_without_its_reply_quote() {
908 let mut edited = record("a", None, 8, 6);
909 edited.body_html =
910 "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\
911 <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\
912 <ol><li>one</li><li>two</li></ol>"
913 .into();
914 let draft = message_draft(&edited);
915 assert_eq!(draft.text(), "Plan for today\n1. one\n2. two");
916 assert_eq!(
917 draft.to_html(),
918 "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>"
919 );
920 }
921
922 #[test]
923 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
924 let mut text = record("a", None, 8, 6);
925 text.body_html = "<p>first line</p><p>second</p>".into();
926 assert_eq!(reply_excerpt(&text), "first line");
927 let mut quoted = record("q", None, 8, 6);
928 quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into();
929 assert_eq!(reply_excerpt(&quoted), "my answer");
930 let mut image = record("b", None, 8, 6);
931 image.body_html = "<img src=\"u\">".into();
932 assert_eq!(reply_excerpt(&image), "Image");
933 let mut long = record("c", None, 8, 6);
934 long.body_html = format!("<p>{}</p>", "x".repeat(200));
935 assert!(reply_excerpt(&long).ends_with("..."));
936 assert_eq!(
937 reply_excerpt(&long).chars().count(),
938 REPLY_EXCERPT_CHARS + 3
939 );
940 }
941
942 fn context() -> RowContext {
943 RowContext {
944 offset: FixedOffset::east_opt(0).unwrap(),
945 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
946 my_user_id: None,
947 names: HashMap::new(),
948 pending_reactions: HashMap::new(),
949 card_overrides: HashMap::new(),
950 translation: TranslationContext::default(),
951 }
952 }
953
954 fn keys(rows: &[Row]) -> Vec<String> {
955 rows.iter().map(|row| row.key().to_owned()).collect()
956 }
957
958 fn translation_context(shown: bool) -> RowContext {
959 use crate::translation::CachedTranslation;
960 let mut context = context();
961 context.translation.enabled = true;
962 context.translation.target = "en".into();
963 context.translation.stamps.insert(
964 "a".into(),
965 "languages=fr:100;length:80;&detector=Bling".into(),
966 );
967 context.my_user_id = Some("me".into());
968 if shown {
969 context.translation.cached.insert(
970 ("a".into(), 0),
971 CachedTranslation {
972 html: "<p><strong>translated</strong> body</p>".into(),
973 source: Some("fr".into()),
974 },
975 );
976 context.translation.shown.insert("a".into());
977 }
978 context
979 }
980
981 #[test]
982 fn a_foreign_message_carries_the_offer_and_keeps_its_text() {
983 let row = message_row(&record("a", None, 8, 6), &translation_context(false));
984 assert!(matches!(
985 row.translation,
986 Some(TranslationLine::Offer { ref language_code, .. }) if language_code == "fr"
987 ));
988 assert_eq!(row.blocks, layout_blocks(&linked_message_spans(&record("a", None, 8, 6))));
989 }
990
991 #[test]
992 fn a_shown_translation_replaces_the_body_and_the_original_comes_back() {
993 let original = message_row(&record("a", None, 8, 6), &translation_context(false)).blocks;
994 let translated = message_row(&record("a", None, 8, 6), &translation_context(true));
995 assert_ne!(translated.blocks, original);
996 assert_eq!(
997 translated.translation,
998 Some(TranslationLine::Translated {
999 language: Some("French".into()),
1000 showing_original: false
1001 })
1002 );
1003 let mut hidden = translation_context(true);
1004 hidden.translation.shown.clear();
1005 let back = message_row(&record("a", None, 8, 6), &hidden);
1006 assert_eq!(back.blocks, original);
1007 assert_eq!(
1008 back.translation,
1009 Some(TranslationLine::Translated {
1010 language: Some("French".into()),
1011 showing_original: true
1012 })
1013 );
1014 }
1015
1016 #[test]
1017 fn own_messages_get_no_offer() {
1018 let mut own = record("a", None, 8, 6);
1019 own.sender_id = Some("me".into());
1020 assert_eq!(message_row(&own, &translation_context(false)).translation, None);
1021 }
1022
1023 #[test]
1024 fn day_header_only_on_first_message_of_a_day() {
1025 let records = vec![
1026 record("a", None, 8, 6),
1027 record("b", None, 9, 6),
1028 record("c", None, 9, 7),
1029 ];
1030 let rows = flat_rows(&records, &context(), false);
1031 let headers: Vec<Option<String>> = rows
1032 .iter()
1033 .map(|row| match row {
1034 Row::Message(message) => message.day_header.clone(),
1035 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
1036 })
1037 .collect();
1038 assert_eq!(
1039 headers,
1040 vec![Some("Yesterday".into()), None, Some("Today".into())]
1041 );
1042 }
1043
1044 #[test]
1045 fn load_older_row_only_when_more_exists() {
1046 let records = vec![record("a", None, 8, 6)];
1047 assert_eq!(
1048 keys(&flat_rows(&records, &context(), true))[0],
1049 LOAD_OLDER_KEY
1050 );
1051 assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]);
1052 }
1053
1054 #[test]
1055 fn threads_group_replies_by_root() {
1056 let records = vec![
1057 record("r1", None, 8, 6),
1058 record("r2", None, 9, 6),
1059 record("x1", Some("r1"), 10, 6),
1060 record("x2", Some("r1"), 11, 6),
1061 record("orphan", Some("missing"), 12, 6),
1062 ];
1063 let threads = group_threads(&records);
1064 assert_eq!(threads.len(), 2);
1065 assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]);
1066 assert!(threads[1].reply_ids.is_empty());
1067 }
1068
1069 fn post_of(row: &Row) -> &PostRow {
1070 let Row::Post(post) = row else {
1071 panic!("post expected")
1072 };
1073 post
1074 }
1075
1076 fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord {
1077 let mut reply = record(id, Some(root), hour, 6);
1078 reply.sender_name = Some(sender.into());
1079 reply
1080 }
1081
1082 #[test]
1083 fn feed_orders_posts_by_last_activity_newest_first() {
1084 let records = vec![
1085 record("r1", None, 8, 6),
1086 record("r2", None, 9, 6),
1087 record("r3", None, 10, 6),
1088 record("x1", Some("r1"), 11, 6),
1089 ];
1090 let rows = thread_list_rows(&records, &context(), false);
1091 assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]);
1092 }
1093
1094 #[test]
1095 fn feed_puts_load_older_at_the_bottom() {
1096 let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)];
1097 let rows = thread_list_rows(&records, &context(), true);
1098 assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]);
1099 }
1100
1101 #[test]
1102 fn post_shows_the_last_three_replies_oldest_first() {
1103 let mut records = vec![record("r1", None, 1, 6)];
1104 for hour in 2..=6 {
1105 records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour));
1106 }
1107 records.reverse();
1108 let rows = thread_list_rows(&records, &context(), false);
1109 let post = post_of(&rows[0]);
1110 let shown: Vec<&str> = post
1111 .replies
1112 .iter()
1113 .map(|reply| reply.key.as_str())
1114 .collect();
1115 assert_eq!(shown, vec!["x4", "x5", "x6"]);
1116 assert_eq!(post.hidden_reply_count, 2);
1117 assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]);
1118 }
1119
1120 #[test]
1121 fn post_without_hidden_replies_has_no_link() {
1122 let records = vec![
1123 record("r1", None, 1, 6),
1124 reply_by("x1", "r1", "Ada", 2),
1125 reply_by("x2", "r1", "Ben", 3),
1126 reply_by("x3", "r1", "Cy", 4),
1127 ];
1128 let rows = thread_list_rows(&records, &context(), false);
1129 assert_eq!(post_of(&rows[0]).hidden_replies_label(), None);
1130 assert_eq!(post_of(&rows[0]).replies.len(), 3);
1131 }
1132
1133 fn label_for(repliers: &[&str]) -> String {
1134 let mut records = vec![record("r1", None, 1, 6)];
1135 for (index, name) in repliers.iter().enumerate() {
1136 records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32));
1137 }
1138 for index in 0..POST_VISIBLE_REPLIES {
1139 records.push(reply_by(
1140 &format!("v{index}"),
1141 "r1",
1142 "Shown",
1143 20 + index as u32,
1144 ));
1145 }
1146 let rows = thread_list_rows(&records, &context(), false);
1147 post_of(&rows[0]).hidden_replies_label().unwrap()
1148 }
1149
1150 #[test]
1151 fn replies_label_names_one_to_three_people() {
1152 assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna");
1153 assert_eq!(
1154 label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]),
1155 "3 replies from Anna and Ben"
1156 );
1157 assert_eq!(
1158 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]),
1159 "4 replies from Anna, Ben and Clara"
1160 );
1161 }
1162
1163 #[test]
1164 fn replies_label_counts_the_others_beyond_three_people() {
1165 assert_eq!(
1166 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]),
1167 "5 replies from Anna, Ben and 3 others"
1168 );
1169 assert_eq!(
1170 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]),
1171 "4 replies from Anna, Ben and 2 others"
1172 );
1173 }
1174
1175 #[test]
1176 fn local_reply_lands_in_its_post_and_local_post_on_top() {
1177 let records = vec![
1178 record("r1", None, 8, 6),
1179 record("r2", None, 9, 6),
1180 reply_by("x1", "r1", "Ada", 10),
1181 ];
1182 let mut rows = thread_list_rows(&records, &context(), true);
1183 let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context());
1184 pending_reply.reply_root = Some("r2".into());
1185 let pending_post = message_row(&record("pending-2", None, 12, 6), &context());
1186 place_local_rows(&mut rows, vec![pending_reply, pending_post]);
1187 assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]);
1188 let replies: Vec<&str> = post_of(&rows[1])
1189 .replies
1190 .iter()
1191 .map(|reply| reply.key.as_str())
1192 .collect();
1193 assert_eq!(replies, vec!["pending-1"]);
1194 }
1195
1196 #[test]
1197 fn local_reply_to_an_unloaded_post_is_not_shown() {
1198 let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false);
1199 let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context());
1200 orphan.reply_root = Some("gone".into());
1201 place_local_rows(&mut rows, vec![orphan]);
1202 assert_eq!(keys(&rows), vec!["r1"]);
1203 }
1204
1205 #[test]
1206 fn subject_reaches_the_post_root() {
1207 let mut with_subject = record("r1", None, 8, 6);
1208 with_subject.subject = Some("Release plan".into());
1209 let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false);
1210 assert_eq!(
1211 post_of(&rows[0]).root.subject.as_deref(),
1212 Some("Release plan")
1213 );
1214 assert_eq!(post_of(&rows[1]).root.subject, None);
1215 }
1216
1217 #[test]
1218 fn thread_view_has_root_then_replies() {
1219 let records = vec![
1220 record("r1", None, 8, 6),
1221 record("r2", None, 9, 6),
1222 record("x1", Some("r1"), 10, 6),
1223 ];
1224 assert_eq!(
1225 keys(&thread_rows(&records, "r1", &context())),
1226 vec!["r1", "x1"]
1227 );
1228 }
1229
1230 #[test]
1231 fn reactions_are_counted_in_first_seen_order() {
1232 let reaction = |kind: &str| ReactionInfo {
1233 reaction_type: kind.into(),
1234 user_id: None,
1235 user_name: None,
1236 created_at: None,
1237 };
1238 let chips = reaction_chips(
1239 &[reaction("heart"), reaction("like"), reaction("heart")],
1240 &context(),
1241 );
1242 assert_eq!(chips.len(), 2);
1243 assert_eq!(chips[0].count, 2);
1244 assert_eq!(chips[1].label, reaction_label("like"));
1245 }
1246
1247 #[test]
1248 fn legacy_laugh_and_sad_use_the_teams_glyphs() {
1249 assert_eq!(reaction_label("laugh"), "\u{1F606}");
1250 assert_eq!(reaction_label("sad"), "\u{1F641}");
1251 assert_eq!(reaction_type_for("\u{1F606}"), "laugh");
1252 assert_eq!(reaction_type_for("\u{1F641}"), "sad");
1253 }
1254
1255 #[test]
1256 fn legacy_and_emoji_reactions_share_a_chip() {
1257 let reaction = |kind: &str| ReactionInfo {
1258 reaction_type: kind.into(),
1259 user_id: None,
1260 user_name: Some("Lea".into()),
1261 created_at: None,
1262 };
1263 let chips = reaction_chips(&[reaction("like"), reaction("\u{1F44D}")], &context());
1264 assert_eq!(chips.len(), 1);
1265 assert_eq!(chips[0].count, 2);
1266 }
1267
1268 #[test]
1269 fn reactor_name_falls_back_to_directory_then_unknown() {
1270 let reaction = |user: &str| ReactionInfo {
1271 reaction_type: "like".into(),
1272 user_id: Some(user.into()),
1273 user_name: None,
1274 created_at: None,
1275 };
1276 let mut context = context();
1277 context.names.insert("known".into(), "Priya Nair".into());
1278 let chips = reaction_chips(&[reaction("known"), reaction("other")], &context);
1279 assert_eq!(chips[0].reactors[0].name, "Priya Nair");
1280 assert_eq!(chips[0].reactors[1].name, "Unknown");
1281 }
1282
1283 fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord {
1284 let mut record = record(id, None, hour, day);
1285 record.sender_id = Some(sender.into());
1286 record.created_at = Utc
1287 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
1288 .unwrap();
1289 record
1290 }
1291
1292 fn series_of(rows: &[Row]) -> Vec<(bool, bool)> {
1293 rows.iter()
1294 .filter_map(|row| match row {
1295 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1296 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
1297 })
1298 .collect()
1299 }
1300
1301 #[test]
1302 fn series_joins_same_sender_within_five_minutes() {
1303 let records = vec![
1304 record_by("a", "ada", 9, 0, 7),
1305 record_by("b", "ada", 9, 4, 7),
1306 record_by("c", "ada", 9, 20, 7),
1307 record_by("d", "bob", 9, 21, 7),
1308 record_by("e", "ada", 9, 22, 7),
1309 ];
1310 let rows = flat_rows(&records, &context(), false);
1311 assert_eq!(
1312 series_of(&rows),
1313 vec![
1314 (false, true),
1315 (true, false),
1316 (false, false),
1317 (false, false),
1318 (false, false)
1319 ]
1320 );
1321 }
1322
1323 #[test]
1324 fn series_window_ends_exactly_at_the_gap_constant() {
1325 let gap = SERIES_GAP_MINUTES as u32;
1326 let records = vec![
1327 record_by("a", "ada", 9, 0, 7),
1328 record_by("b", "ada", 9, gap - 1, 7),
1329 record_by("c", "ada", 9, 2 * gap - 1 + gap, 7),
1330 ];
1331 let rows = flat_rows(&records, &context(), false);
1332 assert_eq!(
1333 series_of(&rows),
1334 vec![(false, true), (true, false), (false, false)]
1335 );
1336 }
1337
1338 #[test]
1339 fn series_breaks_at_a_new_day() {
1340 let records = vec![
1341 record_by("a", "ada", 23, 58, 6),
1342 record_by("b", "ada", 0, 1, 7),
1343 ];
1344 let rows = flat_rows(&records, &context(), false);
1345 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1346 }
1347
1348 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
1349 let corners = bubble_corners(own, Series { has_prev, has_next });
1350 [
1351 corners.top_left,
1352 corners.top_right,
1353 corners.bottom_right,
1354 corners.bottom_left,
1355 ]
1356 }
1357
1358 #[test]
1359 fn corners_match_the_mockup_for_other_senders() {
1360 assert_eq!(corners(false, false, false), [4., 14., 14., 14.]);
1361 assert_eq!(corners(false, false, true), [4., 14., 14., 4.]);
1362 assert_eq!(corners(false, true, true), [4., 14., 14., 4.]);
1363 assert_eq!(corners(false, true, false), [4., 14., 14., 14.]);
1364 }
1365
1366 #[test]
1367 fn corners_match_the_mockup_for_own_messages() {
1368 assert_eq!(corners(true, false, false), [14., 4., 4., 14.]);
1369 assert_eq!(corners(true, false, true), [14., 14., 4., 14.]);
1370 assert_eq!(corners(true, true, true), [14., 4., 4., 14.]);
1371 assert_eq!(corners(true, true, false), [14., 4., 14., 14.]);
1372 }
1373
1374 #[test]
1375 fn own_reaction_is_marked() {
1376 let reaction = |user: &str| ReactionInfo {
1377 reaction_type: "like".into(),
1378 user_id: Some(user.into()),
1379 user_name: None,
1380 created_at: None,
1381 };
1382 let mut context = context();
1383 context.my_user_id = Some("me".into());
1384 let chips = reaction_chips(&[reaction("x"), reaction("me")], &context);
1385 assert!(chips[0].mine);
1386 assert!(!reaction_chips(&[reaction("x")], &context)[0].mine);
1387 }
1388
1389 fn strings(values: &[&str]) -> Vec<String> {
1390 values.iter().map(|value| (*value).to_owned()).collect()
1391 }
1392
1393 #[test]
1394 fn diff_detects_append_prepend_and_replace() {
1395 let base = strings(&["a", "b"]);
1396 assert_eq!(diff_keys(&base, &base), None);
1397 assert_eq!(
1398 diff_keys(&base, &strings(&["a", "b", "c"])),
1399 Some(Splice {
1400 range: 2..2,
1401 count: 1
1402 })
1403 );
1404 assert_eq!(
1405 diff_keys(&base, &strings(&["x", "a", "b"])),
1406 Some(Splice {
1407 range: 0..0,
1408 count: 1
1409 })
1410 );
1411 assert_eq!(
1412 diff_keys(
1413 &strings(&["load-older", "a"]),
1414 &strings(&["load-older", "x", "y", "a"])
1415 ),
1416 Some(Splice {
1417 range: 1..1,
1418 count: 2
1419 })
1420 );
1421 assert_eq!(
1422 diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])),
1423 Some(Splice {
1424 range: 0..1,
1425 count: 0
1426 })
1427 );
1428 assert_eq!(
1429 diff_keys(&base, &strings(&["x"])),
1430 Some(Splice {
1431 range: 0..2,
1432 count: 1
1433 })
1434 );
1435 }
1436
1437 #[test]
1438 fn changed_indices_find_edited_rows() {
1439 let old = flat_rows(
1440 &[record("a", None, 8, 6), record("b", None, 9, 6)],
1441 &context(),
1442 false,
1443 );
1444 let mut edited = record("b", None, 9, 6);
1445 edited.body_html = "<p>changed</p>".into();
1446 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
1447 assert_eq!(changed_indices(&old, &new), vec![1]);
1448 }
1449}