BlueGit

ict rusty-teams

Files

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

rows.rs

rows.rs 46.8 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!(row.blocks, layout_blocks(&linked_message_spans(&record("a", None, 8, 6))));
980 }
981
982 #[test]
983 fn a_shown_translation_replaces_the_body_and_the_original_comes_back() {
984 let original = message_row(&record("a", None, 8, 6), &translation_context(false)).blocks;
985 let translated = message_row(&record("a", None, 8, 6), &translation_context(true));
986 assert_ne!(translated.blocks, original);
987 assert_eq!(
988 translated.translation,
989 Some(TranslationLine::Translated {
990 language: Some("French".into()),
991 showing_original: false
992 })
993 );
994 let mut hidden = translation_context(true);
995 hidden.translation.shown.clear();
996 let back = message_row(&record("a", None, 8, 6), &hidden);
997 assert_eq!(back.blocks, original);
998 assert_eq!(
999 back.translation,
1000 Some(TranslationLine::Translated {
1001 language: Some("French".into()),
1002 showing_original: true
1003 })
1004 );
1005 }
1006
1007 #[test]
1008 fn own_messages_get_no_offer() {
1009 let mut own = record("a", None, 8, 6);
1010 own.sender_id = Some("me".into());
1011 assert_eq!(message_row(&own, &translation_context(false)).translation, None);
1012 }
1013
1014 #[test]
1015 fn day_header_only_on_first_message_of_a_day() {
1016 let records = vec![
1017 record("a", None, 8, 6),
1018 record("b", None, 9, 6),
1019 record("c", None, 9, 7),
1020 ];
1021 let rows = flat_rows(&records, &context(), false);
1022 let headers: Vec<Option<String>> = rows
1023 .iter()
1024 .map(|row| match row {
1025 Row::Message(message) => message.day_header.clone(),
1026 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
1027 })
1028 .collect();
1029 assert_eq!(
1030 headers,
1031 vec![Some("Yesterday".into()), None, Some("Today".into())]
1032 );
1033 }
1034
1035 #[test]
1036 fn load_older_row_only_when_more_exists() {
1037 let records = vec![record("a", None, 8, 6)];
1038 assert_eq!(
1039 keys(&flat_rows(&records, &context(), true))[0],
1040 LOAD_OLDER_KEY
1041 );
1042 assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]);
1043 }
1044
1045 #[test]
1046 fn threads_group_replies_by_root() {
1047 let records = vec![
1048 record("r1", None, 8, 6),
1049 record("r2", None, 9, 6),
1050 record("x1", Some("r1"), 10, 6),
1051 record("x2", Some("r1"), 11, 6),
1052 record("orphan", Some("missing"), 12, 6),
1053 ];
1054 let threads = group_threads(&records);
1055 assert_eq!(threads.len(), 2);
1056 assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]);
1057 assert!(threads[1].reply_ids.is_empty());
1058 }
1059
1060 fn post_of(row: &Row) -> &PostRow {
1061 let Row::Post(post) = row else {
1062 panic!("post expected")
1063 };
1064 post
1065 }
1066
1067 fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord {
1068 let mut reply = record(id, Some(root), hour, 6);
1069 reply.sender_name = Some(sender.into());
1070 reply
1071 }
1072
1073 #[test]
1074 fn feed_orders_posts_by_last_activity_newest_first() {
1075 let records = vec![
1076 record("r1", None, 8, 6),
1077 record("r2", None, 9, 6),
1078 record("r3", None, 10, 6),
1079 record("x1", Some("r1"), 11, 6),
1080 ];
1081 let rows = thread_list_rows(&records, &context(), false);
1082 assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]);
1083 }
1084
1085 #[test]
1086 fn feed_puts_load_older_at_the_bottom() {
1087 let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)];
1088 let rows = thread_list_rows(&records, &context(), true);
1089 assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]);
1090 }
1091
1092 #[test]
1093 fn post_shows_the_last_three_replies_oldest_first() {
1094 let mut records = vec![record("r1", None, 1, 6)];
1095 for hour in 2..=6 {
1096 records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour));
1097 }
1098 records.reverse();
1099 let rows = thread_list_rows(&records, &context(), false);
1100 let post = post_of(&rows[0]);
1101 let shown: Vec<&str> = post
1102 .replies
1103 .iter()
1104 .map(|reply| reply.key.as_str())
1105 .collect();
1106 assert_eq!(shown, vec!["x4", "x5", "x6"]);
1107 assert_eq!(post.hidden_reply_count, 2);
1108 assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]);
1109 }
1110
1111 #[test]
1112 fn post_without_hidden_replies_has_no_link() {
1113 let records = vec![
1114 record("r1", None, 1, 6),
1115 reply_by("x1", "r1", "Ada", 2),
1116 reply_by("x2", "r1", "Ben", 3),
1117 reply_by("x3", "r1", "Cy", 4),
1118 ];
1119 let rows = thread_list_rows(&records, &context(), false);
1120 assert_eq!(post_of(&rows[0]).hidden_replies_label(), None);
1121 assert_eq!(post_of(&rows[0]).replies.len(), 3);
1122 }
1123
1124 fn label_for(repliers: &[&str]) -> String {
1125 let mut records = vec![record("r1", None, 1, 6)];
1126 for (index, name) in repliers.iter().enumerate() {
1127 records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32));
1128 }
1129 for index in 0..POST_VISIBLE_REPLIES {
1130 records.push(reply_by(
1131 &format!("v{index}"),
1132 "r1",
1133 "Shown",
1134 20 + index as u32,
1135 ));
1136 }
1137 let rows = thread_list_rows(&records, &context(), false);
1138 post_of(&rows[0]).hidden_replies_label().unwrap()
1139 }
1140
1141 #[test]
1142 fn replies_label_names_one_to_three_people() {
1143 assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna");
1144 assert_eq!(
1145 label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]),
1146 "3 replies from Anna and Ben"
1147 );
1148 assert_eq!(
1149 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]),
1150 "4 replies from Anna, Ben and Clara"
1151 );
1152 }
1153
1154 #[test]
1155 fn replies_label_counts_the_others_beyond_three_people() {
1156 assert_eq!(
1157 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]),
1158 "5 replies from Anna, Ben and 3 others"
1159 );
1160 assert_eq!(
1161 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]),
1162 "4 replies from Anna, Ben and 2 others"
1163 );
1164 }
1165
1166 #[test]
1167 fn local_reply_lands_in_its_post_and_local_post_on_top() {
1168 let records = vec![
1169 record("r1", None, 8, 6),
1170 record("r2", None, 9, 6),
1171 reply_by("x1", "r1", "Ada", 10),
1172 ];
1173 let mut rows = thread_list_rows(&records, &context(), true);
1174 let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context());
1175 pending_reply.reply_root = Some("r2".into());
1176 let pending_post = message_row(&record("pending-2", None, 12, 6), &context());
1177 place_local_rows(&mut rows, vec![pending_reply, pending_post]);
1178 assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]);
1179 let replies: Vec<&str> = post_of(&rows[1])
1180 .replies
1181 .iter()
1182 .map(|reply| reply.key.as_str())
1183 .collect();
1184 assert_eq!(replies, vec!["pending-1"]);
1185 }
1186
1187 #[test]
1188 fn local_reply_to_an_unloaded_post_is_not_shown() {
1189 let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false);
1190 let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context());
1191 orphan.reply_root = Some("gone".into());
1192 place_local_rows(&mut rows, vec![orphan]);
1193 assert_eq!(keys(&rows), vec!["r1"]);
1194 }
1195
1196 #[test]
1197 fn subject_reaches_the_post_root() {
1198 let mut with_subject = record("r1", None, 8, 6);
1199 with_subject.subject = Some("Release plan".into());
1200 let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false);
1201 assert_eq!(
1202 post_of(&rows[0]).root.subject.as_deref(),
1203 Some("Release plan")
1204 );
1205 assert_eq!(post_of(&rows[1]).root.subject, None);
1206 }
1207
1208 #[test]
1209 fn thread_view_has_root_then_replies() {
1210 let records = vec![
1211 record("r1", None, 8, 6),
1212 record("r2", None, 9, 6),
1213 record("x1", Some("r1"), 10, 6),
1214 ];
1215 assert_eq!(
1216 keys(&thread_rows(&records, "r1", &context())),
1217 vec!["r1", "x1"]
1218 );
1219 }
1220
1221 #[test]
1222 fn reactions_are_counted_in_first_seen_order() {
1223 let reaction = |kind: &str| ReactionInfo {
1224 reaction_type: kind.into(),
1225 user_id: None,
1226 user_name: None,
1227 created_at: None,
1228 };
1229 let chips = reaction_chips(
1230 &[reaction("heart"), reaction("like"), reaction("heart")],
1231 &context(),
1232 );
1233 assert_eq!(chips.len(), 2);
1234 assert_eq!(chips[0].count, 2);
1235 assert_eq!(chips[1].label, reaction_label("like"));
1236 }
1237
1238 #[test]
1239 fn legacy_laugh_and_sad_use_the_teams_glyphs() {
1240 assert_eq!(reaction_label("laugh"), "\u{1F606}");
1241 assert_eq!(reaction_label("sad"), "\u{1F641}");
1242 assert_eq!(reaction_type_for("\u{1F606}"), "laugh");
1243 assert_eq!(reaction_type_for("\u{1F641}"), "sad");
1244 }
1245
1246 #[test]
1247 fn legacy_and_emoji_reactions_share_a_chip() {
1248 let reaction = |kind: &str| ReactionInfo {
1249 reaction_type: kind.into(),
1250 user_id: None,
1251 user_name: Some("Lea".into()),
1252 created_at: None,
1253 };
1254 let chips = reaction_chips(&[reaction("like"), reaction("\u{1F44D}")], &context());
1255 assert_eq!(chips.len(), 1);
1256 assert_eq!(chips[0].count, 2);
1257 }
1258
1259 #[test]
1260 fn reactor_name_falls_back_to_directory_then_unknown() {
1261 let reaction = |user: &str| ReactionInfo {
1262 reaction_type: "like".into(),
1263 user_id: Some(user.into()),
1264 user_name: None,
1265 created_at: None,
1266 };
1267 let mut context = context();
1268 context.names.insert("known".into(), "Priya Nair".into());
1269 let chips = reaction_chips(&[reaction("known"), reaction("other")], &context);
1270 assert_eq!(chips[0].reactors[0].name, "Priya Nair");
1271 assert_eq!(chips[0].reactors[1].name, "Unknown");
1272 }
1273
1274 fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord {
1275 let mut record = record(id, None, hour, day);
1276 record.sender_id = Some(sender.into());
1277 record.created_at = Utc
1278 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
1279 .unwrap();
1280 record
1281 }
1282
1283 fn series_of(rows: &[Row]) -> Vec<(bool, bool)> {
1284 rows.iter()
1285 .filter_map(|row| match row {
1286 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1287 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
1288 })
1289 .collect()
1290 }
1291
1292 #[test]
1293 fn series_joins_same_sender_within_five_minutes() {
1294 let records = vec![
1295 record_by("a", "ada", 9, 0, 7),
1296 record_by("b", "ada", 9, 4, 7),
1297 record_by("c", "ada", 9, 20, 7),
1298 record_by("d", "bob", 9, 21, 7),
1299 record_by("e", "ada", 9, 22, 7),
1300 ];
1301 let rows = flat_rows(&records, &context(), false);
1302 assert_eq!(
1303 series_of(&rows),
1304 vec![
1305 (false, true),
1306 (true, false),
1307 (false, false),
1308 (false, false),
1309 (false, false)
1310 ]
1311 );
1312 }
1313
1314 #[test]
1315 fn series_window_ends_exactly_at_the_gap_constant() {
1316 let gap = SERIES_GAP_MINUTES as u32;
1317 let records = vec![
1318 record_by("a", "ada", 9, 0, 7),
1319 record_by("b", "ada", 9, gap - 1, 7),
1320 record_by("c", "ada", 9, 2 * gap - 1 + gap, 7),
1321 ];
1322 let rows = flat_rows(&records, &context(), false);
1323 assert_eq!(
1324 series_of(&rows),
1325 vec![(false, true), (true, false), (false, false)]
1326 );
1327 }
1328
1329 #[test]
1330 fn series_breaks_at_a_new_day() {
1331 let records = vec![
1332 record_by("a", "ada", 23, 58, 6),
1333 record_by("b", "ada", 0, 1, 7),
1334 ];
1335 let rows = flat_rows(&records, &context(), false);
1336 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1337 }
1338
1339 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
1340 let corners = bubble_corners(own, Series { has_prev, has_next });
1341 [
1342 corners.top_left,
1343 corners.top_right,
1344 corners.bottom_right,
1345 corners.bottom_left,
1346 ]
1347 }
1348
1349 #[test]
1350 fn corners_match_the_mockup_for_other_senders() {
1351 assert_eq!(corners(false, false, false), [14., 14., 14., 14.]);
1352 assert_eq!(corners(false, false, true), [14., 14., 14., 4.]);
1353 assert_eq!(corners(false, true, true), [4., 14., 14., 4.]);
1354 assert_eq!(corners(false, true, false), [4., 14., 14., 14.]);
1355 }
1356
1357 #[test]
1358 fn corners_match_the_mockup_for_own_messages() {
1359 assert_eq!(corners(true, false, false), [14., 14., 14., 14.]);
1360 assert_eq!(corners(true, false, true), [14., 14., 4., 14.]);
1361 assert_eq!(corners(true, true, true), [14., 4., 4., 14.]);
1362 assert_eq!(corners(true, true, false), [14., 4., 14., 14.]);
1363 }
1364
1365 #[test]
1366 fn own_reaction_is_marked() {
1367 let reaction = |user: &str| ReactionInfo {
1368 reaction_type: "like".into(),
1369 user_id: Some(user.into()),
1370 user_name: None,
1371 created_at: None,
1372 };
1373 let mut context = context();
1374 context.my_user_id = Some("me".into());
1375 let chips = reaction_chips(&[reaction("x"), reaction("me")], &context);
1376 assert!(chips[0].mine);
1377 assert!(!reaction_chips(&[reaction("x")], &context)[0].mine);
1378 }
1379
1380 fn strings(values: &[&str]) -> Vec<String> {
1381 values.iter().map(|value| (*value).to_owned()).collect()
1382 }
1383
1384 #[test]
1385 fn diff_detects_append_prepend_and_replace() {
1386 let base = strings(&["a", "b"]);
1387 assert_eq!(diff_keys(&base, &base), None);
1388 assert_eq!(
1389 diff_keys(&base, &strings(&["a", "b", "c"])),
1390 Some(Splice {
1391 range: 2..2,
1392 count: 1
1393 })
1394 );
1395 assert_eq!(
1396 diff_keys(&base, &strings(&["x", "a", "b"])),
1397 Some(Splice {
1398 range: 0..0,
1399 count: 1
1400 })
1401 );
1402 assert_eq!(
1403 diff_keys(
1404 &strings(&["load-older", "a"]),
1405 &strings(&["load-older", "x", "y", "a"])
1406 ),
1407 Some(Splice {
1408 range: 1..1,
1409 count: 2
1410 })
1411 );
1412 assert_eq!(
1413 diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])),
1414 Some(Splice {
1415 range: 0..1,
1416 count: 0
1417 })
1418 );
1419 assert_eq!(
1420 diff_keys(&base, &strings(&["x"])),
1421 Some(Splice {
1422 range: 0..2,
1423 count: 1
1424 })
1425 );
1426 }
1427
1428 #[test]
1429 fn changed_indices_find_edited_rows() {
1430 let old = flat_rows(
1431 &[record("a", None, 8, 6), record("b", None, 9, 6)],
1432 &context(),
1433 false,
1434 );
1435 let mut edited = record("b", None, 9, 6);
1436 edited.body_html = "<p>changed</p>".into();
1437 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
1438 assert_eq!(changed_indices(&old, &new), vec![1]);
1439 }
1440}