BlueGit

ict rusty-teams

Files

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

rows.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
rows.rs 24.5 KiB Download Raw
1use std::collections::BTreeMap;
2use std::ops::Range;
3
4use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
5use store::MessageRecord;
6use teams_core::{FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions};
7
8use crate::format;
9use crate::render::blocks::{Inline, MENTION_PAD, strip_image_placeholders};
10use crate::render::{Block, layout_blocks};
11use crate::sidebar_model::Face;
12
13const REPLY_FACE_LIMIT: usize = 3;
14
15pub const LOAD_OLDER_KEY: &str = "load-older";
16const UNKNOWN_AUTHOR: &str = "Unknown";
17const DELETED_TEXT: &str = "Nachricht gelöscht";
18const SERIES_GAP_MINUTES: i64 = 5;
19const CORNER_RADIUS: f32 = 14.;
20const CORNER_SERIES: f32 = 4.;
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct ReactionChip {
24 pub label: String,
25 pub count: usize,
26 pub mine: bool,
27}
28
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
30pub struct Series {
31 pub has_prev: bool,
32 pub has_next: bool,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct Corners {
37 pub top_left: f32,
38 pub top_right: f32,
39 pub bottom_right: f32,
40 pub bottom_left: f32,
41}
42
43pub fn bubble_corners(own: bool, series: Series) -> Corners {
44 if own {
45 let top_right = if series.has_prev || !series.has_next {
46 CORNER_SERIES
47 } else {
48 CORNER_RADIUS
49 };
50 let bottom_right = if series.has_next || !series.has_prev {
51 CORNER_SERIES
52 } else {
53 CORNER_RADIUS
54 };
55 Corners {
56 top_left: CORNER_RADIUS,
57 top_right,
58 bottom_right,
59 bottom_left: CORNER_RADIUS,
60 }
61 } else {
62 Corners {
63 top_left: CORNER_SERIES,
64 top_right: CORNER_RADIUS,
65 bottom_right: CORNER_RADIUS,
66 bottom_left: if series.has_next {
67 CORNER_SERIES
68 } else {
69 CORNER_RADIUS
70 },
71 }
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub enum Delivery {
77 Delivered,
78 Sending,
79 Failed(String),
80}
81
82#[derive(Debug, Clone, PartialEq)]
83pub struct MessageRow {
84 pub key: String,
85 pub author: String,
86 pub sender_id: Option<String>,
87 pub created_at: DateTime<Utc>,
88 pub series: Series,
89 pub card: bool,
90 pub time: String,
91 pub day_header: Option<String>,
92 pub blocks: Vec<Block>,
93 pub edited: bool,
94 pub deleted: bool,
95 pub reactions: Vec<ReactionChip>,
96 pub images: Vec<ImageRef>,
97 pub files: Vec<FileCard>,
98 pub reply_count: Option<usize>,
99 pub new_marker: bool,
100 pub reply_faces: Vec<Face>,
101 pub last_reply_time: Option<String>,
102 pub open_thread: Option<String>,
103 pub is_reply: bool,
104 pub delivery: Delivery,
105 pub own: bool,
106 pub read: bool,
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct StartInfo {
111 pub title: String,
112 pub user_id: Option<String>,
113}
114
115pub const START_KEY: &str = "conversation-start";
116
117#[derive(Debug, Clone, PartialEq)]
118pub enum Row {
119 LoadOlder,
120 Start(StartInfo),
121 Message(Box<MessageRow>),
122}
123
124fn sender_key(row: &MessageRow) -> &str {
125 row.sender_id.as_deref().unwrap_or(&row.author)
126}
127
128fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
129 !previous.card
130 && !next.card
131 && next.day_header.is_none()
132 && !next.new_marker
133 && sender_key(previous) == sender_key(next)
134 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
135 && next.created_at >= previous.created_at
136}
137
138pub fn assign_series(rows: &mut [Row]) {
139 let mut previous: Option<usize> = None;
140 for index in 0..rows.len() {
141 let Row::Message(_) = &rows[index] else {
142 previous = None;
143 continue;
144 };
145 if let Some(before) = previous {
146 let joined = match (&rows[before], &rows[index]) {
147 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
148 _ => false,
149 };
150 if joined {
151 if let Row::Message(a) = &mut rows[before] {
152 a.series.has_next = true;
153 }
154 if let Row::Message(b) = &mut rows[index] {
155 b.series.has_prev = true;
156 }
157 }
158 }
159 previous = Some(index);
160 }
161}
162
163impl Row {
164 pub fn key(&self) -> &str {
165 match self {
166 Row::LoadOlder => LOAD_OLDER_KEY,
167 Row::Start(_) => START_KEY,
168 Row::Message(message) => &message.key,
169 }
170 }
171}
172
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub struct Thread {
175 pub root_id: String,
176 pub reply_ids: Vec<String>,
177}
178
179pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String {
180 time.with_timezone(&offset).format("%H:%M").to_string()
181}
182
183pub fn reaction_label(reaction_type: &str) -> String {
184 match reaction_type {
185 "like" => "\u{1F44D}".to_owned(),
186 "heart" => "\u{2764}".to_owned(),
187 "laugh" => "\u{1F602}".to_owned(),
188 "surprised" => "\u{1F62E}".to_owned(),
189 "sad" => "\u{1F622}".to_owned(),
190 "angry" => "\u{1F620}".to_owned(),
191 other => other.to_owned(),
192 }
193}
194
195pub fn reaction_chips(reactions: &[ReactionInfo], my_user_id: Option<&str>) -> Vec<ReactionChip> {
196 let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
197 let mut mine: BTreeMap<&str, bool> = BTreeMap::new();
198 let mut order: Vec<&str> = Vec::new();
199 for reaction in reactions {
200 let entry = counts.entry(reaction.reaction_type.as_str()).or_insert(0);
201 if *entry == 0 {
202 order.push(reaction.reaction_type.as_str());
203 }
204 *entry += 1;
205 if my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id {
206 mine.insert(reaction.reaction_type.as_str(), true);
207 }
208 }
209 order
210 .into_iter()
211 .map(|reaction_type| ReactionChip {
212 label: reaction_label(reaction_type),
213 count: counts[reaction_type],
214 mine: mine.contains_key(reaction_type),
215 })
216 .collect()
217}
218
219const REPLY_EXCERPT_CHARS: usize = 90;
220
221pub fn reply_excerpt(record: &MessageRecord) -> String {
222 let own_spans: Vec<Span> = message_spans(record)
223 .into_iter()
224 .filter(|span| !matches!(span, Span::Quote(_)))
225 .collect();
226 let text = strip_image_placeholders(layout_blocks(&own_spans))
227 .into_iter()
228 .find_map(|block| match block {
229 Block::Paragraph(inline) | Block::ListItem(inline) => Some(inline.text),
230 Block::Code(code) => Some(code),
231 Block::Quote(_) => None,
232 })
233 .unwrap_or_default()
234 .replace(MENTION_PAD, "");
235 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
236 let excerpt = match first_line {
237 Some(line) => line.to_owned(),
238 None if !images(record).is_empty() => "Bild".to_owned(),
239 None => files(record)
240 .into_iter()
241 .next()
242 .map_or_else(|| "Nachricht".to_owned(), |card| card.name),
243 };
244 if excerpt.chars().count() > REPLY_EXCERPT_CHARS {
245 let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect();
246 format!("{}...", cut.trim_end())
247 } else {
248 excerpt
249 }
250}
251
252pub struct RowContext {
253 pub offset: FixedOffset,
254 pub today: NaiveDate,
255 pub my_user_id: Option<String>,
256}
257
258pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
259 let local = record.created_at.with_timezone(&context.offset);
260 let images = images(record);
261 let blocks = if record.deleted {
262 vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
263 } else {
264 layout_blocks(&message_spans(record))
265 };
266 let blocks = if images.is_empty() {
267 blocks
268 } else {
269 strip_image_placeholders(blocks)
270 };
271 MessageRow {
272 key: record.message_id.clone(),
273 sender_id: record.sender_id.clone(),
274 created_at: record.created_at,
275 series: Series::default(),
276 card: false,
277 author: record
278 .sender_name
279 .clone()
280 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
281 time: clock_label(record.created_at, context.offset),
282 day_header: Some(format::day_label(local.date_naive(), context.today)),
283 blocks,
284 edited: record.edited_at.is_some() && !record.deleted,
285 deleted: record.deleted,
286 reactions: reaction_chips(&reactions(record), context.my_user_id.as_deref()),
287 images,
288 files: files(record),
289 reply_count: None,
290 new_marker: false,
291 reply_faces: Vec::new(),
292 last_reply_time: None,
293 open_thread: None,
294 is_reply: record.reply_to_id.is_some(),
295 delivery: Delivery::Delivered,
296 read: false,
297 own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
298 }
299}
300
301pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
302 let mut rows = Vec::with_capacity(records.len() + 1);
303 if has_older {
304 rows.push(Row::LoadOlder);
305 }
306 let mut previous_day: Option<NaiveDate> = None;
307 for record in records {
308 let mut row = message_row(record, context);
309 let day = record
310 .created_at
311 .with_timezone(&context.offset)
312 .date_naive();
313 if previous_day == Some(day) {
314 row.day_header = None;
315 }
316 previous_day = Some(day);
317 rows.push(Row::Message(Box::new(row)));
318 }
319 assign_series(&mut rows);
320 rows
321}
322
323pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> {
324 let mut threads: Vec<Thread> = Vec::new();
325 let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new();
326 for record in records.iter().filter(|record| record.reply_to_id.is_none()) {
327 index_by_root.insert(record.message_id.as_str(), threads.len());
328 threads.push(Thread {
329 root_id: record.message_id.clone(),
330 reply_ids: Vec::new(),
331 });
332 }
333 for record in records {
334 let Some(root_id) = record.reply_to_id.as_deref() else {
335 continue;
336 };
337 if let Some(&index) = index_by_root.get(root_id) {
338 threads[index].reply_ids.push(record.message_id.clone());
339 }
340 }
341 threads
342}
343
344fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> {
345 thread
346 .reply_ids
347 .iter()
348 .chain(std::iter::once(&thread.root_id))
349 .filter_map(|id| by_id.get(id.as_str()))
350 .map(|record| record.created_at)
351 .max()
352 .unwrap_or_default()
353}
354
355pub fn thread_list_rows(
356 records: &[MessageRecord],
357 context: &RowContext,
358 has_older: bool,
359) -> Vec<Row> {
360 let by_id: BTreeMap<&str, &MessageRecord> = records
361 .iter()
362 .map(|record| (record.message_id.as_str(), record))
363 .collect();
364 let mut threads = group_threads(records);
365 threads.sort_by_key(|thread| last_activity(thread, &by_id));
366 let mut rows = Vec::with_capacity(threads.len() + 1);
367 if has_older {
368 rows.push(Row::LoadOlder);
369 }
370 let mut previous_day: Option<NaiveDate> = None;
371 for thread in threads {
372 let Some(root) = by_id.get(thread.root_id.as_str()) else {
373 continue;
374 };
375 let mut row = message_row(root, context);
376 let day = last_activity(&thread, &by_id)
377 .with_timezone(&context.offset)
378 .date_naive();
379 row.day_header = (previous_day != Some(day)).then(|| format::day_label(day, context.today));
380 previous_day = Some(day);
381 row.card = true;
382 row.reply_count = Some(thread.reply_ids.len());
383 let replies: Vec<&&MessageRecord> = thread
384 .reply_ids
385 .iter()
386 .filter_map(|id| by_id.get(id.as_str()))
387 .collect();
388 for reply in &replies {
389 let face = Face {
390 user_id: reply.sender_id.clone(),
391 name: reply
392 .sender_name
393 .clone()
394 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
395 };
396 if row.reply_faces.len() < REPLY_FACE_LIMIT && !row.reply_faces.contains(&face) {
397 row.reply_faces.push(face);
398 }
399 }
400 row.last_reply_time = replies
401 .iter()
402 .map(|reply| reply.created_at)
403 .max()
404 .map(|time| {
405 let local = time.with_timezone(&context.offset);
406 format!(
407 "{} {}",
408 format::day_label(local.date_naive(), context.today),
409 clock_label(time, context.offset)
410 )
411 });
412 row.open_thread = Some(thread.root_id.clone());
413 rows.push(Row::Message(Box::new(row)));
414 }
415 rows
416}
417
418pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
419 let members: Vec<MessageRecord> = records
420 .iter()
421 .filter(|record| {
422 record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id)
423 })
424 .cloned()
425 .collect();
426 flat_rows(&members, context, false)
427}
428
429#[derive(Debug, Clone, PartialEq, Eq)]
430pub struct Splice {
431 pub range: Range<usize>,
432 pub count: usize,
433}
434
435pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> {
436 if old == new {
437 return None;
438 }
439 let prefix = old
440 .iter()
441 .zip(new)
442 .take_while(|(left, right)| left == right)
443 .count();
444 let suffix = old[prefix..]
445 .iter()
446 .rev()
447 .zip(new[prefix..].iter().rev())
448 .take_while(|(left, right)| left == right)
449 .count();
450 Some(Splice {
451 range: prefix..old.len() - suffix,
452 count: new.len() - prefix - suffix,
453 })
454}
455
456pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> {
457 let prefix = old
458 .iter()
459 .zip(new)
460 .take_while(|(left, right)| left.key() == right.key())
461 .count();
462 let suffix = old[prefix..]
463 .iter()
464 .rev()
465 .zip(new[prefix..].iter().rev())
466 .take_while(|(left, right)| left.key() == right.key())
467 .count();
468 let mut changed: Vec<usize> = (0..prefix)
469 .filter(|&index| old[index] != new[index])
470 .collect();
471 changed.extend((0..suffix).filter_map(|offset| {
472 let old_index = old.len() - 1 - offset;
473 let new_index = new.len() - 1 - offset;
474 (old[old_index] != new[new_index]).then_some(new_index)
475 }));
476 changed
477}
478
479#[cfg(test)]
480mod tests {
481 use chrono::TimeZone;
482
483 use super::*;
484
485 fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord {
486 MessageRecord {
487 conversation_id: "c".into(),
488 message_id: id.into(),
489 reply_to_id: reply_to.map(str::to_owned),
490 sender_id: Some("u".into()),
491 sender_name: Some("Author".into()),
492 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
493 edited_at: None,
494 deleted: false,
495 body_html: format!("<p>text {id}</p>"),
496 attachments_json: "[]".into(),
497 reactions_json: "[]".into(),
498 mentions_json: "[]".into(),
499 }
500 }
501
502 #[test]
503 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
504 let mut text = record("a", None, 8, 6);
505 text.body_html = "<p>first line</p><p>second</p>".into();
506 assert_eq!(reply_excerpt(&text), "first line");
507 let mut quoted = record("q", None, 8, 6);
508 quoted.body_html = "<blockquote>Jonas<br>old text</blockquote><p>my answer</p>".into();
509 assert_eq!(reply_excerpt(&quoted), "my answer");
510 let mut image = record("b", None, 8, 6);
511 image.body_html = "<img src=\"u\">".into();
512 assert_eq!(reply_excerpt(&image), "Bild");
513 let mut long = record("c", None, 8, 6);
514 long.body_html = format!("<p>{}</p>", "x".repeat(200));
515 assert!(reply_excerpt(&long).ends_with("..."));
516 assert_eq!(
517 reply_excerpt(&long).chars().count(),
518 REPLY_EXCERPT_CHARS + 3
519 );
520 }
521
522 fn context() -> RowContext {
523 RowContext {
524 offset: FixedOffset::east_opt(0).unwrap(),
525 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
526 my_user_id: None,
527 }
528 }
529
530 fn keys(rows: &[Row]) -> Vec<String> {
531 rows.iter().map(|row| row.key().to_owned()).collect()
532 }
533
534 #[test]
535 fn day_header_only_on_first_message_of_a_day() {
536 let records = vec![
537 record("a", None, 8, 6),
538 record("b", None, 9, 6),
539 record("c", None, 9, 7),
540 ];
541 let rows = flat_rows(&records, &context(), false);
542 let headers: Vec<Option<String>> = rows
543 .iter()
544 .map(|row| match row {
545 Row::Message(message) => message.day_header.clone(),
546 Row::LoadOlder | Row::Start(_) => None,
547 })
548 .collect();
549 assert_eq!(
550 headers,
551 vec![Some("Gestern".into()), None, Some("Heute".into())]
552 );
553 }
554
555 #[test]
556 fn load_older_row_only_when_more_exists() {
557 let records = vec![record("a", None, 8, 6)];
558 assert_eq!(
559 keys(&flat_rows(&records, &context(), true))[0],
560 LOAD_OLDER_KEY
561 );
562 assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]);
563 }
564
565 #[test]
566 fn threads_group_replies_by_root() {
567 let records = vec![
568 record("r1", None, 8, 6),
569 record("r2", None, 9, 6),
570 record("x1", Some("r1"), 10, 6),
571 record("x2", Some("r1"), 11, 6),
572 record("orphan", Some("missing"), 12, 6),
573 ];
574 let threads = group_threads(&records);
575 assert_eq!(threads.len(), 2);
576 assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]);
577 assert!(threads[1].reply_ids.is_empty());
578 }
579
580 #[test]
581 fn thread_list_orders_by_last_activity_with_reply_count() {
582 let records = vec![
583 record("r1", None, 8, 6),
584 record("r2", None, 9, 6),
585 record("x1", Some("r1"), 10, 6),
586 ];
587 let rows = thread_list_rows(&records, &context(), false);
588 assert_eq!(keys(&rows), vec!["r2", "r1"]);
589 let Row::Message(last) = &rows[1] else {
590 panic!("message expected")
591 };
592 assert_eq!(last.reply_count, Some(1));
593 assert_eq!(last.open_thread.as_deref(), Some("r1"));
594 }
595
596 #[test]
597 fn thread_view_has_root_then_replies() {
598 let records = vec![
599 record("r1", None, 8, 6),
600 record("r2", None, 9, 6),
601 record("x1", Some("r1"), 10, 6),
602 ];
603 assert_eq!(
604 keys(&thread_rows(&records, "r1", &context())),
605 vec!["r1", "x1"]
606 );
607 }
608
609 #[test]
610 fn reactions_are_counted_in_first_seen_order() {
611 let reaction = |kind: &str| ReactionInfo {
612 reaction_type: kind.into(),
613 user_id: None,
614 user_name: None,
615 };
616 let chips = reaction_chips(
617 &[reaction("heart"), reaction("like"), reaction("heart")],
618 None,
619 );
620 assert_eq!(chips.len(), 2);
621 assert_eq!(chips[0].count, 2);
622 assert_eq!(chips[1].label, reaction_label("like"));
623 }
624
625 fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord {
626 let mut record = record(id, None, hour, day);
627 record.sender_id = Some(sender.into());
628 record.created_at = Utc
629 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
630 .unwrap();
631 record
632 }
633
634 fn series_of(rows: &[Row]) -> Vec<(bool, bool)> {
635 rows.iter()
636 .filter_map(|row| match row {
637 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
638 Row::LoadOlder | Row::Start(_) => None,
639 })
640 .collect()
641 }
642
643 #[test]
644 fn series_joins_same_sender_within_five_minutes() {
645 let records = vec![
646 record_by("a", "ada", 9, 0, 7),
647 record_by("b", "ada", 9, 4, 7),
648 record_by("c", "ada", 9, 20, 7),
649 record_by("d", "bob", 9, 21, 7),
650 record_by("e", "ada", 9, 22, 7),
651 ];
652 let rows = flat_rows(&records, &context(), false);
653 assert_eq!(
654 series_of(&rows),
655 vec![
656 (false, true),
657 (true, false),
658 (false, false),
659 (false, false),
660 (false, false)
661 ]
662 );
663 }
664
665 #[test]
666 fn series_window_ends_exactly_at_the_gap_constant() {
667 let gap = SERIES_GAP_MINUTES as u32;
668 let records = vec![
669 record_by("a", "ada", 9, 0, 7),
670 record_by("b", "ada", 9, gap - 1, 7),
671 record_by("c", "ada", 9, 2 * gap - 1 + gap, 7),
672 ];
673 let rows = flat_rows(&records, &context(), false);
674 assert_eq!(
675 series_of(&rows),
676 vec![(false, true), (true, false), (false, false)]
677 );
678 }
679
680 #[test]
681 fn series_breaks_at_a_new_day() {
682 let records = vec![
683 record_by("a", "ada", 23, 58, 6),
684 record_by("b", "ada", 0, 1, 7),
685 ];
686 let rows = flat_rows(&records, &context(), false);
687 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
688 }
689
690 #[test]
691 fn thread_list_rows_never_join() {
692 let records = vec![
693 record_by("a", "ada", 9, 0, 7),
694 record_by("b", "ada", 9, 1, 7),
695 ];
696 let rows = thread_list_rows(&records, &context(), false);
697 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
698 }
699
700 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
701 let corners = bubble_corners(own, Series { has_prev, has_next });
702 [
703 corners.top_left,
704 corners.top_right,
705 corners.bottom_right,
706 corners.bottom_left,
707 ]
708 }
709
710 #[test]
711 fn corners_match_the_mockup_for_other_senders() {
712 assert_eq!(corners(false, false, false), [4., 14., 14., 14.]);
713 assert_eq!(corners(false, false, true), [4., 14., 14., 4.]);
714 assert_eq!(corners(false, true, true), [4., 14., 14., 4.]);
715 assert_eq!(corners(false, true, false), [4., 14., 14., 14.]);
716 }
717
718 #[test]
719 fn corners_match_the_mockup_for_own_messages() {
720 assert_eq!(corners(true, false, false), [14., 4., 4., 14.]);
721 assert_eq!(corners(true, false, true), [14., 14., 4., 14.]);
722 assert_eq!(corners(true, true, true), [14., 4., 4., 14.]);
723 assert_eq!(corners(true, true, false), [14., 4., 14., 14.]);
724 }
725
726 #[test]
727 fn own_reaction_is_marked() {
728 let reaction = |user: &str| ReactionInfo {
729 reaction_type: "like".into(),
730 user_id: Some(user.into()),
731 user_name: None,
732 };
733 let chips = reaction_chips(&[reaction("x"), reaction("me")], Some("me"));
734 assert!(chips[0].mine);
735 assert!(!reaction_chips(&[reaction("x")], Some("me"))[0].mine);
736 }
737
738 fn strings(values: &[&str]) -> Vec<String> {
739 values.iter().map(|value| (*value).to_owned()).collect()
740 }
741
742 #[test]
743 fn diff_detects_append_prepend_and_replace() {
744 let base = strings(&["a", "b"]);
745 assert_eq!(diff_keys(&base, &base), None);
746 assert_eq!(
747 diff_keys(&base, &strings(&["a", "b", "c"])),
748 Some(Splice {
749 range: 2..2,
750 count: 1
751 })
752 );
753 assert_eq!(
754 diff_keys(&base, &strings(&["x", "a", "b"])),
755 Some(Splice {
756 range: 0..0,
757 count: 1
758 })
759 );
760 assert_eq!(
761 diff_keys(
762 &strings(&["load-older", "a"]),
763 &strings(&["load-older", "x", "y", "a"])
764 ),
765 Some(Splice {
766 range: 1..1,
767 count: 2
768 })
769 );
770 assert_eq!(
771 diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])),
772 Some(Splice {
773 range: 0..1,
774 count: 0
775 })
776 );
777 assert_eq!(
778 diff_keys(&base, &strings(&["x"])),
779 Some(Splice {
780 range: 0..2,
781 count: 1
782 })
783 );
784 }
785
786 #[test]
787 fn changed_indices_find_edited_rows() {
788 let old = flat_rows(
789 &[record("a", None, 8, 6), record("b", None, 9, 6)],
790 &context(),
791 false,
792 );
793 let mut edited = record("b", None, 9, 6);
794 edited.body_html = "<p>changed</p>".into();
795 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
796 assert_eq!(changed_indices(&old, &new), vec![1]);
797 }
798}