Cotton code
538 lines · 18.9 KB · RustRaw
//! `packages/core/__tests__/messages/preview.test.ts`, case for case, plus the//! Node vectors for every string this module produces.use super::*;use crate::messages::GroupEventKind;use crate::messages::{utf16_len, GroupEvent, MessageMedia};use crate::messages::{MessageMediaContact, MessagePoll, MessagePollOption, MessageSystem};fn media(content_type: &str) -> MessageMedia {    MessageMedia::new("k", content_type)}fn source<'a>(body: Option<&'a str>, media: &'a [MessageMedia]) -> PreviewSource<'a> {    PreviewSource {        body,        media,        ..PreviewSource::default()    }}fn poll_meta(question: &str, options: &[(&str, f64)]) -> MessageMeta {    MessageMeta {        poll: Some(MessagePoll {            question: question.to_string(),            options: options                .iter()                .map(|(text, votes)| MessagePollOption {                    text: text.to_string(),                    votes: *votes,                })                .collect(),            ..Default::default()        }),        ..MessageMeta::default()    }}// ── mediaKindOf ──────────────────────────────────────────────────────────────#[test]fn trusts_an_explicit_kind() {    let entry = MessageMedia {        kind: Some(crate::messages::MessageMediaKind::Voice),        ..MessageMedia::new("k", "application/pdf")    };    assert_eq!(media_kind_of(&entry), MessageMediaKind::Voice);}#[test]fn falls_back_to_the_content_type_never_to_a_guess() {    assert_eq!(media_kind_of(&media("image/jpeg")), MessageMediaKind::Image);    assert_eq!(media_kind_of(&media("image/heic")), MessageMediaKind::Image);    assert_eq!(media_kind_of(&media("video/mp4")), MessageMediaKind::Video);    assert_eq!(media_kind_of(&media("audio/mp4")), MessageMediaKind::Audio);    // An imported Ogg Opus is a WhatsApp voice note, with no kind written.    assert_eq!(media_kind_of(&media("audio/ogg")), MessageMediaKind::Voice);    assert_eq!(media_kind_of(&media("audio/ogg; codecs=opus")), MessageMediaKind::Voice);    assert_eq!(media_kind_of(&media("audio/mpeg")), MessageMediaKind::Audio);    assert_eq!(        media_kind_of(&media("application/pdf")),        MessageMediaKind::File    );    assert_eq!(        media_kind_of(&media("application/octet-stream")),        MessageMediaKind::File    );}// ── formatDuration ───────────────────────────────────────────────────────────#[test]fn reads_m_ss_under_an_hour_and_h_mm_ss_over_it() {    assert_eq!(format_duration(0.0), "0:00");    assert_eq!(format_duration(900.0), "0:01");    assert_eq!(format_duration(12_400.0), "0:13");    assert_eq!(format_duration(12_000.0), "0:12");    assert_eq!(format_duration(65_000.0), "1:05");    assert_eq!(format_duration(600_000.0), "10:00");    assert_eq!(format_duration(3_909_000.0), "1:05:09");}#[test]fn never_renders_a_negative_or_a_nan_duration() {    assert_eq!(format_duration(-5.0), "0:00");    assert_eq!(format_duration(f64::NAN), "0:00");}// ── previewForMessage (spec §7.2) ────────────────────────────────────────────#[test]fn uses_the_body_trimmed_on_one_line_capped_at_140() {    assert_eq!(        preview_for_message(&source(Some("  hello  "), &[])),        "hello"    );    assert_eq!(        preview_for_message(&source(Some("line one\nline two"), &[])),        "line one line two"    );    let long = "x".repeat(200);    assert_eq!(        utf16_len(&preview_for_message(&source(Some(&long), &[]))),        140    );}#[test]fn names_the_media_when_there_is_no_caption() {    assert_eq!(        preview_for_message(&source(None, &[media("image/jpeg")])),        "Photo"    );    assert_eq!(        preview_for_message(&source(None, &[media("video/mp4")])),        "Video"    );    let voice = MessageMedia {        kind: Some(crate::messages::MessageMediaKind::Voice),        duration_ms: Some(12_400.0),        ..MessageMedia::new("k", "audio/mp4")    };    assert_eq!(        preview_for_message(&source(None, &[voice])),        "Voice message · 0:13"    );    let voice_no_duration = MessageMedia {        kind: Some(crate::messages::MessageMediaKind::Voice),        ..MessageMedia::new("k", "audio/mp4")    };    assert_eq!(        preview_for_message(&source(None, &[voice_no_duration])),        "Voice message"    );    assert_eq!(        preview_for_message(&source(None, &[media("audio/mpeg")])),        "Audio"    );    let named = MessageMedia {        name: Some("lease.pdf".to_string()),        ..MessageMedia::new("k", "application/pdf")    };    assert_eq!(        preview_for_message(&source(None, &[named])),        "Document · lease.pdf"    );    assert_eq!(        preview_for_message(&source(None, &[media("application/pdf")])),        "Document"    );}#[test]fn joins_the_media_word_to_a_caption_when_both_are_there() {    assert_eq!(        preview_for_message(&source(Some("the view"), &[media("image/jpeg")])),        "Photo · the view"    );}#[test]fn names_an_album_by_its_first_entry() {    let album = [        MessageMedia::new("a", "image/jpeg"),        MessageMedia::new("b", "image/jpeg"),    ];    assert_eq!(preview_for_message(&source(None, &album)), "Photo");}#[test]fn says_a_deleted_message_is_deleted_whatever_else_the_row_still_holds() {    let entries = [media("image/jpeg")];    assert_eq!(        preview_for_message(&PreviewSource {            body: Some("the words that were said"),            media: &entries,            deleted_at: Some("2026-08-26T10:00:00.000Z"),            meta: None,        }),        "This message was deleted"    );}#[test]fn renders_a_system_line_as_itself() {    let meta = MessageMeta {        system: Some(MessageSystem::Flag(true)),        ..MessageMeta::default()    };    assert_eq!(        preview_for_message(&PreviewSource {            body: Some("Ravi left"),            meta: Some(&meta),            ..PreviewSource::default()        }),        "Ravi left"    );}/// The list has no reader to speak to — it is three surfaces wide (row, thread/// denorm, push body) and this module has no catalog. So the body is the/// answer, and the body is written viewer-neutral for exactly this reason: it must/// never say "you" to somebody who did nothing.#[test]fn renders_a_structured_group_event_as_its_neutral_body() {    let meta = MessageMeta {        system: Some(MessageSystem::Event(GroupEvent {            kind: GroupEventKind::Created,            actor: Some("919876500001".to_string()),            subjects: None,            title: None,        })),        ..MessageMeta::default()    };    let line = preview_for_message(&PreviewSource {        body: Some("Asha created the group"),        meta: Some(&meta),        ..PreviewSource::default()    });    assert_eq!(line, "Asha created the group");    let you = regex::Regex::new(r"(?i-u:\byou\b)").expect("compiles");    assert!(!you.is_match(&line));}#[test]fn is_empty_when_there_is_nothing_to_say() {    assert_eq!(preview_for_message(&PreviewSource::default()), "");    assert_eq!(preview_for_message(&source(Some("   "), &[])), "");}// ── messagePreview (the two-argument shim) ───────────────────────────────────#[test]fn keeps_behaving_as_its_callers_expect() {    assert_eq!(message_preview(Some("  hello  "), &[]), "hello");    let long = "x".repeat(200);    assert_eq!(utf16_len(&message_preview(Some(&long), &[])), 140);    assert_eq!(        message_preview(Some(""), &[MessageMedia::new("k", "image/jpeg")]),        "Photo"    );    assert_eq!(message_preview(Some(""), &[]), "");}// ── shouldAdvanceThread ──────────────────────────────────────────────────────#[test]fn lets_a_newer_or_first_row_advance_the_denorm_and_refuses_an_older_one() {    assert!(should_advance_thread(None, "2026-08-23T10:00:00.000Z"));    assert!(should_advance_thread(        Some("2026-08-23T10:00:00.000Z"),        "2026-08-23T11:00:00.000Z"    ));    assert!(should_advance_thread(        Some("2026-08-23T10:00:00.000Z"),        "2026-08-23T10:00:00.000Z"    ));    assert!(!should_advance_thread(        Some("2026-08-23T10:00:00.000Z"),        "2021-03-04T09:00:00.000Z"    ));}// ── messagePreviewText ───────────────────────────────────────────────────────/// An `IMessage` satisfies it as it stands — same rule, the name the UI tracks/// agreed to import.#[test]fn is_the_row_shaped_name_over_a_camel_case_message() {    let empty = MessageMeta::default();    assert_eq!(        message_preview_text(&PreviewSource {            body: Some("  on my way  "),            media: &[],            deleted_at: None,            meta: Some(&empty),        }),        "on my way"    );    assert_eq!(        message_preview_text(&source(None, &[MessageMedia::new("k", "image/jpeg")])),        "Photo"    );    assert_eq!(        message_preview_text(&PreviewSource {            body: Some("gone"),            deleted_at: Some("2026-08-26T10:00:00.000Z"),            ..PreviewSource::default()        }),        "This message was deleted"    );}// ── a shared contact card and an imported poll ───────────────────────────────/// Both active vCard MIME spellings identify a contact card.#[test]fn reads_a_vcf_as_a_contact_from_its_content_type() {    assert_eq!(        media_kind_of(&media("text/vcard")),        MessageMediaKind::Contact    );    assert_eq!(        media_kind_of(&media("text/x-vcard")),        MessageMediaKind::Contact    );}#[test]fn names_who_the_card_is_not_what_the_file_is_called() {    let card = MessageMedia {        name: Some("Anita.vcf".to_string()),        contact: Some(MessageMediaContact {            name: "Anita Rao".to_string(),            phones: vec!["+910123462001".to_string()],            emails: vec![],            org: None,        }),        ..MessageMedia::new("k", "text/vcard")    };    assert_eq!(        preview_for_message(&source(None, &[card])),        "Contact: Anita Rao"    );}#[test]fn falls_back_to_the_filename_for_a_card_nothing_could_be_read_out_of() {    let card = MessageMedia {        name: Some("Anita.vcf".to_string()),        ..MessageMedia::new("k", "text/vcard")    };    assert_eq!(        preview_for_message(&source(None, &[card])),        "Contact: Anita.vcf"    );}#[test]fn says_a_polls_question_rather_than_the_exports_own_poll_paragraph() {    let meta = poll_meta("Which day works?", &[("Thursday", 3.0), ("Friday", 1.0)]);    assert_eq!(        preview_for_message(&PreviewSource {            body: Some(                "POLL:\nWhich day works?\nOPTION: Thursday (3 votes)\nOPTION: Friday (1 vote)"            ),            meta: Some(&meta),            ..PreviewSource::default()        }),        "Poll · Which day works?"    );}#[test]fn still_lets_a_deleted_row_outrank_a_poll() {    let meta = poll_meta("Which day?", &[]);    assert_eq!(        preview_for_message(&PreviewSource {            body: Some("POLL:\nWhich day?\nOPTION: A (1 vote)\nOPTION: B (0 votes)"),            deleted_at: Some("2026-09-05T00:00:00.000Z"),            meta: Some(&meta),            ..PreviewSource::default()        }),        "This message was deleted"    );}// ── a blank line the text export could not render ────────────────────────────/// `[unsupported message]` is the importer's marker, addressed to whoever debugs/// an import — never to the person reading their own chat list.#[test]fn says_what_it_is_in_words_not_in_brackets() {    assert_eq!(        preview_for_message(&source(Some("[unsupported message]"), &[])),        not_in_export_preview()    );    assert_eq!(        message_preview(Some("[unsupported message]"), &[]),        not_in_export_preview()    );}/// The rule is the whole body, because somebody quoting the marker in a sentence/// is saying something and a list must show what they said.#[test]fn leaves_a_message_that_merely_contains_the_words_alone() {    assert_eq!(        preview_for_message(&source(            Some("why does it say [unsupported message] here?"),            &[]        )),        "why does it say [unsupported message] here?"    );}#[test]fn prefers_the_attachments_own_word_when_the_row_somehow_carries_one() {    assert_eq!(        preview_for_message(&source(            Some("[unsupported message]"),            &[MessageMedia::new("k", "image/jpeg")]        )),        "Photo · [unsupported message]"    );}#[test]fn still_lets_a_deleted_row_outrank_the_marker() {    assert_eq!(        preview_for_message(&PreviewSource {            body: Some("[unsupported message]"),            deleted_at: Some("2026-09-05T00:00:00.000Z"),            ..PreviewSource::default()        }),        "This message was deleted"    );}// ── Node vectors ─────────────────────────────────────────────────────────────/// First printed by running the TypeScript (`vec_preview.ts`); since 23 Nov 2026/// a length rounds UP (see `format_duration`), so the fractional ones moved.////// The interesting cases: a part of a second counts as a second, a fractional/// MILLISECOND does not (0.4 ms is nothing), exactly 3 600 000 crosses into the/// `h:mm:ss` form, and a duration past a day keeps counting hours rather than/// growing a day field.#[test]fn node_vectors_for_format_duration() {    assert_eq!(format_duration(999.0), "0:01");    assert_eq!(format_duration(1000.0), "0:01");    assert_eq!(format_duration(1000.4), "0:01");    assert_eq!(format_duration(59_999.0), "1:00");    assert_eq!(format_duration(3_599_999.0), "1:00:00");    assert_eq!(format_duration(3_600_000.0), "1:00:00");    assert_eq!(format_duration(90_061_000.0), "25:01:01");    assert_eq!(format_duration(f64::INFINITY), "0:00");    assert_eq!(format_duration(0.4), "0:00");}/// And the preview line itself, where the cap is the thing to pin: the TypeScript/// cuts at 140 UTF-16 CODE UNITS, so a string of astral emoji is cut at 70 of/// them and a Rust port counting `chars()` would keep 140.#[test]fn node_vectors_for_the_140_unit_cap() {    let emoji = "\u{1f600}".repeat(100);    let cut = preview_for_message(&source(Some(&emoji), &[]));    assert_eq!(utf16_len(&cut), 140);    assert_eq!(cut.chars().count(), 70);    assert_eq!(cut, "\u{1f600}".repeat(70));    // A caption long enough to be cut mid-word keeps the media word and its    // separator, because the cut happens AFTER they are joined.    let caption = "a".repeat(200);    let line = preview_for_message(&source(        Some(&caption),        &[MessageMedia::new("k", "image/jpeg")],    ));    assert_eq!(utf16_len(&line), 140);    assert_eq!(line, format!("Photo · {}", "a".repeat(132)));    // A poll question is capped after the prefix too.    let meta = poll_meta(&"q".repeat(200), &[]);    let poll_line = preview_for_message(&PreviewSource {        body: Some("POLL:"),        meta: Some(&meta),        ..PreviewSource::default()    });    assert_eq!(utf16_len(&poll_line), 140);    assert_eq!(poll_line, format!("Poll · {}", "q".repeat(133)));}/// Whitespace: the collapse is ECMAScript's `\s`, which trims a BOM and does NOT/// trim a NEL. Both directions are Node's answer, not Rust's `str::trim`'s.#[test]fn node_vectors_for_the_one_line_collapse() {    assert_eq!(        preview_for_message(&source(Some("\u{feff}hello\u{feff}"), &[])),        "hello"    );    assert_eq!(        preview_for_message(&source(Some("\u{85}hello"), &[])),        "\u{85}hello"    );    assert_eq!(preview_for_message(&source(Some("a \t\n\r b"), &[])), "a b");    assert_eq!(        preview_for_message(&source(Some("\u{a0}spaced\u{2028}out\u{a0}"), &[])),        "spaced out"    );}/// RULE: A stored chat preview clips plain words, never Markdown syntax, so a link crossing the preview limit cannot leak an opening bracket.#[test]fn chat_previews_strip_markdown_before_clipping() {    let prefix = "a".repeat(130);    let body = format!("{prefix} [example.com](https://example.com/hours) `command`");    let preview = message_preview(Some(&body), &[]);    assert!(!preview.contains(['[', ']', '`', '(']), "{preview}");    assert!(preview.starts_with(&prefix));}fn marked(kind: &str) -> MessageMeta {    let mut meta = MessageMeta::default();    meta.extra.insert(crate::messages::media_only::MEDIA_ONLY_META.into(), serde_json::Value::from(kind));    meta}/// RULE: A media-only message keeps an empty body; its list line is the kit's word for the kind its mark names, never words from the row.#[test]fn a_media_only_message_reads_as_its_marks_kit_line() {    let meta = marked("voice");    let line = preview_for_message(&PreviewSource { body: Some(""), meta: Some(&meta), ..PreviewSource::default() });    assert_eq!(line, crate::lines::resolve("conversation", "preview.voice", &[]));    let meta = marked("sticker");    let line = preview_for_message(&PreviewSource { body: None, meta: Some(&meta), ..PreviewSource::default() });    assert_eq!(line, "Sticker");}/// RULE: An old row whose body is a left-behind label and that carries the mark reads exactly as a new row with an empty body does.#[test]fn an_old_rows_left_behind_label_reads_as_an_empty_body() {    let meta = marked("image");    let old = preview_for_message(&PreviewSource { body: Some("Photo"), meta: Some(&meta), ..PreviewSource::default() });    let new = preview_for_message(&PreviewSource { body: Some(""), meta: Some(&meta), ..PreviewSource::default() });    assert_eq!(old, new);    let placeholder = preview_for_message(&PreviewSource {        body: Some("conversation.preview.photo"),        meta: Some(&meta),        ..PreviewSource::default()    });    assert_eq!(placeholder, new, "an old token body reads as an empty body");    let pictures = [media("image/jpeg")];    let with_bytes = preview_for_message(&PreviewSource { body: Some("Photo"), media: &pictures, meta: Some(&meta), ..PreviewSource::default() });    assert_eq!(with_bytes, "Photo", "never Photo · Photo");    let caption = preview_for_message(&PreviewSource { body: Some("Lunch"), media: &pictures, meta: Some(&meta), ..PreviewSource::default() });    assert_eq!(caption, "Photo · Lunch", "words beside media are kept");    assert_eq!(preview_for_message(&source(Some("Photo"), &[])), "Photo", "an unmarked Photo is somebody's word");}