Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Notes and app-shell speed pass

Yashwanth Kamireddi7f30bf791fbc
diff --git a/.uiverify/calendar-instant.mjs b/.uiverify/calendar-instant.mjs
index 6744052..14e0b18 100644
--- a/.uiverify/calendar-instant.mjs
+++ b/.uiverify/calendar-instant.mjs
@@ -80,12 +80,14 @@ await page.getByRole("alertdialog").getByRole("button", { name: "Delete" }).clic
await page.waitForTimeout(150);
ok(await page.locator(".cx-block", { hasText: "Design review" }).count() === 0, "a deleted event leaves at once");
// A reminder on the calendar ticks there, at once, as in Calendar.
-const ring = page.getByRole("checkbox", { name: /^Complete / }).first();
+// In the grid the ring is for the mouse; the line itself is the control (its card has the
+// ring for the keyboard), so it is found by its class, not as a checkbox.
+const ring = page.locator(".cx-item.is-reminder:not(.is-done) .cx-ring, .cx-reminder:not(.is-done) .cx-ring").first();
const had = await ring.count();
if (had) {
await ring.click();
await page.waitForTimeout(150);
- ok((await ring.getAttribute("aria-checked")) === "true", "a reminder's ring on the calendar ticks it at once");
+ ok(await ring.evaluate((el) => el.classList.contains("is-ticked")), "a reminder's ring on the calendar ticks it at once");
} else ok(false, "no reminder on the calendar to tick");
await b.close();
process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/notes-autosave-quiet.mjs b/.uiverify/notes-autosave-quiet.mjs
new file mode 100644
index 0000000..b32f7a5
--- /dev/null
+++ b/.uiverify/notes-autosave-quiet.mjs
@@ -0,0 +1,84 @@
+// A pause in typing saves the note without anything else happening around it: the controls
+// stay usable, the list is not read again for it, and the note's row says what it now says.
+// A save that fails keeps the edit, and it goes with the next one.
+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 });
+// Each command the window sends, in order; a save held a moment, as the library's write is.
+await ctx.addInitScript(() => {
+ const wrap = () => {
+ const t = window.__TAURI_INTERNALS__;
+ if (!t || t.__logged) return;
+ const inner = t.invoke;
+ t.invoke = async (cmd, args) => {
+ (window.__calls ??= []).push(cmd);
+ if (cmd === "note_save") {
+ await new Promise((r) => setTimeout(r, 300));
+ if (window.__saveFails) { window.__saveFails -= 1; throw "The library couldn’t be written."; }
+ }
+ return inner(cmd, args);
+ };
+ t.__logged = true;
+ };
+ wrap(); document.addEventListener("DOMContentLoaded", wrap);
+});
+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(400);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+await page.locator(".note-row", { hasText: "Curtains" }).first().click();
+await page.waitForTimeout(400);
+await page.locator(".note-rich p").first().click();
+await page.keyboard.press("End");
+await page.evaluate(() => {
+ window.__calls = [];
+ window.__disabled = 0;
+ // Watched every frame through the save: New Note and Pin never greyed out by it.
+ const look = () => {
+ const off = [...document.querySelectorAll('.notes button[aria-label="New note"], .notes button[aria-label="Pin Note"], .notes button[aria-label="Unpin Note"]')]
+ .some((x) => x.disabled);
+ if (off) window.__disabled += 1;
+ if (!window.__stopLook) requestAnimationFrame(look);
+ };
+ requestAnimationFrame(look);
+});
+await page.keyboard.type(" and blinds");
+// Through the pause and the save.
+await page.waitForTimeout(1700);
+const calls = await page.evaluate(() => window.__calls);
+ok(calls.filter((c) => c === "note_save").length === 1, `one save ${JSON.stringify(calls)}`);
+const after = calls.slice(calls.indexOf("note_save") + 1);
+ok(!after.some((c) => ["notes_in", "note_folders", "note_counts", "note_body", "note_runs"].includes(c)),
+ `nothing is read again for it ${JSON.stringify(after)}`);
+ok((await page.evaluate(() => window.__disabled)) === 0, "New Note and Pin stay usable while it saves");
+ok(/Saved|Edited|Today|\d/.test(await page.locator(".note-when").innerText()), `the bar says it is saved "${await page.locator(".note-when").innerText()}"`);
+// The first line was typed in: the row's title follows it, without the list read again.
+ok((await page.locator(".note-row", { hasText: "Curtains and blinds" }).count()) === 1,
+ `the row's title follows the first line ${JSON.stringify(await page.locator(".note-row-name").allInnerTexts())}`);
+
+// And again.
+await page.locator(".note-rich p").first().click();
+await page.keyboard.press("End");
+await page.keyboard.type(" Shopping");
+await page.waitForTimeout(1700);
+ok((await page.locator(".note-row", { hasText: "Curtains and blinds Shopping" }).count()) === 1,
+ `and again ${JSON.stringify(await page.locator(".note-row-name").allInnerTexts())}`);
+
+// A save that fails keeps the edit, which goes with the next.
+await page.evaluate(() => { window.__saveFails = 1; window.__noteSaves = []; });
+await page.keyboard.type(" X");
+await page.waitForTimeout(1700);
+await page.keyboard.type("Y");
+await page.waitForTimeout(1700);
+const last = await page.evaluate(() => (window.__noteSaves ?? []).at(-1)?.body ?? "");
+ok(last.startsWith("Curtains and blinds Shopping XY"), `a failed save's edit goes with the next one ${JSON.stringify(last.split("\n")[0])}`);
+await page.evaluate(() => { window.__stopLook = true; });
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/notes-links-pictures.mjs b/.uiverify/notes-links-pictures.mjs
index ba9fa59..7498cc5 100644
--- a/.uiverify/notes-links-pictures.mjs
+++ b/.uiverify/notes-links-pictures.mjs
@@ -65,7 +65,13 @@ await img.click();
await page.waitForTimeout(150);
const viewer = page.getByRole("dialog", { name: "beach.jpeg" });
ok(await viewer.isVisible(), "a click shows it large, in the window");
-ok((await viewer.locator("img").getAttribute("src")) === (await img.getAttribute("src")), "from the picture already drawn: nothing fetched again");
+ok(/note%2FM1%2Finline$/.test(await img.getAttribute("src")), "the note draws the picture at the size it needs, not the whole photo");
+// At once from the picture already drawn, then whole once that is decoded — never a blank.
+const shownSrc = await viewer.locator("img").getAttribute("src");
+ok(shownSrc === (await img.getAttribute("src")) || /note%2FM1%2Ffile$/.test(shownSrc), `shown from the picture already drawn, or already whole ${shownSrc}`);
+await page.waitForTimeout(400);
+ok(/note%2FM1%2Ffile$/.test(await viewer.locator("img").getAttribute("src")) && (await viewer.locator("img").evaluate((i) => i.complete && i.naturalWidth > 0)),
+ "and then the whole picture, drawn");
ok((await page.evaluate(() => window.__opened ?? [])).length === 0, "and nothing handed to another app");
await viewer.getByRole("button", { name: "Open in Default App" }).click();
await page.waitForTimeout(100);
diff --git a/.uiverify/notes-media.mjs b/.uiverify/notes-media.mjs
index 1469e2d..16d640a 100644
--- a/.uiverify/notes-media.mjs
+++ b/.uiverify/notes-media.mjs
@@ -20,7 +20,7 @@ await page.waitForTimeout(800);
const asked = await page.evaluate(() => [...document.querySelectorAll("img")].map((i) => i.getAttribute("src")).concat(window.__asked ?? []));
const chips = await page.locator(".nf-file").allInnerTexts();
ok(chips.some((c) => /Budget\.xlsx/.test(c) && /XLSX/.test(c)), `a file shows as a chip with its name and kind ${JSON.stringify(chips)}`);
-ok(chips.some((c) => /beach\.jpeg/.test(c)) || asked.some((s) => s?.includes("note%2FM1%2Ffile")), `a picture is drawn from its own route, or its chip when it cannot be had ${JSON.stringify(asked)}`);
+ok(chips.some((c) => /beach\.jpeg/.test(c)) || asked.some((s) => s?.includes("note%2FM1%2Finline")), `a picture is drawn from its own route, or its chip when it cannot be had ${JSON.stringify(asked)}`);
await page.locator(".nf-file", { hasText: "Budget.xlsx" }).click();
await page.waitForTimeout(150);
ok(JSON.stringify(await page.evaluate(() => window.__opened)) === JSON.stringify(["M2"]), "clicking a file opens it");
diff --git a/.uiverify/notes-model.test.mjs b/.uiverify/notes-model.test.mjs
index c6c417e..4db2169 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 } from "../src/screens/notes/model.ts";
+import { groupNotes, listDate, splitTitle, joinTitle, titleAndSnippet } 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,3 +72,9 @@ 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/notes-switch-quiet.mjs b/.uiverify/notes-switch-quiet.mjs
new file mode 100644
index 0000000..bb023a8
--- /dev/null
+++ b/.uiverify/notes-switch-quiet.mjs
@@ -0,0 +1,149 @@
+// Moving through notes and typing in one draw only what changed.
+//
+// Stepping from note to note with the arrow keys: no "Opening…" between them and no plain note
+// drawn first and formatted after — the text and its formatting arrive together, and the notes
+// beside the open one are read ahead. Typing, and moving the cursor, draw the note and its bar:
+// never every row of the list again. Counted from React's own commits (the DevTools hook).
+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 } });
+// React tells a DevTools hook of every commit; this one counts the note rows each commit drew.
+await ctx.addInitScript(() => {
+ window.__rowRenders = 0;
+ window.__commits = 0;
+ window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
+ supportsFiber: true,
+ renderers: new Map(),
+ inject(renderer) { this.renderers.set(1, renderer); return 1; },
+ checkDCE() {},
+ onScheduleFiberRoot() {},
+ onPostCommitFiberRoot() {},
+ onCommitFiberUnmount() {},
+ onCommitFiberRoot(_id, root) {
+ window.__commits += 1;
+ // A row drawn in this commit has props it has never had before: a row left alone keeps
+ // the very props object of the last time it was drawn.
+ const seen = (window.__seenProps ??= new WeakSet());
+ const walk = (f) => {
+ for (let n = f; n; n = n.sibling) {
+ if (n.type === "button" && n.memoizedProps?.className === "note-row" && !seen.has(n.memoizedProps)) {
+ seen.add(n.memoizedProps);
+ window.__rowRenders += 1;
+ }
+ if (n.child) walk(n.child);
+ }
+ };
+ walk(root.current.child);
+ },
+ };
+});
+// Every read of the library takes a moment, as a real one does.
+await ctx.addInitScript(() => {
+ const wrap = () => {
+ const t = window.__TAURI_INTERNALS__;
+ if (!t || t.__slowReads) return;
+ const inner = t.invoke;
+ t.invoke = async (cmd, args) => {
+ if (cmd === "note_body" || cmd === "note_runs") {
+ (window.__reads ??= []).push(cmd);
+ await new Promise((r) => setTimeout(r, cmd === "note_runs" ? 70 : 30));
+ }
+ return inner(cmd, args);
+ };
+ t.__slowReads = true;
+ };
+ wrap(); document.addEventListener("DOMContentLoaded", wrap);
+});
+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(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++; };
+
+// Everything drawn in the note pane while stepping, frame by frame.
+await page.evaluate(() => {
+ window.__seen = { opening: 0, readonly: 0, plainCurtains: 0 };
+ const look = () => {
+ const pane = document.querySelector(".notes .note-body");
+ if (pane?.querySelector(".note-loading")) window.__seen.opening += 1;
+ if (pane?.querySelector(".note-editor.is-readonly")) window.__seen.readonly += 1;
+ // Curtains is set as a phone sets it: a title line. Drawn without it is the plain flash.
+ const rich = pane?.querySelector(".note-rich");
+ if (rich && /Curtains/.test(rich.textContent ?? "") && !rich.querySelector('[data-style="0"]')) window.__seen.plainCurtains += 1;
+ };
+ new MutationObserver(look).observe(document.querySelector(".notes .note-body"), { childList: true, subtree: true });
+});
+const rows = await page.locator(".note-row").count();
+await page.locator(".note-row").first().click();
+await page.waitForTimeout(400);
+const stepped = [];
+for (let i = 0; i < Math.min(rows - 1, 4); i++) {
+ await page.keyboard.press("ArrowDown");
+ // As someone reading down a list: a glance at each.
+ await page.waitForTimeout(260);
+ stepped.push(await page.locator('.note-row[aria-selected="true"] .note-row-name').innerText());
+}
+for (let i = 0; i < 2; i++) {
+ await page.keyboard.press("ArrowUp");
+ await page.waitForTimeout(260);
+}
+const seen = await page.evaluate(() => window.__seen);
+ok(seen.opening === 0, `stepping through notes never shows "Opening…" between them ${JSON.stringify(seen)} ${JSON.stringify(stepped)}`);
+ok(seen.readonly === 0, "nor a note drawn read-only for a moment while its formatting comes");
+ok(seen.plainCurtains === 0, "nor a formatted note drawn plain first");
+
+// A note slow to come still says it is opening, once it is slow.
+await page.evaluate(() => { window.__slowBody = true; });
+await page.evaluate(() => {
+ const t = window.__TAURI_INTERNALS__;
+ const inner = t.invoke;
+ t.invoke = async (cmd, args) => {
+ if (window.__slowBody && cmd === "note_body") await new Promise((r) => setTimeout(r, 900));
+ return inner(cmd, args);
+ };
+});
+// The library changed (an edit sent): what was read ahead is let go of, so the last note —
+// read ahead while stepping past it — has to be read again.
+await page.evaluate(() => window.__emit("quince://outbox-changed", { services: ["notes"] }));
+await page.waitForTimeout(100);
+await page.locator(".note-row").last().click();
+await page.waitForTimeout(100);
+const early = await page.locator(".note-loading").count();
+await page.waitForTimeout(400);
+const later = await page.locator(".note-loading").count();
+ok(early === 0 && later === 1, `a slow note says "Opening…" only once it is slow (at 100 ms: ${early}, at 500 ms: ${later})`);
+await page.evaluate(() => { window.__slowBody = false; });
+await page.waitForTimeout(800);
+
+// Typing draws the note, not the list.
+await page.locator(".note-row", { hasText: "Curtains" }).first().click();
+await page.waitForTimeout(500);
+await page.locator(".note-rich p").last().click();
+await page.keyboard.press("End");
+await page.waitForTimeout(200);
+const before = await page.evaluate(() => ({ rows: window.__rowRenders, commits: window.__commits }));
+await page.keyboard.type(" and blinds", { delay: 30 });
+await page.waitForTimeout(300);
+const typed = await page.evaluate(() => ({ rows: window.__rowRenders, commits: window.__commits }));
+ok(typed.rows - before.rows === 0, `typing eleven characters draws no row of the list again (${typed.rows - before.rows} rows drawn)`);
+
+// Moving the cursor within a line changes nothing on the bar: nothing is drawn for it.
+await page.keyboard.press("Home");
+await page.waitForTimeout(100);
+const moved0 = await page.evaluate(() => window.__commits);
+for (let i = 0; i < 6; i++) await page.keyboard.press("ArrowRight");
+await page.waitForTimeout(150);
+const moved = await page.evaluate(() => window.__commits) - moved0;
+ok(moved === 0, `moving the cursor along a line commits nothing (${moved} commits)`);
+
+// And what was typed is saved, once, as typed.
+await page.waitForTimeout(1300);
+const saves = await page.evaluate(() => (window.__noteSaves ?? []).map((s) => s.body));
+ok(saves.length === 1 && saves[0].includes("and blinds"), `what was typed is saved once ${JSON.stringify(saves)}`);
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/shell-quiet.mjs b/.uiverify/shell-quiet.mjs
new file mode 100644
index 0000000..b6aafee
--- /dev/null
+++ b/.uiverify/shell-quiet.mjs
@@ -0,0 +1,117 @@
+// The shell around the apps does no more than it must, and draws nothing half-made.
+//
+// - The window is shown (window_ready) only once the app in front is drawn with its code in.
+// - "Apple signed you out" is a notice over the foot of the content, never a bar pushing the
+// window down; Sign In is on it.
+// - In a narrow window the sidebar is there at once when asked for: no slide of a large layer.
+// - A sheet still fades in, as the page draws it.
+// - A refresh that changed notes is read by Notes when it is in front, not behind another app.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const logCalls = () => {
+ // Leaving the library lets its listeners go, which the stub has no plugin for.
+ window.__TAURI_EVENT_PLUGIN_INTERNALS__ ??= { unregisterListener() {} };
+ const wrap = () => {
+ const t = window.__TAURI_INTERNALS__;
+ if (!t || t.__logged) return;
+ const inner = t.invoke;
+ t.invoke = async (cmd, args) => {
+ (window.__calls ??= []).push(cmd);
+ if (cmd === "window_ready") {
+ // What is on the page at the moment the window is shown.
+ const pane = document.querySelector(".content .screen-slot:not([hidden])");
+ window.__readyAt = {
+ needsYou: args?.needsYou,
+ rows: document.querySelectorAll(".sidebar .nav-item").length,
+ drawn: Boolean(pane && pane.querySelector(".notes, .rx, .cx, .contacts, .drive, .px-scroll")),
+ };
+ return null;
+ }
+ return inner(cmd, args);
+ };
+ t.__logged = true;
+ };
+ wrap(); document.addEventListener("DOMContentLoaded", wrap);
+};
+
+{
+ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+ await ctx.addInitScript(() => { try { localStorage.setItem("quince.library.screen", "notes"); } catch {} });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+ await ctx.addInitScript(logCalls);
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await page.waitForTimeout(500);
+ const at = await page.evaluate(() => window.__readyAt);
+ ok(at && at.needsYou === false && at.rows > 0 && at.drawn,
+ `the window is shown once the sidebar and the app in front are drawn ${JSON.stringify(at)}`);
+ ok((await page.evaluate(() => window.__calls.filter((c) => c === "window_ready").length)) === 1, "and said once");
+
+ // Notes behind Contacts: a pass that changed notes is not read until Notes is back in front.
+ await openScreen(page, "Contacts");
+ await page.waitForTimeout(300);
+ await page.evaluate(() => { window.__calls = []; });
+ const report = await page.evaluate(() => window.__TAURI_INTERNALS__.invoke("sync_status"));
+ for (let i = 0; i < 3; i++) {
+ await page.evaluate((r) => window.__emit("quince://synced", { ...r, changed: ["notes"] }), report);
+ await page.waitForTimeout(80);
+ }
+ await page.waitForTimeout(200);
+ const hidden = await page.evaluate(() => window.__calls.filter((c) => c === "notes_in").length);
+ ok(hidden === 0, `three passes that changed notes, read by nothing while Notes is out of sight (${hidden} reads)`);
+ await openScreen(page, "Notes");
+ await page.waitForTimeout(300);
+ const shown = await page.evaluate(() => window.__calls.filter((c) => c === "notes_in").length);
+ ok(shown === 1, `read once on coming back (${shown} reads)`);
+
+ // Signed out by Apple: one notice over the foot, the window not moved.
+ const top = await page.locator(".library").evaluate((e) => e.getBoundingClientRect().top);
+ await page.evaluate(() => window.__emit("quince://needs-signin", null));
+ await page.waitForTimeout(300);
+ const notice = page.locator(".toast-host .toast", { hasText: "Apple signed you out" });
+ ok((await notice.count()) === 1, "Apple signing the session out is said in a notice");
+ ok((await page.locator(".library").evaluate((e) => e.getBoundingClientRect().top)) === top, "and the window is not pushed down by it");
+ const foot = await page.locator(".sidebar-foot").boundingBox();
+ ok(foot && foot.y + foot.height <= 800, `the sidebar's foot is still in the window ${JSON.stringify(foot)}`);
+ await notice.getByRole("button", { name: "Sign In" }).click();
+ await page.waitForTimeout(300);
+ ok((await page.locator(".shell form.sheet").count()) === 1 && (await page.locator(".library").count()) === 0,
+ "Sign In on it opens the sign-in");
+
+ await ctx.close();
+}
+
+{
+ // A narrow window: the sidebar there at once, and gone at once.
+ const ctx = await b.newContext({ viewport: { width: 760, height: 700 } });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+ const page = await ctx.newPage();
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await page.waitForTimeout(400);
+ await page.getByRole("button", { name: "Show Sidebar" }).click();
+ const now = await page.locator(".sidebar").evaluate((e) => {
+ const cs = getComputedStyle(e);
+ const r = e.getBoundingClientRect();
+ return { left: r.left, visible: cs.visibility, moves: cs.transitionDuration.split(",").some((d) => parseFloat(d) > 0) && /transform|all/.test(cs.transitionProperty) };
+ });
+ ok(now.visible === "visible" && now.left >= 0 && !now.moves, `the sidebar is in place the moment it is asked for, with no slide ${JSON.stringify(now)}`);
+ await page.keyboard.press("Escape");
+ ok((await page.locator(".sidebar").evaluate((e) => getComputedStyle(e).visibility)) === "hidden", "and gone at once");
+
+ // A sheet still fades in, drawn by the page.
+ await page.keyboard.press("Control+/");
+ const first = await page.locator(".modal-sheet").first().evaluate((e) => e.style.opacity);
+ await page.waitForTimeout(400);
+ const settled = await page.locator(".modal-sheet").first().evaluate((e) => e.style.opacity);
+ ok(first !== "" && Number(first) < 1 && settled === "", `a sheet fades in (${first} → "${settled}")`);
+ await ctx.close();
+}
+
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 86b548c..f0391b7 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -392,7 +392,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
if (args.guid === "nG") {
// "Pasta\n", "Dinner for ", a #tag, " tonight": the tag one inline attachment in its line.
const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });
- return [{ ...plain(6), style: 0 }, plain(11), { ...plain(1), attachment: "T1" }, plain(8)];
+ return [{ ...plain(6), style: 0 }, plain(11), { ...plain(1), attachment: "H1" }, plain(8)];
}
if (args.guid === "nD") {
const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });
@@ -561,7 +561,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
const info = { id: args.id, title: null, width: null, height: null, size: null, hasPreview: false, filename: null, ...A };
return window.__slowInfo ? new Promise((r) => setTimeout(() => r(info), window.__slowInfo)) : info;
}
- if (args.id === "T1") return { id: "T1", uti: "com.apple.notes.inlinetextattachment.hashtag", kind: "inline", filename: null, title: "#Recipes", width: null, height: null, size: null, hasPreview: false };
+ if (args.id === "H1") return { id: "H1", uti: "com.apple.notes.inlinetextattachment.hashtag", kind: "inline", filename: null, title: "#Recipes", width: null, height: null, size: null, hasPreview: false };
if (args.id === "D1") return { id: "D1", uti: "com.apple.paper", kind: "drawing", filename: null, title: null, width: 768, height: 621, size: null, hasPreview: true };
if (args.id === "U1") return { id: "U1", uti: "com.apple.notes.table", kind: "table", filename: null, title: null, width: null, height: null, size: 1116, hasPreview: false };
// Any other id a table is drawn for (note_table answers it): a table, as the backend
diff --git a/crates/quince-icloud/src/notes_attach.rs b/crates/quince-icloud/src/notes_attach.rs
index 1c0f830..fe0e46c 100644
--- a/crates/quince-icloud/src/notes_attach.rs
+++ b/crates/quince-icloud/src/notes_attach.rs
@@ -57,6 +57,9 @@ pub struct Attached {
pub offset: u64,
/// The note's text as written, with the attachment's character in it.
pub body: String,
+ /// How that text is set, as written — Apple's runs, the attachment's among them — so the
+ /// note can be kept as Apple now holds it without reading it back.
+ pub runs: Vec<crate::ckdocument::Run>,
}
/// The type identifier Notes records for a file, from its name.
@@ -478,13 +481,19 @@ async fn attach_file_unguarded(
};
let client = ZoneClient::new(http, root, CONTAINER, params.clone());
- // The note first: there is no point uploading into a note that is not there.
- if client.lookup_record(ZONE, guid).await?.is_none() {
- return Err(Error::Refused("Apple no longer has that note.".into()));
- }
let attachment = uuid::Uuid::new_v4().to_string().to_uppercase();
let media = uuid::Uuid::new_v4().to_string().to_uppercase();
- let asset = upload_asset(http, root, &params, &media, bytes).await?;
+ // The note asked after while the file goes up, not before it: one round trip fewer on
+ // every file added. A note that is gone still adds nothing — the upload alone is never
+ // part of any note, and the loop below looks the note up again before writing.
+ let (there, asset) = tokio::join!(
+ client.lookup_record(ZONE, guid),
+ upload_asset(http, root, &params, &media, bytes)
+ );
+ if there?.is_none() {
+ return Err(Error::Refused("Apple no longer has that note.".into()));
+ }
+ let asset = asset?;
for _ in 0..4 {
let note = client
@@ -553,12 +562,14 @@ async fn attach_file_unguarded(
Ok(()) => {
let body =
crate::ckdocument::stored_text_from_base64(&document).unwrap_or_default();
+ let runs = crate::ckdocument::runs_from_base64(&document);
return Ok(Attached {
attachment,
media,
uti: uti.to_string(),
offset,
body,
+ runs,
});
}
// The note moved (or the zone was busy): nothing was written; place it again.
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 1e105c6..5667592 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -82,18 +82,63 @@ struct SessionFacts {
signed_in: bool,
/// The account it is (`account_tag`).
account: Option<String>,
+ /// The services Apple offers it, for the sidebar (`account_services`).
+ services: Vec<String>,
+ /// Who it is, as Apple names them (`account_info`).
+ name: Option<String>,
+ email: Option<String>,
+ web_access_allowed: Option<bool>,
+ data_protection: Option<bool>,
}
impl SessionFacts {
fn of(client: &Client) -> Self {
+ let s = client.session();
SessionFacts {
has_stored_session: client.has_stored_session(),
- signed_in: client.session().webservices.is_some(),
- account: client.session().dsid.as_deref().map(account_tag),
+ signed_in: s.webservices.is_some(),
+ account: s.dsid.as_deref().map(account_tag),
+ services: s
+ .webservices
+ .as_ref()
+ .and_then(|w| w.as_object())
+ .map(|o| {
+ let mut keys: Vec<String> = o.keys().cloned().collect();
+ keys.sort();
+ keys
+ })
+ .unwrap_or_default(),
+ name: s.account_name.clone(),
+ email: s.account_email.clone().or_else(|| s.apple_id.clone()),
+ web_access_allowed: s.web_access_allowed,
+ data_protection: s.data_protection,
}
}
}
+/// The session's facts now: read from the client when nothing holds it, and kept; what was
+/// last kept when something does — a resume, a sign-in, the heartbeat at the start of every
+/// sync — rather than a wait behind a round trip to Apple. The sidebar and the account card
+/// ask as the window opens, and waiting here left a launch on "Loading…" until Apple answered.
+fn session_facts(auth: &Auth) -> SessionFacts {
+ let fresh = auth
+ .client
+ .try_lock()
+ .ok()
+ .map(|client| SessionFacts::of(&client));
+ let mut kept = auth
+ .known
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ match fresh {
+ Some(facts) => {
+ *kept = facts.clone();
+ facts
+ }
+ None => kept.clone(),
+ }
+}
+
/// Clears the in-flight flag however the guarded block exits.
struct InFlight<'a>(&'a AtomicBool);
@@ -285,7 +330,7 @@ fn note_part(path: &str) -> Option<(String, quince_icloud::note_media::Part)> {
let (id, part) = rest.rsplit_once('/')?;
let part = match part {
"preview" => quince_icloud::note_media::Part::Preview,
- "file" => quince_icloud::note_media::Part::File,
+ "file" | "inline" => quince_icloud::note_media::Part::File,
"drawing" | "drawing-dark" => quince_icloud::note_media::Part::Drawing,
_ => return None,
};
@@ -439,6 +484,46 @@ async fn note_media_shown(
Ok(jpeg)
}
+/// The longest side a note's picture is drawn at in the note. A photo from a phone is 12 to 48
+/// megapixels; drawn in the note at its full size, a long note of them was a decode of each
+/// whole picture while scrolling, and the memory to hold them. The viewer and Open still have
+/// the whole picture.
+const INLINE_LONG: u32 = 1600;
+
+/// A picture made the size a note draws it, or `None` when it already is (or is one that must
+/// not be redrawn: a GIF would lose its motion).
+fn inline_picture(bytes: &[u8]) -> Option<Vec<u8>> {
+ if bytes.starts_with(b"GIF8") {
+ return None;
+ }
+ quince_media::fit(bytes, INLINE_LONG).ok().flatten()
+}
+
+/// A note's picture as drawn in the note: `note_media_shown`'s picture made no larger than
+/// `INLINE_LONG`, made once and kept beside it. One small enough already is served as it is.
+async fn note_media_inline(app: &tauri::AppHandle, id: &str) -> Result<Vec<u8>, String> {
+ let made = state_dir(app)
+ .join("note-media")
+ .join(format!("{}-inline", media_file_id(id)));
+ if let Ok(bytes) = tokio::fs::read(&made).await {
+ return Ok(bytes);
+ }
+ let shown = note_media_shown(app, id, quince_icloud::note_media::Part::File, false).await?;
+ let (shown, small) = crate::cpu::run(move || {
+ let small = inline_picture(&shown);
+ (shown, small)
+ })
+ .await?;
+ let Some(small) = small else {
+ return Ok(shown);
+ };
+ let part = made.with_extension("part");
+ if tokio::fs::write(&part, &small).await.is_ok() {
+ let _ = tokio::fs::rename(&part, &made).await;
+ }
+ Ok(small)
+}
+
/// Show a file the app saved in its folder, in the file manager, chosen: a "Saved to
/// Downloads" toast's Show in Folder. Only a file in Downloads — what the app itself saves
/// there — never any other path the page might name.
@@ -887,24 +972,8 @@ fn state_dir(app: &tauri::AppHandle) -> PathBuf {
#[tauri::command]
async fn auth_status(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<Status> {
timing::mark("auth_status asked");
- let known = |facts: Option<SessionFacts>| {
- let mut kept = auth
- .known
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- match facts {
- Some(facts) => {
- *kept = facts.clone();
- facts
- }
- None => kept.clone(),
- }
- };
// Busy (a resume, a sign-in, the timer's check): what was last known, rather than a wait.
- let facts = match auth.client.try_lock() {
- Ok(client) => known(Some(SessionFacts::of(&client))),
- Err(_) => known(None),
- };
+ let facts = session_facts(&auth);
let owner = data.0.lock().await.state(ACCOUNT_KEY).ok().flatten();
timing::mark("auth_status answered");
Ok(Status {
@@ -1537,11 +1606,11 @@ async fn account_info(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<
.filter(|guid| !guid.is_empty())
.filter(|guid| library.contact_photo_source(guid).ok().flatten().is_some())
};
- let client = auth.client.lock().await;
- let s = client.session();
+ // Never behind the session's lock: see `session_facts`.
+ let s = session_facts(&auth);
Ok(AccountInfo {
- name: s.account_name.clone(),
- email: s.account_email.clone().or_else(|| s.apple_id.clone()),
+ name: s.name,
+ email: s.email,
web_access_allowed: s.web_access_allowed,
data_protection: s.data_protection,
photo_contact,
@@ -1581,18 +1650,9 @@ async fn settings_set(key: String, on: bool, data: State<'_, Data>) -> UiResult<
#[tauri::command]
async fn account_services(auth: State<'_, Auth>) -> UiResult<Vec<String>> {
- let client = auth.client.lock().await;
- Ok(client
- .session()
- .webservices
- .as_ref()
- .and_then(|w| w.as_object())
- .map(|o| {
- let mut keys: Vec<String> = o.keys().cloned().collect();
- keys.sort();
- keys
- })
- .unwrap_or_default())
+ // Apple's list is kept with the session, so it is known before the session is taken up
+ // again: never a wait behind the lock a resume or a sync's heartbeat holds.
+ Ok(session_facts(&auth).services)
}
/// Keep the session warm.
@@ -5041,7 +5101,9 @@ fn window_ready(app: tauri::AppHandle, window: tauri::WebviewWindow, needs_you:
// Started at login, with nothing for the person to do: everything runs, the window waits
// in the tray.
// Never without the tray to come back from.
- if tray_reachable(&app) && login::stay_hidden(needs_you.unwrap_or(true)) {
+ // Asked in this order: started any other way the answer is no, and the tray's question —
+ // a call on the session bus — was asked on the main thread just before every launch's show.
+ if login::stay_hidden(needs_you.unwrap_or(true)) && tray_reachable(&app) {
// Its page has done what a launch needs of it (the session taken up again): it waits,
// drawn and hidden, so the tray opens it at once.
return;
@@ -5228,7 +5290,67 @@ fn app_cache(_webview: &tauri::Webview) {}
/// register after Skykeep. A bus that cannot be asked is taken as a tray that is there.
#[cfg(target_os = "linux")]
fn tray_reachable(_app: &tauri::AppHandle) -> bool {
- linux_tray::made() && status_notifier_host().unwrap_or(true)
+ linux_tray::made() && TRAY_HOST.reachable(|| status_notifier_host().unwrap_or(true))
+}
+
+/// Whether a tray host is there, as last asked. It is asked where a window shows or closes —
+/// on the main thread, where a call on the session bus froze every window for as long as it
+/// took (up to a second) — so the answer kept is used there, and asked again behind it for the
+/// next time. A panel coming or going is heard of from ksni too (`watcher_online`/`_offline`).
+/// Only the very first question, with nothing kept yet, waits for its answer.
+#[cfg(target_os = "linux")]
+static TRAY_HOST: HostSeen = HostSeen::new();
+
+#[cfg(target_os = "linux")]
+struct HostSeen {
+ /// 0 not asked yet, 1 no host, 2 a host.
+ seen: std::sync::atomic::AtomicU8,
+ asking: AtomicBool,
+}
+
+#[cfg(target_os = "linux")]
+impl HostSeen {
+ const fn new() -> Self {
+ Self {
+ seen: std::sync::atomic::AtomicU8::new(0),
+ asking: AtomicBool::new(false),
+ }
+ }
+
+ fn keep(&self, host: bool) {
+ self.seen.store(if host { 2 } else { 1 }, Ordering::SeqCst);
+ }
+
+ /// The answer kept, asked again in the background; asked now only when none is kept.
+ fn reachable(&'static self, ask: fn() -> bool) -> bool {
+ match self.seen.load(Ordering::SeqCst) {
+ 0 => {
+ let host = ask();
+ self.keep(host);
+ host
+ }
+ seen => {
+ self.ask_again(ask);
+ seen == 2
+ }
+ }
+ }
+
+ /// Asked off the main thread, one question at a time.
+ fn ask_again(&'static self, ask: fn() -> bool) {
+ if self.asking.swap(true, Ordering::SeqCst) {
+ return;
+ }
+ let spawned = std::thread::Builder::new()
+ .name("tray-host".into())
+ .spawn(move || {
+ self.keep(ask());
+ self.asking.store(false, Ordering::SeqCst);
+ });
+ if spawned.is_err() {
+ self.asking.store(false, Ordering::SeqCst);
+ }
+ }
}
#[cfg(not(target_os = "linux"))]
@@ -5349,10 +5471,15 @@ mod linux_tray {
item("Quit Skykeep", |app| shutdown(app, 0)),
]
}
- // A panel restarting, or not there yet: the icon comes back when it does.
+ // A panel restarting, or not there yet: the icon comes back when it does. Either way
+ // whether a host is there is asked again, so closing the window knows (TRAY_HOST).
fn watcher_offline(&self, _reason: ksni::OfflineReason) -> bool {
+ super::TRAY_HOST.ask_again(|| super::status_notifier_host().unwrap_or(true));
true
}
+ fn watcher_online(&self) {
+ super::TRAY_HOST.ask_again(|| super::status_notifier_host().unwrap_or(true));
+ }
}
/// The tray's mark at every size a panel draws one, each made from the vector master with
@@ -5409,6 +5536,8 @@ mod linux_tray {
#[cfg(target_os = "linux")]
fn build_tray(app: &tauri::App) -> tauri::Result<()> {
linux_tray::spawn(app.handle().clone());
+ // Asked now, off the main thread, so the first window shown or closed has its answer kept.
+ TRAY_HOST.ask_again(|| status_notifier_host().unwrap_or(true));
Ok(())
}
@@ -5613,6 +5742,8 @@ fn main() {
let drive_thumb = drive_thumb_part(uri.path());
// A drawing's ink for a dark page, rather than a light one.
let ink_dark = uri.path().ends_with("drawing-dark");
+ // A note's picture as the note draws it, rather than whole.
+ let inline = uri.path().ends_with("/inline");
let picture = photos::requested(uri.path());
let fit = photos::requested_fit(uri.path());
let queued = photos::requested_upload(uri.path());
@@ -5693,7 +5824,12 @@ fn main() {
}
// A note's picture, or the rendering of a document or film in it.
if let Some((id, part)) = attachment {
- let response = match note_media_shown(&app, &id, part, ink_dark).await {
+ let shown = if inline {
+ note_media_inline(&app, &id).await
+ } else {
+ note_media_shown(&app, &id, part, ink_dark).await
+ };
+ let response = match shown {
Ok(bytes) => tauri::http::Response::builder()
.status(200)
.header("Content-Type", image_type(&bytes))
@@ -6104,6 +6240,79 @@ fn main() {
#[cfg(test)]
mod tests {
+ /// The sidebar's services and the account's name are answered while the session is busy —
+ /// taken up again, or checked at the start of a sync — from what was kept, never a wait.
+ #[test]
+ fn account_facts_answer_while_the_session_is_busy() {
+ use super::{session_facts, Auth, SessionFacts};
+ let dir = tempfile::tempdir().unwrap();
+ let client = quince_auth::Client::new(dir.path()).unwrap();
+ let auth = Auth {
+ client: std::sync::Arc::new(tokio::sync::Mutex::new(client)),
+ signing_in: std::sync::atomic::AtomicBool::new(false),
+ known: std::sync::Mutex::new(SessionFacts {
+ services: vec!["notes".into(), "reminders".into()],
+ name: Some("Kept Name".into()),
+ ..SessionFacts::default()
+ }),
+ };
+ let busy = auth.client.try_lock().unwrap();
+ let facts = session_facts(&auth);
+ assert_eq!(facts.services, ["notes", "reminders"]);
+ assert_eq!(facts.name.as_deref(), Some("Kept Name"));
+ drop(busy);
+ // Free, it is read from the session itself (signed out here: nothing) and kept.
+ assert!(session_facts(&auth).services.is_empty());
+ assert!(auth.known.lock().unwrap().services.is_empty());
+ }
+
+ /// Whether a tray host is there is asked once, then answered from what was kept while it
+ /// is asked again behind — never a wait on the session bus after the first.
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn the_tray_host_is_asked_off_the_main_thread_after_the_first_time() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ static HOST: super::HostSeen = super::HostSeen::new();
+ static ASKED: AtomicUsize = AtomicUsize::new(0);
+ fn ask() -> bool {
+ ASKED.fetch_add(1, Ordering::SeqCst);
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ false
+ }
+ let first = std::time::Instant::now();
+ assert!(!HOST.reachable(ask));
+ assert!(first.elapsed() >= std::time::Duration::from_millis(50));
+ HOST.keep(true);
+ let again = std::time::Instant::now();
+ assert!(HOST.reachable(ask), "the kept answer");
+ assert!(again.elapsed() < std::time::Duration::from_millis(40));
+ // The question asked again behind lands, and is what the next answer says.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ while ASKED.load(Ordering::SeqCst) < 2 || HOST.asking.load(Ordering::SeqCst) {
+ assert!(std::time::Instant::now() < deadline);
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ assert!(!HOST.reachable(ask));
+ }
+
+ /// A phone's photo is drawn in its note no larger than the note needs; a small one, and a
+ /// GIF (which would lose its motion), as they are.
+ #[test]
+ fn a_note_picture_is_drawn_at_the_size_the_note_needs() {
+ let jpeg = |w: u32, h: u32| {
+ let mut out = std::io::Cursor::new(Vec::new());
+ image::RgbImage::from_pixel(w, h, image::Rgb([200, 120, 40]))
+ .write_to(&mut out, image::ImageFormat::Jpeg)
+ .unwrap();
+ out.into_inner()
+ };
+ let small = super::inline_picture(&jpeg(4032, 3024)).expect("made smaller");
+ let drawn = image::load_from_memory(&small).unwrap();
+ assert_eq!((drawn.width(), drawn.height()), (super::INLINE_LONG, 1200));
+ assert!(super::inline_picture(&jpeg(1200, 800)).is_none());
+ assert!(super::inline_picture(b"GIF89a....").is_none());
+ }
+
/// A shared note's attachment is saved under a plain name in its own folder, whatever its
/// sender called it, and a program in one is shown in its folder, never run.
#[test]
diff --git a/src-tauri/src/notes_cmds.rs b/src-tauri/src/notes_cmds.rs
index f08a03c..0e53db0 100644
--- a/src-tauri/src/notes_cmds.rs
+++ b/src-tauri/src/notes_cmds.rs
@@ -144,6 +144,7 @@ pub async fn note_attach_file(
path: String,
at_offset: u64,
base: Option<String>,
+ app: tauri::AppHandle,
auth: State<'_, Auth>,
data: State<'_, Data>,
) -> UiResult<Attached> {
@@ -160,9 +161,148 @@ pub async fn note_attach_file(
)
.await
.map_err(|e| e.to_string())?;
- // Apple has it. A refresh failing now must not read as the attach failing.
- if let Err(e) = crate::resync_notes(&http, &root, params, &data).await {
- quiet!("notes refresh after an attachment: {e}");
+ // Apple has it, and said what the note now is: kept here as that at once. Waiting for a
+ // whole notes pass first held every file added — each one — on "Adding" for its length.
+ // The pass still runs, behind, for the note's new tag and anything else that moved; one
+ // failing must not read as the attach failing.
+ {
+ let mut library = data.0.lock().await;
+ if let Err(e) = lay_attached(&mut library, &guid, &attached) {
+ quiet!("keeping a note's new attachment: {e}");
+ }
}
+ tauri::async_runtime::spawn(async move {
+ use tauri::Manager;
+ let data = app.state::<Data>();
+ if let Err(e) = crate::resync_notes(&http, &root, params, &data).await {
+ quiet!("notes refresh after an attachment: {e}");
+ }
+ });
Ok(attached)
}
+
+/// A note with a file just added, kept as Apple now holds it: its text and formatting as
+/// written, its time edited moved on — and any edit still on its way to Apple laid back over
+/// it, as a pass lays them, so nothing typed is shown lost meanwhile.
+fn lay_attached(
+ library: &mut quince_core::Library,
+ guid: &str,
+ attached: &Attached,
+) -> quince_core::Result<()> {
+ let (title, snippet) = quince_icloud::notes::title_and_snippet(&attached.body);
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0));
+ library.atomically(|l| {
+ l.set_note_text(
+ guid,
+ &attached.body,
+ &title,
+ Some(snippet.as_str()).filter(|s| !s.is_empty()),
+ )?;
+ if !attached.runs.is_empty() {
+ let runs = serde_json::to_string(&attached.runs)
+ .map_err(|e| quince_core::Error::Io(std::io::Error::other(e.to_string())))?;
+ l.set_note_runs(guid, &runs)?;
+ }
+ l.touch_note(guid, now)?;
+ crate::outbox::replay(l, crate::outbox::NOTES)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::lay_attached;
+ use quince_core::Library;
+ use quince_icloud::ckdocument::Run;
+ use quince_icloud::notes::attach::Attached;
+
+ fn note(lib: &mut Library, guid: &str, body: &str) {
+ lib.put_notes(&[quince_core::notes::Note {
+ guid: guid.into(),
+ folder_guid: None,
+ title: body.into(),
+ snippet: None,
+ body: Some(body.into()),
+ locked: false,
+ pinned: false,
+ created_at: None,
+ modified_at: Some(1),
+ editable: true,
+ etag: None,
+ runs: None,
+ }])
+ .unwrap();
+ }
+
+ fn attached(body: &str, runs: Vec<Run>) -> Attached {
+ Attached {
+ attachment: "A".into(),
+ media: "M".into(),
+ uti: "public.jpeg".into(),
+ offset: 5,
+ body: body.into(),
+ runs,
+ }
+ }
+
+ /// A file added is kept as Apple answered at once — text, formatting with the file's run,
+ /// a new time edited — with no pass waited for.
+ #[test]
+ fn an_added_file_is_kept_without_a_pass() {
+ let mut lib = Library::in_memory().unwrap();
+ note(&mut lib, "N", "Trip\nend");
+ let runs = vec![
+ Run {
+ length: 5,
+ style: Some(0),
+ ..Run::default()
+ },
+ Run {
+ length: 1,
+ attachment: Some("A".into()),
+ ..Run::default()
+ },
+ Run {
+ length: 4,
+ ..Run::default()
+ },
+ ];
+ lay_attached(
+ &mut lib,
+ "N",
+ &attached("Trip\n\u{FFFC}\nend", runs.clone()),
+ )
+ .unwrap();
+ assert_eq!(
+ lib.note_body("N").unwrap().as_deref(),
+ Some("Trip\n\u{FFFC}\nend")
+ );
+ let kept: Vec<Run> = serde_json::from_str(&lib.note_runs("N").unwrap().unwrap()).unwrap();
+ assert_eq!(kept, runs);
+ let n = lib.note("N").unwrap().unwrap();
+ assert_eq!(n.title, "Trip");
+ assert!(n.modified_at.unwrap() > 1);
+ }
+
+ /// Typing still on its way to Apple stays on screen over the note as Apple answered it.
+ #[test]
+ fn typing_not_yet_sent_stays_over_an_added_file() {
+ let mut lib = Library::in_memory().unwrap();
+ note(&mut lib, "N", "Trip\nend");
+ crate::outbox::record_note_save(
+ &mut lib,
+ "N",
+ "Trip\nend and more",
+ Some("Trip\nend".into()),
+ None,
+ None,
+ )
+ .unwrap();
+ lay_attached(&mut lib, "N", &attached("Trip\n\u{FFFC}\nend", Vec::new())).unwrap();
+ assert_eq!(
+ lib.note_body("N").unwrap().as_deref(),
+ Some("Trip\nend and more")
+ );
+ }
+}
diff --git a/src/App.tsx b/src/App.tsx
index c709507..bd8dd68 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,9 +1,10 @@
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { SignIn } from "./screens/SignIn";
import { CodeEntry } from "./screens/CodeEntry";
import { Library } from "./screens/Library";
import { ImportSheet } from "./components/ImportSheet";
import { StatusLine } from "./components/StatusLine";
+import { dismissToast, toast } from "./components/Toast";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { api, NEEDS_CODE, NEEDS_SIGNIN } from "./lib/ipc";
@@ -17,13 +18,24 @@ export default function App() {
// put it there, not after an animation frame: the window is hidden until then, and a hidden
// WebKitGTK window draws no frames, so waiting on one left every launch to the three-second
// fallback. The page is laid out by now and the window paints it as it maps.
+ //
+ // The library says so itself (`onShown`), once its first screen is drawn with its code in:
+ // said as the phase changed, the window mapped onto an empty sidebar and a blank pane.
const [shown, setShown] = useState(false);
+ const show = useCallback(
+ (needsYou: boolean) => {
+ if (shown) return;
+ setShown(true);
+ // Started at login, the window stays in the tray unless the person is needed here.
+ invoke("window_ready", { needsYou }).catch(() => {});
+ },
+ [shown],
+ );
useEffect(() => {
- if (shown || phase === "checking") return;
- setShown(true);
- // Started at login, the window stays in the tray unless the person is needed here.
- invoke("window_ready", { needsYou: phase !== "library" }).catch(() => {});
- }, [phase, shown]);
+ if (phase === "checking" || phase === "library") return;
+ show(true);
+ }, [phase, show]);
+ const libraryShown = useCallback(() => show(false), [show]);
// On launch, try the stored session before showing anything. This is the whole promise:
// a returning user should never see the sign-in screen.
@@ -82,6 +94,19 @@ export default function App() {
void stop.then((unlisten) => unlisten()).catch(() => {});
};
}, []);
+ // Said where everything passing is said, over the foot of the content: drawn above the
+ // library, it pushed the whole window down and cut off the sidebar's foot. It stays until
+ // put away; Sign In is on it.
+ useEffect(() => {
+ if (!lapsed || phase !== "library") return undefined;
+ const id = toast({
+ message: "Apple signed you out. Your copy on this computer is still here.",
+ tone: "error",
+ duration: null,
+ action: { label: "Sign In", run: () => setPhase("signin") },
+ });
+ return () => dismissToast(id);
+ }, [lapsed, phase]);
// Signed out, the window starts over: nothing of the account is left in its memory either —
// no picture, no list, no cached answer — for whoever signs in next.
@@ -97,18 +122,7 @@ export default function App() {
return (
<>
<div className="app-ground" aria-hidden="true" />
- {lapsed && (
- <div className="toast lapsed" role="alert">
- <p>Apple signed you out. Your copy on this computer is still here.</p>
- <button className="primary" onClick={() => setPhase("signin")}>
- Sign In
- </button>
- <button className="quiet" onClick={() => setLapsed(false)}>
- Not Now
- </button>
- </div>
- )}
- <Library onSignOut={signOut} />
+ <Library onSignOut={signOut} onShown={libraryShown} />
<ImportSheet />
</>
);
diff --git a/src/components/ImportSheet.tsx b/src/components/ImportSheet.tsx
index 850d66b..5c69672 100644
--- a/src/components/ImportSheet.tsx
+++ b/src/components/ImportSheet.tsx
@@ -1,9 +1,10 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { listen } from "@tauri-apps/api/event";
import { api, intakeApi, INTAKE, type Arrival, type Calendar, type ImportEvent } from "../lib/ipc";
import { Picker } from "./Picker";
import { useModalFocus } from "../lib/focus";
+import { fadeIn } from "../lib/fade";
import "../styles/intake.css";
/**
@@ -65,6 +66,9 @@ export function ImportSheet() {
function Shell({ label, onCancel, children }: { label: string; onCancel: () => void; children: React.ReactNode }) {
const sheetRef = useRef<HTMLDivElement | null>(null);
useModalFocus(sheetRef);
+ // The next file's sheet takes the last one's place on the same dim, where the page-wide
+ // fade (lib/fade fadeSheetsIn) does not look: it fades itself in, before it is painted.
+ useLayoutEffect(() => fadeIn(sheetRef.current, { duration: 140 }), []);
return (
<div
ref={sheetRef}
diff --git a/src/lib/fade.ts b/src/lib/fade.ts
index 71d3e24..9c5b7ed 100644
--- a/src/lib/fade.ts
+++ b/src/lib/fade.ts
@@ -66,9 +66,14 @@ export function fadeOut(el: HTMLElement | null, done: () => void, duration = 120
}
/**
- * Every sheet, as it is added anywhere in the app, fades in this way — set before the first frame
- * is painted (a mutation observer runs before painting), so none shows whole for a frame first.
- * The full-window dims behind them simply appear: a large surface is never animated.
+ * Every sheet, as it is added, fades in this way — set before the first frame is painted (a
+ * mutation observer runs before painting), so none shows whole for a frame first. The
+ * full-window dims behind them simply appear: a large surface is never animated.
+ *
+ * Every sheet is drawn at the top of the page (components/Portal), so only what is added to
+ * the page's body is looked at. Watching the whole page looked through every row, tile and line
+ * of text added anywhere — a photo grid scrolling, a note typed in — for a sheet. A sheet that
+ * takes another's place on a dim already there fades itself in (`fadeIn`, ImportSheet).
*/
export function fadeSheetsIn() {
const sheets = ".modal-sheet";
@@ -80,7 +85,7 @@ export function fadeSheetsIn() {
node.querySelectorAll<HTMLElement>(sheets).forEach((el) => fadeIn(el, { duration: 140 }));
}
}
- }).observe(document.body, { childList: true, subtree: true });
+ }).observe(document.body, { childList: true });
}
/**
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 43ec8ef..9cc6f70 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -694,7 +694,7 @@ export type NoteAttachment = {
};
/** A note attachment's picture — the file itself, or Apple's rendering of it. */
-export function noteMediaSrc(id: string, part: "file" | "preview" | "drawing" | "drawing-dark"): string {
+export function noteMediaSrc(id: string, part: "file" | "inline" | "preview" | "drawing" | "drawing-dark"): string {
return convertFileSrc(`note/${id}/${part}`, "quince");
}
diff --git a/src/lib/sync.tsx b/src/lib/sync.tsx
index c9a6ce2..b5fb808 100644
--- a/src/lib/sync.tsx
+++ b/src/lib/sync.tsx
@@ -10,6 +10,7 @@ import {
} from "react";
import { listen } from "@tauri-apps/api/event";
import { api, messageOf, SYNCED, type Refresh } from "./ipc";
+import { useScreenActive } from "./screen";
/**
* One refresh for the whole account, shared by every screen.
@@ -203,6 +204,19 @@ export function useRevision(...services: string[]): number {
return services.reduce((n, s) => n + (revisions[s] ?? 0), revisions.all ?? 0);
}
+/**
+ * `useRevision`, for a screen kept out of sight: it holds still while another screen is in
+ * front, and catches up once when this one comes back. Each pass that landed used to have every
+ * kept screen read its whole list again behind the one being looked at (lib/screen).
+ */
+export function useShownRevision(...services: string[]): number {
+ const revision = useRevision(...services);
+ const active = useScreenActive();
+ const seen = useRef(revision);
+ if (active) seen.current = revision;
+ return seen.current;
+}
+
/** "just now", "4 min ago", "yesterday" — how old the library is, in words. */
export function freshness(asOf: number | null): string {
if (asOf === null) return "Not synced yet";
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index 035a6bd..8fd5296 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -1,7 +1,7 @@
import { ToastHost, toast } from "../components/Toast";
import { EmptyState } from "../components/EmptyState";
import { StatusLine } from "../components/StatusLine";
-import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState } from "react";
+import { lazy, Suspense, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { PanelLeft } from "lucide-react";
@@ -23,7 +23,16 @@ import { reveal, type Reveal } from "../lib/reveal";
*/
function screen<P extends object>(load: () => Promise<React.ComponentType<P>>) {
let mod: { default: React.ComponentType<P> } | null = null;
- const fetch = () => load().then((c) => (mod = { default: c }));
+ let loading: Promise<{ default: React.ComponentType<P> }> | null = null;
+ const fetch = () =>
+ (loading ??= load().then(
+ (c) => (mod = { default: c }),
+ (e) => {
+ // Asked again next time: a chunk that failed to arrive once is not gone for good.
+ loading = null;
+ throw e;
+ },
+ ));
const Screen = lazy(() =>
mod
? // A thenable that answers straight away: `lazy` takes it as already resolved.
@@ -169,7 +178,29 @@ const RAIL_KEY = "quince.library.rail";
* as in any window: an app's window is where that app is, not a place cut off from the rest. */
const ONLY = new URLSearchParams(window.location.search).get("app");
-export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<void> }) {
+/**
+ * The code for the screen this window will most likely open on, asked for as this file loads —
+ * beside the session check, rather than after the sidebar's list has come back.
+ */
+const LIKELY = (() => {
+ if (ONLY && ONLY in apps) return ONLY as keyof typeof apps;
+ try {
+ const last = window.localStorage.getItem(LAST_KEY);
+ return last && last in apps ? (last as keyof typeof apps) : null;
+ } catch {
+ return null;
+ }
+})();
+if (LIKELY) void apps[LIKELY].fetch().catch(() => {});
+
+/** Mounted beside a screen under its Suspense, so it mounts in the commit that draws the
+ * screen itself — once its code is in, never while the pane is still blank. */
+function Drawn({ then }: { then: () => void }) {
+ useEffect(() => then(), [then]);
+ return null;
+}
+
+export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) => Promise<void>; onShown?: () => void }) {
const [services, setServices] = useState<string[]>([]);
const [selected, setSelected] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -283,6 +314,23 @@ export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<v
}
}, [selected]);
+ // The window is shown once there is something in it: the sidebar's apps, and the screen in
+ // front drawn with its code in (`Drawn`, beside it under its Suspense) — so it maps on the
+ // app, not on a blank pane that fills a moment later. With no screen to draw it is said as
+ // soon as that is known. (The backend shows the window anyway after three seconds.)
+ const told = useRef(false);
+ const onShownRef = useRef(onShown);
+ onShownRef.current = onShown;
+ const drawn = useCallback(() => {
+ if (told.current) return;
+ told.current = true;
+ onShownRef.current?.();
+ }, []);
+ const noScreen = Boolean(error) || (ready && (!selected || webAccess === false));
+ useEffect(() => {
+ if (noScreen) drawn();
+ }, [noScreen, drawn]);
+
// The other apps' code, fetched while nothing else is happening.
useEffect(() => {
if (!ready) return undefined;
@@ -480,6 +528,7 @@ export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<v
<ScreenBoundary key="settings" name="Settings">
<Suspense fallback={null}>
<SettingsView onSignOut={onSignOut} />
+ <Drawn then={drawn} />
</Suspense>
</ScreenBoundary>
)}
@@ -493,7 +542,10 @@ export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<v
<div key={key} className="screen-slot" hidden={!on} {...(on ? {} : { inert: "" })}>
<ScreenActive.Provider value={on}>
<ScreenBoundary name={SCREENS.find((s) => s.key === key)?.name ?? "This screen"}>
- <Suspense fallback={null}>{screenFor(key)}</Suspense>
+ <Suspense fallback={null}>
+ {screenFor(key)}
+ {on && <Drawn then={drawn} />}
+ </Suspense>
</ScreenBoundary>
</ScreenActive.Provider>
</div>
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index 8c9b282..769ef8d 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -1,4 +1,4 @@
-import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { usePending } from "../lib/pending";
import { useErrorToast } from "../components/Toast";
import { useConfirm } from "../components/Confirm";
@@ -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, type NoteOrder } from "./notes/model";
+import { DEFAULT_ORDER, editorDate, groupNotes, listDate, mergeEdits, splitTitle, titleAndSnippet, 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";
@@ -26,7 +26,7 @@ import { NotePicture } from "./notes/NotePicture";
import { OPEN_NOTE_EVENT } from "./notes/links";
import { useReveal } from "../lib/reveal";
import { Arriving } from "../components/EmptyState";
-import { useArriving, useRevision } from "../lib/sync";
+import { useArriving, useRevision, useShownRevision } from "../lib/sync";
import { Picker } from "../components/Picker";
const ALL = "__all__";
@@ -91,6 +91,59 @@ function fitFolders(aside: HTMLElement | null): number | null {
return clampFolders(widest + pad + 2);
}
+/**
+ * The list of notes, drawn again only when the notes or the open one change. Inline in the
+ * screen, every key typed in a note — and every move of the cursor — drew every row again,
+ * which in an account of thousands was felt in the typing.
+ */
+const NoteRows = memo(function NoteRows({
+ sections,
+ openGuid,
+ rowsRef,
+ onPick,
+}: {
+ sections: Section[];
+ openGuid: string | null;
+ rowsRef: React.MutableRefObject<HTMLDivElement | null>;
+ onPick: (note: Note, e: React.MouseEvent) => void;
+}) {
+ return (
+ <div className="note-rows" ref={rowsRef} role="listbox" aria-label="Notes" data-rows="">
+ {sections.map((section) => (
+ <Fragment key={section.key}>
+ <div className="notes-section" aria-hidden="true">{section.heading}</div>
+ <div role="group" aria-label={section.heading}>
+ {section.notes.map((note) => (
+ <div role="presentation" className="note-item" key={note.guid}>
+ <button
+ className="note-row"
+ role="option"
+ data-guid={note.guid}
+ aria-selected={openGuid === note.guid}
+ onClick={(e) => onPick(note, e)}
+ >
+ <span className="note-row-title">
+ {note.locked && (
+ <LockKeyhole className="note-row-lock" size={12} strokeWidth={2.4} aria-label="Locked" />
+ )}
+ <span className="note-row-name">{wordsOnly(note.title) || "New Note"}</span>
+ </span>
+ <span className="note-row-meta">
+ <span className="note-row-when">{listDate(note.modifiedAt)}</span>
+ <span className="note-row-snippet">
+ {note.locked ? "Locked" : wordsOnly(note.snippet ?? "").slice(0, 80) || "No additional text"}
+ </span>
+ </span>
+ </button>
+ </div>
+ ))}
+ </div>
+ </Fragment>
+ ))}
+ </div>
+ );
+});
+
export function NotesView() {
// The folders' column: as wide as it was left, or — the first time — as wide as the longest
// folder name needs, within reason.
@@ -140,7 +193,11 @@ export function NotesView() {
const [error, setError] = useState<string | null>(null);
useErrorToast(error, () => setError(null));
const [confirm, confirmSheet] = useConfirm();
- const revision = useRevision("notes");
+ /** Moves with every pass that changed notes, shown or not: an edit waiting goes then. */
+ const synced = useRevision("notes");
+ // What the screen reads by: held while another screen is in front, and read once on coming
+ // back (lib/sync).
+ const revision = useShownRevision("notes");
const arriving = useArriving("notes");
// Tables on screen keep up with a phone's edits, as the note's text does.
useEffect(() => {
@@ -332,14 +389,59 @@ export function NotesView() {
*/
const [loadedBody, setLoadedBody] = useState<{ guid: string; text: string } | null>(null);
+ /** 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);
+ 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)
+
+ /**
+ * Saving is not something anyone should have to remember.
+ *
+ * Apple's Notes has no save button because a note is not a document you commit — it is
+ * just there, and what you typed is what it says. Typing schedules a save; leaving the
+ * 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; runs: Run[] | null } | null>(null);
+
+ /**
+ * The notes beside the open one, read ahead — text and formatting — so stepping to one with
+ * the arrow keys draws it in the same frame, rather than a frame of "Opening…" and then the
+ * note. Only ever what the library holds after every save so far (read behind them), let go
+ * of whenever the library changes, and a note typed into is never taken from here.
+ */
+ const ahead = useRef(new Map<string, { text: string; runs: Run[] }>());
+ /** Moves each time the library changes, so a read ahead begun before it is not kept. */
+ const aheadAt = useRef(0);
+ useEffect(() => {
+ ahead.current.clear();
+ aheadAt.current += 1;
+ }, [revision, outbox.tick]);
+
+ // The words and their formatting are read together and arrive together: read one after the
+ // other, the note was drawn plain and then again formatted — a flash on every note opened.
useEffect(() => {
- if (!openGuid) return setLoadedBody(null);
+ setFormatAt(null);
+ if (!openGuid) {
+ setLoadedBody(null);
+ setLoadedRuns(null);
+ return undefined;
+ }
let cancelled = false;
setLoadedBody((current) => (current?.guid === openGuid ? current : null));
- api
- .noteBody(openGuid)
- .then((text) => {
- if (cancelled || text === null) return;
+ Promise.all([
+ api.noteBody(openGuid),
+ // Unreadable formatting still opens the note — as text only (formatSafe stays false),
+ // which saves the words and leaves Apple's formatting as it is.
+ api.noteRuns(openGuid).then((runs) => (Array.isArray(runs) ? runs : []), () => null),
+ ])
+ .then(([text, runs]) => {
+ if (cancelled) return;
+ setLoadedRuns((cur) => (runs !== null ? { guid: openGuid, runs } : cur?.guid === openGuid ? cur : { guid: openGuid, runs: [] }));
+ if (text === null) return;
// Never over what is being typed. A refresh follows every save, and adopting its
// 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 —
@@ -358,29 +460,14 @@ export function NotesView() {
};
}, [openGuid, revision, outbox.tick]);
- /** 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);
- 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(() => {
- setFormatAt(null);
- if (!openGuid) return setLoadedRuns(null);
- let cancelled = false;
- api.noteRuns(openGuid).then(
- (runs) => { if (!cancelled) setLoadedRuns({ guid: openGuid, runs: Array.isArray(runs) ? runs : [] }); },
- // Unreadable formatting still opens the note — as text only (formatSafe stays false),
- // which saves the words and leaves Apple's formatting as it is.
- () => { if (!cancelled) setLoadedRuns((cur) => (cur?.guid === openGuid ? cur : { guid: openGuid, runs: [] })); },
- );
- return () => { cancelled = true; };
- }, [openGuid, revision, outbox.tick]);
- /** 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;
+ /** What the open note says, or null while that is still unknown. Read ahead, it is known at
+ * once (`ahead`) — until its own read lands. */
+ const bodyIn = open !== null && loadedBody?.guid === open.guid;
+ // Never for a note with an edit still waiting to go: only its own read says what it holds.
+ const early = open && !bodyIn && pending.current?.guid !== open.guid ? ahead.current.get(open.guid) : undefined;
+ const body = bodyIn ? loadedBody!.text : (early?.text ?? null);
+ const runs = bodyIn ? (loadedRuns?.guid === open!.guid ? loadedRuns.runs : null) : (early?.runs ?? null);
/**
* 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,
@@ -399,15 +486,6 @@ export function NotesView() {
const dirty = draft !== null && body !== null && draft !== body;
- /**
- * Saving is not something anyone should have to remember.
- *
- * Apple's Notes has no save button because a note is not a document you commit — it is
- * just there, and what you typed is what it says. Typing schedules a save; leaving the
- * 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; 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.
@@ -424,17 +502,40 @@ export function NotesView() {
pending.current = null;
const from = base.current?.guid === next.guid ? base.current.text : null;
const fromRuns = base.current?.guid === next.guid ? (base.current.runs ?? null) : null;
+ // Straight to the library, which keeps it and sends it behind (the outbox): no controls
+ // made busy and no list read again for it — every pause in typing did both, and the next
+ // save waited behind that read. The outbox's own word, when it has sent it, reads again.
let saved: string | null = null;
- const ok = await write(async () => {
+ setError(null);
+ // A read ahead begun before this save lands is not what the note will say: let go.
+ aheadAt.current += 1;
+ try {
saved = await api.noteSave(next.guid, next.body, from, next.runs, next.runs ? fromRuns : null);
- });
- if (!ok || saved === null) {
+ } catch (e) {
+ setError(messageOf(e));
+ }
+ if (saved === null) {
// Not sent: the edit goes back in line (unless newer typing already replaced it), to
// go with the next pause, the next sync or leaving the note — never dropped.
if (!pending.current) pending.current = next;
return;
}
const kept: string = saved;
+ // 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 };
setSaved(true);
@@ -465,13 +566,13 @@ export function NotesView() {
});
inFlight.current = run.catch(() => {});
return run;
- }, [write]);
+ }, []);
// An edit that could not be sent goes again when a sync has just succeeded — Apple is
// reachable — rather than waiting for more typing.
useEffect(() => {
if (pending.current) void flush();
- }, [revision, flush]);
+ }, [synced, flush]);
const type = useCallback(
(typed: string, typedRuns: Run[]) => {
@@ -480,6 +581,7 @@ export function NotesView() {
// 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, runs: formatSafe ? runs : null };
draftRuns.current = typedRuns;
+ ahead.current.delete(open.guid);
setDraft(typed);
setEdits((n) => n + 1);
setSaved(false);
@@ -633,6 +735,8 @@ export function NotesView() {
);
const create = useCallback(async () => {
+ // What was typed a moment ago is handed over first, to the note it was typed in.
+ editorRef.current?.flushChange();
if (composingRef.current) await commitComposing();
await flush();
composeSeq.current += 1;
@@ -812,7 +916,8 @@ export function NotesView() {
at = added.offset + 1;
toast({ message: `Added “${fileName(path)}”`, tone: "done" });
}
- // The note as Apple now holds it, file in place.
+ // The note as Apple now holds it, file in place — kept here as it answered (any typing
+ // still on its way laid over it), so read from the library rather than asked again.
const [nextBody, nextRuns] = await Promise.all([api.noteBody(guid), api.noteRuns(guid)]);
if (nextBody !== null) setLoadedBody({ guid, text: nextBody });
setLoadedRuns({ guid, runs: Array.isArray(nextRuns) ? nextRuns : [] });
@@ -982,9 +1087,13 @@ export function NotesView() {
/** Every change in the editor: to the note being composed, or to the open one. */
const apply = (next: string, nextRuns: Run[]) => {
- if (composingRef.current) {
+ const c = composingRef.current;
+ if (c) {
draftRuns.current = nextRuns;
- setComposing((c) => (c ? { ...c, body: next } : c));
+ // Known at once, not when React gets to it: New Note pressed in the same moment hands
+ // this text over first (`create`), and must not find the note still empty.
+ composingRef.current = { ...c, body: next };
+ setComposing((was) => (was ? { ...was, body: next } : was));
} else type(next, nextRuns);
};
@@ -1040,6 +1149,61 @@ export function NotesView() {
useEffect(() => setDetail(false), [folder]);
const sections = useMemo(() => groupNotes(notes, new Date(), listOrder), [notes, listOrder]);
+ /** The folders as nested, worked out when they change rather than on every key typed. */
+ const nested = useMemo(() => nestFolders(folders), [folders]);
+
+ /** A row clicked: the one function for every row, so the list is not drawn again for it. */
+ const pick = (note: Note, e: React.MouseEvent) => {
+ pickedBy.current = e.detail > 0 ? "pointer" : "keys";
+ // A locked note clicked again, already open: on into its password field.
+ if (e.detail > 0 && note.locked && note.guid === openGuid)
+ document.querySelector<HTMLInputElement>(".notes .note-lock-field")?.focus();
+ void selectNote(note.guid);
+ };
+ const pickRef = useRef(pick);
+ pickRef.current = pick;
+ const pickRow = useCallback((note: Note, e: React.MouseEvent) => pickRef.current(note, e), []);
+
+ // The notes either side of the open one, read ahead once it has opened (see `ahead`): behind
+ // every save already on its way, and dropped if the library changed meanwhile.
+ const bodyShown = body !== null;
+ useEffect(() => {
+ if (!openGuid || !bodyShown) return undefined;
+ const order = sections.flatMap((g) => g.notes);
+ const at = order.findIndex((n) => n.guid === openGuid);
+ if (at < 0) return undefined;
+ const near = [order[at + 1], order[at - 1]].filter(
+ (n): n is Note =>
+ Boolean(n && !n.locked && n.editable && !ahead.current.has(n.guid) && pending.current?.guid !== n.guid),
+ );
+ if (!near.length) return undefined;
+ const when = aheadAt.current;
+ let live = true;
+ void inFlight.current.then(() =>
+ Promise.all(
+ near.map(async (n) => {
+ const [text, runs] = await Promise.all([api.noteBody(n.guid), api.noteRuns(n.guid)]);
+ if (!live || when !== aheadAt.current || text === null || !Array.isArray(runs)) return;
+ if (ahead.current.size > 16) ahead.current.clear();
+ ahead.current.set(n.guid, { text, runs });
+ }),
+ ).catch(() => {}),
+ );
+ return () => {
+ live = false;
+ };
+ }, [openGuid, bodyShown, sections]);
+
+ // "Opening…" only for a note slow to arrive: one read in a moment draws straight away, and
+ // the spinner it used to show first was a flash on every note opened.
+ const waiting = Boolean(open && !open.locked && (body === null || (open.editable && runs === null)));
+ const [slow, setSlow] = useState(false);
+ useEffect(() => {
+ setSlow(false);
+ if (!waiting) return undefined;
+ const t = window.setTimeout(() => setSlow(true), 300);
+ return () => window.clearTimeout(t);
+ }, [waiting, openGuid]);
const heading = searching
? "Search"
: folder === ALL
@@ -1093,7 +1257,7 @@ export function NotesView() {
<span className="source-name notes-folder-name">All iCloud</span>
<span className="count notes-folder-count">{counts.all || ""}</span>
</button>
- {nestFolders(folders)
+ {nested
.filter(({ folder: f }) => f.guid !== TRASH_FOLDER)
.map(({ folder: f, depth }) => {
const own = f.guid !== DEFAULT_FOLDER;
@@ -1274,45 +1438,7 @@ export function NotesView() {
{/* One list box of notes, a group per heading: the open note is its selected option.
The heading is drawn for the eye; the group's name says it to a screen reader. */}
- <div className="note-rows" ref={rowsRef} role="listbox" aria-label="Notes" data-rows="">
- {sections.map((section) => (
- <Fragment key={section.key}>
- <div className="notes-section" aria-hidden="true">{section.heading}</div>
- <div role="group" aria-label={section.heading}>
- {section.notes.map((note) => (
- <div role="presentation" className="note-item" key={note.guid}>
- <button
- className="note-row"
- role="option"
- data-guid={note.guid}
- aria-selected={openGuid === note.guid}
- onClick={(e) => {
- pickedBy.current = e.detail > 0 ? "pointer" : "keys";
- // A locked note clicked again, already open: on into its password field.
- if (e.detail > 0 && note.locked && note.guid === openGuid)
- document.querySelector<HTMLInputElement>(".notes .note-lock-field")?.focus();
- void selectNote(note.guid);
- }}
- >
- <span className="note-row-title">
- {note.locked && (
- <LockKeyhole className="note-row-lock" size={12} strokeWidth={2.4} aria-label="Locked" />
- )}
- <span className="note-row-name">{wordsOnly(note.title) || "New Note"}</span>
- </span>
- <span className="note-row-meta">
- <span className="note-row-when">{listDate(note.modifiedAt)}</span>
- <span className="note-row-snippet">
- {note.locked ? "Locked" : wordsOnly(note.snippet ?? "").slice(0, 80) || "No additional text"}
- </span>
- </span>
- </button>
- </div>
- ))}
- </div>
- </Fragment>
- ))}
- </div>
+ <NoteRows sections={sections} openGuid={openGuid} rowsRef={rowsRef} onPick={pickRow} />
{loaded && notes.length === 0 && !error && !(arriving && !searching) && (
searching ? (
@@ -1573,10 +1699,11 @@ export function NotesView() {
autoFocus={pickedBy.current === "pointer"}
onOpen={(note) => setUnlocked((all) => ({ ...all, [open.guid]: note }))}
/>
- ) : open && body === null ? (
+ ) : waiting ? (
/* Nothing to type into until the note's own text has arrived: an empty box over a
- note whose body had not loaded would write that emptiness back. */
- <EmptyState busy className="note-loading">Opening…</EmptyState>
+ note whose body had not loaded would write that emptiness back. Said only once it
+ is slow in coming. */
+ slow && <EmptyState busy className="note-loading">Opening…</EmptyState>
) : open ? (
<div className="note-editor is-readonly">
<h1 className="note-title">{splitTitle(body ?? "").title}</h1>
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index afd1ff5..1a2db87 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -36,7 +36,7 @@ import {
type UrgentRead,
} from "../lib/ipc";
import { Arriving } from "../components/EmptyState";
-import { useArriving, useRevision } from "../lib/sync";
+import { useArriving, useShownRevision } from "../lib/sync";
import { Picker } from "../components/Picker";
import { RowMenu } from "../components/RowMenu";
import { Glyph, emblemGlyph, type GlyphName } from "../components/Glyph";
@@ -395,7 +395,8 @@ export function RemindersView() {
const [error, setError] = useState<string | null>(null);
useErrorToast(error, () => setError(null));
const [confirm, confirmSheet] = useConfirm();
- const revision = useRevision("reminders");
+ // Held while another screen is in front, and read once on coming back (lib/sync).
+ const revision = useShownRevision("reminders");
const arriving = useArriving("reminders");
/** What each sidebar entry is holding. Apple puts a number on every one. */
const [counts, setCounts] = useState<ReminderCounts | null>(null);
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index e935434..ab223ef 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -22,7 +22,7 @@ import {
calendarFeedsApi,
SUBSCRIPTION_PREFIX } from "../../lib/ipc";
import { parseQuick } from "./quick";
-import { useRevision } from "../../lib/sync";
+import { useShownRevision } from "../../lib/sync";
import { useOutbox } from "../../lib/outbox";
import { Unsent, Waiting } from "../../components/Unsent";
import { Picker } from "../../components/Picker";
@@ -514,7 +514,8 @@ export function CalendarView() {
/** The last event deleted, with its alerts (read from Apple as it goes), held so the deletion
* can be taken back. */
const [undo, setUndo] = useState<(CalendarEvent & { alerts: Promise<number[]> }) | null>(null);
- const revision = useRevision("calendar", "reminders", "contacts");
+ // Held while another screen is in front, and read once on coming back (lib/sync).
+ const revision = useShownRevision("calendar", "reminders", "contacts");
// Changes kept here and not yet at Apple (the outbox): a saved event says so, and one Apple
// turned down is shown with what it held.
const outbox = useOutbox("calendar");
diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsx
index a69ddd2..4517ef5 100644
--- a/src/screens/notes/NoteEditor.tsx
+++ b/src/screens/notes/NoteEditor.tsx
@@ -103,7 +103,7 @@ function size(bytes: number | null): string {
*/
/** A note's picture asked to be shown large: the viewer (NotePicture) listens for it. */
export const PICTURE_EVENT = "quince:note-picture";
-export type PictureShown = { id: string; name: string; src: string; srcDark?: string; drawing?: boolean };
+export type PictureShown = { id: string; name: string; src: string; srcDark?: string; drawing?: boolean; whole?: string };
export function drawMedia(dom: HTMLElement, info: NoteAttachment) {
const name = info.filename ?? info.title ?? (info.kind === "audio" ? "Recording" : "Attachment");
@@ -163,7 +163,7 @@ export function drawMedia(dom: HTMLElement, info: NoteAttachment) {
c.addEventListener("click", open);
return c;
};
- const picture = (part: "file" | "preview" | "drawing" | "drawing-dark", cls: string) => {
+ const picture = (part: "file" | "inline" | "preview" | "drawing" | "drawing-dark", cls: string) => {
const img = document.createElement("img");
img.className = cls;
img.alt = name;
@@ -198,10 +198,15 @@ export function drawMedia(dom: HTMLElement, info: NoteAttachment) {
}
dom.title = `Open ${name}`;
if (info.kind === "image") {
- const img = picture("file", "nf-image");
- // Shown here at once, from the picture already drawn — never a wait on another app.
+ // Drawn in the note no larger than the note needs (a phone's photo is 12 to 48 megapixels,
+ // and a note of them decoded each whole while scrolling); the viewer shows it whole.
+ const img = picture("inline", "nf-image");
+ // Shown here at once, from the picture already drawn — never a wait on another app — and
+ // whole once that is ready (NotePicture).
img.addEventListener("click", () =>
- window.dispatchEvent(new CustomEvent<PictureShown>(PICTURE_EVENT, { detail: { id: info.id, name, src: img.src } })),
+ window.dispatchEvent(
+ new CustomEvent<PictureShown>(PICTURE_EVENT, { detail: { id: info.id, name, src: img.src, whole: noteMediaSrc(info.id, "file") } }),
+ ),
);
dom.className = "nf-attachment is-image";
dom.replaceChildren(img);
@@ -424,6 +429,10 @@ function attachmentView(node: PMNode) {
};
}
+/** How often, at most, a note being typed in is read back for saving (see `report`). The save
+ * itself waits for a pause in typing far longer than this. */
+const REPORT_MS = 150;
+
/** What the toolbar shows as on: the style of the line the cursor is in, and its marks. */
export type EditorStatus = {
style: number | null;
@@ -676,11 +685,22 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
const view = useRef<EditorView | null>(null);
const callbacks = useRef({ onChange, onStatus, onBlur });
callbacks.current = { onChange, onStatus, onBlur };
+ /** The toolbar's state as last told: told again only when something in it changed. Every
+ * move of the cursor told it anew, and the whole screen was drawn again for each. */
+ const told = useRef<EditorStatus | null>(null);
+ const tell = (state: EditorState) => {
+ const next = statusOf(state);
+ const was = told.current;
+ if (was && (Object.keys(next) as (keyof EditorStatus)[]).every((k) => was[k] === next[k])) return;
+ told.current = next;
+ callbacks.current.onStatus?.(next);
+ };
/**
* 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.
+ * the key is drawn rather than before, so a long note types as fast as a short one: at most
+ * once in REPORT_MS while keys keep coming, rather than once a key. Done at once whenever
+ * the note is left, so nothing typed can be missed.
*/
const later = useRef<number | null>(null);
const report = () => {
@@ -698,7 +718,7 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
later.current = window.setTimeout(() => {
later.current = null;
report();
- }, 0);
+ }, REPORT_MS);
};
useEffect(() => {
@@ -762,7 +782,7 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
// it was — text dragged and dropped where it lay, a mark set where it already is —
// is not, and must never become a save.
if (tr.docChanged && !next.doc.eq(before.doc)) reportSoon();
- callbacks.current.onStatus?.(statusOf(next));
+ tell(next);
},
// A paste never brings an attachment's reference: Apple keeps each table or picture in
// one place in one note, and a pasted copy referred to the same one twice, which made
@@ -875,7 +895,7 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
},
});
view.current = v;
- callbacks.current.onStatus?.(statusOf(v.state));
+ tell(v.state);
if (autoFocus) {
v.focus();
v.dispatch(v.state.tr.setSelection(TextSelection.atEnd(v.state.doc)));
@@ -957,7 +977,7 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
// 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));
+ tell(next);
},
focus: () => view.current?.focus(),
flushChange: () => {
diff --git a/src/screens/notes/NotePicture.tsx b/src/screens/notes/NotePicture.tsx
index 2a5ebd0..8732309 100644
--- a/src/screens/notes/NotePicture.tsx
+++ b/src/screens/notes/NotePicture.tsx
@@ -36,6 +36,24 @@ export function NotePicture() {
window.addEventListener("keydown", key, true);
return () => window.removeEventListener("keydown", key, true);
}, [shown]);
+ // The picture as the note drew it, at once; then the whole picture in its place once it is
+ // read and decoded — never a blank frame waiting for it.
+ const [whole, setWhole] = useState<string | null>(null);
+ useEffect(() => {
+ setWhole(null);
+ const src = shown?.whole;
+ if (!src) return undefined;
+ let live = true;
+ const img = new Image();
+ img.src = src;
+ img.decode().then(
+ () => live && setWhole(src),
+ () => {},
+ );
+ return () => {
+ live = false;
+ };
+ }, [shown]);
const sheetRef = useRef<HTMLElement | null>(null);
useModalFocus(sheetRef, shown !== null);
if (!shown) return null;
@@ -56,7 +74,7 @@ export function NotePicture() {
<img src={shown.srcDark} alt={shown.name} draggable={false} className="nf-drawing nf-ink-dark" />
</>
) : (
- <img src={shown.src} alt={shown.name} draggable={false} />
+ <img src={whole ?? shown.src} alt={shown.name} draggable={false} />
)}
<figcaption>
<span className="nf-picture-name">{problem ?? shown.name}</span>
diff --git a/src/screens/notes/model.ts b/src/screens/notes/model.ts
index 3ce5412..c070f62 100644
--- a/src/screens/notes/model.ts
+++ b/src/screens/notes/model.ts
@@ -109,6 +109,19 @@ 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;
}
diff --git a/src/styles/app.css b/src/styles/app.css
index 4667e15..4acd6f3 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -525,14 +525,12 @@
/* Room at the top for the button that opened it, which stays where it was. */
padding-top: 52px;
box-shadow: var(--glass-specular), 0 0 0 var(--hairline) var(--glass-edge), var(--shadow-sheet);
- transform: translateX(calc(-100% - 16px));
+ /* Out and back at once, as the scrim is: a full-height, shadowed layer sliding over the
+ content is the large-layer motion that flickered on his WebKitGTK (tokens.css). */
visibility: hidden;
- transition: transform var(--spring-quick-d) var(--spring-quick), visibility 0s linear var(--spring-quick-d);
}
.is-sidebar-open .sidebar {
- transform: none;
visibility: visible;
- transition: transform var(--spring-quick-d) var(--spring-quick), visibility 0s;
}
.sidebar-toggle {
position: absolute;