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
Live sync: what arrives appears in place, and nothing else moves
Yashwanth Kamireddi145df55ae7c7
diff --git a/.uiverify/arrival.mjs b/.uiverify/arrival.mjsnew file mode 100644index 0000000..af5033b--- /dev/null+++ b/.uiverify/arrival.mjs@@ -0,0 +1,132 @@+// What a sync landing does to the screen, frame by frame: the instruments the live-sync suites+// share (photos-arrival, notes-live-caret, sync-quiet). Installed before the app, armed just+// before a landing is played in, read once it has settled.+//+// Per frame it counts the items drawn again from nothing (same id, a new element), the new ones,+// the ones on screen whose picture is not showing, and how far each item that was on screen+// has moved; over the whole landing, the pictures fetched again, the elements given a part-way+// opacity (a fade), and every element added and taken away.++/** In the page: `window.__arrival.arm(cfg)`, then `window.__arrival.done` once it has watched. */+export function instrument() {+ const A = (window.__arrival = { armed: false, done: false });+ document.addEventListener("load", (e) => {+ if (A.armed && e.target instanceof HTMLImageElement) A.loads.push({ old: !!e.target.__seen, src: e.target.getAttribute("src") });+ }, true);+ const label = (n) => (n.nodeType !== 1 ? null : `${n.tagName.toLowerCase()}${typeof n.className === "string" && n.className.trim() ? "." + n.className.trim().split(/\s+/)[0] : ""}`);+ A.arm = (cfg) => {+ A.cfg = cfg;+ A.t0 = performance.now();+ A.armed = true;+ A.done = false;+ A.loads = [];+ A.srcChanges = 0;+ A.removed = {};+ A.added = {};+ A.faded = new Map();+ A.frames = [];+ const vh = window.innerHeight;+ const before = new Map();+ for (const el of document.querySelectorAll(cfg.items)) {+ el.__seen = 1;+ const id = el.getAttribute(cfg.idAttr);+ const r = el.getBoundingClientRect();+ if (id) before.set(id, { el, top: Math.round(r.top), left: Math.round(r.left), shown: r.bottom > 0 && r.top < vh && r.width > 0 });+ }+ for (const img of document.querySelectorAll("img")) img.__seen = 1;+ A.before = before;+ const opacityOf = (el) => {+ const o = el.style?.opacity;+ if (o !== "" && o !== undefined && +o > 0 && +o < 1) {+ const item = el.closest?.(cfg.items);+ const id = item?.getAttribute(cfg.idAttr) ?? label(el);+ A.faded.set(id, { item: !!item, fresh: !!item && !before.has(item.getAttribute(cfg.idAttr)) });+ }+ };+ A.mo = new MutationObserver((ms) => {+ for (const m of ms) {+ if (m.type === "childList") {+ for (const n of m.removedNodes) { const l = label(n); if (l) A.removed[l] = (A.removed[l] ?? 0) + 1; }+ for (const n of m.addedNodes) { const l = label(n); if (l) A.added[l] = (A.added[l] ?? 0) + 1; }+ } else if (m.attributeName === "src" && m.target.__seen) A.srcChanges++;+ else if (m.attributeName === "style") opacityOf(m.target);+ }+ });+ A.mo.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["src", "style"] });+ let n = 0;+ const frame = () => {+ const f = { t: Math.round(performance.now() - A.t0) };+ const items = [...document.querySelectorAll(cfg.items)];+ const shown = (el) => { const r = el.getBoundingClientRect(); return r.bottom > 0 && r.top < vh && r.width > 0; };+ let remade = 0, fresh = 0, blank = 0, moved = 0;+ const here = new Set();+ for (const el of items) {+ const id = el.getAttribute(cfg.idAttr);+ const was = before.get(id);+ if (!el.__seen) { if (was) remade++; else fresh++; }+ if (was && was.shown) {+ if (shown(el)) here.add(id);+ if (cfg.pictures) {+ const img = el.querySelector("img");+ if (!img || !img.complete || !img.naturalWidth || getComputedStyle(img).opacity === "0") blank++;+ }+ const r = el.getBoundingClientRect();+ moved = Math.max(moved, Math.abs(Math.round(r.top) - was.top), Math.abs(Math.round(r.left) - was.left));+ }+ }+ // An item that was on screen and is gone (a whole grid swapped for its placeholder).+ let lost = 0;+ for (const [id, was] of before) if (was.shown && !here.has(id)) lost++;+ Object.assign(f, { items: items.length, remade, fresh, blank, moved, lost });+ for (const el of document.querySelectorAll(cfg.items)) opacityOf(el), el.querySelectorAll("[style]").forEach(opacityOf);+ if (cfg.probe) Object.assign(f, (0, eval)(cfg.probe));+ A.frames.push(f);+ if (++n < (cfg.frames ?? 60)) requestAnimationFrame(frame);+ else { A.mo.disconnect(); A.armed = false; A.done = true; }+ };+ requestAnimationFrame(frame);+ };+ A.read = () => {+ const max = (k) => Math.max(0, ...A.frames.map((f) => (typeof f[k] === "number" ? f[k] : 0)));+ const faded = [...A.faded.entries()];+ return {+ remade: max("remade"), fresh: max("fresh"), blank: max("blank"), moved: max("moved"), lost: max("lost"),+ oldLoads: A.loads.filter((l) => l.old).length, loads: A.loads.length, srcChanges: A.srcChanges,+ fadedFresh: faded.filter(([, v]) => v.fresh).length, fadedOther: faded.filter(([, v]) => !v.fresh).map(([k]) => k),+ removed: A.removed, added: A.added, last: A.frames.at(-1), frames: A.frames,+ };+ };+}++export const status = (changed) => ({+ services: [{ service: "photos", label: "Photos", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) }],+ asOf: Math.floor(Date.now() / 1000), tookMs: 10, ...(changed === undefined ? {} : { changed }),+});++/** One landing, measured: `mutate` changes what the library holds, then the pass lands. */+export async function land(page, cfg, { mutate, changed, settle = 300 } = {}) {+ await page.mouse.move(2, 2);+ if (mutate) await page.evaluate(mutate);+ await page.evaluate(([cfg, payload]) => { window.__arrival.arm(cfg); window.__emit("quince://synced", payload); }, [cfg, status(changed)]);+ await page.waitForFunction(() => window.__arrival.done, null, { timeout: 20000 });+ await page.waitForTimeout(settle);+ return page.evaluate(() => window.__arrival.read());+}++/** Pictures served for the stub's `quince://` addresses (see stub's convertFileSrc), a few ms late as from disk. */+export const PICS = "http://pics.test";+export async function servePictures(ctx, { delay = 15 } = {}) {+ await ctx.addInitScript(([pics]) => { window.__picBase = pics; }, [PICS]);+ ctx.__pictureHits = [];+ await ctx.route(`${PICS}/**`, async (route) => {+ const path = decodeURIComponent(route.request().url().slice(PICS.length + 1));+ ctx.__pictureHits.push(path);+ const [, id = "x"] = /(?:pic|note|rimg)\/([^/~]+)/.exec(path) ?? [];+ let h = 0;+ for (const c of id) h = (h * 31 + c.charCodeAt(0)) >>> 0;+ const col = [h % 200 + 30, (h >> 8) % 200 + 30, (h >> 16) % 200 + 30];+ await new Promise((r) => setTimeout(r, delay));+ await route.fulfill({ contentType: "image/svg+xml", headers: { "cache-control": "max-age=3600" },+ body: `<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256"><rect width="256" height="256" fill="rgb(${col.join(",")})"/></svg>` });+ });+}diff --git a/.uiverify/list-arrival.mjs b/.uiverify/list-arrival.mjsnew file mode 100644index 0000000..ca36b96--- /dev/null+++ b/.uiverify/list-arrival.mjs@@ -0,0 +1,101 @@+// A reminder, a note or a card made on the phone lands in the list on screen and fades in,+// briefly and alone: no other row fades, moves above it or is made again. Never one made here,+// never a batch, never on opening or switching a list, never with reduced motion.+//+// URL=http://localhost:4173 node .uiverify/list-arrival.mjs (ENGINE=webkit for WebKit)+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+import { instrument, land } from "./arrival.mjs";++const URL = process.env.URL ?? process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const say = (r) => `faded ${r.fadedFresh} new + [${r.fadedOther.join(",")}], remade ${r.remade}, fresh ${r.fresh}`;+// What the person does sets nothing fading for a moment after (lib/arrival): wait it out.+const still = (page) => page.waitForTimeout(4300);++function extra() {+ const internals = window.__TAURI_INTERNALS__;+ const invoke = internals.invoke;+ internals.invoke = async (cmd, args) => {+ const answer = await invoke(cmd, args);+ if (cmd === "notes_in" && Array.isArray(answer)) return [...(window.__phoneNotes ?? []), ...answer];+ if (cmd === "contacts_list" && Array.isArray(answer)) return [...answer, ...(window.__phoneCards ?? [])];+ return answer;+ };+}+async function open(screen, fixture, reduced = false) {+ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 }, reducedMotion: reduced ? "reduce" : "no-preference" });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, ...fixture });+ await ctx.addInitScript(instrument);+ await ctx.addInitScript(extra);+ const page = await ctx.newPage();+ page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));+ await page.goto(URL, { waitUntil: "networkidle" });+ await openScreen(page, screen);+ await page.waitForTimeout(600);+ return { ctx, page };+}+const reminder = (guid, title) => ({ guid, listGuid: "l1", title, notes: null, dueAt: null, completedAt: null, priority: 0, flagged: false, parentGuid: null, etag: "x" });++// Reminders.+{+ const { ctx, page } = await open("Reminders", { remindersFixture: true });+ await page.evaluate(() => { window.__filterLists = true; });+ await page.locator(".rx-list, .source-row", { hasText: "Daily" }).first().click();+ await page.locator(".rx-row").first().waitFor();+ await still(page);+ const cfg = { items: ".rx-row", idAttr: "data-guid", frames: 30 };+ let r = await land(page, cfg, { changed: ["reminders"], mutate: `window.__extraReminders = [${JSON.stringify(reminder("rP1", "Added on the phone"))}]` });+ ok(r.fresh === 1 && r.fadedFresh === 1 && r.fadedOther.length === 0 && r.remade === 0, `Reminders: one added on the phone fades in alone (${say(r)})`);+ r = await land(page, cfg, { changed: ["reminders"], mutate: `window.__extraReminders = [...window.__extraReminders, ...Array.from({ length: 20 }, (_, i) => (${JSON.stringify(reminder("x", "From the phone"))}))].map((x, i) => (i ? { ...x, guid: "rB" + i, title: "From the phone " + i } : x))` });+ ok(r.fresh === 20 && r.fadedFresh === 0 && r.fadedOther.length === 0, `Reminders: twenty at once simply appear (${say(r)})`);+ // Its own: typed in here, it shows as it is made, never fading in.+ await page.locator(".rx-add input, form.rx-add input").first().click().catch(() => {});+ await page.keyboard.type("Made here");+ await page.evaluate((cfg) => window.__arrival.arm(cfg), { ...cfg, frames: 90 });+ await page.keyboard.press("Enter");+ await page.waitForFunction(() => window.__arrival.done, null, { timeout: 10000 });+ await page.evaluate(() => window.__emit("quince://synced", { services: [], asOf: 1, tookMs: 1, changed: ["reminders"] }));+ await page.waitForTimeout(600);+ r = await page.evaluate(() => window.__arrival.read());+ ok(r.fadedFresh === 0 && r.fadedOther.length === 0, `Reminders: one made here never fades in (${say(r)})`);+ // Another list: all its rows are new, none arrived.+ await still(page);+ await page.evaluate((cfg) => window.__arrival.arm(cfg), { ...cfg, frames: 40 });+ await page.evaluate(() => [...document.querySelectorAll(".rx-list, .source-row")].find((e) => /GYM/.test(e.textContent))?.click());+ await page.waitForFunction(() => window.__arrival.done, null, { timeout: 10000 });+ r = await page.evaluate(() => window.__arrival.read());+ ok(r.fresh > 0 && r.fadedFresh === 0 && r.fadedOther.length === 0, `Reminders: switching lists fades nothing (${say(r)})`);+ await ctx.close();+}++// Notes.+{+ const { ctx, page } = await open("Notes", { notesFixture: true });+ await page.locator(".note-row").first().waitFor();+ await still(page);+ const cfg = { items: ".note-row", idAttr: "data-guid", frames: 30 };+ const note = { guid: "nP1", folderGuid: "f1", title: "From my phone", snippet: "Written there", body: null, locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1700000000, etag: "p" };+ const r = await land(page, cfg, { changed: ["notes"], mutate: `window.__phoneNotes = [${JSON.stringify(note)}]` });+ ok(r.fresh === 1 && r.fadedFresh === 1 && r.fadedOther.length === 0, `Notes: a note written on the phone fades in alone (${say(r)})`);+ await ctx.close();+}++// Contacts, and reduced motion.+for (const reduced of [false, true]) {+ const { ctx, page } = await open("Contacts", { contactsFixture: true }, reduced);+ await page.locator(".contact-row").first().waitFor();+ await still(page);+ const cfg = { items: ".contact-row", idAttr: "data-guid", frames: 30 };+ const card = { guid: "cP1", firstName: "Aaron", lastName: "Phone", company: null, isCompany: false, birthday: null, notes: null, etag: null, methods: [] };+ const r = await land(page, cfg, { changed: ["contacts"], mutate: `window.__phoneCards = [${JSON.stringify(card)}]` });+ if (reduced) ok(r.fresh === 1 && r.fadedFresh === 0 && r.fadedOther.length === 0, `Contacts: with reduced motion a new card is there at once (${say(r)})`);+ else ok(r.fresh === 1 && r.fadedFresh === 1 && r.fadedOther.length === 0, `Contacts: a card made on the phone fades in alone (${say(r)})`);+ await ctx.close();+}++await b.close();+console.log(failures ? `${failures} failed` : "all passed");+process.exit(failures ? 1 : 0);diff --git a/.uiverify/notes-live-caret.mjs b/.uiverify/notes-live-caret.mjsnew file mode 100644index 0000000..6d42c2d--- /dev/null+++ b/.uiverify/notes-live-caret.mjs@@ -0,0 +1,126 @@+// A note open here, changed on the phone: the change lands in place. The caret stays on the+// character it was on (a line added above it no longer moves it to another line), the lines the+// phone did not touch keep their elements (a picture in them is not drawn again), and the view+// scrolled part way down a long note stays on the lines it showed.+//+// URL=http://localhost:4173 node .uiverify/notes-live-caret.mjs (ENGINE=webkit for WebKit)+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";++const URL = process.env.URL ?? process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++// One note whose text the test plays in as the phone changes it.+function live() {+ const internals = window.__TAURI_INTERNALS__;+ const invoke = internals.invoke;+ window.__live = { body: "Shopping\nLine two\nmilk", at: 1788600000 };+ internals.invoke = async (cmd, args) => {+ if (args?.guid === "nLIVE") {+ if (cmd === "note_body") return window.__live.body;+ if (cmd === "note_runs") return [];+ if (cmd === "note_row") return null;+ }+ const answer = await invoke(cmd, args);+ if (cmd === "notes_in" && Array.isArray(answer)) {+ const lines = window.__live.body.split("\n");+ return [{ guid: "nLIVE", folderGuid: "f1", title: lines[0], snippet: lines.slice(1, 3).join(" "), body: null,+ locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: window.__live.at, etag: String(window.__live.at) }, ...answer];+ }+ return answer;+ };+}++const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });+await ctx.addInitScript(live);+const page = await ctx.newPage();+page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));+await page.goto(URL, { waitUntil: "networkidle" });+await openScreen(page, "Notes");+await page.locator('.note-row[data-guid="nLIVE"]').click();+await page.locator(".note-editor .ProseMirror").waitFor();+await page.waitForTimeout(500);++let at = 1792600000;+/** The phone saves `body`; a sync lands with it. */+const phone = async (body) => {+ at += 10;+ await page.evaluate(([body, at]) => {+ window.__live = { body, at };+ window.__emit("quince://synced", { services: [], asOf: at, tookMs: 1, changed: ["notes"] });+ }, [body, at]);+ await page.waitForFunction((want) => {+ const ed = document.querySelector(".note-editor .ProseMirror");+ return ed && [...ed.children].map((c) => c.textContent).join("\n") === want;+ }, body, { timeout: 5000 }).catch(() => {});+ await page.waitForTimeout(150);+};+/** Where the caret is: the line it is in, and how far along it. */+const caret = () => page.evaluate(() => {+ const ed = document.querySelector(".note-editor .ProseMirror");+ const sel = getSelection();+ if (!sel.rangeCount || !ed.contains(sel.anchorNode)) return null;+ const line = [...ed.children].find((c) => c.contains(sel.anchorNode));+ const r = document.createRange();+ r.setStart(line, 0);+ r.setEnd(sel.anchorNode, sel.anchorOffset);+ return { line: line.textContent, at: r.toString().length };+});+const text = () => page.evaluate(() => [...document.querySelector(".note-editor .ProseMirror").children].map((c) => c.textContent).join("\n"));++// The caret after "Line two".+await page.evaluate(() => {+ const ed = document.querySelector(".note-editor .ProseMirror");+ const p = [...ed.children].find((c) => c.textContent === "Line two");+ const t = document.createTreeWalker(p, NodeFilter.SHOW_TEXT).nextNode();+ ed.focus();+ getSelection().collapse(t, t.data.length);+});+await page.waitForTimeout(150);+// Each line's element, marked, to tell one kept from one made again.+await page.evaluate(() => { [...document.querySelector(".note-editor .ProseMirror").children].forEach((c, i) => { c.__mark = i + 1; }); });++await phone("Shopping\nLine two\nmilk and eggs");+let c = await caret();+ok((await text()) === "Shopping\nLine two\nmilk and eggs", "words typed on the phone arrive in the open note");+ok(c?.line === "Line two" && c.at === 8, `…and the caret stays where it was (${JSON.stringify(c)})`);+const kept = await page.evaluate(() => [...document.querySelector(".note-editor .ProseMirror").children].slice(0, 2).every((c, i) => c.__mark === i + 1));+ok(kept, "the lines the phone did not touch keep their elements");++await phone("Shopping\nNew first item\nLine two\nmilk and eggs");+c = await caret();+ok((await text()) === "Shopping\nNew first item\nLine two\nmilk and eggs", "a line added on the phone above the caret arrives");+ok(c?.line === "Line two" && c.at === 8, `…and the caret stays on its own line, not the one now in its place (${JSON.stringify(c)})`);++await phone("Shopping list\nNew first item\nLine two\nmilk and eggs");+c = await caret();+ok(c?.line === "Line two" && c.at === 8, `words added on the phone earlier in the note leave the caret on its character (${JSON.stringify(c)})`);++await phone("Shopping list\nLine two\nmilk and eggs");+c = await caret();+ok(c?.line === "Line two" && c.at === 8, `a line taken out above the caret leaves it on its own (${JSON.stringify(c)})`);++// A long note, scrolled part way, the caret elsewhere: lines added at its top leave the view still.+const long = ["Long list", ...Array.from({ length: 120 }, (_, i) => `Item ${i + 1}`)].join("\n");+await phone(long);+await page.evaluate(() => document.activeElement?.blur());+const scroller = ".note-editor";+await page.evaluate((s) => { document.querySelector(s).scrollTop = 1200; }, scroller);+await page.waitForTimeout(200);+const where = () => page.evaluate((s) => {+ const sc = document.querySelector(s);+ const top = sc.getBoundingClientRect().top;+ const line = [...sc.querySelectorAll(".ProseMirror > *")].find((c) => c.getBoundingClientRect().top >= top);+ return { line: line?.textContent, top: Math.round(line?.getBoundingClientRect().top ?? 0) };+}, scroller);+const was = await where();+await phone(long.replace("Long list\n", "Long list\nAdded on the phone\nAnd another\n"));+const now = await where();+ok(now.line === was.line && Math.abs(now.top - was.top) <= 1, `lines added above the view leave it on the lines it showed (${JSON.stringify(was)} → ${JSON.stringify(now)})`);++await b.close();+console.log(failures ? `${failures} failed` : "all passed");+process.exit(failures ? 1 : 0);diff --git a/.uiverify/photos-arrival.mjs b/.uiverify/photos-arrival.mjsnew file mode 100644index 0000000..9bc8c9c--- /dev/null+++ b/.uiverify/photos-arrival.mjs@@ -0,0 +1,155 @@+// A photo taken on the phone arrives in the open library in place, and nothing else moves: the+// tiles already drawn keep their elements and their pictures (no grey flash, no grid swapped for+// its placeholder and back), a month that gains a photo draws it rather than losing its last+// row, a new month draws no other month again, and the view scrolled down stays on the same+// photos when photos land above it. Only the new tile fades in, briefly — not for a batch, not+// for the person's own upload, not with reduced motion, not on opening or switching views.+//+// URL=http://localhost:4173 node .uiverify/photos-arrival.mjs (ENGINE=webkit for WebKit)+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+import { instrument, land, servePictures } from "./arrival.mjs";++const URL = process.env.URL ?? process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++// Six hundred photos over ten months, newest first, twelve hours apart.+function library() {+ const P = (id, takenAt, extra = {}) => ({ id, master: `m${id}`, takenAt, addedAt: takenAt, kind: "image",+ width: 4032, height: 3024, duration: null, filename: `IMG_${id}.JPG`, size: 2400000, uti: "public.jpeg",+ favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null, ...extra });+ window.__photos = Array.from({ length: 600 }, (_, i) => P(`p${i + 1}`, 1792500000 - i * 43200));+ window.__mkPhoto = P;+ window.__arrive = (photos) => { window.__photos = [...photos, ...window.__photos].sort((a, b) => b.takenAt - a.takenAt); };+}+const cfg = { items: ".px-tile", idAttr: "data-id", pictures: true, frames: 50 };+const newest = 1792500000;++async function open({ reduced = false } = {}) {+ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 }, reducedMotion: reduced ? "reduce" : "no-preference" });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+ await ctx.addInitScript(instrument);+ await ctx.addInitScript(library);+ await servePictures(ctx);+ const page = await ctx.newPage();+ page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));+ await page.goto(URL, { waitUntil: "networkidle" });+ await openScreen(page, "Photos");+ await page.locator(".px-tile").first().waitFor();+ await page.waitForTimeout(1200);+ return { ctx, page };+}+const arrive = (photos) => `window.__arrive(${photos})`;+const one = (id, at, extra = "{}") => `[window.__mkPhoto(${JSON.stringify(id)}, ${at}, ${extra})]`;+const many = (n, from, tag = "pN") => `Array.from({ length: ${n} }, (_, i) => window.__mkPhoto("${tag}" + i, ${from} + (${n} - i) * 60))`;+const say = (r) => `remade ${r.remade}, blank ${r.blank}, lost ${r.lost}, moved ${r.moved}, fresh ${r.fresh}, faded ${r.fadedFresh}+[${r.fadedOther.join(",")}], old pictures loaded ${r.oldLoads}`;++{+ const { ctx, page } = await open();+ // F5: a tile's picture is addressed with its version, so the engine may keep it for good.+ const src = await page.locator(".px-tile img").first().getAttribute("src");+ ok(/pic%2Fp1~[0-9a-z]+%2Ffit|pic\/p1~[0-9a-z]+\/fit/.test(src ?? ""), `a tile's picture carries its version (${src?.slice(-40)})`);++ // Nothing new: nothing drawn again, nothing fetched again.+ const hits = ctx.__pictureHits.length;+ let r = await land(page, cfg, { changed: ["photos"] });+ ok(r.remade === 0 && r.blank === 0 && r.loads === 0 && Object.keys(r.removed).length === 0, `a landing with nothing new changes nothing (${say(r)}, removed ${JSON.stringify(r.removed)})`);+ ok(ctx.__pictureHits.length === hits, `…and asks for no picture (${ctx.__pictureHits.length - hits})`);++ // A heart given on the phone: the tile shows it, its picture is not fetched again.+ r = await land(page, cfg, { changed: ["photos"], mutate: `window.__photos = window.__photos.map((p) => p.id === "p2" ? { ...p, favorite: true, changeTag: "t2" } : p)` });+ ok((await page.locator('.px-tile[data-id="p2"] .px-heart').count()) === 1, "a heart given on the phone shows on its tile");+ ok(r.remade === 0 && r.srcChanges === 0 && r.oldLoads === 0 && r.fadedFresh === 0 && r.fadedOther.length === 0, `…which is not drawn again, fetched again or faded (${say(r)}, src changes ${r.srcChanges})`);++ // One new photo at the top of the newest month, the grid at the top.+ r = await land(page, cfg, { changed: ["photos"], mutate: arrive(one("pA", newest + 600)) });+ ok(r.remade === 0, `a photo arriving draws no other tile again (${say(r)})`);+ ok(r.blank === 0, `no tile already showing goes blank, not for a frame (${r.blank})`);+ ok(r.fresh === 1 && (await page.locator('.px-tile[data-id="pA"]').count()) === 1, "the new photo is in the grid");+ ok(r.fadedFresh === 1 && r.fadedOther.length === 0, `only the new tile fades in (${r.fadedFresh} new, others [${r.fadedOther.join(",")}])`);+ ok(r.oldLoads === 0, `no picture already shown is fetched again (${r.oldLoads})`);++ // A month that is built whole gains a photo in its middle: it draws all of its photos.+ const month = await page.evaluate(() => {+ const sec = document.querySelectorAll(".px-month")[1];+ const ids = [...sec.querySelectorAll(".px-tile")].map((t) => t.dataset.id);+ return { label: sec.getAttribute("aria-label"), ids };+ });+ const after = await page.evaluate((id) => window.__photos.find((p) => p.id === id).takenAt, month.ids[1]);+ // Frame by frame: the month's tiles, and whether any of it went back to its placeholder block.+ const inMonth = `(() => { const sec = document.querySelector('.px-month[aria-label="${month.label}"]'); return { monthTiles: sec ? sec.querySelectorAll(".px-tile").length : -1, monthLater: sec ? sec.querySelectorAll(".px-later").length : -1 }; })()`;+ r = await land(page, { ...cfg, probe: inMonth }, { changed: ["photos"], mutate: arrive(one("pB", after + 30)) });+ const fewest = Math.min(...r.frames.map((f) => f.monthTiles));+ const blocks = Math.max(...r.frames.map((f) => f.monthLater));+ ok(r.last.monthTiles === month.ids.length + 1 && blocks === 0 && fewest >= month.ids.length, `a whole month that gains a photo draws every one of them, in every frame (${r.last.monthTiles} of ${month.ids.length + 1}, fewest ${fewest}, ${blocks} placeholder blocks)`);+ ok(r.remade === 0 && r.blank === 0, `…drawing none of them again (${say(r)})`);++ // A photo from a month newer than any: a new month at the top, and no other month built again.+ r = await land(page, cfg, { changed: ["photos"], mutate: arrive(one("pC", newest + 40 * 86400)) });+ ok(r.remade === 0 && r.blank === 0, `a new month draws no other month again (${say(r)})`);+ ok(r.fresh === 1 && r.fadedFresh === 1 && r.fadedOther.length === 0, `…and its one photo fades in alone (${say(r)})`);++ // Thirty at once: they appear, none fades.+ r = await land(page, cfg, { changed: ["photos"], mutate: arrive(many(30, newest + 50 * 86400)) });+ ok(r.remade === 0 && r.blank === 0, `thirty arriving at once draw no other tile again (${say(r)})`);+ ok(r.fadedFresh === 0 && r.fadedOther.length === 0, `…and none of them fades in (${r.fadedFresh})`);++ // The person's own upload coming back: it simply appears.+ await page.evaluate(() => window.__emit("quince://photo-upload", { id: "u1", batch: "b1", name: "IMG_pOWN.JPG", within: "", sent: 1000, total: 1000, folder: false, error: null, state: "done" }));+ await page.waitForTimeout(200);+ r = await land(page, cfg, { changed: ["photos"], mutate: arrive(one("pOWN", newest + 60 * 86400)) });+ ok(r.fresh === 1 && r.fadedFresh === 0, `a photo uploaded from here appears without a fade (${say(r)})`);++ // Scrolled down: photos landing above leave the view on the same photos.+ await page.evaluate(() => { document.querySelector(".px-scroll").scrollTop = 2500; });+ await page.waitForTimeout(1200);+ r = await land(page, cfg, { changed: ["photos"], mutate: arrive(many(5, newest + 70 * 86400, "pU")) });+ ok(r.moved <= 1 && r.lost === 0, `photos landing above the view move nothing in it (moved ${r.moved}px, lost ${r.lost})`);+ ok(r.remade === 0 && r.blank === 0, `…and draw nothing in it again (${say(r)})`);+ // And another month built above: still in place.+ r = await land(page, cfg, { changed: ["photos"], mutate: arrive(one("pD", newest + 120 * 86400)) });+ ok(r.moved <= 1 && r.lost === 0 && r.remade === 0, `a new month above the view moves nothing in it (${say(r)})`);+ await ctx.close();+}++// Reduced motion: the photo is there at once.+{+ const { ctx, page } = await open({ reduced: true });+ const r = await land(page, cfg, { changed: ["photos"], mutate: arrive(one("pR", newest + 600)) });+ ok(r.fresh === 1 && r.fadedFresh === 0 && r.fadedOther.length === 0, `with reduced motion a new photo is there at once (${say(r)})`);+ await ctx.close();+}++// Opening Photos and switching views never fades a tile.+{+ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+ await ctx.addInitScript(library);+ await ctx.addInitScript(() => {+ window.__fades = 0;+ new MutationObserver((ms) => {+ for (const m of ms) {+ const o = m.target.style?.opacity;+ if (o && +o > 0 && +o < 1 && m.target.closest?.(".px-tile")) window.__fades++;+ }+ }).observe(document, { subtree: true, attributes: true, attributeFilter: ["style"] });+ });+ await servePictures(ctx);+ const page = await ctx.newPage();+ await page.goto(URL, { waitUntil: "networkidle" });+ await openScreen(page, "Photos");+ await page.locator(".px-tile").first().waitFor();+ await page.waitForTimeout(800);+ await page.locator(".source-row", { hasText: "Favorites" }).first().click().catch(() => {});+ await page.waitForTimeout(600);+ await page.locator(".source-row", { hasText: "Library" }).first().click().catch(() => {});+ await page.waitForTimeout(800);+ ok((await page.evaluate(() => window.__fades)) === 0, `opening Photos and switching views fades no tile (${await page.evaluate(() => window.__fades)})`);+ await ctx.close();+}++await b.close();+console.log(failures ? `${failures} failed` : "all passed");+process.exit(failures ? 1 : 0);diff --git a/.uiverify/sync-quiet.mjs b/.uiverify/sync-quiet.mjsnew file mode 100644index 0000000..58d9573--- /dev/null+++ b/.uiverify/sync-quiet.mjs@@ -0,0 +1,136 @@+// A sync that brought nothing new for a list draws none of its rows again, and one that changed+// a single row draws that row alone: each row read again unchanged keeps the object it had+// (lib/same), so the rows around it — memo'd by their row — stay as they were. Measured by the+// props each row was last drawn with: a row drawn again was handed new ones.+//+// URL=http://localhost:4173 node .uiverify/sync-quiet.mjs (ENGINE=webkit for WebKit)+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";++const URL = process.env.URL ?? process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++/** Each row's component, by its element: the nearest drawn-by-a-function fiber above it. */+const mark = (rows) => window.__rowProps = new Map([...document.querySelectorAll(rows)].map((el) => {+ const key = Object.keys(el).find((k) => k.startsWith("__reactFiber$"));+ let f = key ? el[key] : null;+ while (f && ![0, 14, 15].includes(f.tag)) f = f.return;+ return [el, f ? f.memoizedProps : null];+}));+/** How many of the rows marked were drawn again since, and how many are new. */+const drawn = (rows) => {+ let again = 0, fresh = 0;+ for (const el of document.querySelectorAll(rows)) {+ const key = Object.keys(el).find((k) => k.startsWith("__reactFiber$"));+ let f = key ? el[key] : null;+ while (f && ![0, 14, 15].includes(f.tag)) f = f.return;+ if (!window.__rowProps.has(el)) fresh++;+ else if (window.__rowProps.get(el) !== f?.memoizedProps) {+ again++;+ const was = window.__rowProps.get(el) ?? {};+ (window.__why ??= new Set());+ for (const k of Object.keys(f.memoizedProps)) if (was[k] !== f.memoizedProps[k]) window.__why.add(k);+ }+ }+ return { again, fresh, rows: document.querySelectorAll(rows).length };+};+const landing = async (page, changed, mutate) => {+ if (mutate) await page.evaluate(mutate);+ await page.evaluate((c) => window.__emit("quince://synced", { services: [], asOf: Math.floor(Date.now() / 1000), tookMs: 1, changed: c }), changed);+ await page.waitForTimeout(500);+};++async function screen(name, fixture, setup) {+ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, ...fixture });+ if (setup) await ctx.addInitScript(setup);+ const page = await ctx.newPage();+ page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));+ await page.goto(URL, { waitUntil: "networkidle" });+ await openScreen(page, name);+ await page.waitForTimeout(800);+ return { ctx, page };+}++// Reminders: the fixture's list, read through a hook that lets the test change one row.+{+ const { ctx, page } = await screen("Reminders", { remindersFixture: true }, () => {+ const internals = window.__TAURI_INTERNALS__;+ const invoke = internals.invoke;+ internals.invoke = async (cmd, args) => {+ const answer = await invoke(cmd, args);+ if (Array.isArray(answer) && /^reminders_(in|smart|search)$/.test(cmd) && window.__retitle)+ return answer.map((r, i) => (i === 0 ? { ...r, title: window.__retitle } : r));+ return answer;+ };+ });+ const rows = ".rx-row";+ await page.locator(rows).first().waitFor();+ await page.evaluate(mark, rows);+ await landing(page, ["reminders"]);+ let d = await page.evaluate(drawn, rows);+ ok(d.again === 0, `Reminders: a sync with nothing new draws no row again (${d.again} of ${d.rows})`);+ await page.evaluate(mark, rows);+ await landing(page, ["reminders"], "window.__retitle = 'Renamed on the phone'");+ d = await page.evaluate(drawn, rows);+ const titles = await page.evaluate(() => [...document.querySelectorAll(".rx-row")].map((r) => r.querySelector("input.rx-title")?.value ?? r.textContent));+ ok(titles.filter((t) => t.includes("Renamed on the phone")).length === 1, `Reminders: the reminder renamed on the phone shows its new name (${JSON.stringify(titles)})`);+ ok(d.again <= 1, `Reminders: …and only its row is drawn again (${d.again} of ${d.rows}; ${await page.evaluate(() => [...(window.__why ?? [])].join(","))})`);+ await ctx.close();+}++// Contacts.+{+ const { ctx, page } = await screen("Contacts", { contactsFixture: true }, () => {+ const internals = window.__TAURI_INTERNALS__;+ const invoke = internals.invoke;+ internals.invoke = async (cmd, args) => {+ const answer = await invoke(cmd, args);+ if (cmd === "contacts_list" && Array.isArray(answer) && window.__recompany)+ return answer.map((c, i) => (i === 1 ? { ...c, company: window.__recompany } : c));+ return answer;+ };+ });+ const rows = ".contact-row";+ await page.locator(rows).first().waitFor();+ await page.evaluate(mark, rows);+ await landing(page, ["contacts"]);+ let d = await page.evaluate(drawn, rows);+ ok(d.again === 0, `Contacts: a sync with nothing new draws no row again (${d.again} of ${d.rows})`);+ await page.evaluate(mark, rows);+ await landing(page, ["contacts"], "window.__recompany = 'Changed on the phone'");+ d = await page.evaluate(drawn, rows);+ ok(d.again <= 1, `Contacts: one card changed on the phone draws its row alone (${d.again} of ${d.rows})`);+ await ctx.close();+}++// Notes: the folder's list.+{+ const { ctx, page } = await screen("Notes", { notesFixture: true }, () => {+ const internals = window.__TAURI_INTERNALS__;+ const invoke = internals.invoke;+ internals.invoke = async (cmd, args) => {+ const answer = await invoke(cmd, args);+ if (cmd === "notes_in" && Array.isArray(answer) && window.__resnip)+ return answer.map((n) => (n.guid === "n3" ? { ...n, snippet: window.__resnip } : n));+ return answer;+ };+ });+ const rows = ".note-row";+ await page.locator(rows).first().waitFor();+ await page.evaluate(mark, rows);+ await landing(page, ["notes"]);+ let d = await page.evaluate(drawn, rows);+ ok(d.again === 0, `Notes: a sync with nothing new draws no row again (${d.again} of ${d.rows})`);+ await page.evaluate(mark, rows);+ await landing(page, ["notes"], "window.__resnip = 'Typed on the phone'");+ d = await page.evaluate(drawn, rows);+ ok((await page.locator(rows, { hasText: "Typed on the phone" }).count()) === 1, "Notes: the note changed on the phone shows its new words");+ await ctx.close();+}++await b.close();+console.log(failures ? `${failures} failed` : "all passed");+process.exit(failures ? 1 : 0);diff --git a/src-tauri/src/alerts.rs b/src-tauri/src/alerts.rsindex 9bd56d2..fcad2c3 100644--- a/src-tauri/src/alerts.rs+++ b/src-tauri/src/alerts.rs@@ -64,8 +64,8 @@ fn answer(app: &AppHandle, due: &DueAlarm, due_then: Option<Option<i64>>, action{quiet!("an alert's reminder could not be completed: {e}");}- // Every open screen looks again, as after any pass.- let report = crate::refresh::status(&data.0).await;+ // Reminders looks again; no other screen has anything new.+ let report = crate::refresh::status_changed(&data.0, &["reminders"]).await;app.emit(crate::SYNCED, &report).ok();});}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex a92cc6d..6e9a1d6 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -2227,8 +2227,12 @@ fn spawn_holidays(app: tauri::AppHandle) {std::fs::write(&path, &text).ok();*app.state::<Occasions>().feed.lock().await =quince_icloud::occasions::parse_feed(&text);- app.emit(SYNCED, refresh::status(&app.state::<Data>().0).await)- .ok();+ // Holidays are the calendar's; no other screen reads them.+ app.emit(+ SYNCED,+ refresh::status_changed(&app.state::<Data>().0, &["calendar"]).await,+ )+ .ok();}}}@@ -2361,8 +2365,12 @@ fn spawn_subscriptions(app: tauri::AppHandle) {}).collect();}- app.emit(SYNCED, refresh::status(&app.state::<Data>().0).await)- .ok();+ // The subscribed calendars are the calendar's alone to read again.+ app.emit(+ SYNCED,+ refresh::status_changed(&app.state::<Data>().0, &["calendar"]).await,+ )+ .ok();loop {let due: Vec<Subscription> = app.state::<Feeds>()@@ -2414,8 +2422,11 @@ async fn refresh_subscription(app: &tauri::AppHandle, id: &str) -> UiResult<Subs};save_subscriptions(app, &subs)?;drop(subs);- app.emit(SYNCED, refresh::status(&app.state::<Data>().0).await)- .ok();+ app.emit(+ SYNCED,+ refresh::status_changed(&app.state::<Data>().0, &["calendar"]).await,+ )+ .ok();outcome}@@ -6102,12 +6113,12 @@ fn main() {return;}// A photo's picture made the size it is shown at.- if let Some((id, long)) = fit {+ if let Some((id, long, marked)) = fit {let response = match photos::fitted(&app, &id, long).await {Ok(bytes) => tauri::http::Response::builder().status(200).header("Content-Type", image_type(&bytes))- .header("Cache-Control", "private, max-age=86400")+ .header("Cache-Control", photos::fit_cache(marked)).body(bytes),Err(_) => tauri::http::Response::builder().status(404)diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rsindex 2d92083..4ba73a7 100644--- a/src-tauri/src/photos.rs+++ b/src-tauri/src/photos.rs@@ -177,11 +177,26 @@ pub fn requested(path: &str) -> Option<(String, Size)> {pub const FITS: [u32; 11] = [128, 256, 384, 512, 768, 1024, 1536, 2048, 2560, 3072, 3840];/// A `quince://` request for a picture made the size it is shown at: `pic/<asset id>/fit<N>`,-/// N one of [`FITS`].-pub fn requested_fit(path: &str) -> Option<(String, u32)> {+/// N one of [`FITS`] — or `pic/<asset id>~<mark>/fit<N>`, the mark saying what the picture is+/// made from (the window's `pictureVersion`, of the photo's original). Whether it was marked+/// comes back too: a marked address is the same pixels for good, so it may be kept for good.+pub fn requested_fit(path: &str) -> Option<(String, u32, bool)> {let path = crate::percent_decode(path.trim_start_matches('/'));let (id, size) = path.strip_prefix("pic/")?.rsplit_once('/')?;let long: u32 = size.strip_prefix("fit")?.parse().ok()?;+ let (id, marked) = match id.split_once('~') {+ Some((id, mark))+ if !mark.is_empty()+ && mark.len() <= 16+ && mark+ .chars()+ .all(|c| c.is_ascii_digit() || c.is_ascii_lowercase()) =>+ {+ (id, true)+ }+ Some(_) => return None,+ None => (id, false),+ };if !FITS.contains(&long)|| id.is_empty()|| !id@@ -190,7 +205,17 @@ pub fn requested_fit(path: &str) -> Option<(String, u32)> {{return None;}- Some((id.to_string(), long))+ Some((id.to_string(), long, marked))+}++/// How long the engine may keep a fitted picture: for good when its address is marked with+/// what it is made from (it cannot change without the address changing), a day when not.+pub fn fit_cache(marked: bool) -> &'static str {+ if marked {+ "private, max-age=31536000, immutable"+ } else {+ "private, max-age=86400"+ }}/// Pictures being made at once: one per core, so a grid filling in never starves the window.@@ -2761,8 +2786,12 @@ async fn refresh_photos(app: &AppHandle) {let auth = app.state::<Auth>();let data = app.state::<Data>();crate::refresh::some(&auth.client, &data.0, &["photos"]).await;- app.emit(crate::SYNCED, crate::refresh::status(&data.0).await)- .ok();+ // What it stored was told as it landed (refresh::on_landed); this brings the freshness.+ app.emit(+ crate::SYNCED,+ crate::refresh::status_changed(&data.0, &[]).await,+ )+ .ok();}#[cfg(test)]@@ -2904,9 +2933,12 @@ mod tests {fn a_fitted_picture_is_asked_for_by_its_step_only() {assert_eq!(requested_fit("/pic/A1-b/fit1024"),- Some(("A1-b".into(), 1024))+ Some(("A1-b".into(), 1024, false))+ );+ assert_eq!(+ requested_fit("pic%2FA1%2Ffit256"),+ Some(("A1".into(), 256, false)));- assert_eq!(requested_fit("pic%2FA1%2Ffit256"), Some(("A1".into(), 256)));// Not a step (the cache would grow without end), not a picture, not a path.assert_eq!(requested_fit("/pic/A1/fit1000"), None);assert_eq!(requested_fit("/pic/A1/full"), None);@@ -2914,6 +2946,29 @@ mod tests {assert_eq!(requested_fit("/pic/A1/fitx"), None);}+ /// A picture's address marked with what it is made from is the same photo's picture, and+ /// may be kept for good; the unmarked one still works, kept for a day as before. A mark is+ /// a few letters and digits, never a way out of the cache.+ #[test]+ fn a_marked_picture_is_the_same_photo_kept_for_good() {+ assert_eq!(+ requested_fit("pic%2FA1-b~1x9z%2Ffit256"),+ Some(("A1-b".into(), 256, true))+ );+ assert_eq!(+ requested_fit("/pic/A1~k3/fit1024"),+ Some(("A1".into(), 1024, true))+ );+ assert_eq!(requested_fit("/pic/A1~/fit256"), None);+ assert_eq!(requested_fit("/pic/A1~X/fit256"), None);+ assert_eq!(requested_fit("/pic/A1~a~b/fit256"), None);+ assert_eq!(requested_fit("/pic/~ab/fit256"), None);+ assert_eq!(requested_fit("/pic/..~ab/fit256"), None);+ assert_eq!(requested_fit("/pic/A1~0123456789abcdefg/fit256"), None);+ assert!(fit_cache(true).contains("immutable"));+ assert!(!fit_cache(false).contains("immutable"));+ }+#[test]fn quicktime_or_mpeg4() {assert_eq!(video_type(b"\0\0\0\x14ftypqt "), "video/quicktime");diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rsindex 37f0746..cc4e9db 100644--- a/src-tauri/src/refresh.rs+++ b/src-tauri/src/refresh.rs@@ -603,6 +603,17 @@ async fn run(client: &Arc<Mutex<Client>>, data: &LibraryLock, services: &[&str])}}+/// [`status`], saying whose rows changed: only those apps' screens read their lists again, and+/// with none named, none does — the freshness alone is new. Sent without it, every open screen+/// read its whole list again (Photos its whole index) for a calendar feed fetched, a+/// subscription loaded or a pass already told as it landed.+pub async fn status_changed(data: &LibraryLock, changed: &[&'static str]) -> Refresh {+ Refresh {+ changed: Some(changed.to_vec()),+ ..status(data).await+ }+}+/// What the library already knows, without asking Apple anything.////// The window renders from this the instant it opens, so freshness is on screen before the@@ -763,6 +774,24 @@ wheremod tests {use super::*;+ /// A freshness sent with the services it changed names exactly those, and one that+ /// changed nothing names none — never "unknown", which has every screen read again.+ #[tokio::test]+ async fn a_status_sent_names_whose_rows_changed() {+ let data = LibraryLock::new(quince_core::Library::in_memory().unwrap(), None);+ let told = status_changed(&data, &["calendar"]).await;+ assert_eq!(told.changed, Some(vec!["calendar"]));+ let json = serde_json::to_value(&told).unwrap();+ assert_eq!(json["changed"], serde_json::json!(["calendar"]));+ let quiet = status_changed(&data, &[]).await;+ assert_eq!(quiet.changed, Some(Vec::new()));+ assert_eq!(+ serde_json::to_value(&quiet).unwrap()["changed"],+ serde_json::json!([])+ );+ assert_eq!(quiet.services.len(), status(&data).await.services.len());+ }+#[test]fn the_default_window_reaches_back_a_month_and_forward_a_quarter() {let (from, to, _zone) = default_window();diff --git a/src/lib/arrival.ts b/src/lib/arrival.tsnew file mode 100644index 0000000..81df4cb--- /dev/null+++ b/src/lib/arrival.ts@@ -0,0 +1,60 @@+import { useLayoutEffect, useRef, type RefObject } from "react";+import { fadeIn } from "./fade";++/**+ * Rows a sync brought into the list on screen — a reminder added on the phone, a note, a card —+ * fade in, each alone and briefly (lib/fade: the page paints it, nothing is handed to the+ * compositor), and nothing else on screen moves for them.+ *+ * Only something that came from elsewhere: never the person's own. A row they made shows as+ * it is made (its stand-in, then the real one in its place), so nothing fades for a moment+ * after their last key or click, nor while anything of theirs is still on its way to Apple.+ * Never on opening a list or going to another one (its rows are all new, none arrived), never+ * for a batch — more than a few at once simply appear — and never with reduced motion.+ */+export const ARRIVALS = 12;+/** How long after the person's own key or click nothing fades: their own rows land meanwhile. */+const OWN_MS = 4000;+const FADE_MS = 120;++let lastInput = -Infinity;+let watching = false;+function watchInput() {+ if (watching || typeof window === "undefined") return;+ watching = true;+ const seen = () => {+ lastInput = performance.now();+ };+ // Captured, so a control that stops its key or click still counts.+ window.addEventListener("pointerdown", seen, true);+ window.addEventListener("keydown", seen, true);+ window.addEventListener("drop", seen, true);+}++/**+ * Watch `ids` (the rows drawn, in `box`, each with `attr` its id) within one `scope` (the list+ * and how it is shown): rows new to a list already drawn fade in. `busy` is true while the+ * person's own changes are on their way (the outbox), and for a moment after.+ */+export function useArrivals(box: RefObject<HTMLElement | null>, ids: readonly string[], scope: string, busy = false, attr = "data-guid") {+ watchInput();+ const last = useRef<{ scope: string; ids: Set<string> } | null>(null);+ const busyUntil = useRef(-Infinity);+ if (busy) busyUntil.current = Infinity;+ else if (busyUntil.current === Infinity) busyUntil.current = performance.now() + OWN_MS;+ useLayoutEffect(() => {+ const was = last.current;+ last.current = { scope, ids: new Set(ids) };+ const now = performance.now();+ // The list's first rows, another list, or the person at work: nothing has arrived.+ if (!was || was.scope !== scope || was.ids.size === 0 || now - lastInput < OWN_MS || now < busyUntil.current) return;+ const added = ids.filter((id) => !was.ids.has(id));+ if (added.length === 0 || added.length > ARRIVALS) return;+ const el = box.current;+ if (!el) return;+ for (const id of added) {+ const esc = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(id) : id;+ fadeIn(el.querySelector<HTMLElement>(`[${attr}="${esc}"]`), { duration: FADE_MS });+ }+ }, [ids, scope]); // eslint-disable-line react-hooks/exhaustive-deps+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 944dc27..dcf00e6 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -759,9 +759,22 @@ export const FITS = [128, 256, 384, 512, 768, 1024, 1536, 2048, 2560, 3072, 3840* resampled with care by the app. The engine then draws it at its own size: shrunk by* WebKitGTK instead, a large picture came out jagged.*/-export function fitSrc(id: string, long: number): string {+export function fitSrc(photo: string | Pick<Photo, "id" | "master">, long: number): string {const step = FITS.find((f) => f >= long) ?? FITS[FITS.length - 1];- return convertFileSrc(`pic/${id}/fit${step}`, "quince");+ if (typeof photo === "string") return convertFileSrc(`pic/${photo}/fit${step}`, "quince");+ return convertFileSrc(`pic/${photo.id}~${pictureVersion(photo.master)}/fit${step}`, "quince");+}++/**+ * What a photo's pictures are made from, as a short mark in their address: its original (the+ * master — every picture here is made from it, see photos.rs). Two addresses alike are the same+ * pixels, so the engine keeps the picture for good (the scheme says so for a marked address)+ * and never asks for it again; a photo whose original changed has a new address and is fetched.+ */+export function pictureVersion(master: string): string {+ let h = 0x811c9dc5;+ for (let i = 0; i < master.length; i++) h = Math.imul(h ^ master.charCodeAt(i), 0x01000193) >>> 0;+ return h.toString(36);}/** A shared album (Apple's sharedstreams service). */diff --git a/src/lib/same.ts b/src/lib/same.tsnew file mode 100644index 0000000..dcdf188--- /dev/null+++ b/src/lib/same.ts@@ -0,0 +1,44 @@+/**+ * A list read again, drawn only where it changed.+ *+ * Every read of the library answers with new objects, the same rows as before included, and a+ * row drawn from a new object draws again: a sync that brought one reminder had every row of+ * the list drawn again, and one that brought nothing had the whole screen drawn again for it.+ * Here each row equal to the one it had keeps the object it had, so the rows around a change+ * (memo'd by their row) stay as they are — and a list equal throughout is the list it was, so+ * nothing is drawn at all.+ */+export function keepSame<T>(was: readonly T[] | null | undefined, next: T[], keyOf: (row: T) => string): T[] {+ if (!was || was.length === 0) return next;+ const before = new Map<string, T>();+ for (const row of was) before.set(keyOf(row), row);+ let changed = was.length !== next.length;+ const out = next.map((row, i) => {+ const had = before.get(keyOf(row));+ if (had !== undefined && same(had, row)) {+ if (was[i] !== had) changed = true;+ return had;+ }+ changed = true;+ return row;+ });+ return changed ? out : (was as T[]);+}++/** Whether two values read from the library are the same throughout. */+export function same(a: unknown, b: unknown): boolean {+ if (a === b) return true;+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;+ if (Array.isArray(a)) {+ if (!Array.isArray(b) || a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) if (!same(a[i], b[i])) return false;+ return true;+ }+ if (Array.isArray(b)) return false;+ const x = a as Record<string, unknown>;+ const y = b as Record<string, unknown>;+ const keys = Object.keys(x);+ if (keys.length !== Object.keys(y).length) return false;+ for (const k of keys) if (!(k in y) || !same(x[k], y[k])) return false;+ return true;+}diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsxindex eafed3a..21f9ec0 100644--- a/src/screens/ContactsView.tsx+++ b/src/screens/ContactsView.tsx@@ -34,6 +34,8 @@ import { REFUSED_LINK, outsideHref } from "../lib/links";import { DateField, dateWords } from "./contacts/DateField";import { PhotoSheet } from "./contacts/PhotoSheet";import { DuplicatesBanner, DuplicatesView } from "./contacts/Duplicates";+import { keepSame } from "../lib/same";+import { useArrivals } from "../lib/arrival";/** The sidebar row that is every contact rather than a list. */const ALL = "";@@ -295,7 +297,8 @@ export function ContactsView() {const mine = ++reads.current;const found = await api.contactsList(query.trim() || null);if (mine !== reads.current) return;- setContacts(Array.isArray(found) ? found : []);+ // Each card unchanged keeps its row as it was (lib/same).+ setContacts((was) => keepSame(was, Array.isArray(found) ? found : [], (c) => c.guid));setLoaded(true);}, []);@@ -721,6 +724,9 @@ export function ContactsView() {return { contact: c, letter, starts: i === 0 || letterOf(all[i - 1]) !== letter };}), [sorted]);const rowsRef = useRef<HTMLUListElement | null>(null);+ // A card made on the phone, landing in the list on screen, fades in (lib/arrival).+ const contactIds = useMemo(() => contacts.map((c) => c.guid), [contacts]);+ useArrivals(rowsRef, contactIds, `${list}\u0000${search.trim()}`, outbox.waiting.size > 0);const [listFocused, setListFocused] = useState(false);const searchRef = useRef<HTMLInputElement | null>(null);/** The row for a person brought into view and given focus, as the arrows and the index do. */diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsxindex 1f58c47..9694832 100644--- a/src/screens/DriveView.tsx+++ b/src/screens/DriveView.tsx@@ -31,6 +31,7 @@ import { RowMenu } from "../components/RowMenu";import { dateText, timeText } from "../lib/when";import { Clock } from "lucide-react";import { useReveal } from "../lib/reveal";+import { keepSame } from "../lib/same";/** iCloud Drive's own four orders, as its "by Name" menu offers them. */const SORTS = [@@ -670,7 +671,8 @@ export function DriveView() {// rows, their selection and their pictures exactly as they were.const next = Array.isArray(fresh) ? fresh : [];const same = sameItems(itemsRef.current, next);- setItems((was) => (sameItems(was, next) ? was : next));+ // And then only the rows that changed: the others keep their objects (lib/same).+ setItems((was) => (sameItems(was, next) ? was : keepSame(was, next, (i) => i.drivewsid)));// Pictures only when something in the folder changed (or they never came): a check that// found nothing new already has every picture it had, and asking again every ten seconds// redrew every row with them.diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 58eb4d1..fd8160a 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -29,6 +29,8 @@ import { Arriving } from "../components/EmptyState";import { useArriving, useRevision, useShownRevision } from "../lib/sync";import { Picker } from "../components/Picker";import { holdTyping } from "../lib/updates";+import { keepSame } from "../lib/same";+import { useArrivals } from "../lib/arrival";const ALL = "__all__";@@ -265,7 +267,8 @@ export function NotesView() {]);if (mine !== reads.current) return;setFolders(Array.isArray(found) ? found : []);- setNotes(over(Array.isArray(list) ? list : []));+ // Each note unchanged keeps its row as it was (lib/same).+ setNotes((was) => keepSame(was, over(Array.isArray(list) ? list : []), (n) => n.guid));setLoaded(true);}, [folder, query, searching, scoped, over]);@@ -657,6 +660,10 @@ export function NotesView() {folderGuid: string | null;body: string;} | null>(null);+ // A note written on the phone, landing in the list on screen, fades in (lib/arrival) — not+ // one written here, which is being composed until it lands.+ const noteIds = useMemo(() => notes.map((n) => n.guid), [notes]);+ useArrivals(rowsRef, noteIds, `${folder}\u0000${searching ? query : ""}\u0000${scoped}\u0000${listOrder.by}`, outbox.waiting.size > 0 || composing !== null);const setComposing = useCallback((next:diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsxindex 88fd7e2..e422a33 100644--- a/src/screens/PhotosView.tsx+++ b/src/screens/PhotosView.tsx@@ -44,6 +44,7 @@ import { AdjustDate } from "./photos/AdjustDate";import { useReveal } from "../lib/reveal";import { Picker } from "../components/Picker";import { PAGE, PhotoList, PhotoStore } from "./photos/list";+import { same } from "../lib/same";/** The sidebar, in Photos' order, each with the symbol Photos gives it. */const VIEWS: { key: PhotoView; label: string; Icon: LucideIcon }[] = [@@ -183,7 +184,7 @@ function Filmstrip({ photos, at, onPick }: { photos: PhotoList; at: number; onPi{/* At once, never lazily: a slip coming into the strip showed empty for a moment. */}{/* One size for every slip, shown or not, so a step never asks for a new picture; decodedbefore it is drawn (they are small), so none appears blank first. */}- <img src={fitSrc(p.id, SHOWN * 2 * (window.devicePixelRatio || 1))} alt="" decoding="async" draggable={false} />+ <img src={fitSrc(p, SHOWN * 2 * (window.devicePixelRatio || 1))} alt="" decoding="async" draggable={false} /></button>,);}@@ -214,6 +215,43 @@ function Filmstrip({ photos, at, onPick }: { photos: PhotoList; at: number; onPi* full quality at once, never a smaller copy first.*/const decoded = new Set<string>();+/**+ * Photos a sync has just brought into the view on screen, with when: each one's tile fades its+ * picture in as it lands (see Tile), and nothing else moves. Only for a moment — a month built+ * later, as the grid is scrolled to it, draws its photos as it always does.+ */+const arrived = new Map<string, number>();+/** More than this many at once is a batch (an import, a first sync): they simply appear. */+const ARRIVALS = 12;+/** How long an arrival is one: its tile is made within a frame or two of it being drawn. */+const ARRIVAL_MS = 1500;+/** Whether a tile being made now is for a photo that has just arrived. */+function justArrived(id: string): boolean {+ const at = arrived.get(id);+ return at !== undefined && performance.now() - at < ARRIVAL_MS;+}++/**+ * The tile at the top of the view and where it stands, for keeping it there while photos land+ * above it (see PhotosView). The grid's tiles are in the page in the order they are drawn, so+ * the first one reaching below the header is found in a few steps, not by measuring them all.+ */+function anchorOf(el: HTMLElement | null): { id: string; top: number } | null {+ if (!el || el.scrollTop <= 0 || !el.clientHeight) return null;+ const tiles = el.querySelectorAll<HTMLElement>(".px-tile");+ if (!tiles.length) return null;+ const edge = el.getBoundingClientRect().top + (parseFloat(getComputedStyle(el).paddingTop) || 0);+ let [lo, hi] = [0, tiles.length - 1];+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (tiles[mid].getBoundingClientRect().bottom > edge) hi = mid;+ else lo = mid + 1;+ }+ const tile = tiles[lo];+ const id = tile.dataset.id;+ return id ? { id, top: tile.getBoundingClientRect().top } : null;+}+/** The rest on a tile before its picture is fetched (see Tile). */let resting: number | undefined;const warming = new Map<string, Promise<boolean>>();@@ -224,7 +262,7 @@ function viewSrc(p: Photo): string {const box = stageBox.w ? stageBox : { w: Math.max(320, window.innerWidth - 400), h: Math.max(240, window.innerHeight - 140) };const r = p.width && p.height ? p.width / p.height : 4 / 3;const w = Math.min(box.w, box.h * r, (p.width || 4000) * 1.5);- return fitSrc(p.id, Math.max(w, w / r) * (window.devicePixelRatio || 1));+ return fitSrc(p, Math.max(w, w / r) * (window.devicePixelRatio || 1));}/*** A small picture of a photo the window has already got and decoded — the grid's tile or the@@ -267,7 +305,7 @@ function warm(p: Photo): Promise<boolean> {* as a square (so its longer side reaches past the cell). */function tileSrc(p: Photo, cell: number, fit: boolean): string {const r = p.width && p.height ? Math.max(p.width, p.height) / Math.min(p.width, p.height) : 1;- return fitSrc(p.id, fit ? cell : cell * r);+ return fitSrc(p, fit ? cell : cell * r);}/** What a tile can ask of the screen; one object, kept the same, so tiles need not redraw. */@@ -306,6 +344,9 @@ const Tile = memo(function Tile({act: Acts;}) {const born = useRef(performance.now());+ // Just arrived from the phone: its picture fades in once, briefly — the one thing that moves.+ const arriving = useRef<boolean | null>(null);+ if (arriving.current === null) arriving.current = justArrived(photo.id);// The thumbnail goes under the tile's picture only when that picture cannot be made, or is// still not here after a long moment (made from Apple, not the disk). Nearly every picture is made ahead (photos_prepare) and lands at once, and// the thumbnail asked for alongside it doubled each tile's requests — every one a trip through@@ -389,6 +430,10 @@ const Tile = memo(function Tile({onLoad={(e) => {landed.current = true;e.currentTarget.dataset.in = performance.now() - born.current > 80 ? "fade" : "now";+ if (arriving.current) {+ arriving.current = false;+ fadeIn(e.currentTarget, { duration: 120 });+ }}}onError={under}/>@@ -439,7 +484,7 @@ function idsOf(items: Item[]): Set<string> {* month again — every one was handed the whole selection — 166 ms on a 20,000-photo library.*/function sameMonth(a: MonthProps, b: MonthProps): boolean {- if (a.label !== b.label || a.month !== b.month || a.items !== b.items || a.list !== b.list || a.deleted !== b.deleted || a.eager !== b.eager || a.across !== b.across+ if (a.label !== b.label || a.view !== b.view || a.month !== b.month || a.items !== b.items || a.list !== b.list || a.deleted !== b.deleted || a.eager !== b.eager || a.across !== b.across|| a.fit !== b.fit || a.cell !== b.cell || a.act !== b.act) return false;if (a.chosen !== b.chosen) {// Only the photos whose selection changed are looked at (worked out once per change, not@@ -489,6 +534,8 @@ type Item = { id: string; index: number };type MonthProps = {label: string;+ /** The view it is drawn in (see Month's `whole`). */+ view: string;month: string;items: Item[];list: PhotoList;@@ -504,6 +551,7 @@ type MonthProps = {const Month = memo(function Month({label,+ view,month,items,list,@@ -517,6 +565,7 @@ const Month = memo(function Month({act,}: {label: string;+ view: string;month: string;items: Item[];list: PhotoList;@@ -534,7 +583,13 @@ const Month = memo(function Month({// rows a frame once the month comes near (see buildSoon). Built whole in one go, a month of a// hundred and fifty photos was one task of 50–110 ms — a frame dropped every time a fast// scroll reached the next month.- const [built, setBuilt] = useState(eager ? items.length : 0);+ const [builtTo, setBuilt] = useState(eager ? items.length : 0);+ // Once built whole, it stays whole as it grows: a photo arriving in it is drawn with the rest,+ // where its last row used to go back to the placeholder. Whole for the view it was built in —+ // another view's month of the same name builds a few rows a frame, as a new month does.+ const whole = useRef<string | null>(null);+ if (builtTo >= items.length) whole.current = view;+ const built = whole.current === view ? items.length : builtTo;const builtNow = useRef(built);builtNow.current = built;const step = useRef(across);@@ -552,19 +607,21 @@ const Month = memo(function Month({if (!watching) return "";const store = list.store;if (seen.current.version === store.version && seen.current.items === items) return seen.current.sig;- // How many from its start are here, and each one's change count: a photo read again or- // changed here (a heart) draws its tile again, and nothing else does.+ // How many from its start are here, how many in all, and each one's change count: a photo+ // read again or changed here (a heart) draws its tile again, and nothing else does.let ready = 0;+ let here = 0;let turns = 0;for (const { id } of items) {- if (!store.get(id)) break;- ready++;+ if (!store.get(id)) continue;+ if (here === ready) ready++;+ here++;turns += store.turns(id);}- seen.current = { version: store.version, items, sig: `${ready}:${turns}` };+ seen.current = { version: store.version, items, sig: `${ready}:${here}:${turns}` };return seen.current.sig;});- const ready = watching ? Number(sig.split(":")[0] || 0) : 0;+ const [ready, here] = watching ? sig.split(":").map((n) => Number(n || 0)) : [0, 0];useEffect(() => {if (eager && items.length) void list.need(items[0].index, items[items.length - 1].index);}, [eager, list, items]);@@ -618,17 +675,24 @@ const Month = memo(function Month({};}, [list, items]); // eslint-disable-line react-hooks/exhaustive-deps// Built part way when the zoom changed, or its photos part way here: what shows stays on whole- // rows, and the rest is the block below.- const upTo = Math.min(built, ready);+ // rows, and the rest is the block below. Once its grid is showing, it keeps showing: a photo+ // not here yet (one just arrived, fetched as it is drawn) holds its cell as a plain box, and+ // the tiles around it stay as they are. Stopping at it, the grid went back to its placeholder+ // and every tile was made again when it came — the grey flash of a photo arriving. Only a month+ // whose photos have all been let go (far off, see photos/list) goes back to its block.+ const showing = useRef(false);+ const upTo = showing.current && here > 0 ? built : Math.min(built, ready);const shownCount = upTo >= items.length ? items.length : Math.floor(upTo / across) * across;const live = shownCount > 0;+ showing.current = live;return (<section ref={ref} className="px-month" aria-label={label || undefined} data-month={month || undefined}>{label && <h2 className="px-month-title">{label}</h2>}{live && (<div className="px-grid" role="listbox" aria-multiselectable="true" aria-label={label || "Photos"}>{(shownCount < items.length ? items.slice(0, shownCount) : items).map(({ id, index }) => {- const photo = list.store.get(id)!;+ const photo = list.store.get(id);+ if (!photo) return <div key={id} className="px-ph" aria-hidden="true" />;const t = deleted ? timeLeft(photo, true) : null;return (<Tile@@ -747,6 +811,7 @@ export function PhotosView() {// the order only when its photos arrive, all with them — not a frame before, over the last// view's photos.const [drawn, setDrawn] = useState<{ view: PhotoView; album: PhotoAlbum | null; query: string }>({ view, album, query: "" });+ const drawnKey = `${drawn.view}/${drawn.album?.id ?? ""}/${drawn.query}`;// What is typed in the search field, and — a moment after the typing stops — what is searched.const [query, setQuery] = useState("");const [searching, setSearching] = useState("");@@ -786,6 +851,21 @@ export function PhotosView() {drawnNow.current = drawn;const photosNow = useRef(photos);photosNow.current = photos;+ /** The list the last read drew: an arrival is only one over a list read whole, not one changed here. */+ const readList = useRef<PhotoList | null>(null);+ /** Photos changed here a moment ago, by id: one coming back from Apple is no arrival. */+ const ownIds = useRef(new Map<string, number>());+ const ownTouch = (ids: Iterable<string>) => {+ const now = Date.now();+ for (const id of ids) ownIds.current.set(id, now);+ for (const [id, at] of ownIds.current) if (now - at > 120_000) ownIds.current.delete(id);+ };+ /** The files being sent from here, by name: each lands in the library as a photo of that name. */+ const uploadsNow = useRef(uploads);+ uploadsNow.current = uploads;+ const ownNames = () => new Set([...uploadsNow.current.values()].filter((u) => u.state !== "failed" && u.state !== "cancelled").map((u) => u.name));+ /** The tile at the top of the view as a read with new photos was drawn, kept there (see below). */+ const anchorAt = useRef<{ id: string; top: number; list: PhotoList } | null>(null);const read = useCallback(async () => {if (burstOpen.current) return;const mine = ++reads.current;@@ -811,18 +891,41 @@ export function PhotosView() {indexed = true;if (mine !== reads.current) return;const next = new PhotoList(read, store);+ const before = photosNow.current;+ if (again && before && !next.same(before)) {+ // Photos new to the view being looked at (taken on the phone a moment ago) are fetched+ // before the list with them is drawn, so each lands as its tile with its photo — drawn+ // first, its month showed its placeholder where its photos had been until they came.+ const fresh = next.ids.filter((id) => before.indexOf(id) < 0);+ await store.take(fresh.slice(0, 2 * PAGE));+ if (mine !== reads.current) return;+ // A few arriving where the grid was already drawn from a whole read fade in, each alone;+ // a batch, the person's own, or anything over a partial first page simply appears.+ const own = ownNames();+ const arriving = before === readList.current && !before.partial && fresh.length <= ARRIVALS+ ? fresh.filter((id) => !ownIds.current.has(id) && !own.has(store.get(id)?.filename ?? ""))+ : [];+ const at = performance.now();+ for (const [id, when] of arrived) if (at - when > ARRIVAL_MS) arrived.delete(id);+ for (const id of arriving) arrived.set(id, at);+ const keep = anchorOf(scroller.current);+ anchorAt.current = keep && { ...keep, list: next };+ }// Read again (a sync landed, a change was made): what is held is fetched again where the// grid is, and only a list that changed is drawn again.if (again) store.refresh();store.use(next);- setPhotos((before) => (next.same(before) ? before : next));+ readList.current = before && next.same(before) ? before : next;+ setPhotos((was) => (next.same(was) ? was : next));const near = again ? store.near : 0;void next.need(near - PAGE, near + PAGE);// The same view read again is the same view drawn: a new object here built every month// afresh and faded the grid in again at each landing.setDrawn((was) => (was.view === view && was.album === album && was.query === searching ? was : { view, album, query: searching }));- setCounts(Object.fromEntries(c));- setAlbums(a);+ // The sidebar's counts and albums, drawn again only when one of them changed.+ const counted = Object.fromEntries(c);+ setCounts((was) => (same(was, counted) ? was : counted));+ setAlbums((was) => (same(was, a) ? was : a));// An album deleted elsewhere is not left open, empty.if (album && !a.some(([x]) => x.id === album.id)) setAlbum(null);}, [view, album, searching, want?.by, want?.oldest]); // eslint-disable-line react-hooks/exhaustive-deps@@ -842,17 +945,18 @@ export function PhotosView() {// the line under the title.const byDay = zoom >= DAYS_FROM;const months = useMemo(() => {- const out: { label: string; month: string; items: Item[] }[] = [];+ const out: { key: string; label: string; month: string; items: Item[] }[] = [];// An album keeps its own order, and Recently Deleted is in the order things were deleted:// grouped by the month they were taken, the same month came back again and again. Both are// one grid, as icloud.com shows them.if (!photos) return out;- if (drawn.album || drawn.view === "recentlyDeleted") return [{ label: "", month: "", items: photos.ids.map((id, index) => ({ id, index })) }];+ if (drawn.album || drawn.view === "recentlyDeleted") return [{ key: "", label: "", month: "", items: photos.ids.map((id, index) => ({ id, index })) }];const thisYear = new Date().getFullYear();const rated = drawn.view === "rated" && !drawn.album;// Named once a month (or day), not once a photo: fifty thousand dates formatted on every// read was most of laying the grid out.const names = new Map<number, [string, string]>();+ const seen = new Map<string, number>();let lastKey = NaN;let lastLabel = "";let lastMonth = "";@@ -883,7 +987,13 @@ export function PhotosView() {}const last = out[out.length - 1];if (last && last.label === label) last.items.push({ id, index });- else out.push({ label, month, items: [{ id, index }] });+ else {+ // A name seen before (search results are not in date order) is told apart by how many+ // times it has come.+ const times = (seen.get(label) ?? 0) + 1;+ seen.set(label, times);+ out.push({ key: times > 1 ? `${label}#${times}` : label, label, month, items: [{ id, index }] });+ }});return out;}, [photos, drawn, byDay]);@@ -1519,6 +1629,7 @@ export function PhotosView() {}try {// The whole selection in one call: the library changes at once, Apple hears it batched.+ ownTouch(list);await api.photosSetFlag(list, flag, on);read().catch(() => {});} catch (e) {@@ -1540,6 +1651,7 @@ export function PhotosView() {try {const made = await api.photosAlbumCreate(name, parent ?? undefined, folder);setAlbums((list) => list.map((x) => (x[0].id === temp.id ? [made, x[1]] : x)));+ ownTouch(then);if (then.length) await api.photosAlbumAdd(made.id, then);read().catch(() => {});} catch (e) {@@ -1601,6 +1713,7 @@ export function PhotosView() {const before = albums;setAlbums((list) => list.map((x) => (x[0].id === a.id ? [x[0], x[1] + ids.length] : x)));try {+ ownTouch(ids);await api.photosAlbumAdd(a.id, ids);toast({ message: ids.length === 1 ? `Added to ${a.name}` : `${ids.length} added to ${a.name}`, tone: "done" });read().catch(() => {});@@ -2145,6 +2258,7 @@ export function PhotosView() {const keywords = async (p: Photo, words: string[]) => {store.patch([p.id], (x) => ({ ...x, keywords: words }));try {+ ownTouch([p.id]);await api.photoSetKeywords(p.id, words);} catch (e) {store.put([p]);@@ -2158,6 +2272,7 @@ export function PhotosView() {if (leaves) setPhotos((all) => all?.without(new Set([p.id])) ?? all);else store.patch([p.id], (x) => ({ ...x, rating }));try {+ ownTouch([p.id]);await api.photoSetRating(p.id, rating);read().catch(() => {});} catch (e) {@@ -2172,6 +2287,7 @@ export function PhotosView() {if (t === (p.title ?? "") && c === (p.caption ?? "")) return;store.patch([p.id], (x) => ({ ...x, title: t || null, caption: c || null }));try {+ ownTouch([p.id]);await api.photoSetText(p.id, t, c);} catch (e) {store.put([p]);@@ -2202,6 +2318,7 @@ export function PhotosView() {setAdjusting(null);store.patch([p.id], (x) => ({ ...x, takenAt }));try {+ ownTouch([p.id]);await api.photoSetDate(p.id, takenAt);read().catch(() => {});} catch (e) {@@ -2485,6 +2602,23 @@ export function PhotosView() {}if (top !== null) el.scrollTop = Math.max(0, top - k.top);}, [across]); // eslint-disable-line react-hooks/exhaustive-deps+ /*+ * Photos landing above the view leave it on the photos it showed, as a chat keeps its place+ * when older messages load: the tile at its top is put back where it was, before the frame is+ * painted. The engine's own anchoring is off here (photos.css says why), and WebKit has none.+ * At the very top nothing is kept: the new photos are what is there to be seen.+ */+ useLayoutEffect(() => {+ const k = anchorAt.current;+ const el = scroller.current;+ if (!k || k.list !== photos || !el) return;+ anchorAt.current = null;+ const esc = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(k.id) : k.id;+ const tile = el.querySelector<HTMLElement>(`.px-tile[data-id="${esc}"]`);+ if (!tile) return;+ const by = tile.getBoundingClientRect().top - k.top;+ if (Math.abs(by) >= 0.5) el.scrollTop += by;+ }, [photos]);// A cell's width in device pixels, for the size each tile's picture is made at; in steps of// 32, so a window being resized does not redraw every tile on every frame.const [gridWidth, setGridWidth] = useState(0);@@ -3077,8 +3211,11 @@ export function PhotosView() {)}{!waiting && months.map((m, k) => (<Month- key={`${k}/${m.label}`}+ // By its name, never its place: a new month at the top moved every month's place,+ // and each was made again from nothing — every tile and every picture.+ key={m.key}label={m.label}+ view={drawnKey}month={m.month}items={m.items}list={photos!}diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsxindex 2e9bef1..ab4a35a 100644--- a/src/screens/RemindersView.tsx+++ b/src/screens/RemindersView.tsx@@ -45,6 +45,8 @@ import { dateText, timeText } from "../lib/when";import { parseReminder, understood, type QuickReminder } from "./reminderQuick.ts";import { useReveal } from "../lib/reveal";import { instantIn, wallIn, zoneName, type Wall } from "./calendar/model";+import { keepSame, same } from "../lib/same";+import { useArrivals } from "../lib/arrival";/** Apple's built-in views, in Apple's order, each with the glyph and system colour its app uses. */const SMART: { kind: SmartList; title: string; glyph: GlyphName; colour: string }[] = [@@ -462,7 +464,15 @@ export function RemindersView() {const named = (Array.isArray(allTags) ? allTags : []).filter((t) => t.name);const custom = (Array.isArray(smart) ? smart : []).filter((x) => x.kind === "custom");setTags(named);- setTagsOf(new Map(Object.entries(extras?.tagsByReminder ?? {})));+ // Each row's tags kept as the array it had when they are the same: a new one each read drew+ // every row with a tag again for any change at all (lib/same).+ setTagsOf((was) => {+ const next = new Map(Object.entries(extras?.tagsByReminder ?? {}).map(([k, v]) => {+ const had = was.get(k);+ return [k, had && same(had, v) ? had : v] as const;+ }));+ return next.size === was.size && [...next].every(([k, v]) => was.get(k) === v) ? was : next;+ });setCustomLists(custom);setCustomCounts(new Map(custom.map((x) => [x.guid, extras?.customCounts?.[x.guid] ?? 0])));};@@ -496,6 +506,10 @@ export function RemindersView() {const { hold, over } = usePending<Reminder>();/** Changes kept here and not yet at Apple, and any Apple turned down. */const outbox = useOutbox("reminders");+ // A reminder added on the phone, landing in the list on screen, fades in (lib/arrival).+ const mainRef = useRef<HTMLElement | null>(null);+ const itemIds = useMemo(() => items.map((r) => r.guid), [items]);+ useArrivals(mainRef, itemIds, `${JSON.stringify(selection)}\u0000${showDone}\u0000${sought.trim()}`, outbox.waiting.size > 0 || itemIds.some((g) => g.startsWith(STAND_IN)));/** Each read is numbered: one overtaken by a later pick is dropped, never drawn late. */const reads = useRef(0);const readItems = useCallback(async (): Promise<Reminder[]> => {@@ -524,7 +538,8 @@ export function RemindersView() {if (seq !== reads.current) return fresh;// The view, its reminders and its headings, together.setShown(sel);- setItems(fresh);+ // Each reminder unchanged keeps its row as it was (lib/same).+ setItems((was) => keepSame(was, fresh, (r) => r.guid));setListSections(Array.isArray(sections) ? sections : []);setUnknownRules(unknown);return fresh;@@ -1833,7 +1848,7 @@ export function RemindersView() {)}</aside>- <section className="rx-main">+ <section className="rx-main" ref={mainRef}><button className="compact-back" onClick={() => setDetail(false)}><ChevronLeft size={18} strokeWidth={2.25} aria-hidden="true" /><span>Lists</span>diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsxindex 4517ef5..824388e 100644--- a/src/screens/notes/NoteEditor.tsx+++ b/src/screens/notes/NoteEditor.tsx@@ -967,16 +967,43 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(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)));+ const was = v.state.doc;+ if (doc.eq(was)) return;+ // What is on screen and stays still: the caret's line when it is in view, or else the+ // first line in view — measured now, put back where it was once the change is in.+ const keep = steady(v);+ // Only the part that differs is replaced, and the caret is carried through the change:+ // a line added above it on the phone leaves it on its own character. Replaced whole, the+ // caret was put back by its count from the start, and that count was now another line;+ // and every line was drawn again, a picture in it fetched and decoded again.+ let tr = v.state.tr;+ const start = was.content.findDiffStart(doc.content);+ const end = was.content.findDiffEnd(doc.content);+ if (start !== null && end) {+ let { a, b } = end;+ // The ends cross where the change repeats what is next to it ("aa" to "aaa"): it is+ // the same change, counted on from the start.+ const over = start - Math.min(a, b);+ if (over > 0) {+ a += over;+ b += over;+ }+ tr.replace(start, a, doc.slice(start, b));+ }+ if (!tr.doc.eq(doc)) {+ // A change the slice did not fit as it is (never seen, but never risked): the whole+ // note, the caret kept by its place, as before.+ const { from, to } = v.state.selection;+ tr = v.state.tr.replaceWith(0, was.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);+ if (keep) keep(tr.mapping);tell(next);},focus: () => view.current?.focus(),@@ -1008,6 +1035,48 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor();});+/**+ * A change taken in from elsewhere leaves the view where it was: the caret's line, when the+ * caret is in view, or else the first line in view, stays at the same height on the screen.+ * Measured before the change; the returned function, given how positions moved, scrolls the+ * note back by however far that line went. At the very top with no caret in view nothing is+ * kept: lines added at the top are what is there to be seen.+ */+function steady(v: EditorView): ((mapping: Transaction["mapping"]) => void) | null {+ const scroller = v.dom.closest<HTMLElement>(".note-editor");+ if (!scroller) return null;+ const box = scroller.getBoundingClientRect();+ const seen = (top: number, bottom: number) => bottom > box.top && top < box.bottom;+ let pos: number | null = null;+ const head = v.state.selection.head;+ if (v.hasFocus()) {+ const c = v.coordsAtPos(head);+ if (seen(c.top, c.bottom)) pos = head;+ }+ if (pos === null && scroller.scrollTop > 0) {+ for (const line of v.dom.children) {+ const r = line.getBoundingClientRect();+ if (r.bottom <= box.top) continue;+ try {+ pos = v.posAtDOM(line, 0);+ } catch {+ pos = null;+ }+ break;+ }+ }+ if (pos === null) return null;+ const at = pos;+ const top = v.coordsAtPos(at).top;+ return (mapping) => {+ // Carried past anything put in just where it stood: the line it was on, not the new one.+ const moved = mapping.map(at, 1);+ if (moved < 0 || moved > v.state.doc.content.size) return;+ const by = v.coordsAtPos(moved).top - top;+ if (Math.abs(by) >= 0.5) scroller.scrollTop += by;+ };+}+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/photos/Slideshow.tsx b/src/screens/photos/Slideshow.tsxindex 7580dc1..72b9088 100644--- a/src/screens/photos/Slideshow.tsx+++ b/src/screens/photos/Slideshow.tsx@@ -42,7 +42,7 @@ function boxOf(p: Photo) {/** The picture a photo is shown at: whole on this screen, in device pixels — never smaller. */export const screenSrc = (p: Photo) => {const { w, h } = boxOf(p);- return fitSrc(p.id, Math.max(w, h) * (window.devicePixelRatio || 1));+ return fitSrc(p, Math.max(w, h) * (window.devicePixelRatio || 1));};/** Fetched and decoded ahead, by address: the next is ready before its turn. */diff --git a/src/screens/photos/list.ts b/src/screens/photos/list.tsindex 62d88cd..545d9ef 100644--- a/src/screens/photos/list.ts+++ b/src/screens/photos/list.ts@@ -148,6 +148,21 @@ export class PhotoStore {return Promise.all(pages).then(() => {});}+ /**+ * These photos here before what shows them is drawn: the ones a sync brought into the view+ * being looked at. Drawn before they were here, their month showed its placeholder where its+ * photos had been, and every tile in it was made again when they came.+ */+ take(ids: string[]): Promise<void> {+ const wanted = ids.filter((id) => !this.photos.has(id));+ if (wanted.length === 0) return Promise.resolve();+ const pages: Promise<void>[] = [];+ for (let i = 0; i < wanted.length; i += PAGE) {+ pages.push(api.photosGet(wanted.slice(i, i + PAGE)).then((read) => this.put(read), () => {}));+ }+ return Promise.all(pages).then(() => {});+ }+/** Photos by id, fetched where they are not here: for an action on a selection. */async load(ids: string[]): Promise<Photo[]> {const missing = ids.filter((id) => !this.photos.has(id));@@ -188,6 +203,8 @@ export class PhotoList {readonly first: number | null;readonly last: number | null;private places: Map<string, number> | null = null;+ /** Only the first page of the view, painted before its index came (see `of`). */+ partial = false;constructor(index: PhotoIndex, readonly store: PhotoStore) {this.ids = index.ids;@@ -201,7 +218,7 @@ export class PhotoList {static of(photos: Photo[], store: PhotoStore, keyOf: (p: Photo) => number): PhotoList {store.put(photos);const taken = photos.map((p) => p.takenAt);- return new PhotoList(+ const list = new PhotoList({ids: photos.map((p) => p.id),keys: photos.map(keyOf),@@ -211,6 +228,8 @@ export class PhotoList {},store,);+ list.partial = true;+ return list;}get length(): number {