Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Notes: the editor always shows the note that is picked
Yashwanth Kamireddi4d4724e32f5b
diff --git a/.uiverify/notes-follow.mjs b/.uiverify/notes-follow.mjsnew file mode 100644index 0000000..ba42d8b--- /dev/null+++ b/.uiverify/notes-follow.mjs@@ -0,0 +1,234 @@+// The list and the editor always agree: the note highlighted is the note shown, by its id.+//+// A note pasted into and saved, then another opened and typed in — it goes to the top, as an+// edited note does — then a third opened: the editor shows the third note, never the one just+// left, and what is typed there is saved to the third note alone. The same when switching+// straight after typing, before the pause that saves, and with a sync landing in between.+// Titles stay as Apple holds them while an edit leaves the title line alone. Only the edited+// note moves in the list; opening notes moves nothing.+//+// The library here is a small stand-in for the Rust one (notes.rs, outbox.rs): a save keeps+// the text, keeps Apple's title unless the title line changed, and moves the time edited on+// only when something changed. Names and text are invented.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";++const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });+await ctx.addInitScript(() => {+ const t = window.__TAURI_INTERNALS__;+ const inner = t.invoke;+ const hour = 3600;+ // Three days ago, an hour apart: one date group, newest first A … F.+ const at = Math.floor(Date.now() / 1000) - 3 * 86400;+ const words = (l) => l.replace(/[\uFFFC\u2028]/g, " ").split(/\s+/).filter(Boolean).join(" ");+ const lines = (body) => body.split("\n").map((l) => words(l.replace(/\r$/, ""))).filter((l) => /[\p{L}\p{N}]/u.test(l));+ // Everything up to the end of the title line: an edit that leaves it alone leaves the title.+ const head = (body) => {+ let from = 0;+ for (const l of body.split("\n")) {+ const end = from + l.length;+ if (/[\p{L}\p{N}]/u.test(words(l))) return body.slice(0, end);+ from = end + 1;+ }+ return body;+ };+ const store = [+ ["nA", "Alpine trip\nPack the alpine boots"],+ ["nB", "Birch notes\nBirch bark sample"],+ ["nC", "Cedar list\nCedar planks"],+ ["nD", "Dahlia ideas\nDahlia bulbs"],+ ["nE", "Elm street\nElm leaves"],+ // Apple's own title, as the phone set it, which is not the first line with words on it.+ ["nF", "\u{1F3D5}\u{1F3D5}\u{1F3D5}\nTent\nStove", "\u{1F3D5}\u{1F3D5}\u{1F3D5}"],+ ].map(([guid, body, title], i) => ({+ guid, folderGuid: "f1", title: title ?? lines(body)[0], snippet: lines(body)[1] ?? null, body,+ locked: false, editable: true, pinned: false, createdAt: at - 10 * hour, modifiedAt: at - i * hour, etag: null,+ }));+ window.__fx = store;+ const runsOf = (body) => {+ const ls = body.split("\n");+ return ls.map((l, i) => ({ length: l.length + (i < ls.length - 1 ? 1 : 0), style: i === 0 ? 0 : null, indent: 0,+ checked: null, bold: false, italic: false, underline: false, strike: false, link: null }));+ };+ const savedRuns = {};+ const row = (n) => ({ ...n, body: null });+ t.invoke = async (cmd, args) => {+ const n = store.find((x) => x.guid === args?.guid);+ switch (cmd) {+ case "notes_in": return store.map(row);+ case "note_counts": return [store.length, [["f1", store.length]]];+ case "note_body": await new Promise((r) => setTimeout(r, 15)); return n ? n.body : null;+ case "note_runs": await new Promise((r) => setTimeout(r, 25)); return n ? (savedRuns[n.guid] ?? runsOf(n.body)) : [];+ case "note_row": return n ? row(n) : null;+ case "notes_search": return [];+ case "note_save": {+ (window.__fxSaves ??= []).push({ guid: args.guid, body: args.body });+ if (!n) throw "That note is no longer in the local library.";+ const before = n.body;+ if (args.body !== before || args.runs) {+ if (head(before) !== head(args.body)) n.title = lines(args.body)[0] ?? "";+ n.snippet = lines(args.body)[1] ?? null;+ n.body = args.body;+ if (args.runs) savedRuns[n.guid] = args.runs;+ if (args.body !== before) n.modifiedAt = Math.max(n.modifiedAt ?? 0, Math.floor(Date.now() / 1000));+ }+ return n.body;+ }+ default: return inner(cmd, args);+ }+ };+});+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });+await page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Notes");+await page.waitForTimeout(500);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++const order = () => page.$$eval(".note-row", (rs) => rs.map((r) => r.getAttribute("data-guid")));+const selected = () => page.$$eval('.note-row[aria-selected="true"]', (rs) => rs.map((r) => r.getAttribute("data-guid")));+const shown = () => page.evaluate(() => document.querySelector(".notes .note-rich")?.textContent ?? "");+const body = (guid) => page.evaluate((g) => window.__fx.find((n) => n.guid === g).body, guid);+const row = (guid) => page.locator(`.note-row[data-guid="${guid}"]`);+const toEnd = async () => {+ await page.locator(".notes .note-rich p").last().click();+ await page.keyboard.press("Control+End");+};+const paste = async (text) => {+ // The editor takes in where the cursor went before the paste lands.+ await page.waitForTimeout(150);+ const handled = await page.evaluate((t) => {+ const el = document.querySelector(".notes .note-rich");+ const dt = new DataTransfer();+ dt.setData("text/plain", t);+ const e = new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true });+ if (!e.clipboardData) return false;+ el.dispatchEvent(e);+ return true;+ }, text);+ if (!handled) await page.keyboard.insertText(text);+};+/** The note on screen is `guid`'s: highlighted, and its own words in the editor. */+const agrees = async (guid, others, label) => {+ const sel = await selected();+ const text = await shown();+ const own = (await body(guid)).split("\n")[1];+ const foreign = [];+ for (const o of others) if (o !== guid && text.includes((await body(o)).split("\n")[1])) foreign.push(o);+ ok(sel.length === 1 && sel[0] === guid && text.includes(own) && foreign.length === 0,+ `${label}: highlighted ${JSON.stringify(sel)}, editor shows ${guid}'s text${foreign.length ? ` — and ${foreign.join(", ")}'s` : ""} ${JSON.stringify(text.slice(0, 80))}`);+};+const ALL = ["nA", "nB", "nC", "nD", "nE", "nF"];++// 1. Paste into C and let it save; open E and type, let it save (E goes to the top); then the+// note under E — read ahead as its neighbour — is opened.+await row("nC").click();+await page.waitForTimeout(400);+await toEnd();+await paste("\nPasted line one\nPasted line two");+await page.waitForTimeout(1400);+await row("nE").click();+await page.waitForTimeout(400);+await toEnd();+await page.keyboard.type(" and oaks", { delay: 20 });+await page.waitForTimeout(1400);+const afterE = await order();+ok(afterE[0] === "nE", `the edited note goes to the top ${JSON.stringify(afterE)}`);+const next = afterE[1];+await row(next).click();+await page.waitForTimeout(400);+await agrees(next, ALL, `opened ${next} after E moved`);+await toEnd();+await page.keyboard.type(" kept", { delay: 20 });+await page.waitForTimeout(1400);+const lastSave = await page.evaluate(() => (window.__fxSaves ?? []).at(-1));+ok(lastSave?.guid === next && !lastSave.body.includes("Elm") && lastSave.body.endsWith(" kept"),+ `typing there saves to ${next} alone, with its own text ${JSON.stringify(lastSave)}`);+ok((await body("nE")).includes("and oaks") && !(await body("nE")).includes("kept"), "E keeps what was typed in it, and nothing else");+ok((await body("nC")).includes("Pasted line two"), "the paste was saved to C");++// 2. Quickly: typing, then at once a neighbour — before the pause that saves.+await row("nD").click();+await page.waitForTimeout(500);+let o = await order();+const besideD = o[o.indexOf("nD") + 1] ?? o[o.indexOf("nD") - 1];+await toEnd();+await page.keyboard.type(" fast", { delay: 15 });+await row(besideD).click();+await page.waitForTimeout(300);+await agrees(besideD, ALL, `switched to ${besideD} at once after typing in D`);+await page.waitForTimeout(1300);+ok((await body("nD")).endsWith(" fast"), "what was typed in D just before leaving it is saved to D");+ok(!(await body(besideD)).includes("fast"), `and not to ${besideD}`);++// 3. With a sync landing between the typing and the switch.+await row("nB").click();+await page.waitForTimeout(500);+o = await order();+const besideB = o[o.indexOf("nB") + 1] ?? o[o.indexOf("nB") - 1];+await toEnd();+await page.keyboard.type(" synced", { delay: 15 });+await page.evaluate(() => window.__emit("quince://synced", { services: [], asOf: Math.floor(Date.now() / 1000), tookMs: 5 }));+await page.waitForTimeout(60);+await row(besideB).click();+await page.waitForTimeout(80);+await page.evaluate(() => window.__emit("quince://synced", { services: [], asOf: Math.floor(Date.now() / 1000), tookMs: 5 }));+await page.waitForTimeout(400);+await agrees(besideB, ALL, `switched to ${besideB} with syncs landing`);+await page.waitForTimeout(1300);+ok((await body("nB")).endsWith(" synced") && !(await body(besideB)).includes("synced"), "B's typing saved to B alone");++// 4. Opening notes moves nothing, and saves nothing.+const saves0 = await page.evaluate(() => (window.__fxSaves ?? []).length);+const still = await order();+for (const g of [still[3], still[1], still[4], still[2]]) {+ await row(g).click();+ await page.waitForTimeout(250);+}+await page.waitForTimeout(1200);+ok(JSON.stringify(await order()) === JSON.stringify(still), `opening notes moves none of them ${JSON.stringify(await order())}`);+ok((await page.evaluate(() => (window.__fxSaves ?? []).length)) === saves0, "and saves none of them");++// 5. An edit moves only the edited note, to the top; selection and editor stay with it; a sync+// after changes nothing.+const lastRow = still.at(-1);+await row(lastRow).click();+await page.waitForTimeout(400);+await toEnd();+await page.keyboard.type(" moved", { delay: 15 });+await page.waitForTimeout(1400);+const moved = await order();+ok(JSON.stringify(moved) === JSON.stringify([lastRow, ...still.filter((g) => g !== lastRow)]),+ `only ${lastRow} moved, to the top; every other row kept its place ${JSON.stringify(still)} → ${JSON.stringify(moved)}`);+await agrees(lastRow, ALL, "after its move the edited note is still the one highlighted and shown");+await page.evaluate(() => window.__emit("quince://synced", { services: [], asOf: Math.floor(Date.now() / 1000), tookMs: 5 }));+await page.waitForTimeout(500);+ok(JSON.stringify(await order()) === JSON.stringify(moved), "a sync after it moves nothing");++// 6. Titles: an edit below the title line keeps the title Apple holds (the phone's), and an+// edit of the title line takes the new first line.+await row("nF").click();+await page.waitForTimeout(400);+await toEnd();+await page.keyboard.type(" and lamp", { delay: 15 });+await page.waitForTimeout(1400);+const fTitle = await row("nF").locator(".note-row-name").innerText();+ok(fTitle === "\u{1F3D5}\u{1F3D5}\u{1F3D5}", `an edit below the title keeps Apple's title (${JSON.stringify(fTitle)})`);+await row("nA").click();+await page.waitForTimeout(400);+await page.locator(".notes .note-rich p").first().click();+await page.keyboard.press("Control+Home");+await page.keyboard.press("Enter");+await page.keyboard.press("Enter");+await page.keyboard.press("ArrowUp");+await page.keyboard.type("Summit plan", { delay: 15 });+await page.waitForTimeout(1400);+const aTitle = await row("nA").locator(".note-row-name").innerText();+const aStored = await page.evaluate(() => window.__fx.find((n) => n.guid === "nA").title);+ok(aTitle === "Summit plan" && aTitle === aStored, `a new first line is the title, as the library keeps it (row ${JSON.stringify(aTitle)}, library ${JSON.stringify(aStored)})`);++await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/notes-model.test.mjs b/.uiverify/notes-model.test.mjsindex 4db2169..c6c417e 100644--- a/.uiverify/notes-model.test.mjs+++ b/.uiverify/notes-model.test.mjs@@ -1,7 +1,7 @@// The rules Notes' list and editor follow, checked directly.import { test } from "node:test";import assert from "node:assert/strict";-import { groupNotes, listDate, splitTitle, joinTitle, titleAndSnippet } from "../src/screens/notes/model.ts";+import { groupNotes, listDate, splitTitle, joinTitle } from "../src/screens/notes/model.ts";const now = new Date(2026, 8, 30, 12, 0);const at = (y, m, d, h = 9) => Math.floor(new Date(y, m, d, h).getTime() / 1000);@@ -72,9 +72,3 @@ test("every note appears exactly once, in every order", () => {assert.deepEqual(seen, ["a", "b", "c", "d"], `${by} ${groupByDate}`);}});--test("a saved note's row reads as the backend lists it: the first lines with words", () => {- assert.deepEqual(titleAndSnippet("Groceries\nMilk, eggs\nBread"), { title: "Groceries", snippet: "Milk, eggs" });- assert.deepEqual(titleAndSnippet("\u2501\u2501\u2501\n Trip \uFFFC plan \n\n\uFFFC\nend"), { title: "Trip plan", snippet: "end" });- assert.deepEqual(titleAndSnippet(""), { title: "", snippet: "" });-});diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex f0391b7..7dbe6ec 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -490,8 +490,25 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note(window.__noteSaves ??= []).push(args);// A test can play the other device: what Apple answers is what it now holds.const kept = window.__phoneEdit ? window.__phoneEdit(args) : args.body;- // Kept, as Apple keeps it: the next read of the note gives what was saved.+ // Kept, as Apple keeps it: the next read of the note gives what was saved. Its row as+ // the library keeps it (outbox.rs lay_note): the title Apple holds while the title line+ // is untouched, else the first line with words; the time edited moved on by a change.const n = noteList.find((x) => x.guid === args.guid);+ if (n && kept !== n.body) {+ const words = (l) => l.replace(/[\uFFFC\u2028]/g, " ").split(/\s+/).filter(Boolean).join(" ");+ const lines = (t) => t.split("\n").map(words).filter((l) => /[\p{L}\p{N}]/u.test(l));+ const head = (t) => {+ let from = 0;+ for (const l of t.split("\n")) {+ if (/[\p{L}\p{N}]/u.test(words(l))) return t.slice(0, from + l.length);+ from += l.length + 1;+ }+ return t;+ };+ if (n.body == null || head(n.body) !== head(kept)) n.title = lines(kept)[0] ?? "";+ n.snippet = lines(kept)[1] ?? null;+ n.modifiedAt = Math.max(n.modifiedAt ?? 0, Math.floor(Date.now() / 1000));+ }if (n) n.body = kept;if (args.runs && kept === args.body) (window.__savedRuns ??= {})[args.guid] = args.runs;return kept;@@ -798,6 +815,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notereturn window.__table.map((r) => r.slice());}case "note_body": return (noteList.find((n) => n.guid === args?.guid) ?? {}).body ?? null;+ case "note_row": {+ const n = noteList.find((x) => x.guid === args?.guid);+ return n ? { ...n, body: null } : null;+ }case "note_counts": {const per = new Map();for (const n of noteList) per.set(n.folderGuid, (per.get(n.folderGuid) ?? 0) + 1);diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex 2e9d7c3..893e8ba 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -496,6 +496,32 @@ pub fn title_and_snippet(body: &str) -> (String, String) {(title, snippet)}+/// Whether an edit from `before` to `after` leaves the note's title line — and every line+/// above it — exactly as it was.+///+/// While it does, the title Apple holds stays: it is the one the phone set, by the phone's own+/// rule, and the phone and this list show it. Worked out again here on every save, a note the+/// phone titled by a line this rule passes over (a row of emoji, say) was retitled by an edit+/// to its last line — a different title here than on the phone, for a line nobody touched.+#[must_use]+pub fn title_line_unchanged(before: &str, after: &str) -> bool {+ title_head(before) == title_head(after)+}++/// A note's text up to the end of its title line: the first line with words on it, as+/// [`title_and_snippet`] finds it — or the whole text, when no line has words.+fn title_head(body: &str) -> &str {+ let mut from = 0;+ for line in body.split('\n') {+ let end = from + line.len();+ if words_only(line).chars().any(char::is_alphanumeric) {+ return &body[..end];+ }+ from = end + 1;+ }+ body+}+/// A line of a note as words: without the marks Apple puts in the text where an attachment/// sits (U+FFFC) or a line breaks inside a paragraph (U+2028). A table placed after a note's/// first words made the title "frfge", drawn as a box in every list.@@ -599,6 +625,16 @@ pub async fn edit_rich_cloudkit_from(return Ok(theirs);};let (title, snippet) = title_and_snippet(&target);+ // Apple's title, exactly as it holds it, while the edit leaves the title line alone+ // (`title_line_unchanged`); the new first line's when the edit reached it.+ let held_title = current+ .pointer("/fields/TitleEncrypted")+ .filter(|_| title_line_unchanged(&theirs, &target))+ .filter(|_| {+ field::document_text(¤t, "TitleEncrypted")+ .is_some_and(|t| !words_only(&t).is_empty())+ })+ .cloned();let Some(tag) = current.get("recordChangeTag").and_then(Value::as_str) else {return Err(Error::Refused("Apple did not say which version of the note it holds.".into(),@@ -612,10 +648,10 @@ pub async fn edit_rich_cloudkit_from(tag,serde_json::json!({"TextDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": rewritten },- "TitleEncrypted": {+ "TitleEncrypted": held_title.unwrap_or_else(|| serde_json::json!({"type": "ENCRYPTED_BYTES","value": crate::ckdocument::bare_text_to_base64(&title),- },+ })),"SnippetEncrypted": {"type": "ENCRYPTED_BYTES","value": crate::ckdocument::bare_text_to_base64(&snippet),@@ -1734,6 +1770,26 @@ mod tests {assert_eq!(words_only("one\u{2028}two"), "one two");}+ /// An edit below the title line leaves the title Apple holds; one that reaches the title+ /// line, or a line above it, does not.+ #[test]+ fn an_edit_below_the_title_line_keeps_the_title() {+ let tent = "\u{1F3D5}\u{1F3D5}\n\nTent\nStove";+ assert!(title_line_unchanged(tent, "\u{1F3D5}\u{1F3D5}\n\nTent\nStove and lamp"));+ assert!(title_line_unchanged("Groceries\nMilk", "Groceries\nMilk\nEggs"));+ assert!(title_line_unchanged("Groceries", "Groceries\nMilk"));+ // The title line itself, or anything above it.+ assert!(!title_line_unchanged(tent, "\u{1F3D5}\u{1F3D5}\n\nTents\nStove"));+ assert!(!title_line_unchanged(tent, "\u{1F3D5}\n\nTent\nStove"));+ assert!(!title_line_unchanged("Groceries\nMilk", "Shopping\nMilk"));+ assert!(!title_line_unchanged("Groceries\nMilk", "\nGroceries\nMilk"));+ // A pasted block above the old title is a new title line.+ assert!(!title_line_unchanged("Cedar list\nplanks", "Pasted\nCedar list\nplanks"));+ // No line with words: only the same text is the same title.+ assert!(title_line_unchanged("\u{FFFC}", "\u{FFFC}"));+ assert!(!title_line_unchanged("\u{FFFC}", "\u{FFFC}\nhello"));+ }+#[test]fn a_title_is_the_first_line_with_words_on_it() {let pasted = "━━━━━━━━━━━━━━━━\n\n𝗨𝗡𝗜𝗧 𝟭: 𝗜𝗡𝗧𝗥𝗢\n• ──\nQuantum states";@@ -2240,6 +2296,74 @@ mod write_tests {serde_json::from_slice::<Value>(&modify.body).unwrap()["operations"][0]["record"].clone()}+ /// A note as the phone titled it, by a line this app's rule would pass over.+ async fn titled_server(existing: &str, title: &str) -> MockServer {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path_regex(r".*/records/lookup$"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "records": [{+ "recordName": "Note/1",+ "recordType": "Note",+ "recordChangeTag": "fresh",+ "fields": {+ "TextDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": document(existing) },+ "TitleEncrypted": { "type": "ENCRYPTED_BYTES", "value": crate::ckdocument::bare_text_to_base64(title) }+ }+ }]+ })))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path_regex(r".*/records/modify$"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(json!({ "records": [{ "recordName": "Note/1" }] })),+ )+ .mount(&server)+ .await;+ server+ }++ /// An edit below the title line writes back the title Apple holds — the phone's — not one+ /// worked out here; an edit of the title line writes the new one.+ #[tokio::test]+ async fn an_edit_keeps_apples_title_until_the_title_line_changes() {+ let camp = "\u{1F3D5}\u{1F3D5}";+ let text = format!("{camp}\nTent\nStove");+ let server = titled_server(&text, camp).await;+ edit_cloudkit_from(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ ¬e("Note/1"),+ Some(&text),+ &format!("{text} and lamp"),+ )+ .await+ .unwrap();+ assert_eq!(+ sent(&server).await["fields"]["TitleEncrypted"]["value"],+ crate::ckdocument::bare_text_to_base64(camp)+ );++ let server = titled_server(&text, camp).await;+ edit_cloudkit_from(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ ¬e("Note/1"),+ Some(&text),+ "Camping\nTent\nStove",+ )+ .await+ .unwrap();+ assert_eq!(+ sent(&server).await["fields"]["TitleEncrypted"]["value"],+ crate::ckdocument::bare_text_to_base64("Camping")+ );+ }+/// The phone added to the very line being edited here: both additions are written, as/// Notes merges them — the phone's first — and neither device's words are lost.#[tokio::test]diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 5667592..b2849c5 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -2974,6 +2974,16 @@ async fn note_body(guid: String, data: State<'_, Data>) -> UiResult<Option<Strin.map_err(|e| e.to_string())}+/// One note's row as the library lists it — title, preview, time edited — without its text:+/// what a save just made of it, for the list to show at once without reading every row again.+#[tauri::command]+async fn note_row(guid: String, data: State<'_, Data>) -> UiResult<Option<Note>> {+ data.0+ .read(|library| library.note(&guid))+ .await+ .map_err(|e| e.to_string())+}+/// A note written out as Markdown at `path` (chosen in the save dialog): its text as it is on/// screen, typing not yet sent included, set as it is in Notes — headings, lists,/// checklists, code, quotes, bold, italic, links.@@ -6092,6 +6102,7 @@ fn main() {note_folder_rename,note_folder_delete,note_body,+ note_row,note_export_markdown,note_runs,note_table,diff --git a/src-tauri/src/outbox.rs b/src-tauri/src/outbox.rsindex b6cb0ea..ff98103 100644--- a/src-tauri/src/outbox.rs+++ b/src-tauri/src/outbox.rs@@ -212,6 +212,11 @@ pub struct NoteSave {pub base: Option<String>,pub runs: Option<Vec<Run>>,pub base_runs: Option<Vec<Run>>,+ /// When it was typed, unix seconds: the note's time edited while it waits. A pass before it+ /// is sent brings Apple's older time, and laid back without it the note dropped down the+ /// list until the send, then jumped back up. Absent in a save queued before it was kept.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub at: Option<i64>,}/// A card saved here: as the form left it, and as it opened (`None` for a new card).@@ -373,11 +378,13 @@ pub fn record_note_save(.into_iter().next_back().and_then(|p| serde_json::from_str(&p.payload).ok().map(|s| (p, s)));+ let at = chrono_now();let save = |base, base_runs| NoteSave {body: body.to_string(),base,runs: runs.clone(),base_runs,+ at: Some(at),};match waiting {Some((p, before)) if p.tries == 0 => {@@ -424,7 +431,7 @@ pub fn record_note_save(}}lay_note(l, guid, body, runs.as_deref())?;- l.touch_note(guid, chrono_now())+ l.touch_note(guid, at)})}@@ -460,7 +467,19 @@ fn lay_note(body: &str,runs: Option<&[Run]>,) -> quince_core::Result<()> {- let (title, snippet) = quince_icloud::notes::title_and_snippet(body);+ let (derived, snippet) = quince_icloud::notes::title_and_snippet(body);+ // The title the library holds — Apple's, as the phone set it — while the edit leaves the+ // title line alone; the new first line's once it reaches it (notes.rs+ // `title_line_unchanged`, the rule the send follows too, so here and the phone agree).+ let held = l.note(guid)?.map(|n| n.title).filter(|t| !t.trim().is_empty());+ let title = match (held, l.note_body(guid)?) {+ (Some(held), Some(before))+ if quince_icloud::notes::title_line_unchanged(&before, body) =>+ {+ held+ }+ _ => derived,+ };l.set_note_text(guid,body,@@ -995,6 +1014,9 @@ fn lay(l: &mut Library, p: &Pending) -> quince_core::Result<()> {if let Ok(s) = serde_json::from_str::<NoteSave>(&p.payload) {if l.note(&p.record)?.is_some() {lay_note(l, &p.record, &s.body, s.runs.as_deref())?;+ if let Some(at) = s.at {+ l.touch_note(&p.record, at)?;+ }}}}@@ -2504,6 +2526,63 @@ mod tests {);}+ /// A note as a pass stores it: Apple's title and time edited.+ fn titled(lib: &mut Library, guid: &str, title: &str, body: &str, modified: i64) {+ lib.put_notes(&[quince_core::notes::Note {+ guid: guid.into(),+ folder_guid: None,+ title: title.into(),+ snippet: None,+ body: Some(body.into()),+ locked: false,+ pinned: false,+ created_at: None,+ modified_at: Some(modified),+ editable: true,+ etag: None,+ runs: None,+ }])+ .unwrap();+ }++ /// A save keeps the title Apple holds — the phone's — while the title line is untouched,+ /// before it is sent and across a pass; an edit of the title line takes the new one.+ #[test]+ fn a_save_keeps_apples_title_until_the_title_line_changes() {+ let mut lib = Library::in_memory().unwrap();+ let camp = "\u{1F3D5}\u{1F3D5}";+ let text = format!("{camp}\nTent\nStove");+ titled(&mut lib, "N", camp, &text, 100);+ record_note_save(&mut lib, "N", &format!("{text} and lamp"), None, None, None).unwrap();+ assert_eq!(lib.note("N").unwrap().unwrap().title, camp);+ titled(&mut lib, "N", camp, &text, 100);+ replay(&mut lib, NOTES).unwrap();+ assert_eq!(lib.note("N").unwrap().unwrap().title, camp, "laid back over a pass");+ record_note_save(&mut lib, "N", "Camping\nTent\nStove", None, None, None).unwrap();+ assert_eq!(lib.note("N").unwrap().unwrap().title, "Camping");+ }++ /// A note edited here keeps its time edited while the save waits: a pass bringing Apple's+ /// older time does not drop it back down the list until the save is sent. A save that+ /// changes nothing moves nothing.+ #[test]+ fn a_waiting_save_keeps_its_time_edited_across_a_pass() {+ let mut lib = Library::in_memory().unwrap();+ titled(&mut lib, "N", "Groceries", "Groceries\nMilk", 100);+ titled(&mut lib, "M", "Errands", "Errands\nBank", 200);+ record_note_save(&mut lib, "M", "Errands\nBank", None, None, None).unwrap();+ assert_eq!(lib.note("M").unwrap().unwrap().modified_at, Some(200), "nothing changed, nothing moved");+ record_note_save(&mut lib, "N", "Groceries\nMilk\nEggs", None, None, None).unwrap();+ let edited = lib.note("N").unwrap().unwrap().modified_at.unwrap();+ assert!(edited > 200);+ // A pass before the send: Apple still has the old text and the old time.+ titled(&mut lib, "N", "Groceries", "Groceries\nMilk", 100);+ replay(&mut lib, NOTES).unwrap();+ let n = lib.note("N").unwrap().unwrap();+ assert_eq!(n.modified_at, Some(edited));+ assert_eq!(lib.note_body("N").unwrap().as_deref(), Some("Groceries\nMilk\nEggs"));+ }+/// Contacts: a new card gets its id here, shows at once, and edits before it is sent stay/// one create; a pass that does not have it yet keeps it.#[test]diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 9cc6f70..790e277 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -290,6 +290,9 @@ export const api = {* of thousands slow.*/noteBody: (guid: string) => invoke<string | null>("note_body", { guid }),+ /** One note's row as the library lists it now — title, preview, time edited — with no body.+ * Null when there is no such note any more. */+ noteRow: (guid: string) => invoke<Note | null>("note_row", { guid }),noteExportMarkdown: (body: string, runs: unknown[], path: string) =>invoke<void>("note_export_markdown", { body, runs, path }),/**diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 769ef8d..cc3dc55 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -10,7 +10,7 @@ import { useOutbox } from "../lib/outbox";import { ArrowDownUp, ChevronLeft, Folder, FolderOpen, FolderPlus, ListChecks, LockKeyhole, LockKeyholeOpen, Paperclip, Pin, PinOff, Share, SquarePen, Trash2 } from "lucide-react";import { pickOpen, pickSave } from "../lib/pick";import { getCurrentWebview } from "@tauri-apps/api/webview";-import { DEFAULT_ORDER, editorDate, groupNotes, listDate, mergeEdits, splitTitle, titleAndSnippet, type NoteOrder, type Section } from "./notes/model";+import { DEFAULT_ORDER, editorDate, groupNotes, listDate, mergeEdits, splitTitle, type NoteOrder, type Section } from "./notes/model";import { api, messageOf, nestFolders, notesLockApi, type Note, type NoteFolder, type UnlockedNote } from "../lib/ipc";import { LockScreen } from "./notes/LockedNote";import { fileName, useAttachEnabled } from "./notes/attach";@@ -184,6 +184,10 @@ export function NotesView() {const [folder, setFolder] = useState<string>(ALL);const [notes, setNotes] = useState<Note[]>([]);const [openGuid, setOpenGuid] = useState<string | null>(null);+ /** `openGuid` as last drawn, for work that finishes later — a save landing — to tell whether+ * the note it was for is still the one on screen. */+ const openGuidRef = useRef(openGuid);+ openGuidRef.current = openGuid;/*** In a narrow window only one column shows, as on iPhone: the list, or — once a note is* picked or begun — that note, with a way back. A wide window shows both and ignores this.@@ -203,8 +207,14 @@ export function NotesView() {useEffect(() => {if (revision) refreshTables();}, [revision]);- /** The body being typed, held apart from the note until it is saved. */- const [draft, setDraft] = useState<string | null>(null);+ /**+ * The body being typed, held apart from the note until it is saved — with the note it was+ * typed in. Only that note's editor ever shows it: held bare, the text typed in one note was+ * still the draft for the first frame of the next, and a note read ahead opened in that very+ * frame — its editor made with the other note's words, which the next key then saved over it.+ */+ const [drafted, setDrafted] = useState<{ guid: string; text: string } | null>(null);+ const draft = drafted !== null && drafted.guid === openGuid ? drafted.text : null;/** `draft`, for effects that read it without re-running on every keystroke. */const draftRef = useRef<string | null>(null);draftRef.current = draft;@@ -372,7 +382,7 @@ export function NotesView() {adopting.current = null;return;}- setDraft(null);+ setDrafted((d) => (d !== null && d.guid === openGuid ? d : null));setSaved(false);}, [openGuid]);@@ -446,10 +456,11 @@ export function NotesView() {// answer under someone's cursor is how a half-saved note replaced a whole one. Typing// already kept, with nothing new since, is not being typed: what Apple made of it —// merged with another device's edit, once sent — is taken in.- setDraft((typing) => {+ setDrafted((d) => {+ const typing = d !== null && d.guid === openGuid ? d.text : null;const settled = typing !== null && !pending.current && base.current?.guid === openGuid && typing === base.current.text;if (typing === null || settled) setLoadedBody({ guid: openGuid, text });- return typing;+ return d;});}).catch((e) => {@@ -524,24 +535,33 @@ export function NotesView() {// Read ahead before this save, it is not what the note says now.ahead.current.delete(next.guid);aheadAt.current += 1;- // Its row says what it now says, at the top of a list by Date Edited, as the library- // does once it is read again.- const { title, snippet } = titleAndSnippet(kept);- const now = Math.floor(Date.now() / 1000);- setNotes((rows) => {- const row = rows.find((n) => n.guid === next.guid);- if (!row) return rows;- const was = { title: row.title, snippet: row.snippet, modifiedAt: row.modifiedAt };- const is = { title, snippet: snippet || null, modifiedAt: Math.max(row.modifiedAt ?? 0, now) };- if (was.title === is.title && was.snippet === is.snippet && was.modifiedAt === is.modifiedAt) return rows;- return rows.map((n) => (n === row ? { ...n, ...is } : n));- });- const keptRunsForBase = next.runs ? (kept === next.body ? next.runs : carryRuns(next.body, next.runs, kept)) : null;- base.current = { guid: next.guid, text: kept, runs: keptRunsForBase };+ // Its row says what the library now says of it — title, preview, time edited — read+ // back rather than worked out here: the library keeps the title Apple holds while the+ // title line is untouched, and moves the time on only when something really changed. A+ // copy of those rules here had drifted from them, retitling notes and moving them.+ const row = await api.noteRow(next.guid).catch(() => null);+ if (row) {+ setNotes((rows) => {+ const at = rows.findIndex((n) => n.guid === row.guid);+ if (at < 0) return rows;+ const was = rows[at];+ if (was.title === row.title && was.snippet === row.snippet && was.modifiedAt === row.modifiedAt) return rows;+ const out = rows.slice();+ out[at] = { ...was, title: row.title, snippet: row.snippet, modifiedAt: row.modifiedAt };+ return out;+ });+ }+ const keptRuns = next.runs ? (kept === next.body ? next.runs : carryRuns(next.body, next.runs, kept)) : null;+ // Left since: the library has it, and the note now open is another's — nothing on screen+ // is this note's to update. Laid over the open note, its text became that note's.+ if (openGuidRef.current !== next.guid) {+ if (base.current?.guid === next.guid) base.current = null;+ return;+ }+ base.current = { guid: next.guid, text: kept, runs: keptRuns };setSaved(true);// What Apple now holds becomes what this note reads, text and formatting together, so// what is on screen and what was saved agree without a refresh.- const keptRuns = next.runs ? (kept === next.body ? next.runs : carryRuns(next.body, next.runs, kept)) : null;adopted.current = `${next.guid}\u0000${kept}\u0000${JSON.stringify(keptRuns ?? (loadedRunsRef.current?.guid === next.guid ? loadedRunsRef.current.runs : null))}`;setLoadedBody({ guid: next.guid, text: kept });if (keptRuns) setLoadedRuns({ guid: next.guid, runs: keptRuns });@@ -550,8 +570,8 @@ export function NotesView() {// The draft is never handed back to the library's copy, which can lag a save, and was// how a five-line note once became a single letter.if (kept !== next.body) {- setDraft((typing) => {- const now = typing ?? next.body;+ setDrafted((d) => {+ const now = d !== null && d.guid === next.guid ? d.text : next.body;const merged = now === next.body ? kept : (mergeEdits(next.body, now, kept) ?? now);if (merged !== now) {// Another device's words, taken into the editor with the formatting moved along.@@ -560,7 +580,7 @@ export function NotesView() {editorRef.current?.replace(merged, laid);if (merged !== kept) pending.current = { guid: next.guid, body: merged, runs: next.runs ? laid : null };}- return merged;+ return { guid: next.guid, text: merged };});}});@@ -582,7 +602,7 @@ export function NotesView() {if (base.current?.guid !== open.guid) base.current = { guid: open.guid, text: body, runs: formatSafe ? runs : null };draftRuns.current = typedRuns;ahead.current.delete(open.guid);- setDraft(typed);+ setDrafted({ guid: open.guid, text: typed });setEdits((n) => n + 1);setSaved(false);// Compared only when the text is back to what Apple holds — never on an ordinary key,@@ -688,7 +708,7 @@ export function NotesView() {// The note is made from its text; its formatting follows straight after — the first// line a title, as Notes makes it, and whatever was set while composing.const typedRuns = draftRuns.current && runsFit(latest, draftRuns.current) ? titled(latest, draftRuns.current) : null;- setDraft(latest);+ setDrafted({ guid, text: latest });setEdits((n) => n + 1);pending.current = { guid, body: latest, runs: typedRuns };// Its formatting known from the start — what was set while composing, or the title line@@ -1107,12 +1127,14 @@ export function NotesView() {const key = `${open.guid}\u0000${body}\u0000${JSON.stringify(runs)}`;if (adopted.current === key) return;adopted.current = key;- // Only over nothing new: no typing at all, or none since what Apple last confirmed.- if (pending.current || (draftRef.current !== null && draftRef.current !== base.current?.text)) return;+ // Only over nothing new in this note: no typing at all, or none since what Apple last+ // confirmed. Another note's edit still on its way is no reason to keep this one's editor+ // from what it holds.+ if (pending.current?.guid === open.guid || (draftRef.current !== null && draftRef.current !== base.current?.text)) return;editorRef.current?.replace(body, formatSafe ? runs : null);draftRuns.current = formatSafe ? runs : null;if (draftRef.current !== null && draftRef.current !== body) {- setDraft(null);+ setDrafted(null);base.current = null;}}, [open, body, runs, formatSafe]);diff --git a/src/screens/notes/model.ts b/src/screens/notes/model.tsindex c070f62..3ce5412 100644--- a/src/screens/notes/model.ts+++ b/src/screens/notes/model.ts@@ -109,19 +109,6 @@ export function splitTitle(text: string): { title: string; rest: string } {return at < 0 ? { title: text, rest: "" } : { title: text.slice(0, at), rest: text.slice(at + 1) };}-/**- * A note's title and snippet as the backend lists them (notes.rs `title_and_snippet`): the- * first line with words on it, then the next — without the marks where attachments sit. For a- * row to show a save at once, before the library is read again.- */-export function titleAndSnippet(body: string): { title: string; snippet: string } {- const lines = body- .split("\n")- .map((l) => l.replace(/\r$/, "").replace(/[\uFFFC\u2028]/g, " ").split(/\s+/).filter(Boolean).join(" "))- .filter((l) => /[\p{L}\p{N}]/u.test(l));- return { title: lines[0] ?? "", snippet: lines[1] ?? "" };-}-export function joinTitle(title: string, rest: string, hadBreak: boolean): string {return rest.length > 0 || hadBreak ? `${title}\n${rest}` : title;}