BlueGit

ict rusty-teams

Files

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

rows.rs

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