BlueGit

ict rusty-teams

Files

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

rows.rs

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