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: edit formatted, as icloud.com and the Mac do — ProseMirror editor over Apple's runs; Aa panel (B/I/U/S + styles, current ticked), checklist button, circle ticks, Return carries/ends lists, Mac style keys; saves text+runs together, merges phone edits with formatting carried; long notes convert after paint
Yashwanth Kamireddi657cf9b44d6d
diff --git a/.uiverify/compact.mjs b/.uiverify/compact.mjsindex a550225..90ea7f1 100644--- a/.uiverify/compact.mjs+++ b/.uiverify/compact.mjs@@ -54,8 +54,9 @@ if ((await toggle.count()) === 1) {await page.locator(".note-row", { hasText: "Curtains" }).click();await page.waitForTimeout(300);const title = await page.evaluate(() => {- const t = document.querySelector(".note-title");- return t ? { value: t.value, height: t.getBoundingClientRect().height } : null;+ // The note's first line, set as its title.+ const t = document.querySelector(".note-rich .nf-p");+ return t ? { value: t.textContent, height: t.getBoundingClientRect().height } : null;});ok(!(await visible(".notes-list")) && (await visible(".note-body")), "a note opens in its place","the note did not take the list's place");diff --git a/.uiverify/notes-compose.mjs b/.uiverify/notes-compose.mjsindex 9aea557..fd84522 100644--- a/.uiverify/notes-compose.mjs+++ b/.uiverify/notes-compose.mjs@@ -74,14 +74,15 @@ await page.getByRole("button", { name: "New note" }).click();await page.waitForTimeout(150);await page.keyboard.type("Shopping");await page.waitForTimeout(1600); // the pause: long enough to create the note-// Enter in the title goes on to the body, as in Notes.+// Return after the title goes on to the body, as in Notes.await page.keyboard.type("\nmilk and bread");await page.waitForTimeout(1600); // and long enough to save what followed+// The editor is one document; its first line is the title.const text = () => page.evaluate(() => {- const t = document.querySelector(".note-editor .note-title")?.value ?? null;- const r = document.querySelector(".note-editor .note-text")?.value ?? null;- return { title: t, rest: r, focused: Boolean(document.activeElement?.closest(".note-editor")) };+ const lines = [...document.querySelectorAll(".note-editor .note-rich .nf-p")].map((p) => p.textContent);+ return { title: lines[0] ?? null, rest: lines.length ? lines.slice(1).join("\n") : null,+ focused: Boolean(document.activeElement?.closest(".note-editor")) };});const after = await text();const result = await page.evaluate(() => ({@@ -105,8 +106,9 @@ ok(result.saves.some(([g, body]) => g === "N1" && body === "Shopping\nmilk and b"what was typed after the pause is saved onto that note", `saves ${JSON.stringify(result.saves)}`);// Backspace at the start of the body joins it back onto the title, as in Notes.-await page.locator(".note-editor .note-text").focus();-await page.evaluate(() => document.querySelector(".note-editor .note-text").setSelectionRange(0, 0));+await page.locator(".note-rich .nf-p").nth(1).click();+await page.waitForTimeout(50);+await page.keyboard.press("Home");await page.keyboard.press("Backspace");await page.waitForTimeout(150);const joined = await text();@@ -114,8 +116,18 @@ ok(joined.title === "Shoppingmilk and bread" && joined.rest === "","Backspace at the start of the body joins it to the title", `after Backspace: ${JSON.stringify(joined)}`);// Enter in the middle of the title splits it there.-await page.locator(".note-editor .note-title").focus();-await page.evaluate(() => document.querySelector(".note-editor .note-title").setSelectionRange(8, 8));+await page.locator(".note-rich .nf-p").first().click();+await page.evaluate(() => {+ // The caret after "Shopping", placed exactly.+ const text = document.querySelector(".note-rich .nf-p").firstChild;+ const r = document.createRange();+ r.setStart(text, 8);+ r.collapse(true);+ const sel = window.getSelection();+ sel.removeAllRanges();+ sel.addRange(r);+});+await page.waitForTimeout(80);await page.keyboard.press("Enter");await page.waitForTimeout(150);const split = await text();diff --git a/.uiverify/notes-formatted.mjs b/.uiverify/notes-formatted.mjsindex 92ba276..d7a94b6 100644--- a/.uiverify/notes-formatted.mjs+++ b/.uiverify/notes-formatted.mjs@@ -1,45 +1,86 @@-// A note formatted on a phone shows formatted here: its checklist with ticks, its dashed-// list; a click into it is editing.+// A note is edited formatted, as Notes edits it on icloud.com and the Mac: a phone's+// checklist and dashed list show as they are; the circle ticks; Aa sets a line's style and+// B/I/U/S the selection, with the current style ticked; the checklist button makes and+// unmakes items; Return carries a list on and ends it on an empty item; and every change+// goes to Apple as the text with its runs.import { engine } from "./engine.mjs";import { SERVICES, installStub, openScreen } from "./stub.mjs";const b = await engine.launch();const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });await page.goto("http://localhost:4173", { waitUntil: "networkidle" });await openScreen(page, "Notes");await page.locator(".note-row", { hasText: "Curtains" }).click();await page.waitForTimeout(400);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };-const ticked = await page.locator(".nf-check.is-done").count();-const marks = await page.locator(".nf-mark").allInnerTexts();-ok(ticked === 1, `a ticked checklist item shows ticked [${ticked}]`);-ok(marks.length > 0 && marks.every((m) => m === "–"), `a dashed list shows its dashes ${JSON.stringify(marks.slice(0, 3))}`);-// A tap on a ticked circle unticks it at once, and asks Apple to.-const circle = page.locator(".nf-check .nf-circle").first();-await circle.click();-await page.waitForTimeout(150);-ok((await circle.getAttribute("aria-checked")) === "false", "a tap on a ticked circle unticks it at once");-const sent = await page.evaluate(() => window.__paragraphs?.at(-1));-ok(sent?.checked === false && typeof sent?.start === "number" && sent.start > 0, `and asks Apple for that line ${JSON.stringify(sent)}`);-ok(await page.evaluate(() => document.activeElement?.tagName !== "TEXTAREA"), "a tick does not start editing");-await page.locator(".nf-body, .nf-item:not(.nf-check)").first().click();-await page.waitForTimeout(200);-ok(await page.evaluate(() => document.activeElement?.classList.contains("note-text") && document.activeElement.tagName === "TEXTAREA"),- "a click into it is editing");-// Aa: a line clicked, then Heading — shown at once, and asked of Apple for that line alone.-await page.keyboard.press("Escape");-await page.locator(".note-row", { hasText: "Curtains" }).click();-await page.waitForTimeout(300);-const fan = page.locator(".note-read [data-start]", { hasText: "Fan" }).first();-await fan.click();-await page.waitForTimeout(200);+const line = (text) => page.locator(".note-rich .nf-p", { hasText: text }).first();+const lastSave = async () => { await page.waitForTimeout(1200); return page.evaluate(() => window.__noteSaves?.at(-1)); };+const runAt = (save, text) => {+ if (!save) return null;+ const at = save.body.indexOf(text);+ let n = 0;+ for (const r of save.runs ?? []) { if (at < n + r.length) return r; n += r.length; }+ return null;+};++ok((await page.locator('.note-rich .nf-p[data-style="103"][data-checked="true"]').count()) === 1, "a ticked checklist item shows ticked");+ok((await page.locator('.note-rich .nf-p[data-style="101"]').count()) >= 3, "a dashed list shows as one");++// The circle ticks and unticks, and the change is saved with the formatting.+const item = page.locator('.note-rich .nf-p[data-style="103"]').first();+const box = await item.boundingBox();+await page.mouse.click(box.x + 6, box.y + 10);+await page.waitForTimeout(100);+ok((await item.getAttribute("data-checked")) === null, "a click on the circle unticks it at once");+let save = await lastSave();+ok(save?.runs && runAt(save, "Bathroom")?.style === 103 && runAt(save, "Bathroom")?.checked === false, `and the untick is saved ${JSON.stringify(runAt(save, "Bathroom"))}`);++// Aa → Heading on the line the cursor is in; the panel ticks the current style.+await line("Fan").click();await page.getByRole("button", { name: "Format" }).click();-await page.getByRole("menuitem", { name: "Heading", exact: true }).click();-await page.waitForTimeout(300);-ok((await page.locator(".nf-heading", { hasText: "Fan" }).count()) === 1, "Aa → Heading shows the line as a heading at once");-const styled = await page.evaluate(() => window.__paragraphs?.at(-1));-ok(styled?.style === 1 && styled?.expect === "Fan", `and asks Apple for that line alone ${JSON.stringify(styled)}`);+ok((await page.getByRole("menuitemradio", { checked: true }).innerText()).includes("Dashed List"), "Aa ticks the line's own style");+await page.getByRole("menuitemradio", { name: "Heading", exact: true }).click();+ok((await line("Fan").getAttribute("data-style")) === "1", "Aa → Heading sets the line at once");+ok(await page.evaluate(() => document.activeElement?.classList.contains("note-rich")), "and the cursor stays in the note");+save = await lastSave();+ok(runAt(save, "Fan")?.style === 1 && runAt(save, "wall clock")?.style === 101, `only that line, saved ${JSON.stringify([runAt(save, "Fan"), runAt(save, "wall clock")?.style])}`);++// Bold on a selected word, from the panel and from the keyboard.+await line("wall clock").click();+await page.keyboard.press("End");+await page.keyboard.press("Shift+Home");+await page.getByRole("button", { name: "Format" }).click();+await page.getByRole("button", { name: "Bold" }).click();+ok((await line("wall clock").locator("strong").count()) === 1, "B makes the selection bold at once");+ok((await page.getByRole("button", { name: "Bold" }).getAttribute("aria-pressed")) === "true", "and the panel shows it on");+await page.keyboard.press("Escape");+await page.keyboard.press("Control+i");+ok((await line("wall clock").locator("em").count()) === 1, "Ctrl-I makes it italic");+save = await lastSave();+const clock = runAt(save, "clock");+ok(clock?.bold && clock?.italic, `and both are saved ${JSON.stringify(clock)}`);++// The checklist button makes the line an item, and again makes it a plain line.+await line("Bed").click();+await page.getByRole("button", { name: "Make a checklist" }).click();+ok((await line("Bed").getAttribute("data-style")) === "103", "the checklist button makes an item");+await page.getByRole("button", { name: "Make a checklist" }).click();+ok((await line("Bed").getAttribute("data-style")) === "none", "and pressed again, a plain line");++// Return carries a list on, and Return on an empty item ends it.+await line("Knife").click();+await page.waitForTimeout(50); // a person's pause between a click and a key+await page.keyboard.press("End");+await page.keyboard.press("Enter");+await page.keyboard.type("Spoon");+ok((await line("Spoon").getAttribute("data-style")) === "101", "Return carries the list on");+await page.keyboard.press("Enter");+await page.keyboard.press("Enter");+ok((await page.locator('.note-rich .nf-p[data-style="none"]').count()) >= 2, "Return on an empty item ends the list");+save = await lastSave();+ok(save.body.includes("Spoon") && runAt(save, "Spoon")?.style === 101, "and the new item is saved in the list");await b.close();-process.exitCode = failures ? 1 : 0;+process.exitCode = failures ? 1 : process.exitCode ?? 0;diff --git a/.uiverify/notes-long.mjs b/.uiverify/notes-long.mjsindex c1d439e..291da38 100644--- a/.uiverify/notes-long.mjs+++ b/.uiverify/notes-long.mjs@@ -1,9 +1,9 @@// A very long note types as a short one does, and saves exactly what was typed.//-// React keeps a controlled textarea's text node equal to its value, rewriting all of it on-// every key: in a 300,000-character note that made each keystroke a relayout of the whole-// note. Watched here directly — the text node must not be touched while typing — because a-// timing would pass or fail with the machine.+// A keystroke must change the line typed in and nothing else: an editor that redrew the note+// — React rewriting a controlled field, or the whole document set again — made each key a+// relayout of 300,000 characters. Watched directly: no line of the note but the one typed+// in is added, removed or replaced while typing, and each key is handled well inside a frame.import { engine } from "./engine.mjs";const b = await engine.launch();@@ -39,23 +39,31 @@ await page.waitForTimeout(600);let failures = 0;const ok = (pass, yes, no) => { console.log(pass ? `PASS ${yes}` : `FAIL ${no}`); if (!pass) failures++; };-await page.locator(".note-text").click();+await page.locator(".note-rich .nf-p").last().click();await page.keyboard.press("Control+End");+await page.waitForTimeout(50);await page.evaluate(() => {window.__rewrites = 0;new MutationObserver((m) => { window.__rewrites += m.length; })- .observe(document.querySelector(".note-text"), { childList: true, characterData: true, subtree: true });+ .observe(document.querySelector(".note-rich"), { childList: true });+ // How long each key takes to be handled, start to the next frame.+ window.__keyMs = [];+ document.addEventListener("keydown", () => {+ const t = performance.now();+ requestAnimationFrame(() => window.__keyMs.push(performance.now() - t));+ }, true);});-await page.keyboard.type(" and the end", { delay: 5 });+await page.keyboard.type(" and the end", { delay: 20 });await page.waitForTimeout(100);const rewrites = await page.evaluate(() => window.__rewrites);-ok(rewrites === 0, "typing in a long note leaves its text alone — no rewrite of the whole note per key",- `the note's text was rewritten ${rewrites} times while typing twelve characters`);+ok(rewrites === 0, "typing in a long note touches only the line typed in",+ `lines of the note were replaced ${rewrites} times while typing twelve characters`);+const slowest = await page.evaluate(() => Math.max(...window.__keyMs));+ok(slowest < 50, `and each key is drawn quickly (slowest ${slowest.toFixed(1)} ms)`, `a key took ${slowest.toFixed(1)} ms to draw`);// Leaving the note saves it: every character there, and the new ones at the end.-await page.locator(".note-title").click();await page.locator(".notes-search").click();-await page.waitForTimeout(400);+await page.waitForTimeout(600);const saved = await page.evaluate(() => {const last = window.__saves.at(-1);return last && { length: last.body?.length, tail: last.body?.slice(-24), expected: window.__bodyLength + 12 };diff --git a/.uiverify/notes-merge.mjs b/.uiverify/notes-merge.mjsindex 7596045..698fd4a 100644--- a/.uiverify/notes-merge.mjs+++ b/.uiverify/notes-merge.mjs@@ -13,25 +13,28 @@ await page.waitForTimeout(300);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };// Edit at the end, as a person adds a line.-const read = page.locator(".note-read");-if (await read.count()) await read.click();-const box = page.locator("textarea.note-text");-await box.focus();+await page.locator(".note-rich .nf-p").last().click();+await page.waitForTimeout(50);await page.keyboard.press("Control+End");+await page.waitForTimeout(50);// Meanwhile the phone changed the title: Apple answers with both.await page.evaluate(() => { window.__phoneEdit = (a) => a.body.replace(/^Curtains/, "Curtains (phone)"); });await page.keyboard.type("\nnew line from Linux");await page.waitForTimeout(1500);const sent = await page.evaluate(() => window.__noteSaves?.at(-1));ok(typeof sent?.base === "string" && sent.base.startsWith("Curtains\n"), "a save says what the edit began from");-const title = await page.locator("textarea.note-title, .note-title").first().inputValue().catch(() => "");-const text = await box.inputValue();-ok(title.includes("(phone)") && text.includes("new line from Linux"), `both edits are on screen [${title} … ${text.slice(-24)}]`);+const lines = await page.locator(".note-rich .nf-p").allTextContents();+const title = lines[0] ?? "";+const text = lines.join("\n");+ok(title.includes("(phone)") && text.endsWith("cover\nnew line from Linux"), `both edits are on screen [${title} … ${text.slice(-24)}]`);// The next save begins from what Apple confirmed, so it does not undo the phone's edit.await page.evaluate(() => { window.__phoneEdit = null; });await page.keyboard.type(" again");await page.waitForTimeout(1500);const again = await page.evaluate(() => window.__noteSaves?.at(-1));ok(again?.base?.includes("(phone)") && again?.body?.includes("(phone)"), "the next save keeps the phone's edit");+// And the formatting moved with it: the phone's words did not unset the lines below.+ok((await page.locator('.note-rich .nf-p[data-style="101"]').count()) >= 3 && (await page.locator(".note-rich .nf-p").first().getAttribute("data-style")) === "0",+ "the note keeps its formatting through the merge");await b.close();process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/notes-rich.test.mjs b/.uiverify/notes-rich.test.mjsnew file mode 100644index 0000000..63fd989--- /dev/null+++ b/.uiverify/notes-rich.test.mjs@@ -0,0 +1,39 @@+// A note into the editor and back: Apple's text and runs survive the round trip exactly.+import { test } from "node:test";+import assert from "node:assert/strict";+import { toDoc, fromDoc, carryRuns, STYLE } from "../src/screens/notes/rich.ts";++const r = (length, extra = {}) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false,+ underline: false, strike: false, link: null, ...extra });++test("a formatted note goes in and comes out the same", () => {+ const text = "Shopping\nBuy milk now\nCall the bank\n• Fan";+ const runs = [+ r(9, { style: STYLE.title }),+ r(4, { style: STYLE.checklist, checked: true }), r(4, { style: STYLE.checklist, checked: true, bold: true }),+ r(5, { style: STYLE.checklist, checked: true }),+ r(14, { style: STYLE.dashed }),+ r(5, { italic: true, link: "https://example.com" }),+ ];+ const back = fromDoc(toDoc(text, runs));+ assert.equal(back.text, text);+ assert.deepEqual(back.runs, runs);+});++test("attachments and line breaks keep their place", () => {+ const text = "ab c";+ const back = fromDoc(toDoc(text, [r(text.length)]));+ assert.equal(back.text, text);+});++test("without runs that fit, every line is plain and the text is kept", () => {+ const text = "One\nTwo\n";+ const back = fromDoc(toDoc(text, [r(2)]));+ assert.equal(back.text, text);+ assert.ok(back.runs.every((x) => x.style === null && !x.bold));+});++test("runs follow another device's edit merged in", () => {+ const out = carryRuns("abc\ndef", [r(3, { bold: true }), r(4)], "abcXY\ndef");+ assert.deepEqual(out.map((x) => [x.length, x.bold]), [[5, true], [4, false]]);+});diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 1a13f16..dd7a51e 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -189,6 +189,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "reminders_smart": return !remindersFixture || remindersFixture === "lists" ? [] : reminderItems.filter(r => !r.completedAt);case "note_paragraph": (window.__paragraphs ??= []).push(args); return null;case "note_runs": {+ if (window.__savedRuns?.[args.guid]) return window.__savedRuns[args.guid];// Curtains, set as a phone sets one: a title, then a dashed list and a ticked item.if (args.guid !== "n1") return [];const body = (noteList.find((n) => n.guid === "n1") ?? {}).body ?? "";@@ -213,10 +214,16 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notewindow.__noteFolders = (window.__noteFolders ?? noteFolders.slice()).filter((f) => f.guid !== args.guid);(window.__folderCalls ??= []).push(["delete", args.guid]);return null;- case "note_save":+ case "note_save": {(window.__noteSaves ??= []).push(args);// A test can play the other device: what Apple answers is what it now holds.- return window.__phoneEdit ? window.__phoneEdit(args) : args.body;+ const kept = window.__phoneEdit ? window.__phoneEdit(args) : args.body;+ // Kept, as Apple keeps it: the next read of the note gives what was saved.+ const n = noteList.find((x) => x.guid === args.guid);+ if (n) n.body = kept;+ if (args.runs && kept === args.body) (window.__savedRuns ??= {})[args.guid] = args.runs;+ return kept;+ }case "note_delete": case "note_move": return null;case "note_pin": {const n = noteList.find((x) => x.guid === args?.guid);diff --git a/check.sh b/check.shindex 8a946ed..4a65870 100755--- a/check.sh+++ b/check.sh@@ -21,6 +21,7 @@ step "rust tests" cargo test --workspace --quietstep "typescript" npx tsc --noEmitstep "calendar layout" node --test .uiverify/calendar-model.test.mjsstep "notes layout" node --test .uiverify/notes-model.test.mjs+step "notes editor model" node --test .uiverify/notes-rich.test.mjsstep "frontend build" npm run build# The browser checks need the built bundle served.diff --git a/probe/examples/notes_tables_read.rs b/probe/examples/notes_tables_read.rsnew file mode 100644index 0000000..5c8a2f0--- /dev/null+++ b/probe/examples/notes_tables_read.rs@@ -0,0 +1,47 @@+//! Read-only: every table in Notes — its attachment record and the CRDT inside — dumped so+//! the shape can be matched exactly before Quince writes one. Nothing is written.+use anyhow::{anyhow, Result};+#[tokio::main]+async fn main() -> Result<()> {+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");+ let mut client = quince_auth::Client::new(&dir)?;+ if !client.resume().await? {+ return Err(anyhow!("no session"));+ }+ let root = client.session().service_url("ckdatabasews").ok_or_else(|| anyhow!("no ckdatabasews"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let walk = zc.all_records("Notes", None).await?;+ let mut kinds = std::collections::BTreeMap::<String, usize>::new();+ for r in &walk.records {+ *kinds.entry(r["recordType"].as_str().unwrap_or("?").to_string()).or_default() += 1;+ }+ println!("records: {kinds:?}");+ for r in walk.records.iter().filter(|r| r["recordType"] == "Attachment") {+ let f = &r["fields"];+ let uti = f["UTI"]["value"].as_str().or(f["UTIEncrypted"]["value"].as_str()).unwrap_or("");+ let keys: Vec<&String> = f.as_object().map(|o| o.keys().collect()).unwrap_or_default();+ for k in ["Note", "TitleEncrypted", "FallbackTitle", "FallbackSubtitleIOS", "MinimumSupportedNotesVersion", "UTIEncrypted", "CreationDate"] {+ println!(" {k} = {}", f[k].to_string().chars().take(160).collect::<String>());+ }+ if let Some(note) = f["Note"]["value"]["recordName"].as_str() {+ if let Some(n) = walk.records.iter().find(|x| x["recordName"] == note) {+ let body = n["fields"]["TextDataEncrypted"]["value"].as_str().unwrap_or("");+ let raw = quince_icloud::ckdocument::debug_inflate(body).unwrap_or_default();+ println!(" note text: {:?}", quince_icloud::ckdocument::text_from_base64(body));+ for (i, run) in quince_icloud::ckdocument::debug_attribute_runs(&raw).iter().enumerate() {+ println!(" run {i}: {}", quince_icloud::ckdocument::debug_tree(run, 6).join(" | "));+ }+ }+ }+ println!("attachment {} uti={uti} keys={keys:?}", r["recordName"]);+ if let Some(m) = f["MergeableDataEncrypted"]["value"].as_str() {+ if let Some(raw) = quince_icloud::ckdocument::debug_inflate(m) {+ for line in quince_icloud::ckdocument::debug_tree(&raw, 12).iter() {+ println!(" {line}");+ }+ }+ }+ }+ Ok(())+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex b55a1e2..06825c2 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -144,8 +144,8 @@ export const api = {*/noteBody: (guid: string) => invoke<string | null>("note_body", { guid }),/** Answers with the text Apple now holds — ours, or ours combined with another device's. */- noteSave: (guid: string, body: string, base: string | null) =>- invoke<string>("note_save", { guid, body, base }),+ noteSave: (guid: string, body: string, base: string | null, runs: import("../screens/notes/Formatted").Run[] | null = null) =>+ invoke<string>("note_save", { guid, body, base, runs }),noteCreate: (folderGuid: string | null, body: string) =>invoke<string>("note_create", { folderGuid, body }),noteDelete: (guid: string) => invoke<void>("note_delete", { guid }),diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex fc62526..4e755f7 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -1,17 +1,35 @@-import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";import { Notice } from "../components/Notice";-import { flushSync } from "react-dom";-import { ChevronLeft, Folder, FolderOpen, FolderPlus, Pin, PinOff, SquarePen, Trash2 } from "lucide-react";-import { LongTextarea } from "../components/LongTextarea";-import { editorDate, groupNotes, joinTitle, listDate, mergeEdits, splitTitle } from "./notes/model";+import { ChevronLeft, Folder, FolderOpen, FolderPlus, ListChecks, Pin, PinOff, SquarePen, Trash2 } from "lucide-react";+import { editorDate, groupNotes, listDate, mergeEdits, splitTitle } from "./notes/model";import { api, messageOf, nestFolders, type Note, type NoteFolder } from "../lib/ipc";import { RowMenu } from "../components/RowMenu";-import { FormattedBody, restyle, runsFit, STYLE, type Run } from "./notes/Formatted";+import { FormattedBody, type Run } from "./notes/Formatted";+import { carryRuns, runsFit } from "./notes/rich";+import { NoteEditor, type EditorHandle, type EditorStatus } from "./notes/NoteEditor";+import { FormatPanel } from "./notes/FormatPanel";import { useSync } from "../lib/sync";import { Picker } from "../components/Picker";const ALL = "__all__";+/** A new note's first line set as its title, as Notes sets it, unless it was given a style. */+function titled(text: string, runs: Run[]): Run[] {+ const end = text.indexOf("\n");+ const firstLine = end < 0 ? text.length : end + 1;+ const out: Run[] = [];+ let at = 0;+ for (const r of runs) {+ const from = at;+ at += r.length;+ if (from >= firstLine || r.style !== null) { out.push(r); continue; }+ const inside = Math.min(at, firstLine) - from;+ out.push({ ...r, length: inside, style: 0 });+ if (r.length > inside) out.push({ ...r, length: r.length - inside });+ }+ return out;+}+/** Apple's Recently Deleted, by the record name that is the same in every language. */const TRASH_FOLDER = "TrashFolder-CloudKit";/** Apple's own "Notes" folder: it can be neither renamed nor deleted. */@@ -34,6 +52,11 @@ export function NotesView() {const { revision } = useSync();/** The body being typed, held apart from the note until it is saved. */const [draft, setDraft] = useState<string | null>(null);+ /** `draft`, for effects that read it without re-running on every keystroke. */+ const draftRef = useRef<string | null>(null);+ draftRef.current = draft;+ /** Counts every change made in the editor, formatting as much as text. */+ const [edits, setEdits] = useState(0);const [busy, setBusy] = useState(false);const [saved, setSaved] = useState(false);@@ -180,14 +203,13 @@ export function NotesView() {/** How the open note is set, from Apple's attribute runs, read with its body. */const [loadedRuns, setLoadedRuns] = useState<{ guid: string; runs: Run[] } | null>(null);- /** Showing the note formatted; a click into its text switches to editing it. */- const [reading, setReading] = useState(true);- /** Where the line the Aa menu acts on begins, in the note's whole text. */- const [lineAt, setLineAt] = useState<number | null>(null);- const [styleMenu, setStyleMenu] = useState<{ x: number; y: number; alignRight: boolean } | null>(null);+ const loadedRunsRef = useRef(loadedRuns);+ loadedRunsRef.current = loadedRuns;+ /** The line the cursor is in and its marks, for the toolbar to show as on. */+ const [status, setStatus] = useState<EditorStatus | null>(null);+ const [formatAt, setFormatAt] = useState<{ x: number; y: number } | null>(null)useEffect(() => {- setReading(true);- setLineAt(null);+ setFormatAt(null);if (!openGuid) return setLoadedRuns(null);let cancelled = false;api.noteRuns(openGuid).then(@@ -197,70 +219,21 @@ export function NotesView() {return () => { cancelled = true; };}, [openGuid, revision]);- /**- * Tick a checklist item, as a tap on its circle does on the phone: shown at once, then- * written; a refusal puts the tick back and says why.- */- const tick = async (guid: string, start: number, checked: boolean) => {- const text = loadedBody?.guid === guid ? loadedBody.text : "";- const nl = text.indexOf("\n", start);- const end = nl < 0 ? text.length : nl + 1;- const flip = (on: boolean) =>- setLoadedRuns((cur) => {- if (!cur || cur.guid !== guid) return cur;- let at = 0;- const runs = cur.runs.map((r) => {- const inside = at >= start && at < end && r.style === 103;- at += r.length;- return inside ? { ...r, checked: on } : r;- });- return { guid, runs };- });- flip(checked);- try {- await api.noteParagraph(guid, start, { checked, expect: text.slice(start, nl < 0 ? text.length : nl) });- } catch (e) {- flip(!checked);- setError(messageOf(e));- }- };-- /**- * Set the line the cursor is on to one of Notes' styles, as the Aa menu does. Anything- * typed is saved first, so the line is the line Apple holds; the style shows at once, the- * note shown formatted, and a refusal puts it back with the reason.- */- const applyStyle = async (style: number) => {- if (!open || lineAt === null) return;- const guid = open.guid;- await flush();- // Only over text Apple has: a save that did not go through leaves the typing on screen,- // and showing the formatted copy instead would hide it.- if (pending.current) return;- const text = (base.current?.guid === guid ? base.current.text : null) ?? (loadedBody?.guid === guid ? loadedBody.text : null);- if (text === null || (draft !== null && draft !== text)) return;- const nl = text.indexOf("\n", lineAt);- const expect = text.slice(lineAt, nl < 0 ? text.length : nl);- const before = loadedRuns?.guid === guid ? loadedRuns.runs : null;- if (before && runsFit(text, before)) {- setLoadedRuns({ guid, runs: restyle(text, before, lineAt, style) });- setDraft(null);- setLoadedBody({ guid, text });- setReading(true);- }- try {- await api.noteParagraph(guid, lineAt, { style, expect });- } catch (e) {- if (before) setLoadedRuns({ guid, runs: before });- setError(messageOf(e));- }- };-/** What the open note says, or null while that is still unknown. */const body = open && loadedBody?.guid === open.guid ? loadedBody.text : null;const runs = open && loadedRuns?.guid === open.guid ? loadedRuns.runs : null;- // Formatted only while it is exactly what Apple holds: untouched here, the runs adding up.- const formatted = Boolean(body !== null && runs && draft === null && runsFit(body, runs));+ /**+ * Whether this note's formatting can be written from the editor: only when the runs read+ * describe the text exactly. Otherwise the editor shows it plain and saves the text alone,+ * which keeps Apple's formatting where it is — never a plain copy written over it.+ */+ const formatSafe = body !== null && runsFit(body, runs);+ /** The editor, to hand it what Apple holds and to run the toolbar's commands. */+ const editorRef = useRef<EditorHandle | null>(null);+ /** A new note's id once it is made, so the editor it was typed in stays the one shown. */+ const adoptedKey = useRef<string | null>(null);+ /** The formatting on screen now, beside `draft` — the text on screen now. */+ const draftRuns = useRef<Run[] | null>(null);const dirty = draft !== null && body !== null && draft !== body;@@ -272,7 +245,7 @@ export function NotesView() {* note or the field takes it immediately, so nothing is ever waiting on a timer when you* walk away.*/- const pending = useRef<{ guid: string; body: string } | null>(null);+ const pending = useRef<{ guid: string; body: string; runs: Run[] | null } | null>(null);/*** The text Apple last confirmed for the open note: what an edit began from. Sent with each* save, so the save can tell an edit made on another device since and keep both.@@ -290,20 +263,34 @@ export function NotesView() {const from = base.current?.guid === next.guid ? base.current.text : null;let saved: string | null = null;const ok = await write(async () => {- saved = await api.noteSave(next.guid, next.body, from);+ saved = await api.noteSave(next.guid, next.body, from, next.runs);});if (!ok || saved === null) return;const kept: string = saved;base.current = { guid: next.guid, text: kept };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 });// Apple holds `kept` — ours, or ours with another device's edit combined. What is on// screen takes it in: unchanged if nothing was typed since, combined if something was.// 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) => {- if (typing === null || typing === next.body) return kept;- return mergeEdits(next.body, typing, kept) ?? typing;+ const now = typing ?? 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.+ const laid = draftRuns.current ? carryRuns(now, draftRuns.current, merged) : null;+ draftRuns.current = laid;+ editorRef.current?.replace(merged, laid);+ if (merged !== kept) pending.current = { guid: next.guid, body: merged, runs: next.runs ? laid : null };+ }+ return merged;});}});@@ -312,16 +299,21 @@ export function NotesView() {}, [write]);const type = useCallback(- (typed: string) => {+ (typed: string, typedRuns: Run[]) => {// Nothing may be typed into a note whose text has not arrived.if (!open || body === null) return;// The first keystroke in a note marks what it read as the base of the edit.if (base.current?.guid !== open.guid) base.current = { guid: open.guid, text: body };+ draftRuns.current = typedRuns;setDraft(typed);+ setEdits((n) => n + 1);setSaved(false);- pending.current = typed === body ? null : { guid: open.guid, body: typed };+ // Compared only when the text is back to what Apple holds — never on an ordinary key,+ // which in a long note would be a second walk of the whole thing per keystroke.+ const unchanged = typed === body && (!formatSafe || JSON.stringify(typedRuns) === JSON.stringify(runs));+ pending.current = unchanged ? null : { guid: open.guid, body: typed, runs: formatSafe ? typedRuns : null };},- [open, body]+ [open, body, runs, formatSafe]);// A pause in typing is the signal. Long enough not to write on every keystroke, short@@ -330,7 +322,8 @@ export function NotesView() {if (!pending.current) return undefined;const timer = window.setTimeout(() => void flush(), 900);return () => window.clearTimeout(timer);- }, [draft, flush]);+ // `edits` as well as the text: a change of style alone leaves the text as it was.+ }, [draft, edits, flush]);// Leaving the note takes whatever is outstanding with it, before the draft is cleared; the// next note's edit begins from what that note reads, never from this one's.@@ -402,14 +395,23 @@ export function NotesView() {const guid = await api.noteCreate(draft.folderGuid, draft.body);const latest = composingRef.current?.body ?? draft.body;adopting.current = guid;+ // The same editor goes on as this note: nothing remounts under the cursor.+ adoptedKey.current = guid;setLoadedBody({ guid, text: draft.body });- if (latest !== draft.body) {- setDraft(latest);- pending.current = { guid, body: latest };- } else {- setDraft(null);- pending.current = null;- }+ base.current = { guid, text: draft.body };+ // 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);+ setEdits((n) => n + 1);+ pending.current = { guid, body: latest, runs: typedRuns };+ // In the list at once, so the note is open — and its editor still there — before the+ // list is read again.+ const now = Math.floor(Date.now() / 1000);+ setNotes((ns) => ns.some((n) => n.guid === guid) ? ns : [{+ guid, folderGuid: draft.folderGuid, title: splitTitle(latest).title || "New Note", snippet: null, body: null,+ locked: false, pinned: false, createdAt: now, modifiedAt: now, editable: true, etag: null,+ } as Note, ...ns]);setOpenGuid(guid);setComposing(null);await read();@@ -440,8 +442,6 @@ export function NotesView() {[composing, commitComposing]);- const editor = useRef<HTMLTextAreaElement | null>(null);- const bodyEditor = useRef<HTMLTextAreaElement | null>(null);const create = useCallback(async () => {if (composingRef.current) await commitComposing();await flush();@@ -449,7 +449,7 @@ export function NotesView() {setOpenGuid(null);setDetail(true);// Straight into the new note, as Apple's New Note does.- window.requestAnimationFrame(() => editor.current?.focus());+ window.requestAnimationFrame(() => editorRef.current?.focus());}, [commitComposing, flush, folder, setComposing]);/**@@ -553,43 +553,40 @@ export function NotesView() {return () => window.clearTimeout(timer);}, [saved]);- /** What the editor holds right now, whoever is writing it. */- const text = composing ? composing.body : (draft ?? body ?? "");- const { title: titleLine, rest } = splitTitle(text);- const hadBreak = text.includes("\n");const canEdit = Boolean(composing) || Boolean(open && !open.locked && open.editable && body !== null);- /** Every change to either half of the editor becomes one change to the whole note. */- const apply = (next: string) => {- if (composingRef.current) setComposing((c) => (c ? { ...c, body: next } : c));- else type(next);- };- /**- * Make a change that moves the cursor into the other half, all at once. Waiting a frame to- * move focus left a gap a fast typist fills: the letter after Enter landed back in the- * title. The change is applied and drawn synchronously, and focus moves in the same turn.- */- const moveWith = (next: string, el: HTMLTextAreaElement | null, at: number) => {- flushSync(() => apply(next));- if (!el) return;- el.focus();- el.setSelectionRange(at, at);- };- const place = (el: HTMLTextAreaElement | null, at: number) => {- if (!el) return;- el.focus();- el.setSelectionRange(at, at);+ /** Every change in the editor: to the note being composed, or to the open one. */+ const apply = (next: string, nextRuns: Run[]) => {+ if (composingRef.current) {+ draftRuns.current = nextRuns;+ setComposing((c) => (c ? { ...c, body: next } : c));+ } else type(next, nextRuns);};- // The title grows onto more lines as it is typed, as a heading does, rather than scrolling.- useLayoutEffect(() => {- const el = editor.current;- if (!el) return;- el.style.height = "0px";- el.style.height = `${el.scrollHeight}px`;- // `detail` too: in a narrow window the note is hidden until opened, and a hidden title- // measures nothing — it came up zero lines tall, and the note had no title.- }, [titleLine, openGuid, composing, detail]);+ // What Apple holds, taken into the editor when nothing is being typed — a change made on+ // the phone arrives in the open note without it being reopened.+ // Keyed to Apple's copy alone: a save, a keystroke or a re-render is never a reason to+ // put the editor back to an older text.+ const adopted = useRef<string | null>(null);+ useEffect(() => {+ if (!open || body === null) return;+ 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;+ editorRef.current?.replace(body, formatSafe ? runs : null);+ draftRuns.current = formatSafe ? runs : null;+ if (draftRef.current !== null && draftRef.current !== body) {+ setDraft(null);+ base.current = null;+ }+ }, [open, body, runs, formatSafe]);++ const leave = () => {+ editorRef.current?.flushChange();+ void (composingRef.current ? commitComposing() : flush());+ };// Another folder is another list, and a narrow window shows that list, not a note from the last.useEffect(() => setDetail(false), [folder]);@@ -798,38 +795,45 @@ export function NotesView() {</p>{!composing && open && !open.locked && (<div className="note-bar-actions">- {styleMenu && (- <RowMenu- at={styleMenu}- onClose={() => setStyleMenu(null)}- entries={[- { label: "Title", run: () => void applyStyle(STYLE.title) },- { label: "Heading", run: () => void applyStyle(STYLE.heading) },- { label: "Subheading", run: () => void applyStyle(STYLE.subheading) },- { label: "Body", run: () => void applyStyle(STYLE.body) },- { label: "Monospaced", run: () => void applyStyle(STYLE.mono) },- null,- { label: "• Bulleted List", run: () => void applyStyle(STYLE.bulleted) },- { label: "– Dashed List", run: () => void applyStyle(STYLE.dashed) },- { label: "1. Numbered List", run: () => void applyStyle(STYLE.numbered) },- { label: "Checklist", run: () => void applyStyle(STYLE.checklist) },- ]}- />- )}{!inTrash && open.editable && (- <button- className="notes-icon notes-aa"- aria-label="Format"- aria-haspopup="menu"- title={lineAt === null ? "Format — click a line first" : "Format"}- disabled={busy || lineAt === null}- onClick={(e) => {- const r = e.currentTarget.getBoundingClientRect();- setStyleMenu({ x: r.right, y: r.bottom + 4, alignRight: true });- }}- >- Aa- </button>+ <>+ <button+ className={`notes-icon notes-aa${formatAt ? " is-on" : ""}`}+ aria-label="Format"+ aria-haspopup="dialog"+ aria-expanded={Boolean(formatAt)}+ title="Choose a style to apply to text"+ disabled={!canEdit}+ // Keeps the cursor where it is in the note while the panel is open.+ onMouseDown={(e) => e.preventDefault()}+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect();+ setFormatAt((at) => (at ? null : { x: r.left + r.width / 2, y: r.bottom + 6 }));+ }}+ >+ Aa+ </button>+ <button+ className={`notes-icon${status?.checklist ? " is-on" : ""}`}+ aria-label="Make a checklist"+ aria-pressed={Boolean(status?.checklist)}+ title="Make a checklist"+ disabled={!canEdit}+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => editorRef.current?.toggleChecklist()}+ >+ <ListChecks size={18} strokeWidth={2} aria-hidden="true" />+ </button>+ {formatAt && (+ <FormatPanel+ at={formatAt}+ status={status}+ onClose={() => setFormatAt(null)}+ onStyle={(style) => editorRef.current?.setStyle(style)}+ onMark={(mark) => editorRef.current?.toggleMark(mark)}+ />+ )}+ </>)}{!inTrash && <Pickerlabel={`Folder for ${open.title}`}@@ -896,117 +900,28 @@ export function NotesView() {* saved is always the two put back together.*/}{canEdit ? (- <div className="note-editor">- <textarea- key="title"- ref={editor}- className="note-title"- onSelect={() => setLineAt(0)}- rows={1}- aria-label={composing ? "New note" : `Title of ${open?.title ?? "note"}`}+ <div className="note-editor"+ onKeyDown={(e) => {+ if ((e.metaKey || e.ctrlKey) && e.key === "s") {+ e.preventDefault();+ leave();+ }+ }}+ >+ <NoteEditor+ // One editor per note, so nothing typed in one can be shown in another.+ key={composing || (open && adoptedKey.current === open.guid) ? "composing" : open?.guid}+ ref={editorRef}+ text={composing ? composing.body : (draft ?? body ?? "")}+ runs={composing ? draftRuns.current : formatSafe ? runs : null}+ editable+ autoFocus={Boolean(composing)}+ label={composing ? "New note" : `${open?.title ?? "Note"}`}placeholder={composing ? "New Note" : undefined}- value={titleLine}- spellCheck- onChange={(e) => apply(joinTitle(e.target.value, rest, hadBreak))}- onKeyDown={(e) => {- const el = e.currentTarget;- if (e.key === "Enter") {- e.preventDefault();- const at = el.selectionStart;- moveWith(- `${titleLine.slice(0, at)}\n${titleLine.slice(at)}${hadBreak ? `\n${rest}` : ""}`,- bodyEditor.current,- 0- );- } else if (e.key === "ArrowDown" && el.selectionStart === titleLine.length) {- e.preventDefault();- place(bodyEditor.current, 0);- } else if ((e.metaKey || e.ctrlKey) && e.key === "s") {- e.preventDefault();- void (composingRef.current ? commitComposing() : flush());- }- }}- onBlur={(e) => {- if (e.relatedTarget === bodyEditor.current) return;- void (composingRef.current ? commitComposing() : flush());- }}+ onChange={apply}+ onStatus={setStatus}+ onBlur={leave}/>- {reading && formatted && !composing ? (- <div- className="note-text note-read"- role="textbox"- aria-readonly="false"- aria-label={`Body of ${open?.title ?? "note"}`}- tabIndex={0}- onClick={(e) => {- const line = (e.target as HTMLElement).closest("[data-start]");- const at = line ? Number(line.getAttribute("data-start")) : null;- if (at !== null) setLineAt(at);- setReading(false);- // Into the text at the line clicked, so the cursor and the Aa menu agree.- window.setTimeout(() => {- const el = bodyEditor.current;- if (!el) return;- el.focus();- if (at !== null) {- const pos = Math.max(0, at - titleLine.length - 1);- el.setSelectionRange(pos, pos);- }- }, 0);- }}- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- setReading(false);- window.setTimeout(() => bodyEditor.current?.focus(), 0);- }- }}- >- <FormattedBody- text={body ?? ""}- runs={runs ?? []}- skip={titleLine.length + 1}- onTick={open ? (start, checked) => void tick(open.guid, start, checked) : undefined}- />- </div>- ) : (- <LongTextarea- key="body"- ref={bodyEditor}- className="note-text"- onSelect={(e) => {- // The line the cursor is on, in the whole note: title line, then the body.- const el = e.currentTarget;- const offset = titleLine.length + 1 + el.selectionStart;- const all = titleLine + "\n" + el.value;- setLineAt(all.lastIndexOf("\n", offset - 1) + 1);- }}- aria-label={composing ? "New note text" : `Body of ${open?.title ?? "note"}`}- value={rest}- spellCheck- onChange={(e) => apply(joinTitle(titleLine, e.target.value, true))}- onKeyDown={(e) => {- const el = e.currentTarget;- if (e.key === "Backspace" && el.selectionStart === 0 && el.selectionEnd === 0 && hadBreak) {- e.preventDefault();- moveWith(titleLine + rest, editor.current, titleLine.length);- } else if (e.key === "ArrowUp" && !rest.slice(0, el.selectionStart).includes("\n")) {- e.preventDefault();- place(editor.current, titleLine.length);- } else if ((e.metaKey || e.ctrlKey) && e.key === "s") {- e.preventDefault();- void (composingRef.current ? commitComposing() : flush());- }- }}- onBlur={(e) => {- if (e.relatedTarget === editor.current) return;- // Leaving the text — not for the Aa menu, which acts on it — shows the note- // formatted again once nothing is left unsaved.- if (!(e.relatedTarget as HTMLElement | null)?.closest(".notes-aa")) setReading(true);- void (composingRef.current ? commitComposing() : flush());- }}- />- )}</div>) : open?.locked ? (<p className="cal-empty">diff --git a/src/screens/notes/FormatPanel.tsx b/src/screens/notes/FormatPanel.tsxnew file mode 100644index 0000000..4bcbb5a--- /dev/null+++ b/src/screens/notes/FormatPanel.tsx@@ -0,0 +1,122 @@+import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { Check } from "lucide-react";+import { Portal } from "../../components/Portal";+import type { EditorStatus } from "./NoteEditor";+import { STYLE } from "./rich";++/** The styles, in icloud.com's order, each drawn the way it sets a line. */+const STYLES: { style: number | null; label: string; className: string; mark?: string }[] = [+ { style: STYLE.title, label: "Title", className: "fp-title" },+ { style: STYLE.heading, label: "Heading", className: "fp-heading" },+ { style: STYLE.subheading, label: "Subheading", className: "fp-subheading" },+ { style: null, label: "Body", className: "fp-body" },+ { style: STYLE.mono, label: "Monospaced", className: "fp-mono" },+ { style: STYLE.bulleted, label: "Bulleted List", className: "fp-list", mark: "•" },+ { style: STYLE.dashed, label: "Dashed List", className: "fp-list", mark: "-" },+ { style: STYLE.numbered, label: "Numbered List", className: "fp-list", mark: "1." },+];++const MARKS = [+ { mark: "bold", label: "Bold", glyph: <b>B</b> },+ { mark: "italic", label: "Italic", glyph: <i>I</i> },+ { mark: "underline", label: "Underline", glyph: <u>U</u> },+ { mark: "strike", label: "Strikethrough", glyph: <s>S</s> },+] as const;++/**+ * Notes' Aa panel: bold, italic, underline and strikethrough across the top, the paragraph+ * styles beneath with the current one ticked — as icloud.com and the Mac lay it out. It acts+ * on the note without taking the cursor out of it, so a style is chosen and typing goes on.+ */+export function FormatPanel({+ at,+ status,+ onClose,+ onStyle,+ onMark,+}: {+ at: { x: number; y: number };+ status: EditorStatus | null;+ onClose: () => void;+ onStyle: (style: number | null) => void;+ onMark: (mark: "bold" | "italic" | "underline" | "strike") => void;+}) {+ const box = useRef<HTMLDivElement | null>(null);+ const [pos, setPos] = useState({ left: at.x, top: at.y });+ useLayoutEffect(() => {+ const el = box.current;+ if (!el) return;+ const { width, height } = el.getBoundingClientRect();+ const left = Math.max(8, Math.min(at.x - width / 2, window.innerWidth - width - 8));+ const top = at.y + height > window.innerHeight - 8 ? Math.max(8, window.innerHeight - height - 8) : at.y;+ setPos({ left, top });+ }, [at]);+ useEffect(() => {+ const down = (e: MouseEvent) => {+ const t = e.target as HTMLElement;+ if (!box.current?.contains(t) && !t.closest(".notes-aa")) onClose();+ };+ const key = (e: KeyboardEvent) => e.key === "Escape" && onClose();+ document.addEventListener("mousedown", down);+ window.addEventListener("keydown", key);+ window.addEventListener("resize", onClose);+ return () => {+ document.removeEventListener("mousedown", down);+ window.removeEventListener("keydown", key);+ window.removeEventListener("resize", onClose);+ };+ }, [onClose]);++ const current = status?.style ?? null;+ const isCurrent = (style: number | null) =>+ style === null ? current === null || current === STYLE.body : current === style;++ return (+ <Portal>+ <div+ ref={box}+ className="format-panel"+ role="dialog"+ aria-label="Format"+ style={{ left: pos.left, top: pos.top }}+ // Clicks here never take focus from the note.+ onMouseDown={(e) => e.preventDefault()}+ >+ <div className="fp-marks" role="group" aria-label="Text style">+ {MARKS.map(({ mark, label, glyph }) => (+ <button+ key={mark}+ type="button"+ className="fp-mark"+ aria-label={label}+ aria-pressed={Boolean(status?.[mark])}+ title={label}+ onClick={() => onMark(mark)}+ >+ {glyph}+ </button>+ ))}+ </div>+ <div className="fp-styles" role="menu" aria-label="Paragraph style">+ {STYLES.map(({ style, label, className, mark }) => (+ <button+ key={label}+ type="button"+ role="menuitemradio"+ aria-checked={isCurrent(style)}+ className={`fp-style ${className}`}+ onClick={() => {+ onStyle(style);+ onClose();+ }}+ >+ <span className="fp-check" aria-hidden="true">{isCurrent(style) && <Check size={15} strokeWidth={2} />}</span>+ {mark && <span className="fp-list-mark" aria-hidden="true">{mark}</span>}+ <span>{label}</span>+ </button>+ ))}+ </div>+ </div>+ </Portal>+ );+}diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsxnew file mode 100644index 0000000..1cf02ba--- /dev/null+++ b/src/screens/notes/NoteEditor.tsx@@ -0,0 +1,328 @@+import "prosemirror-view/style/prosemirror.css";+import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";+import { EditorState, TextSelection, type Command, type Transaction } from "prosemirror-state";+import { EditorView } from "prosemirror-view";+import { history, undo, redo } from "prosemirror-history";+import { keymap } from "prosemirror-keymap";+import { baseKeymap, splitBlockAs, toggleMark, chainCommands } from "prosemirror-commands";+import type { Node as PMNode } from "prosemirror-model";+import type { Run } from "./Formatted";+import { fromDoc, LIST_STYLES, schema, STYLE, toDoc } from "./rich";++/** What the toolbar shows as on: the style of the line the cursor is in, and its marks. */+export type EditorStatus = {+ style: number | null;+ bold: boolean;+ italic: boolean;+ underline: boolean;+ strike: boolean;+ checklist: boolean;+};++export type EditorHandle = {+ /** Set every line the selection touches to one of Notes' styles. */+ setStyle: (style: number | null) => void;+ /** Lines to checklist items, or — when they all are — back to plain lines. */+ toggleChecklist: () => void;+ toggleMark: (mark: "bold" | "italic" | "underline" | "strike") => void;+ /** Take in text Apple now holds, keeping the cursor where it was as near as it can. */+ replace: (text: string, runs: Run[] | null) => void;+ focus: () => void;+ /** Hand over any change not yet reported, now. */+ flushChange: () => void;+};++type Props = {+ text: string;+ runs: Run[] | null;+ editable: boolean;+ label: string;+ placeholder?: string;+ autoFocus?: boolean;+ onChange: (text: string, runs: Run[]) => void;+ onStatus?: (status: EditorStatus) => void;+ onBlur?: () => void;+};++/** Every paragraph the selection touches, with where it starts. */+function linesIn(state: EditorState): { node: PMNode; pos: number }[] {+ const out: { node: PMNode; pos: number }[] = [];+ const { from, to } = state.selection;+ state.doc.nodesBetween(from, to, (node, pos) => {+ if (node.type === schema.nodes.paragraph) out.push({ node, pos });+ return node.type === schema.nodes.doc;+ });+ return out;+}++function restyle(style: number | null, tick?: (was: PMNode) => boolean | null): Command {+ return (state, dispatch) => {+ const tr = state.tr;+ for (const { node, pos } of linesIn(state)) {+ const checked = style === STYLE.checklist ? (tick ? tick(node) : (node.attrs.style === STYLE.checklist ? node.attrs.checked : false)) : null;+ tr.setNodeMarkup(pos, undefined, {+ ...node.attrs,+ style,+ checked,+ // Out of a list, a line is not indented as one.+ indent: style !== null && LIST_STYLES.includes(style) ? node.attrs.indent : 0,+ });+ }+ dispatch?.(tr.scrollIntoView());+ return true;+ };+}++/** Indent or outdent the lines in a list, as Tab and Command-] do. */+function shift(by: 1 | -1, onlyLists: boolean): Command {+ return (state, dispatch) => {+ const lines = linesIn(state);+ if (onlyLists && !lines.every(({ node }) => LIST_STYLES.includes(node.attrs.style))) return false;+ const tr = state.tr;+ for (const { node, pos } of lines) {+ tr.setNodeMarkup(pos, undefined, { ...node.attrs, indent: Math.max(0, Math.min(8, node.attrs.indent + by)) });+ }+ dispatch?.(tr);+ return true;+ };+}++const parentOf = (state: EditorState) => state.selection.$from.parent;+const inList = (state: EditorState) => LIST_STYLES.includes(parentOf(state).attrs.style);++/**+ * Return as Notes has it: in a list the next line is another item — a new checklist item+ * unticked — and Return on an empty item ends the list; after a title or heading the next+ * line is body text.+ */+const enter: Command = (state, dispatch) => {+ const p = parentOf(state);+ if (inList(state) && p.content.size === 0 && state.selection.empty) {+ return restyle(null)(state, dispatch);+ }+ return splitBlockAs((node, atEnd) => {+ const style = node.attrs.style as number | null;+ if (LIST_STYLES.includes(style as number)) {+ return { type: schema.nodes.paragraph, attrs: { ...node.attrs, checked: style === STYLE.checklist ? false : null } };+ }+ if (atEnd && (style === STYLE.title || style === STYLE.heading || style === STYLE.subheading)) {+ return { type: schema.nodes.paragraph, attrs: { style: null, indent: 0, checked: null } };+ }+ return { type: schema.nodes.paragraph, attrs: { ...node.attrs } };+ })(state, dispatch);+};++/** Backspace at the very start of a list item makes it a plain line, before joining lines. */+const backspace: Command = (state, dispatch) => {+ const { $from, empty } = state.selection;+ if (!empty || $from.parentOffset !== 0 || !inList(state)) return false;+ return restyle(null)(state, dispatch);+};++const lineBreak: Command = (state, dispatch) => {+ dispatch?.(state.tr.replaceSelectionWith(schema.nodes.line_break.create()).scrollIntoView());+ return true;+};++const tab: Command = (state, dispatch) => {+ if (shift(1, true)(state, dispatch)) return true;+ dispatch?.(state.tr.insertText("\t"));+ return true;+};++function statusOf(state: EditorState): EditorStatus {+ const p = parentOf(state);+ const marks = state.storedMarks ?? state.selection.$from.marks();+ const { from, to, empty } = state.selection;+ const has = (name: string) => {+ const type = schema.marks[name];+ return empty ? marks.some((m) => m.type === type) : state.doc.rangeHasMark(from, to, type);+ };+ return {+ style: p.attrs.style,+ bold: has("bold"),+ italic: has("italic"),+ underline: has("underline"),+ strike: has("strike"),+ checklist: p.attrs.style === STYLE.checklist,+ };+}++/**+ * A note, edited formatted — as Notes edits it on icloud.com, a Mac or a phone. Typing, the+ * Aa styles, the checklist button and the keys all change the same document, which is read+ * back as Apple's text and runs on every change.+ */+export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(+ { text, runs, editable, label, placeholder, autoFocus, onChange, onStatus, onBlur },+ ref,+) {+ const host = useRef<HTMLDivElement | null>(null);+ const view = useRef<EditorView | null>(null);+ const callbacks = useRef({ onChange, onStatus, onBlur });+ callbacks.current = { onChange, onStatus, onBlur };++ /**+ * The note read back as Apple's text and runs — a walk of the whole note — done just after+ * the key is drawn rather than before, so a long note types as fast as a short one. Done at+ * once whenever the note is left, so nothing typed can be missed.+ */+ const later = useRef<number | null>(null);+ const report = () => {+ if (later.current !== null) {+ window.clearTimeout(later.current);+ later.current = null;+ }+ const v = view.current;+ if (!v) return;+ const out = fromDoc(v.state.doc);+ callbacks.current.onChange(out.text, out.runs);+ };+ const reportSoon = () => {+ if (later.current !== null) return;+ later.current = window.setTimeout(() => {+ later.current = null;+ report();+ }, 0);+ };++ useEffect(() => {+ if (!host.current) return undefined;+ const state = EditorState.create({+ doc: toDoc(text, runs),+ plugins: [+ history(),+ keymap({+ "Mod-z": undo,+ "Mod-Shift-z": redo,+ "Mod-y": redo,+ "Mod-b": toggleMark(schema.marks.bold),+ "Mod-i": toggleMark(schema.marks.italic),+ "Mod-u": toggleMark(schema.marks.underline),+ "Mod-]": shift(1, false),+ "Mod-[": shift(-1, false),+ Tab: tab,+ "Shift-Tab": shift(-1, false),+ Enter: enter,+ "Shift-Enter": lineBreak,+ Backspace: backspace,+ // The Mac's Format ▸ keys for Notes' styles.+ "Mod-Shift-t": restyle(STYLE.title),+ "Mod-Shift-h": restyle(STYLE.heading),+ "Mod-Shift-j": restyle(STYLE.subheading),+ "Mod-Shift-b": restyle(null),+ "Mod-Shift-m": restyle(STYLE.mono),+ "Mod-Shift-7": restyle(STYLE.bulleted),+ "Mod-Shift-8": restyle(STYLE.dashed),+ "Mod-Shift-9": restyle(STYLE.numbered),+ "Mod-Shift-l": (s, d) => toggleChecklistCmd(s, d),+ }),+ keymap(baseKeymap),+ ],+ });+ const v = new EditorView(host.current, {+ state,+ editable: () => editable,+ attributes: {+ class: "note-rich",+ role: "textbox",+ "aria-multiline": "true",+ "aria-label": label,+ spellcheck: "true",+ ...(placeholder ? { "data-placeholder": placeholder } : {}),+ },+ dispatchTransaction(tr: Transaction) {+ const next = v.state.apply(tr);+ v.updateState(next);+ if (tr.docChanged) reportSoon();+ callbacks.current.onStatus?.(statusOf(next));+ },+ handleDOMEvents: {+ blur: () => {+ if (later.current !== null) report();+ callbacks.current.onBlur?.();+ return false;+ },+ // A checklist item's circle ticks it, as a tap does on the phone.+ mousedown: (vw, event) => {+ const line = (event.target as HTMLElement).closest?.('p[data-style="103"]') as HTMLElement | null;+ if (!line || !editable) return false;+ const box = line.getBoundingClientRect();+ const pad = parseFloat(getComputedStyle(line).paddingInlineStart) || 0;+ if (event.clientX - box.left > pad) return false;+ const pos = vw.posAtDOM(line, 0) - 1;+ const node = vw.state.doc.nodeAt(pos);+ if (!node) return false;+ event.preventDefault();+ vw.dispatch(vw.state.tr.setNodeMarkup(pos, undefined, { ...node.attrs, checked: !node.attrs.checked }));+ return true;+ },+ },+ });+ view.current = v;+ callbacks.current.onStatus?.(statusOf(v.state));+ if (autoFocus) {+ v.focus();+ v.dispatch(v.state.tr.setSelection(TextSelection.atEnd(v.state.doc)));+ }+ return () => {+ if (later.current !== null) report();+ v.destroy();+ view.current = null;+ };+ // One editor per note: the parent keys it by the note, and replace() takes later text.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ view.current?.setProps({ editable: () => editable });+ }, [editable]);++ useImperativeHandle(ref, () => ({+ setStyle: (style) => {+ const v = view.current;+ if (!v) return;+ restyle(style)(v.state, v.dispatch);+ v.focus();+ },+ toggleChecklist: () => {+ const v = view.current;+ if (!v) return;+ toggleChecklistCmd(v.state, v.dispatch);+ v.focus();+ },+ toggleMark: (mark) => {+ const v = view.current;+ if (!v) return;+ toggleMark(schema.marks[mark])(v.state, v.dispatch);+ v.focus();+ },+ replace: (nextText, nextRuns) => {+ const v = view.current;+ if (!v) return;+ const doc = toDoc(nextText, nextRuns);+ if (doc.eq(v.state.doc)) return;+ const { from, to } = v.state.selection;+ const tr = v.state.tr.replaceWith(0, v.state.doc.content.size, doc.content);+ const size = tr.doc.content.size;+ const near = (at: number) => tr.doc.resolve(Math.max(0, Math.min(at, size)));+ tr.setSelection(TextSelection.between(near(from), near(to)));+ tr.setMeta("addToHistory", false);+ // Taken in quietly: what Apple holds is not an edit to send back.+ const next = v.state.apply(tr);+ v.updateState(next);+ callbacks.current.onStatus?.(statusOf(next));+ },+ focus: () => view.current?.focus(),+ flushChange: () => {+ if (later.current !== null) report();+ },+ }));++ return <div ref={host} className="note-rich-host" />;+});++const toggleChecklistCmd: Command = (state, dispatch) => {+ const all = linesIn(state).every(({ node }) => node.attrs.style === STYLE.checklist);+ return chainCommands(restyle(all ? null : STYLE.checklist))(state, dispatch);+};diff --git a/src/screens/notes/rich.ts b/src/screens/notes/rich.tsnew file mode 100644index 0000000..ecf1133--- /dev/null+++ b/src/screens/notes/rich.ts@@ -0,0 +1,230 @@+/**+ * A note as an editor holds it, and back: Apple's text and attribute runs turned into a+ * ProseMirror document of paragraphs — each with Notes' style, indent and checklist tick —+ * holding text with bold, italic, underline, strikethrough and links, and that document+ * turned back into exactly the text and runs Apple keeps.+ *+ * The round trip is lossless for everything the editor shows: a note read in and written+ * straight back gives the same text and the same runs. What it does not show — fonts,+ * colours, an attachment's insides — the backend keeps from Apple's own copy, so it is never+ * at stake here. An attachment's place in the text (U+FFFC) and a line break inside a+ * paragraph (U+2028, Shift-Return) travel as nodes of their own, so they cannot be typed+ * over by accident or lost.+ */+import { Schema, type Node as PMNode, type Mark } from "prosemirror-model";+import type { Run } from "./Formatted";++/** Apple's paragraph styles. */+export const STYLE = {+ title: 0,+ heading: 1,+ subheading: 2,+ body: 3,+ mono: 4,+ bulleted: 100,+ dashed: 101,+ numbered: 102,+ checklist: 103,+} as const;++export const LIST_STYLES: readonly number[] = [STYLE.bulleted, STYLE.dashed, STYLE.numbered, STYLE.checklist];+const ATTACHMENT = "";+const LINE_BREAK = " ";++export const schema = new Schema({+ nodes: {+ doc: { content: "paragraph+" },+ paragraph: {+ content: "inline*",+ attrs: {+ style: { default: null as number | null },+ indent: { default: 0 },+ checked: { default: null as boolean | null },+ },+ parseDOM: [{ tag: "p" }],+ toDOM: (node) => [+ "p",+ {+ class: "nf-p",+ "data-style": node.attrs.style === null ? "none" : String(node.attrs.style),+ ...(node.attrs.checked ? { "data-checked": "true" } : {}),+ style: node.attrs.indent ? `--indent: ${node.attrs.indent}` : "",+ },+ 0,+ ],+ },+ text: { group: "inline" },+ /** Where an attachment sits — a picture, a sketch, a table — kept, not edited. */+ attachment: {+ group: "inline",+ inline: true,+ atom: true,+ selectable: true,+ toDOM: () => ["span", { class: "nf-attachment", contenteditable: "false", title: "Attachment — open it on an Apple device" }, "Attachment"],+ },+ /** Shift-Return: a new line in the same paragraph. */+ line_break: {+ group: "inline",+ inline: true,+ selectable: false,+ parseDOM: [{ tag: "br" }],+ toDOM: () => ["br"],+ },+ },+ marks: {+ bold: { parseDOM: [{ tag: "strong" }, { tag: "b" }], toDOM: () => ["strong", 0] },+ italic: { parseDOM: [{ tag: "em" }, { tag: "i" }], toDOM: () => ["em", 0] },+ underline: { parseDOM: [{ tag: "u" }], toDOM: () => ["u", 0] },+ strike: { parseDOM: [{ tag: "s" }, { tag: "del" }], toDOM: () => ["s", 0] },+ link: {+ attrs: { href: {} },+ inclusive: false,+ parseDOM: [{ tag: "a[href]", getAttrs: (d) => ({ href: (d as HTMLElement).getAttribute("href") }) }],+ toDOM: (m) => ["a", { href: m.attrs.href, rel: "noreferrer", target: "_blank" }, 0],+ },+ },+});++const plain = (length: number): Run => ({+ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null,+});++/** Whether `runs` describe exactly this text. */+export function runsFit(text: string, runs: Run[] | null): runs is Run[] {+ return !!runs && runs.length > 0 && runs.reduce((n, r) => n + r.length, 0) === text.length;+}++/** The run each UTF-16 unit of the text lies in. */+function perUnit(text: string, runs: Run[]): Run[] {+ const out: Run[] = [];+ for (const r of runs) for (let i = 0; i < r.length; i++) out.push(r);+ while (out.length < text.length) out.push(runs[runs.length - 1] ?? plain(1));+ return out;+}++function marksOf(run: Run): Mark[] {+ const m: Mark[] = [];+ if (run.bold) m.push(schema.marks.bold.create());+ if (run.italic) m.push(schema.marks.italic.create());+ if (run.underline) m.push(schema.marks.underline.create());+ if (run.strike) m.push(schema.marks.strike.create());+ if (run.link) m.push(schema.marks.link.create({ href: run.link }));+ return m;+}++/** Apple's text and runs as a document. Without runs that fit, every line is plain body. */+export function toDoc(text: string, runs: Run[] | null): PMNode {+ const fits = runsFit(text, runs);+ const units = fits ? perUnit(text, runs) : [];+ const paragraphs: PMNode[] = [];+ let start = 0;+ for (;;) {+ const nl = text.indexOf("\n", start);+ const end = nl < 0 ? text.length : nl;+ // A paragraph is set by the run its newline is in — or, for the last line, its last unit.+ const own = fits ? (units[nl < 0 ? Math.max(end - 1, start) : nl] ?? units[units.length - 1]) : null;+ const inline: PMNode[] = [];+ let i = start;+ while (i < end) {+ const ch = text[i];+ if (ch === ATTACHMENT) {+ inline.push(schema.nodes.attachment.create());+ i += 1;+ continue;+ }+ if (ch === LINE_BREAK) {+ inline.push(schema.nodes.line_break.create());+ i += 1;+ continue;+ }+ let j = i + 1;+ while (j < end && text[j] !== ATTACHMENT && text[j] !== LINE_BREAK && (!fits || units[j] === units[i])) j++;+ inline.push(schema.text(text.slice(i, j), fits ? marksOf(units[i]) : []));+ i = j;+ }+ paragraphs.push(+ schema.nodes.paragraph.create(+ {+ style: own?.style ?? null,+ indent: own?.indent ?? 0,+ checked: own?.style === STYLE.checklist ? Boolean(own.checked) : null,+ },+ inline,+ ),+ );+ if (nl < 0) break;+ start = nl + 1;+ }+ return schema.nodes.doc.create(null, paragraphs);+}++const same = (a: Run, b: Run) =>+ a.style === b.style && a.indent === b.indent && a.checked === b.checked && a.bold === b.bold &&+ a.italic === b.italic && a.underline === b.underline && a.strike === b.strike && a.link === b.link;++/** A document as Apple's text and runs. */+export function fromDoc(doc: PMNode): { text: string; runs: Run[] } {+ let text = "";+ const runs: Run[] = [];+ const push = (piece: string, run: Run) => {+ if (!piece) return;+ text += piece;+ const last = runs[runs.length - 1];+ if (last && same(last, run)) last.length += piece.length;+ else runs.push({ ...run, length: piece.length });+ };+ doc.forEach((para, _offset, index) => {+ const p = {+ style: para.attrs.style as number | null,+ indent: para.attrs.indent as number,+ checked: para.attrs.style === STYLE.checklist ? Boolean(para.attrs.checked) : null,+ };+ const base: Run = { ...plain(0), ...p };+ para.forEach((child) => {+ if (child.type === schema.nodes.attachment) return push(ATTACHMENT, base);+ if (child.type === schema.nodes.line_break) return push(LINE_BREAK, base);+ const has = (name: string) => child.marks.some((m) => m.type.name === name);+ push(child.text ?? "", {+ ...base,+ bold: has("bold"),+ italic: has("italic"),+ underline: has("underline"),+ strike: has("strike"),+ link: (child.marks.find((m) => m.type.name === "link")?.attrs.href as string | undefined) ?? null,+ });+ });+ // The newline carries the paragraph's setting, as Apple stores it.+ if (index < doc.childCount - 1) push("\n", base);+ });+ return { text, runs };+}++/** The one stretch `to` changed from `from`, in UTF-16 units: where, removed, inserted. */+function change(from: string, to: string): [number, number, number] {+ let pre = 0;+ const max = Math.min(from.length, to.length);+ while (pre < max && from[pre] === to[pre]) pre++;+ let suf = 0;+ while (suf < max - pre && from[from.length - 1 - suf] === to[to.length - 1 - suf]) suf++;+ return [pre, from.length - pre - suf, to.length - pre - suf];+}++/**+ * `runs`, which describe `from`, laid over `to` — the same text with another device's edit+ * merged in. What is new takes the setting of what is just before it. The backend does the+ * same with the same rule, so the screen and Apple agree.+ */+export function carryRuns(from: string, runs: Run[], to: string): Run[] {+ if (!runsFit(from, runs)) return [plain(to.length)];+ const units = perUnit(from, runs);+ const [at, removed, inserted] = change(from, to);+ const fill = at > 0 ? units[at - 1] : (units[at + removed] ?? plain(1));+ const next = [...units.slice(0, at), ...Array<Run>(inserted).fill(fill), ...units.slice(at + removed)];+ const out: Run[] = [];+ for (const r of next) {+ const last = out[out.length - 1];+ if (last && same(last, r)) last.length += 1;+ else out.push({ ...r, length: 1 });+ }+ return out;+}diff --git a/src/styles/notes.css b/src/styles/notes.cssindex 2a714fd..d3571a3 100644--- a/src/styles/notes.css+++ b/src/styles/notes.css@@ -295,3 +295,106 @@ textarea.note-title::placeholder { color: var(--text-3); }.note-formatted a { color: var(--gold); text-decoration: underline; }/* Aa, as Notes writes it on its toolbar. */.notes-aa { font-weight: 600; font-size: 14px; letter-spacing: -0.02em; width: auto; padding-inline: 8px; }++/* ---- the editor ------------------------------------------------------------------+ One document, edited formatted, as Notes edits it. Sizes after Notes on the Mac: title+ 24, heading 19, subheading 16, body 15; lists hang their marks in the margin. */+.note-rich-host { flex: 1; display: flex; flex-direction: column; min-height: 0; }+.note-rich {+ flex: 1;+ min-height: 240px;+ outline: none;+ color: var(--text);+ font-size: var(--t-15);+ line-height: 1.55;+ overflow-wrap: anywhere;+ white-space: pre-wrap;+ caret-color: var(--notes-accent, var(--gold));+ counter-reset: nf-num;+}+.note-rich .nf-p { margin: 0; min-height: 1.55em; padding-inline-start: calc(var(--indent, 0) * 1.5em); position: relative; }+/* An empty new note says what it is for. */+.note-rich[data-placeholder] .nf-p:only-child:has(> br:only-child)::after,+.note-rich[data-placeholder] .nf-p:only-child:empty::after {+ content: attr(data-placeholder);+ content: "New Note";+ position: absolute; inset-inline-start: 0; top: 0;+ color: var(--text-3); pointer-events: none; font-size: 24px; font-weight: 700;+}+/* The title, explicit or — Notes' own rule — the first line when it has no style. */+.note-rich .nf-p[data-style="0"],+.note-rich .nf-p:first-child[data-style="none"] { font-size: 24px; font-weight: 700; letter-spacing: -0.015em; line-height: 1.3; margin-bottom: 6px; }+.note-rich .nf-p[data-style="1"] { font-size: 19px; font-weight: 700; line-height: 1.35; margin-top: 4px; }+.note-rich .nf-p[data-style="2"] { font-size: 16px; font-weight: 600; }+.note-rich .nf-p[data-style="4"] { font-family: ui-monospace, "SF Mono", "JetBrains Mono", monospace; font-size: 13.5px; }+/* Lists: the mark sits in a gutter of its own, so wrapped lines line up with the text. */+.note-rich .nf-p[data-style="100"],+.note-rich .nf-p[data-style="101"],+.note-rich .nf-p[data-style="102"],+.note-rich .nf-p[data-style="103"] { padding-inline-start: calc(var(--indent, 0) * 1.5em + 1.6em); }+.note-rich .nf-p[data-style="100"]::before,+.note-rich .nf-p[data-style="101"]::before,+.note-rich .nf-p[data-style="102"]::before {+ position: absolute; inset-inline-start: calc(var(--indent, 0) * 1.5em); width: 1.6em;+ color: var(--text-2); font-variant-numeric: tabular-nums; pointer-events: none;+}+.note-rich .nf-p[data-style="100"]::before { content: "•"; }+.note-rich .nf-p[data-style="101"]::before { content: "–"; }+.note-rich .nf-p:not([data-style="102"]) { counter-reset: nf-num; }+.note-rich .nf-p[data-style="102"] { counter-increment: nf-num; }+.note-rich .nf-p[data-style="102"]::before { content: counter(nf-num) "."; }+/* A checklist item's circle: clicking it ticks the line (the editor reads the click). */+.note-rich .nf-p[data-style="103"]::before {+ content: ""; position: absolute; inset-inline-start: calc(var(--indent, 0) * 1.5em); top: 0.3em;+ width: 17px; height: 17px; box-sizing: border-box; border: 1.5px solid var(--text-3); border-radius: 50%;+ cursor: pointer; transition: background-color 120ms ease, border-color 120ms ease;+}+.note-rich .nf-p[data-style="103"][data-checked="true"]::before {+ border-color: var(--notes-accent, var(--gold));+ background: var(--notes-accent, var(--gold))+ url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path d='M4 8.2l2.6 2.6L12 5.4' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>") center/12px no-repeat;+}+.note-rich .nf-p[data-style="103"][data-checked="true"] { color: var(--text-3); }+.note-rich a { color: var(--notes-accent, var(--gold)); text-decoration: underline; }+.note-rich .nf-attachment {+ display: inline-block; padding: 0 6px; margin: 0 1px; border-radius: 5px;+ background: color-mix(in srgb, var(--text) 8%, transparent); color: var(--text-2); font-size: var(--t-13);+}+.note-rich ::selection { background: color-mix(in srgb, var(--notes-accent, var(--gold)) 32%, transparent); }+.notes-icon.is-on { background: color-mix(in srgb, var(--text) 10%, transparent); }++/* ---- Aa ----------------------------------------------------------------------------+ As icloud.com and the Mac draw it: the four marks in a row, the styles beneath, each set+ the way it sets a line, the current one ticked. Opens without animation, as menus do. */+.format-panel {+ position: fixed;+ z-index: 60;+ width: 276px;+ padding: 10px 8px 8px;+ border-radius: 12px;+ background: var(--sheet);+ border: 0.5px solid var(--glass-edge, var(--separator));+ box-shadow: 0 11px 34px rgba(0, 0, 0, 0.18), 0 0 0 0.5px rgba(0, 0, 0, 0.06);+ color: var(--text);+}+.fp-marks { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; padding: 0 4px 8px; border-bottom: 1px solid var(--separator); margin-bottom: 6px; }+.fp-mark {+ height: 30px; border: 0; border-radius: 8px; background: none; box-shadow: none;+ color: var(--text); font: inherit; font-size: 16px; cursor: default;+}+.fp-mark:hover { background: color-mix(in srgb, var(--text) 7%, transparent); }+.fp-mark[aria-pressed="true"] { background: color-mix(in srgb, var(--notes-accent, var(--gold)) 22%, transparent); color: var(--notes-accent-strong, var(--gold-strong)); }+.fp-styles { display: flex; flex-direction: column; }+.fp-style {+ display: grid; grid-template-columns: 22px auto 1fr; align-items: center; column-gap: 2px;+ min-height: 34px; padding: 4px 10px 4px 4px; border: 0; border-radius: 8px;+ background: none; box-shadow: none; color: var(--text); font: inherit; font-size: var(--t-15); text-align: start; cursor: default;+}+.fp-style:hover, .fp-style:focus-visible { background: color-mix(in srgb, var(--text) 7%, transparent); outline: none; }+.fp-style:not(:has(.fp-list-mark)) > span:last-child { grid-column: 2 / 4; }+.fp-check { display: grid; place-items: center; color: var(--text); }+.fp-title { font-size: 22px; font-weight: 700; letter-spacing: -0.01em; }+.fp-heading { font-size: 18px; font-weight: 700; }+.fp-subheading { font-size: 15px; font-weight: 600; }+.fp-mono { font-family: ui-monospace, "SF Mono", "JetBrains Mono", monospace; font-size: 14px; }+.fp-list-mark { width: 16px; color: var(--text-2); }