366 lines · 21.3 KB · RustRaw
use super::can::Can;use super::compose;use super::lay::{self, lay, Laid, Slot};use super::list::{self, Listed};use super::shapes::*;const MIN: i64 = 60_000;fn m(id: &str, sender: &str, at_min: i64, day: i64) -> Laid { Laid { id: id.into(), sender: sender.into(), at_ms: at_min * MIN, day, event: false }}fn heads_tails(slots: &[Slot]) -> Vec<(usize, bool, bool)> { slots.iter().filter_map(|s| match s { Slot::Message { index, head, tail, .. } => Some((*index, *head, *tail)), _ => None }).collect()}#[test]fn one_senders_run_has_one_head_and_one_tail() { let page = [m("a", "x", 0, 1), m("b", "x", 1, 1), m("c", "x", 2, 1), m("d", "me", 3, 1)]; let slots = lay(&page, None, None, None); assert_eq!(slots[0], Slot::Day { index: 0 }); assert_eq!(heads_tails(&slots), vec![(0, true, false), (1, false, false), (2, false, true), (3, true, true)]);}#[test]fn a_gap_a_day_and_an_event_break_a_run() { let mut event = m("e", "x", 3, 1); event.event = true; let page = [m("a", "x", 0, 1), m("b", "x", 0 + 6, 1), event, m("c", "x", 4 + 6, 1), m("d", "x", 11, 2)]; let slots = lay(&page, None, None, None); let days: Vec<usize> = slots.iter().filter_map(|s| match s { Slot::Day { index } => Some(*index), _ => None }).collect(); assert_eq!(days, vec![0, 4]); assert!(heads_tails(&slots).iter().all(|(_, head, tail)| *head && *tail), "{slots:?}");}fn faces(slots: &[Slot]) -> Vec<usize> { slots.iter().filter_map(|s| match s { Slot::Message { index, face: true, .. } => Some(*index), _ => None }).collect()}// RULE: a sender's picture stands once over their unbroken words in a day, however long they paused between// lines (an imported chat's lines are often minutes apart); another sender, an event, a new day or the unread// divider shows it again. The pause still starts a new run for spacing and tails.#[test]fn the_picture_stands_once_over_one_senders_words() { let mut event = m("e", "", 40, 1); event.event = true; let page = [m("a", "x", 0, 1), m("b", "x", 9, 1), m("c", "x", 30, 1), m("d", "y", 31, 1), m("f", "x", 32, 1), event, m("g", "x", 41, 1), m("h", "x", 42, 2)]; let slots = lay(&page, None, None, None); assert_eq!(faces(&slots), vec![0, 3, 4, 6, 7], "{slots:?}"); assert_eq!(heads_tails(&slots)[1], (1, true, true), "a pause still starts a run"); // The page above holds the stretch's start: no picture again on this page. let above = m("z", "x", 0, 1); assert!(faces(&lay(&[m("a", "x", 20, 1)], Some(&above), None, None)).is_empty()); assert_eq!(faces(&lay(&page[..3], None, None, Some("b"))), vec![0, 1], "the unread divider shows it again");}#[test]fn pages_meet_without_a_seam() { let above = m("z", "x", 0, 1); let below = m("c", "x", 3, 1); let page = [m("a", "x", 1, 1), m("b", "x", 2, 1)]; let slots = lay(&page, Some(&above), Some(&below), None); // No divider: the day's divider stands over `z`, in the page above. assert!(!slots.iter().any(|s| matches!(s, Slot::Day { .. }))); assert_eq!(heads_tails(&slots), vec![(0, false, false), (1, false, false)]);}#[test]fn the_unread_divider_breaks_a_run_even_on_the_next_page() { let page = [m("a", "x", 0, 1), m("b", "x", 1, 1), m("c", "x", 2, 1)]; let slots = lay(&page, None, None, Some("b")); assert!(slots.contains(&Slot::Unread { index: 1 })); assert_eq!(heads_tails(&slots), vec![(0, true, true), (1, true, false), (2, false, true)]); let below = m("d", "x", 3, 1); let slots = lay(&page, None, Some(&below), Some("d")); assert_eq!(heads_tails(&slots).last(), Some(&(2, false, true)));}#[test]fn initials_tints_lengths_and_sizes() { assert_eq!(lay::initials("asha rao"), "AR"); assert_eq!(lay::initials("Example"), "E"); // A number is no name: no digit stands for a person, only the neutral glyph (CALLS WALK 1 showed "1" for +1555…). assert_eq!(lay::initials("+91 98"), "#"); assert_eq!(lay::initials("+15550194427"), "#"); assert_eq!(lay::initials("Asha 2nd"), "AN"); assert_eq!(lay::initials("Room 42"), "R"); assert_eq!(lay::initials(" "), "#"); assert_eq!(lay::tint("thread-1"), lay::tint("thread-1")); assert!(lay::tint("x") < TINTS); assert_eq!(lay::length(12_000.0), "0:12"); assert_eq!(lay::length(3_909_000.0), "1:05:09"); assert_eq!(lay::size(2_516_582.0), "2.4 MB"); assert_eq!(lay::size(300.0), "1 KB");}#[test]fn only_what_a_source_can_do_is_offered() { let cotton = Can::of("cotton", false); assert_eq!(cotton.message_actions(true, true, false, false, true), ["reply", "react", "copy", "forward", "edit", "pin", "delete", "select"]); assert_eq!(cotton.message_actions(false, true, false, true, true), ["reply", "react", "copy", "forward", "unpin", "select"]); let imported = Can::of("whatsapp", false); assert!(!imported.send && !imported.reply); assert_eq!(imported.message_actions(true, true, false, false, true), ["copy", "forward", "pin", "select"]); assert_eq!(imported.message_actions(true, true, true, false, true), ["select"]); assert!(Can::of("instagram", true).reply);}#[test]fn the_button_is_send_with_text_and_mic_only_where_voice_sends() { let cotton = Can::of("cotton", false); assert_eq!(compose::button(&cotton, " ", false), Button::Mic, "a Cotton chat records a voice message"); assert_eq!(compose::button(&Can::of("instagram", true), " ", false), Button::Idle); assert_eq!(compose::button(&cotton, "hi", false), Button::Send); assert_eq!(compose::button(&cotton, "", true), Button::Idle, "an edit records nothing"); let lines = list::lines(); let quoted = compose::Quoted { message: "m1".into(), sender: "Asha".into(), line: "see you".into() }; let a = compose::answer(&lines, "t", &cotton, "ok", Some("ed), None, 0); let strip = a.strip.expect("a reply strip"); assert_eq!((strip.kind, strip.title.as_str(), strip.cancel.as_str()), (StripKind::Reply, "Reply to Asha", "Cancel")); assert_eq!((a.placeholder.as_str(), a.button_label.as_str()), ("Message", "Send")); let e = compose::answer(&lines, "t", &cotton, "ok", Some("ed), Some("ed), 0); assert_eq!(e.strip.expect("an edit strip").kind, StripKind::Edit); assert_eq!(e.button_label, "Save"); assert!(!e.attach); let waiting = compose::answer(&lines, "t", &cotton, "", None, None, 1); assert_eq!((waiting.button, waiting.send_enabled, waiting.button_label.as_str()), (Button::Send, true, "Send"), "a picture waiting sends with nothing written"); assert_eq!(compose::answer(&lines, "t", &Can::of("whatsapp", false), "", None, None, 1).button, Button::Idle, "nothing is attached where nothing sends"); assert_eq!(a.place, None, "no mark unless the caller says where it goes");}/// RULE (FEEDBACK-2 A): where a message goes is said in words before it is sent, the same mark on the header and by/// the field, from the route's place.#[test]fn the_place_mark_says_where_a_message_goes() { let lines = list::lines(); let cotton = compose::place_mark(&lines, crate::messages::send::Route::Cotton.place()); assert_eq!((cotton.id.as_str(), cotton.mark.as_str()), ("cotton", "on Cotton")); let whatsapp = compose::place_mark(&lines, "whatsapp"); assert_eq!((whatsapp.id.as_str(), whatsapp.mark.as_str()), ("whatsapp", "via WhatsApp")); let mut a = compose::answer(&lines, "t", &Can::of("cotton", false), "", None, None, 0); a.place = Some(whatsapp); assert_eq!(serde_json::to_value(&a).unwrap()["place"], serde_json::json!({ "id": "whatsapp", "mark": "via WhatsApp" }));}#[test]fn the_fan_is_never_trimmed_and_names_each_source_the_person_has() { let rows = [ Listed { group: false, source: "cotton".into(), archived: false, unread: true, waiting: true }, Listed { group: true, source: "whatsapp".into(), archived: false, unread: false, waiting: false }, Listed { group: false, source: "whatsapp".into(), archived: true, unread: true, waiting: true }, ]; let counts = list::counts(&rows); assert_eq!((counts.all, counts.people, counts.groups, counts.unread, counts.archived), (2, 1, 1, 1, 1)); let fan = list::fan(&list::lines(), &counts, &Filter::Unread); let ids: Vec<&str> = fan.iter().map(|t| t.id.as_str()).collect(); assert_eq!(ids, ["all", "people", "groups", "unread", "archived", "cotton", "whatsapp", "calls", "account"]); assert!(fan[3].on && !fan[0].on); assert_eq!(fan[6].label, "WhatsApp"); assert!(list::keeps(&Filter::Archived, &rows[2]) && !list::keeps(&Filter::All, &rows[2])); assert!(list::keeps(&Filter::Source("whatsapp".into()), &rows[1])); assert_eq!(Filter::parse(Some("sms")), Filter::Source("sms".into()));}// FEEDBACK1 item 6 (owner, 22 Nov 2026): "Waiting on you" becomes Unread, which lists only the// unread chats (unread messages, or marked unread by hand); the last word being theirs is not a filter.#[test]fn the_filters_are_all_unread_and_groups_and_unread_keeps_only_unread_chats() { let rows = [ Listed { group: false, source: "cotton".into(), archived: false, unread: true, waiting: false }, Listed { group: true, source: "cotton".into(), archived: false, unread: false, waiting: true }, Listed { group: false, source: "cotton".into(), archived: true, unread: true, waiting: true }, ]; let counts = list::counts(&rows); assert_eq!(counts.unread, 1, "an archived conversation is not counted unread"); let chips = list::filters(&list::lines(), &counts, &Filter::Unread); let said: Vec<(&str, &str, Option<u32>, bool)> = chips.iter().map(|c| (c.id.as_str(), c.label.as_str(), c.count, c.on)).collect(); assert_eq!(said, [("all", "All", None, false), ("unread", "Unread", Some(1), true), ("groups", "Groups", None, false)]); assert!(list::keeps(&Filter::Unread, &rows[0]) && !list::keeps(&Filter::Unread, &rows[1]) && !list::keeps(&Filter::Unread, &rows[2]), "their last word alone is not unread"); assert_eq!(Filter::parse(Some("unread")), Filter::Unread); assert_eq!(list::empty(&list::lines(), &Filter::Unread, false), "Nothing unread."); let none = list::filters(&list::lines(), &list::counts(&rows[1..2]), &Filter::All); assert_eq!(none[1].count, None, "no count stands when nothing is unread"); // A phone that still asks Waiting on you is answered as before. assert_eq!(Filter::parse(Some("waiting")), Filter::Waiting);}// FEEDBACK1 item 6: a chat held offers Mark as unread (or Mark as read), so a person can leave it to answer later.#[test]fn a_chat_held_offers_mark_as_unread_or_read_then_the_swipes_acts() { let lines = list::lines(); let held = list::hold(&lines, false, false, false, false, "Asha"); let said: Vec<(&str, &str)> = held.iter().map(|a| (a.act.as_str(), a.label.as_str())).collect(); assert_eq!(said, [("unread", "Mark as unread"), ("pinChat", "Pin"), ("mute", "Mute"), ("archive", "Archive"), ("deleteChat", "Delete")]); assert!(held[4].confirm.as_deref().is_some_and(|c| c.contains("Asha")), "Delete asks first, naming them"); let unread = list::hold(&lines, true, true, true, true, "Asha"); assert_eq!(unread.iter().map(|a| a.label.as_str()).collect::<Vec<_>>(), ["Mark as read", "Unpin", "Unmute", "Unarchive", "Delete"]);}// RULE (owner, Comms 28): a chat row swipes to exactly one act a side: right Unread (or Read), left Archive (or// Unarchive). Pin, Mute and Delete are the long press's alone.#[test]fn a_chat_row_swipes_one_act_a_side() { let lines = list::lines(); let acts = |s: &[Swipe]| s.iter().map(|a| (a.act.clone(), a.label.clone())).collect::<Vec<_>>(); let (leading, trailing) = list::swipes(&lines, false, false, false, false, "Asha"); assert_eq!(acts(&leading), [("unread".to_string(), "Unread".to_string())]); assert_eq!(acts(&trailing), [("archive".to_string(), "Archive".to_string())]); let (leading, trailing) = list::swipes(&lines, true, true, true, true, "Asha"); assert_eq!(acts(&leading), [("read".to_string(), "Read".to_string())]); assert_eq!(acts(&trailing), [("unarchive".to_string(), "Unarchive".to_string())]); let held = list::hold(&lines, false, false, false, false, "Asha"); for act in ["pinChat", "mute", "deleteChat"] { assert!(held.iter().any(|a| a.act == act), "{act} stays in the long press"); }}#[test]fn shapes_cross_the_wire_in_camel_case() { let item = Item::Day { label: "Today".into(), numeral: None, words: None }; assert_eq!(serde_json::to_value(&item).unwrap(), serde_json::json!({ "item": "day", "label": "Today" })); let row = ListRow { thread: "t".into(), name: "Asha".into(), group: false, source: "cotton".into(), picture: Picture { photo: None, initials: "A".into(), tint: 3 }, last_line: Some(LastLine { text: "hi".into(), sender: None, mark: Some(Mark::Photo), mine: true, tick: Some(Tick::Read), state: None }), when: Some("09:41".into()), unread: 0, marked_unread: false, pinned: true, muted: false, archived: false, typing: None, draft: None, leading: vec![], trailing: vec![], badge: None, sendable: true, hold: vec![], }; let v = serde_json::to_value(&row).unwrap(); assert_eq!(v["lastLine"]["tick"], "read"); assert_eq!(v["lastLine"]["mark"], "photo"); assert_eq!(v["markedUnread"], false); assert!(ACTS.contains(&"pinChat")); assert_eq!((badge(3).as_str(), badge(999).as_str(), badge(1000).as_str()), ("3", "999", "999+"));}#[test]fn every_theme_carries_every_token_in_both_appearances() { use super::themes::{colours, known, themes, TOKENS}; let all = themes(); assert!(known(&all.defaults.light_theme) && known(&all.defaults.dark_theme)); assert_eq!((all.tints.light.len(), all.tints.dark.len(), all.names.light.len(), all.names.dark.len()), (TINTS as usize, TINTS as usize, TINTS as usize, TINTS as usize)); let lines = list::lines(); for theme in &all.themes { for appearance in [&theme.light, &theme.dark] { let keys: Vec<&str> = appearance.keys().map(String::as_str).collect(); let mut wanted: Vec<&str> = TOKENS.to_vec(); wanted.sort(); assert_eq!(keys, wanted, "{}", theme.id); assert!(appearance.values().all(|c| c.starts_with('#') && (c.len() == 7 || c.len() == 9)), "{}", theme.id); } assert!(matches!(theme.ground.as_str(), "plain" | "weave"), "{}", theme.id); assert!(lines.say(&format!("app.theme.names.{}", theme.id), &[]).is_some_and(|n| !n.is_empty()), "{} has a name", theme.id); assert_eq!(colours(theme, true)["tint.7"], all.tints.dark[7]); }}// RULE: a file's own name is never drawn as its caption: an export's document line leaves the name (without its// staging number, sometimes with a page count) where a caption stands; real words beside a picture stay.#[test]fn a_file_name_is_not_a_caption() { use super::bubble::{text_of, Row}; use crate::messages::{MessageMedia, MessageMeta}; fn said(body: &str, media: &[MessageMedia], meta: Option<&MessageMeta>) -> Option<String> { text_of(&Row { body: Some(body), media, meta, deleted_at: None }) } let file = |mime: &str, name: Option<&str>| MessageMedia { key: "w/messages/t/ab".into(), content_type: mime.into(), name: name.map(str::to_string), ..MessageMedia::default() }; let shot = [file("image/png", Some("00000011-Screenshot 2026-11-03 at 10.15.22.png"))]; assert_eq!(said("Screenshot 2026-11-03 at 10.15.22.png", &shot, None), None); assert_eq!(said("\u{200e}SCREENSHOT 2026-11-03 at 10.15.22.png ", &shot, None), None); assert_eq!(said("00000011-Screenshot 2026-11-03 at 10.15.22.png", &shot, None), None); assert_eq!(said("The view from the top", &shot, None).as_deref(), Some("The view from the top")); assert_eq!(said("[attachment: Screenshot 2026-11-03 at 10.15.22.png]", &shot, None), None, "the importer's marker beside the picture"); let meta: MessageMeta = serde_json::from_value(serde_json::json!({ "attachment": { "name": "00000012-Plan.pdf" } })).unwrap(); assert_eq!(said("Plan.pdf \u{2022} 3 pages", &[file("application/pdf", None)], Some(&meta)), None, "the importer's record names it too"); // Words with no file drawn are the message, whatever they say. assert_eq!(said("Screenshot 2026-11-03 at 10.15.22.png", &[], None).as_deref(), Some("Screenshot 2026-11-03 at 10.15.22.png"));}// ── the voice player's bars (assets/design/chat/voice-player.html, "The waveform rule") ──// RULE: Every voice message draws 36 bars whatever its length: more samples are gathered by their peaks, so a// loud word never disappears; fewer are stretched, each bar taking the sample under it.#[test]fn a_voice_messages_bars_are_36_gathered_by_their_peaks_or_stretched() { use super::bubble::{bars, BARS}; assert_eq!(BARS, 36); // 64 samples, one loud word among quiet ones: its bar is full height. let mut long = vec![0.2; 64]; long[37] = 0.9; let drawn = bars(&long); assert_eq!(drawn.len(), 36); assert_eq!(drawn.iter().filter(|&&b| b == 1.0).count(), 1, "the loud word stands: {drawn:?}"); assert!(drawn.iter().all(|&b| (0.0..=1.0).contains(&b))); // Each bar is the highest of its share: bar i covers samples floor(i*64/36)..floor((i+1)*64/36). let at = (0..36).find(|&i| (i * 64 / 36..((i + 1) * 64 / 36).max(i * 64 / 36 + 1)).contains(&37)).unwrap(); assert_eq!(drawn[at], 1.0); // Nine samples (a two-second note): stretched, each bar the sample under it, in order. let short = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0]; let drawn = bars(&short); assert_eq!(drawn.len(), 36); assert_eq!(&drawn[..4], &[0.1, 0.1, 0.1, 0.1]); assert_eq!(drawn[35], 1.0); assert!(drawn.windows(2).all(|w| w[0] <= w[1]), "the shape keeps its order: {drawn:?}");}// RULE: The bars are scaled to the note's own loudest sample, so a quiet speaker's note is no flatter than a loud// one's; a silent note (its loudest under 0.05) draws every bar at its least.#[test]fn a_voice_messages_bars_are_scaled_to_its_loudest_and_silence_is_flat() { use super::bubble::bars; let loud: Vec<f64> = (0..64).map(|i| if i % 2 == 0 { 0.8 } else { 0.4 }).collect(); let quiet: Vec<f64> = loud.iter().map(|v| v / 4.0).collect(); assert_eq!(bars(&loud), bars(&quiet), "a quiet speaker's note has the same shape"); assert_eq!(bars(&loud).iter().copied().fold(0.0, f64::max), 1.0); assert!(bars(&[0.01, 0.04, 0.02]).iter().all(|&b| b == 0.0), "silence"); assert!(bars(&[]).iter().all(|&b| b == 0.0)); assert!(bars(&[f64::NAN, 2.0, -1.0]).iter().all(|b| (0.0..=1.0).contains(b)), "out of range is clamped");}// RULE: The chat list's line and the bubble say a note's length alike (owner's lane, 23 Nov 2026: a 2.6 s note// read "Voice message · 0:02" in the list and 0:03 in its chat). Both round up from durationMs, as the players'// countdowns do.#[test]fn the_list_line_and_the_bubble_say_the_same_length() { use super::bubble::{media_parts, Row}; use crate::messages::display::message_line; use crate::messages::preview::PreviewSource; use crate::messages::MessageMedia; for (ms, said) in [(2_400.0, "0:03"), (2_500.0, "0:03"), (2_600.0, "0:03"), (59_500.0, "1:00"), (2_000.0, "0:02"), (42_000.0, "0:42")] { // The list names a length for a voice message only (audio and video lines are their word alone); an imported // Ogg Opus with no kind written is a voice message too. for kind in [Some(crate::constants::MessageMediaKind::Voice), None] { let content_type = if kind.is_some() { "audio/mp4" } else { "audio/ogg" }; let media = [MessageMedia { key: "k".into(), content_type: content_type.into(), kind, duration_ms: Some(ms), ..MessageMedia::default() }]; let bubble = media_parts(&Row { body: None, media: &media, meta: None, deleted_at: None })[0].length.clone().unwrap(); let line = message_line(&PreviewSource { body: None, media: &media, ..PreviewSource::default() }); assert_eq!(bubble, said, "{kind:?} {ms} ms in the bubble"); assert!(line.ends_with(&format!(" · {said}")), "{kind:?} {ms} ms in the list: {line}"); } }}// RULE: A voice part carries its length as a number and its bars; a part with no waveform carries no bars (the// player draws its thin track); played is absent unless false.#[test]fn a_voice_part_carries_its_length_in_ms_and_its_bars() { use super::bubble::{media_parts, Row}; use crate::messages::MessageMedia; let with = MessageMedia { key: "k".into(), content_type: "audio/mp4".into(), kind: Some(crate::constants::MessageMediaKind::Voice), duration_ms: Some(42_400.0), waveform: Some(vec![0.5; 64]), ..MessageMedia::default() }; let without = MessageMedia { waveform: None, ..with.clone() }; let media = [with, without]; let parts = media_parts(&Row { body: None, media: &media, meta: None, deleted_at: None }); assert_eq!(parts[0].duration_ms, Some(42_400)); assert_eq!(parts[0].length.as_deref(), Some("0:43")); assert_eq!(parts[0].bars.as_ref().map(Vec::len), Some(36)); assert!(parts[1].bars.is_none()); let json = serde_json::to_value(&parts[0]).unwrap(); assert_eq!(json["durationMs"], 42_400); assert!(json.get("played").is_none(), "played is absent unless false: {json}"); let mut unplayed = parts[0].clone(); unplayed.played = false; assert_eq!(serde_json::to_value(&unplayed).unwrap()["played"], false); let back: MediaPart = serde_json::from_value(json).unwrap(); assert!(back.played, "absent reads as played");}