Cotton code
430 lines · 24.9 KB · RustRaw
//! The Bear-like Notes on a phone that never signed in (CONTRACT.md): the//! side page, pins, the new views and rows, search words, find, note links//! kept right on a rename, info, tag icons, settings, the delete ask. Every//! note is invented.use serde_json::{json, Value};use crate::handle::{CottonHandle, OpenConfig, OpenMode};use crate::methods::dispatch;fn phone(dir: &tempfile::TempDir) -> CottonHandle {    let manifest = json!({        "genesis": "personal", "flavour": "notes", "name": "Cotton Notes", "databases": "single", "database": "personal",        "business": { "server": { "real": "https://cottondb.com", "dev": "https://dev.example.invalid" } },        "fan": { "home": false, "tools": false, "opens": "notebook" }, "kit": "notes", "ground": "blank"    });    let handle = CottonHandle::open(OpenConfig {        mode: OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(manifest),    })    .expect("an open core");    dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started on the phone");    handle}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}fn write(handle: &CottonHandle, text: &str) -> String {    let id = ask(handle, "notes.new", json!({}))["id"].as_str().unwrap().to_string();    ask(handle, "notes.edit", json!({ "id": id, "text": text }));    id}fn ids(answer: &Value) -> Vec<String> {    answer["rows"].as_array().unwrap().iter().map(|row| row["id"].as_str().unwrap().to_string()).collect()}fn list(handle: &CottonHandle, request: Value) -> Value {    ask(handle, "notes.list", request)}fn body(handle: &CottonHandle, id: &str) -> String {    ask(handle, "notes.open", json!({ "id": id }))["text"].as_str().unwrap().to_string()}#[test]fn the_side_page_answers_places_tags_lists_and_the_foot_in_one() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let garden = write(&phone, "# Garden\nBeds #home/garden\n- [ ] dig\n- [x] seed");    let _work = write(&phone, "# Plans\n#work and #work/plans");    let _loose = write(&phone, "# Loose\nNo tag here");    let binned = write(&phone, "# Old\n#work");    ask(&phone, "notes.bin", json!({ "id": binned }));    let side = ask(&phone, "notes.side", json!({}));    let count = |id: &str| side["places"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap()["count"].as_u64().unwrap();    assert_eq!((count("all"), count("pinned"), count("todo"), count("today"), count("untagged")), (3, 0, 1, 3, 1));    let labels: Vec<&str> = side["places"].as_array().unwrap().iter().map(|p| p["label"].as_str().unwrap()).collect();    assert_eq!(labels, ["Notes", "Pinned", "To-do", "Today", "Untagged"]);    let foot: Vec<(&str, u64)> = side["foot"].as_array().unwrap().iter().map(|p| (p["id"].as_str().unwrap(), p["count"].as_u64().unwrap())).collect();    assert_eq!(foot, [("archive", 0), ("bin", 1)]);    let tree = side["tags"]["tree"].as_array().unwrap();    let home = tree.iter().find(|t| t["tag"] == "home").unwrap();    assert_eq!(home["icon"], "tag_home");    assert_eq!(home["children"][0]["icon"], "tag_garden");    assert_eq!(home["children"][0]["list"], json!({ "view": "tag", "tag": "home/garden" }));    // A root tag pinned goes first; a nested one is refused.    let pinned = ask(&phone, "notes.pin_tag", json!({ "tag": "home", "pinned": true }));    assert_eq!(pinned["tags"]["tree"][0]["tag"], "home");    assert_eq!(pinned["tags"]["tree"][0]["pinned"], true);    assert!(dispatch(&phone, "notes.pin_tag", &json!({ "tag": "home/garden" })).is_err());    // A chosen icon wins and goes back with null.    let chosen = ask(&phone, "notes.tag_icon", json!({ "tag": "work", "icon": "tag_star" }));    let work = chosen["tags"]["tree"].as_array().unwrap().iter().find(|t| t["tag"] == "work").unwrap().clone();    assert_eq!((work["icon"].as_str(), work["icon_chosen"].as_bool()), (Some("tag_star"), Some(true)));    let back = ask(&phone, "notes.tag_icon", json!({ "tag": "work", "icon": null }));    assert_eq!(back["tags"]["tree"].as_array().unwrap().iter().find(|t| t["tag"] == "work").unwrap()["icon"], "tag_work");    assert!(dispatch(&phone, "notes.tag_icon", &json!({ "tag": "work", "icon": "no_such" })).is_err());    assert!(ask(&phone, "notes.tag_icons", json!({}))["icons"].as_array().unwrap().len() >= 16);    let _ = garden;}#[test]fn a_pinned_note_tops_every_list_and_a_tag_pin_tops_that_tag_alone() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let first = write(&phone, "# First\n#work");    let second = write(&phone, "# Second\n#work");    let third = write(&phone, "# Third\n#work");    assert_eq!(ids(&list(&phone, json!({}))), [third.clone(), second.clone(), first.clone()]);    let pinned = ask(&phone, "notes.pin", json!({ "id": first }));    assert_eq!(pinned["pinned_in_notes"], true);    let all = list(&phone, json!({}));    assert_eq!(ids(&all), [first.clone(), third.clone(), second.clone()]);    assert_eq!((all["rows"][0]["pinned"].as_bool(), all["pinned_count"].as_u64()), (Some(true), Some(1)));    assert_eq!(ids(&list(&phone, json!({ "view": "pinned" }))), [first.clone()]);    // Pinned inside work only: top of work, not of Notes.    ask(&phone, "notes.pin", json!({ "id": second, "tag": "Work" }));    // Both pinned in work, newest edit first (a pin is no edit).    assert_eq!(ids(&list(&phone, json!({ "view": "tag", "tag": "work" })))[..2].to_vec(), [second.clone(), first.clone()]);    assert_eq!(ids(&list(&phone, json!({})))[1], third);    ask(&phone, "notes.unpin", json!({ "id": first }));    assert_eq!(ids(&list(&phone, json!({}))), [third, second, first]);}#[test]fn rows_carry_checklist_progress_and_the_views_todo_and_today_answer() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let open_one = write(&phone, "# Shop\n- [ ] milk\n- [x] bread");    let done = write(&phone, "# Done\n- [x] all");    let plain = write(&phone, "# Words");    let all = list(&phone, json!({}));    let row = |id: &str| all["rows"].as_array().unwrap().iter().find(|r| r["id"] == id).unwrap().clone();    assert_eq!(row(&open_one)["checklist"], json!({ "done": 1, "total": 2 }));    assert_eq!(row(&plain)["checklist"], Value::Null);    assert_eq!((row(&plain)["thumbnail"].clone(), row(&plain)["by_assistant"].clone()), (Value::Null, json!(false)));    assert_eq!(ids(&list(&phone, json!({ "view": "todo" }))), [open_one.clone()]);    assert_eq!(ids(&list(&phone, json!({ "view": "today" }))).len(), 3);    assert_eq!(ids(&list(&phone, json!({ "search": "@done" }))), [done]);}#[test]fn search_words_narrow_the_list() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let a = write(&phone, "# Café plans\nNext week in the garden #home/garden");    let b = write(&phone, "# Weeds\nThe garden again #home");    let c = write(&phone, "# Office\nA garden of desks #work\n![](photo:nothing)");    let found = |search: &str| {        let mut out = ids(&list(&phone, json!({ "search": search })));        out.sort();        out    };    let sorted = |mut v: Vec<String>| {        v.sort();        v    };    assert_eq!(found("garden"), sorted(vec![a.clone(), b.clone(), c.clone()]));    assert_eq!(found("garden -weeds"), sorted(vec![a.clone(), c.clone()]));    assert_eq!(found("cafe"), vec![a.clone()]);    assert_eq!(found("\"next week\""), vec![a.clone()]);    assert_eq!(found("#home"), sorted(vec![a.clone(), b.clone()]));    assert_eq!(found("garden -#home"), vec![c.clone()]);    assert_eq!(found("@images"), vec![c.clone()]);    let answer = list(&phone, json!({ "search": "#home @todo" }));    assert_eq!(answer["search_terms"], json!([{ "kind": "tag", "not": false, "said": "#home" }, { "kind": "special", "not": false, "said": "@todo" }]));    assert!(ids(&answer).is_empty());}#[test]fn find_in_a_note_answers_utf16_matches() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let found = ask(&phone, "notes.find", json!({ "text": "😀 Rose, rosé and ROSE", "words": "rose" }));    assert_eq!(found["count"], 3);    assert_eq!(found["matches"][0], json!({ "start": 3, "end": 7 }));    assert_eq!(found["count_words"], "3 found");}#[test]fn note_links_suggest_open_and_survive_a_rename() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let garden = write(&phone, "# Garden plans\n## Spring\nSeeds");    let _other = write(&phone, "# Gardening books");    let here = write(&phone, "# Diary\nSee [[Garden plans]] and [[garden plans/Spring]] and [[Nowhere]]");    // Drawn with the note each opens.    let opened = ask(&phone, "notes.open", json!({ "id": here }));    let linked: Vec<(String, Value)> = opened["links"].as_array().unwrap().iter().map(|l| (l["target"].as_str().unwrap().to_string(), l["note"].clone())).collect();    assert_eq!(linked, [("Garden plans".to_string(), json!(garden)), ("garden plans/Spring".to_string(), json!(garden)), ("Nowhere".to_string(), Value::Null)]);    assert_eq!(opened["links"][1]["heading"], "Spring");    // Suggestions while typing.    let typed = "Then [[gard";    let suggested = ask(&phone, "notes.links", json!({ "id": here, "text": typed, "cursor": typed.len() }));    assert_eq!(suggested["open"], true);    assert_eq!(suggested["notes"].as_array().unwrap().len(), 2);    assert_eq!(suggested["replace"], json!({ "start": 5, "end": 11 }));    assert_eq!(ask(&phone, "notes.links", json!({ "text": "plain", "cursor": 5 }))["open"], false);    // Opening: the note and its heading; a missing one is offered, then made.    let link = ask(&phone, "notes.link", json!({ "target": "Garden plans/Spring" }));    assert_eq!((link["id"].as_str(), link["heading_at"].as_u64()), (Some(garden.as_str()), Some(15)));    let missing = ask(&phone, "notes.link", json!({ "target": "Nowhere" }));    assert_eq!(missing["offer"], "Make a note called Nowhere");    let made = ask(&phone, "notes.link", json!({ "target": "Nowhere", "make": true }));    assert_eq!(made["title"], "Nowhere");    // Info: links here, contents.    let info = ask(&phone, "notes.info", json!({ "id": garden }));    assert_eq!(info["links_here"][0]["id"], json!(here));    assert_eq!(info["contents"].as_array().unwrap().len(), 2);    // Renamed: the links follow.    let title = ask(&phone, "notes.open", json!({ "id": garden }))["title"].as_str().unwrap().to_string();    ask(&phone, "notes.edit", json!({ "id": garden, "text": "# Allotment\n## Spring\nSeeds" }));    let left = ask(&phone, "notes.leave", json!({ "id": garden, "title": title }));    assert_eq!(left["relinked"], 1);    assert_eq!(body(&phone, &here), "# Diary\nSee [[Allotment]] and [[Allotment/Spring]] and [[Nowhere]]");}#[test]fn a_rename_leaves_links_alone_that_opened_an_older_namesake() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let _older = write(&phone, "# Ideas");    let newer = write(&phone, "# Ideas");    let here = write(&phone, "# Links\n[[Ideas]]");    ask(&phone, "notes.edit", json!({ "id": newer, "text": "# Ideas 2" }));    assert_eq!(ask(&phone, "notes.leave", json!({ "id": newer, "title": "Ideas" }))["relinked"], 0);    assert_eq!(body(&phone, &here), "# Links\n[[Ideas]]");}#[test]fn deleting_for_good_asks_first_and_only_a_confirmed_call_deletes() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let id = write(&phone, "# Keep me\nwords");    ask(&phone, "notes.bin", json!({ "id": id }));    let asked = ask(&phone, "notes.remove", json!({ "id": id }));    assert_eq!(asked["ask"]["act"], "Delete");    assert!(asked["ask"]["message"].as_str().unwrap().contains("Keep me"));    assert_eq!(ids(&list(&phone, json!({ "view": "bin" }))), [id.clone()]);    let emptied = ask(&phone, "notes.empty_bin", json!({}));    assert!(emptied["ask"]["message"].as_str().unwrap().contains("1 note"));    assert_eq!(ids(&list(&phone, json!({ "view": "bin" }))).len(), 1);    ask(&phone, "notes.remove", json!({ "id": id, "confirmed": true }));    assert!(ids(&list(&phone, json!({ "view": "bin" }))).is_empty());}#[test]fn settings_keep_spacing_and_hide_marks_and_read_old_theme_ids_as_new() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let first = ask(&phone, "notes.settings", json!({}));    assert_eq!((first["light_theme"].as_str(), first["dark_theme"].as_str(), first["hide_marks"].as_bool()), (Some("linen"), Some("slate"), Some(true)));    let set = ask(&phone, "notes.settings", json!({ "paragraph_spacing": 0.6, "hide_marks": false, "light_theme": "chalk", "dark_theme": "dusk" }));    assert_eq!((set["paragraph_spacing"].as_f64(), set["hide_marks"].as_bool()), (Some(0.6), Some(false)));    assert_eq!((set["light_theme"].as_str(), set["dark_theme"].as_str()), (Some("linen"), Some("dusk")));    assert_eq!(set["dark"]["ground"], "#000000");    assert!(dispatch(&phone, "notes.settings", &json!({ "paragraph_spacing": 3.0 })).is_err());    let themes = ask(&phone, "notes.themes", json!({}));    let names: Vec<&str> = themes["themes"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();    assert_eq!(names, ["Linen", "Slate", "Print", "Dusk"]);    assert_eq!(themes["faces"], json!({ "text": "Figtree", "code": "JetBrains Mono" }));    assert!(themes["themes"][0]["light"]["link"].as_str().is_some_and(|c| c.starts_with('#')));    // Marks shown dim, not hidden, when asked.    let styled = ask(&phone, "notes.style", json!({ "text": "**b**", "hide_marks": false }));    assert!(styled["spans"].as_array().unwrap().iter().filter(|s| s["style"] == "mark").all(|s| s["look"] == "dim"));}#[test]fn folds_and_a_picture_width_come_with_the_drawing() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let text = "# T\n## A\nwords\n![](photo:x)";    let styled = ask(&phone, "notes.style", json!({ "text": text }));    assert_eq!(styled["folds"].as_array().unwrap().len(), 2);    let sized = ask(&phone, "notes.format", json!({ "text": text, "cursor": text.len(), "action": { "action": "picture_width", "width": "medium" } }));    assert_eq!(sized["text"], "# T\n## A\nwords\n![](photo:x)<!-- {\"width\":320} -->");    let picture = sized["blocks"].as_array().unwrap().iter().find(|b| b["kind"] == "picture").unwrap().clone();    assert_eq!(picture["width"], "medium");    let fold = ask(&phone, "notes.format", json!({ "text": text, "cursor": 12, "action": { "action": "fold" } }));    assert_eq!((fold["fold"]["kind"].as_str(), fold["text"].as_str()), (Some("heading"), Some(text)));    assert_eq!(fold["fold"]["line"], 4);}/// A synthetic picture kept as a photo record: a tiny real PNG, so a PDF lays it.fn photo(phone: &CottonHandle, dir: &std::path::Path, n: u8) -> String {    let path = dir.join(format!("invented-{n}.png"));    std::fs::write(&path, tiny_png(n)).unwrap();    super::keep_picture(phone, &path.to_string_lossy(), "image/png", Some("invented.png")).expect("the picture is kept")}/// A 2×2 RGB PNG, its colour set by `n`.fn tiny_png(n: u8) -> Vec<u8> {    use std::io::Write;    fn chunk(out: &mut Vec<u8>, name: &[u8], data: &[u8]) {        out.extend((data.len() as u32).to_be_bytes());        let mut body = name.to_vec();        body.extend(data);        out.extend(&body);        let mut crc = flate2::Crc::new();        crc.update(&body);        out.extend(crc.sum().to_be_bytes());    }    let mut raw = Vec::new();    for _ in 0..2 {        raw.push(0u8);        raw.extend([n, 40, 200, n, 40, 200]);    }    let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());    z.write_all(&raw).unwrap();    let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];    chunk(&mut out, b"IHDR", &[0, 0, 0, 2, 0, 0, 0, 2, 8, 2, 0, 0, 0]);    chunk(&mut out, b"IDAT", &z.finish().unwrap());    chunk(&mut out, b"IEND", &[]);    out}#[test]fn an_assistants_write_files_its_tags_at_once_and_its_picture_shows_once() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let picture = photo(&phone, dir.path(), 1);    let body = format!("Plan #plans/week and #two words#\n\n![a view](cotton:photo/{picture})");    let made = super::with_write(&phone, "mcp", |ctx| {        let args = json!({ "title": "Week", "body": body, "attachments": [{ "kind": "photo", "id": picture }] }).as_object().cloned().unwrap();        Ok(cotton_tools::mcp::handlers::records_1::notes::create_note(ctx, &args).unwrap())    })    .unwrap();    let id = made["id"].as_str().unwrap().to_string();    // Filed before any phone looks.    let filed = super::with_read(&phone, "test", |ctx| {        Ok(json!(super::tag_groups(ctx)?.into_iter().filter(|g| g.members.contains(&id)).map(|g| g.tag).collect::<Vec<_>>()))    })    .unwrap();    let mut filed: Vec<String> = serde_json::from_value(filed).unwrap();    filed.sort();    assert_eq!(filed, ["plans/week", "two words"]);    // The old address draws the photo, once.    let opened = ask(&phone, "notes.open", json!({ "id": id }));    let text = opened["text"].as_str().unwrap();    assert_eq!(text.matches(picture.trim_start_matches("photo:")).count(), 1, "{text}");    assert!(opened["pictures"][format!("cotton:photo/{picture}")]["key"].is_string(), "{}", opened["pictures"]);    // An edit dropping a tag takes it out at once too.    super::with_write(&phone, "mcp", |ctx| {        let args = json!({ "id": id, "body": "Plan #plans/week" }).as_object().cloned().unwrap();        Ok(cotton_tools::mcp::handlers::records_1::notes::update_note(ctx, &args).unwrap())    })    .unwrap();    let left = super::with_read(&phone, "test", |ctx| Ok(json!(super::tag_groups(ctx)?.into_iter().map(|g| g.tag).collect::<Vec<_>>()))).unwrap();    assert_eq!(left, json!(["plans/week"]));}#[test]fn notes_export_as_markdown_textbundle_html_and_pdf() {    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let picture = photo(&phone, dir.path(), 2);    let text = format!("# Garden plans\nSome ==bright== words, **bold**, a [link](https://example.com) and [[Seeds]] #home/garden\n\n- [ ] dig\n- [x] seed\n> a quote\n\n```\nlet x = 1;\n```\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\n![a view]({picture})<!-- {{\"width\":160}} -->\n");    let one = write(&phone, &text);    let two = write(&phone, "# Second\nMore words, café ünïcode");    let file = |answer: &Value| std::fs::read(answer["path"].as_str().unwrap()).unwrap();    let md = ask(&phone, "notes.export", json!({ "ids": [one], "format": "markdown" }));    assert_eq!((md["file_name"].as_str(), md["mime"].as_str()), (Some("Garden plans.md"), Some("text/markdown")));    assert_eq!(String::from_utf8(file(&md)).unwrap(), text);    let pack = ask(&phone, "notes.export", json!({ "ids": [one], "format": "textbundle" }));    assert_eq!(pack["file_name"], "Garden plans.textpack");    let bytes = file(&pack);    let entries = cotton_core::import::zip::list_zip_entries(&bytes).unwrap();    let names: Vec<String> = entries.iter().map(|e| e.name.clone()).collect();    assert!(names.contains(&"Garden plans.textbundle/text.md".to_string()) && names.contains(&"Garden plans.textbundle/info.json".to_string()), "{names:?}");    assert!(names.iter().any(|n| n.starts_with("Garden plans.textbundle/assets/") && n.ends_with(".png")), "{names:?}");    let md_entry = entries.iter().find(|e| e.name.ends_with("text.md")).unwrap();    let bundled = String::from_utf8(cotton_core::import::zip::read_zip_entry(&bytes, md_entry).unwrap()).unwrap();    assert!(bundled.contains("![a view](assets/") && bundled.contains("<!-- {\"width\":160} -->"), "{bundled}");    let html = ask(&phone, "notes.export", json!({ "ids": [one], "format": "html" }));    let page = String::from_utf8(file(&html)).unwrap();    for part in ["<h1 class=\"title\">Garden plans</h1>", "<mark>bright</mark>", "<strong>bold</strong>", "<a href=\"https://example.com\">link</a>", "<span class=\"note-link\">Seeds</span>", "<ul class=\"checks\">", "<blockquote>", "<pre><code>let x = 1;</code></pre>", "<table>", "<img class=\"small\" src=\"data:image/png;base64,"] {        assert!(page.contains(part), "{part} in {page}");    }    assert!(!page.contains("**") && !page.contains("<!--"), "{page}");    let pdf = ask(&phone, "notes.export", json!({ "ids": [one, two], "format": "pdf" }));    let doc = file(&pdf);    let said = String::from_utf8_lossy(&doc);    assert!(doc.starts_with(b"%PDF-1.7") && said.contains("/Count 2") && said.contains("/FontFile2") && said.contains("/Subtype /Image") && said.contains("/URI (https://example.com)"), "pdf");    assert_eq!(pdf["count"], 2);    // RULE (the iPhone walk, 24 Nov 2026): a note with no heading is named by its first line, as the list titles it.    let untitled = write(&phone, "Shopping for Sunday\n- [ ] bread #home");    let plain = ask(&phone, "notes.export", json!({ "ids": [untitled], "format": "markdown" }));    assert_eq!(plain["file_name"], "Shopping for Sunday.md");    // Every note of a list, zipped.    let all = ask(&phone, "notes.export", json!({ "view": "all", "format": "markdown" }));    assert_eq!((all["file_name"].as_str(), all["count"].as_u64()), (Some("Notes.zip"), Some(3)));    assert!(dispatch(&phone, "notes.export", &json!({ "ids": [one], "format": "docx" })).is_err());}/// The reference app's export shape, with invented notes: a TextBundle and a/// TextPack, each with info.json under the app's own key, multi-word and/// nested tags, highlights, a picture with its width and a [[link]].#[test]fn a_reference_app_textbundle_and_textpack_come_in_with_their_dates() {    use std::io::Write;    let dir = tempfile::tempdir().unwrap();    let phone = phone(&dir);    let bundle = dir.path().join("Export/Seed list.textbundle");    std::fs::create_dir_all(bundle.join("assets")).unwrap();    std::fs::write(bundle.join("text.md"), "# Seed list\n\nSow ==early== #garden/beds and #slow growing#\n\n![](assets/seed.png)<!-- {\"width\":245} -->\n\nSee [[Allotment diary]]\n").unwrap();    std::fs::write(bundle.join("assets/seed.png"), tiny_png(9)).unwrap();    std::fs::write(bundle.join("info.json"), r#"{"type":"public.plain-text","version":2,"creatorIdentifier":"net.shinyfrog.bear","net.shinyfrog.bear":{"creationDate":"2021-03-04T05:06:07Z","modificationDate":"2022-08-09T10:11:12.345Z","pinned":"yes","uniqueIdentifier":"AAAA-INVENTED"}}"#).unwrap();    let pack = dir.path().join("Allotment diary.textpack");    let mut zip = zip::ZipWriter::new(std::fs::File::create(&pack).unwrap());    let options = zip::write::SimpleFileOptions::default();    zip.start_file("Allotment diary.textbundle/text.md", options).unwrap();    zip.write_all(b"# Allotment diary\n\nRain again #garden\n- [ ] net the beans\n").unwrap();    zip.start_file("Allotment diary.textbundle/info.json", options).unwrap();    zip.write_all(br#"{"net.shinyfrog.bear":{"creationDate":"2020-01-02T03:04:05Z","modificationDate":"2020-02-03T04:05:06Z","pinned":"no"}}"#).unwrap();    zip.finish().unwrap();    let came = ask(&phone, "notes.import", json!({ "files": [{ "path": dir.path().join("Export").to_string_lossy() }, { "path": pack.to_string_lossy(), "name": "Allotment diary.textpack" }] }));    assert_eq!((came["notes"].as_u64(), came["pictures"].as_u64()), (Some(2), Some(1)), "{came}");    let all = list(&phone, json!({}));    let rows = all["rows"].as_array().unwrap();    let seed = rows.iter().find(|r| r["title"] == "Seed list").unwrap().clone();    let diary = rows.iter().find(|r| r["title"] == "Allotment diary").unwrap().clone();    // Pinned from its info.json, so on top; its dates kept.    assert_eq!((rows[0]["id"].clone(), seed["pinned"].clone()), (seed["id"].clone(), json!(true)));    assert!(seed["edited_at"].as_str().unwrap().starts_with("2022-08-09T10:11:12"), "{seed}");    assert!(diary["edited_at"].as_str().unwrap().starts_with("2020-02-03T04:05:06"), "{diary}");    let info = ask(&phone, "notes.info", json!({ "id": seed["id"] }));    assert!(info["created_at"].as_str().unwrap().starts_with("2021-03-04T05:06:07"), "{info}");    let mut tags: Vec<String> = seed["tags"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_string()).collect();    tags.sort();    assert_eq!(tags, ["garden/beds", "slow growing"]);    assert_eq!(ids(&list(&phone, json!({ "view": "tag", "tag": "garden" }))).len(), 2);    // The picture at its width, the highlight a highlight, the link opening the diary.    let opened = ask(&phone, "notes.open", json!({ "id": seed["id"] }));    assert_eq!(opened["blocks"].as_array().unwrap().iter().find(|b| b["kind"] == "picture").unwrap()["width"], "medium");    assert!(opened["spans"].as_array().unwrap().iter().any(|s| s["style"] == "highlight"));    assert_eq!(opened["links"][0]["note"], diary["id"]);    assert_eq!(diary["checklist"], json!({ "done": 0, "total": 1 }));}