Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Notes: merge two edits as Notes does — character by character, both sides' text kept, never refused (the 'changed on another device… nothing was saved' error); dates and times from cached formatters
Yashwanth Kamireddi43a86603074a
diff --git a/.uiverify/notes-rich.test.mjs b/.uiverify/notes-rich.test.mjsindex 63fd989..adf7c64 100644--- a/.uiverify/notes-rich.test.mjs+++ b/.uiverify/notes-rich.test.mjs@@ -37,3 +37,11 @@ test("runs follow another device's edit merged in", () => {const out = carryRuns("abc\ndef", [r(3, { bold: true }), r(4)], "abcXY\ndef");assert.deepEqual(out.map((x) => [x.length, x.bold]), [[5, true], [4, false]]);});++import { mergeEdits } from "../src/screens/notes/model.ts";+test("two edits merge as Notes merges them — nothing typed is lost", () => {+ assert.equal(mergeEdits("Tea filter\n", "Tea filter\nSpoon", "Tea filter\nKnife"), "Tea filter\nKnifeSpoon");+ assert.equal(mergeEdits("a b c", "a X c", "a Y c"), "a YX c");+ assert.equal(mergeEdits("milk\neggs\nbread\njam", "milk!\neggs\nbread\njam?", "milk\neggs\nbutter\njam"), "milk!\neggs\nbutter\njam?");+ assert.equal(mergeEdits("one two three", "one three", "one two three!"), "one three!");+});diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex fb74384..7f2a1a2 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -562,8 +562,72 @@ pub async fn edit_rich_cloudkit_from())}-/// Combine two edits of `base` — `mine` and `theirs` — when they change different stretches-/// of it, or are the same edit; `None` when they overlap and one would have to lose.+/// One edit of `base`, character by character: which of its characters it removed, and what+/// it put in each gap between them (gap `i` is just before character `i`).+struct Script {+ removed: Vec<bool>,+ added: Vec<Vec<char>>,+}++/// The edit that turns `base` into `other`, as removals and additions. The unchanged start+/// and end are matched directly; the stretch between by longest common subsequence, so an+/// edit in two places reads as two edits — or, when that stretch is too large to compare+/// cheaply, as one replacement of it.+fn script(base: &[char], other: &[char]) -> Script {+ let mut removed = vec![false; base.len()];+ let mut added = vec![Vec::new(); base.len() + 1];+ let pre = base.iter().zip(other).take_while(|(a, b)| a == b).count();+ let max_suf = base.len().min(other.len()) - pre;+ let suf = base+ .iter()+ .rev()+ .zip(other.iter().rev())+ .take(max_suf)+ .take_while(|(a, b)| a == b)+ .count();+ let (b, o) = (&base[pre..base.len() - suf], &other[pre..other.len() - suf]);+ if b.len().saturating_mul(o.len()) <= 4_000_000 {+ // lcs[i][j]: the longest common subsequence of b[i..] and o[j..].+ let w = o.len() + 1;+ let mut lcs = vec![0u32; (b.len() + 1) * w];+ for i in (0..b.len()).rev() {+ for j in (0..o.len()).rev() {+ lcs[i * w + j] = if b[i] == o[j] {+ lcs[(i + 1) * w + j + 1] + 1+ } else {+ lcs[(i + 1) * w + j].max(lcs[i * w + j + 1])+ };+ }+ }+ let (mut i, mut j) = (0, 0);+ while i < b.len() || j < o.len() {+ if i < b.len() && j < o.len() && b[i] == o[j] {+ i += 1;+ j += 1;+ } else if j < o.len() && (i == b.len() || lcs[i * w + j + 1] >= lcs[(i + 1) * w + j]) {+ added[pre + i].push(o[j]);+ j += 1;+ } else {+ removed[pre + i] = true;+ i += 1;+ }+ }+ } else {+ for r in &mut removed[pre..pre + b.len()] {+ *r = true;+ }+ added[pre + b.len()] = o.to_vec();+ }+ Script { removed, added }+}++/// Combine two edits of `base` — `mine` and `theirs` — the way Notes' own merge does: nothing+/// either side wrote is lost. What either removed goes; what either added stays, in place;+/// two additions at the same point are both kept, the other device's first, and an addition+/// both made is kept once.+///+/// It used to refuse when the two touched the same place — and a refusal was a save that did+/// not happen, with "changed on another device" over a note nobody else was really editing.pub fn merge_edits(base: &str, mine: &str, theirs: &str) -> Option<String> {if mine == theirs || base == theirs {return Some(mine.to_string());@@ -572,39 +636,20 @@ pub fn merge_edits(base: &str, mine: &str, theirs: &str) -> Option<String> {return Some(theirs.to_string());}let b: Vec<char> = base.chars().collect();- let m: Vec<char> = mine.chars().collect();- let t: Vec<char> = theirs.chars().collect();- // Each edit as one stretch of `base` replaced: [from, to) → replacement.- let span = |other: &[char]| {- let pre = b.iter().zip(other).take_while(|(x, y)| x == y).count();- let max_suf = b.len().min(other.len()) - pre;- let suf = b- .iter()- .rev()- .zip(other.iter().rev())- .take(max_suf)- .take_while(|(x, y)| x == y)- .count();- (pre, b.len() - suf, other[pre..other.len() - suf].to_vec())- };- let (m0, m1, mr) = span(&m);- let (t0, t1, tr) = span(&t);- // Apart only if one ends strictly before the other begins; two inserts at one point, or- // touching stretches, are the same place.- let (first, second) = if m1 < t0 {- ((m0, m1, mr), (t0, t1, tr))- } else if t1 < m0 {- ((t0, t1, tr), (m0, m1, mr))- } else {- return None;- };- let mut out: Vec<char> = Vec::with_capacity(b.len() + first.2.len() + second.2.len());- out.extend_from_slice(&b[..first.0]);- out.extend_from_slice(&first.2);- out.extend_from_slice(&b[first.1..second.0]);- out.extend_from_slice(&second.2);- out.extend_from_slice(&b[second.1..]);- Some(out.into_iter().collect())+ let m = script(&b, &mine.chars().collect::<Vec<_>>());+ let t = script(&b, &theirs.chars().collect::<Vec<_>>());+ let mut out = String::with_capacity(mine.len().max(theirs.len()) + 16);+ for gap in 0..=b.len() {+ let (ta, ma) = (&t.added[gap], &m.added[gap]);+ out.extend(ta.iter());+ if ma != ta {+ out.extend(ma.iter());+ }+ if gap < b.len() && !m.removed[gap] && !t.removed[gap] {+ out.push(b[gap]);+ }+ }+ Some(out)}/// Set one paragraph of a note — a style from the Aa menu, or a checklist tick — written@@ -2132,15 +2177,40 @@ mod merge_tests {);}- /// Edits in the same place cannot both be kept, so neither is chosen silently.+ /// Edits in the same place both survive, as Notes merges them: nothing typed is lost.#[test]- fn edits_in_one_place_are_refused() {- assert_eq!(merge_edits("a b c", "a X c", "a Y c"), None);+ fn edits_in_one_place_both_survive() {assert_eq!(- merge_edits("ab", "aXb", "aYb"),- None,+ merge_edits("a b c", "a X c", "a Y c").as_deref(),+ Some("a YX c")+ );+ assert_eq!(+ merge_edits("ab", "aXb", "aYb").as_deref(),+ Some("aYXb"),"two inserts at one point");+ // Both typed at the end: the phone's line, then this one's.+ assert_eq!(+ merge_edits("Tea filter\n", "Tea filter\nSpoon", "Tea filter\nKnife").as_deref(),+ Some("Tea filter\nKnifeSpoon")+ );+ // One deleted a word the other edited beside: the deletion and the edit both hold.+ assert_eq!(+ merge_edits("one two three", "one three", "one two three!").as_deref(),+ Some("one three!")+ );+ }++ /// Edits in two places on one side, and another on the other, all survive.+ #[test]+ fn several_edits_on_each_side_combine() {+ let base = "milk\neggs\nbread\njam";+ let mine = "milk!\neggs\nbread\njam?";+ let theirs = "milk\neggs\nbutter\njam";+ assert_eq!(+ merge_edits(base, mine, theirs).as_deref(),+ Some("milk!\neggs\nbutter\njam?")+ );}#[test]diff --git a/probe/examples/notes_merge_live.rs b/probe/examples/notes_merge_live.rsindex 9d5ce32..c1117e6 100644--- a/probe/examples/notes_merge_live.rs+++ b/probe/examples/notes_merge_live.rs@@ -60,7 +60,7 @@ async fn main() -> Result<()> {.unwrap_or("")));- // Same place, both sides: refused.+ // Same place, both sides: both kept, as Notes merges them.let refused = quince_icloud::notes::edit_cloudkit_from(&http,&root,@@ -73,7 +73,7 @@ async fn main() -> Result<()> {println!("same-place edit: {}",match refused {- Ok(t) => format!("WROTE {t:?}"),+ Ok(t) => format!("merged {t:?}"),Err(e) => format!("refused — {e}"),});diff --git a/probe/examples/notes_one_read.rs b/probe/examples/notes_one_read.rsnew file mode 100644index 0000000..866af54--- /dev/null+++ b/probe/examples/notes_one_read.rs@@ -0,0 +1,54 @@+//! Read-only: one note's text and runs as Apple holds them, by title.+use anyhow::{anyhow, Result};+#[tokio::main]+async fn main() -> Result<()> {+ let want = std::env::args()+ .nth(1)+ .ok_or_else(|| anyhow!("pass a title"))?;+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");+ let mut client = quince_auth::Client::new(&dir)?;+ if !client.resume().await? {+ return Err(anyhow!("no session"));+ }+ let root = client+ .session()+ .service_url("ckdatabasews")+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let walk = zc.all_records("Notes", None).await?;+ for r in walk.records.iter().filter(|r| r["recordType"] == "Note") {+ let body = r["fields"]["TextDataEncrypted"]["value"]+ .as_str()+ .unwrap_or("");+ let text = quince_icloud::ckdocument::text_from_base64(body).unwrap_or_default();+ if !text.starts_with(&want) {+ continue;+ }+ println!(+ "{} tag={} modified={}",+ r["recordName"], r["recordChangeTag"], r["fields"]["ModificationDate"]["value"]+ );+ println!("text {:?}", text);+ let runs = quince_icloud::ckdocument::runs_from_base64(body);+ println!(+ "runs {:?}",+ runs.iter()+ .map(|x| (x.length, x.style, x.checked))+ .collect::<Vec<_>>()+ );+ println!(+ "sum {} vs utf16 {}",+ runs.iter().map(|r| r.length).sum::<u64>(),+ text.encode_utf16().count()+ );+ println!(+ "rewritable {}",+ quince_icloud::ckdocument::is_rewritable(+ &base64::Engine::decode(&base64::engine::general_purpose::STANDARD, body.trim())+ .unwrap_or_default()+ )+ );+ }+ Ok(())+}diff --git a/src/components/AppIcon.tsx b/src/components/AppIcon.tsxindex 99bbca9..0348658 100644--- a/src/components/AppIcon.tsx+++ b/src/components/AppIcon.tsx@@ -1,4 +1,5 @@import { useId } from "react";+import { dateText } from "../lib/when";/*** Each screen's mark in the sidebar, drawn after the app it stands in for — Reminders' three@@ -94,7 +95,7 @@ export function AppIcon({ app, size = 22 }: { app: string; size?: number }) {<><text x="12" y="8" textAnchor="middle" fontSize="5" fontWeight="600" fill="#ff453a"fontFamily="-apple-system, 'SF Pro Text', Inter, system-ui, sans-serif" letterSpacing="0.2">- {today.toLocaleDateString(undefined, { weekday: "short" }).slice(0, 3)}+ {dateText(today, { weekday: "short" }).slice(0, 3)}</text><text x="12" y="19.4" textAnchor="middle" fontSize="11.6" fontWeight="300" className="ai-ink"fontFamily="-apple-system, 'SF Pro Display', Inter, system-ui, sans-serif" letterSpacing="-0.4">diff --git a/src/components/TimeField.tsx b/src/components/TimeField.tsxindex 2be31e7..eef393b 100644--- a/src/components/TimeField.tsx+++ b/src/components/TimeField.tsx@@ -1,4 +1,5 @@import { useEffect, useState } from "react";+import { timeText } from "../lib/when";/*** A time of day, typed as a person says it — "9", "930", "9:30", "9.30pm", "21:15",@@ -77,7 +78,7 @@ const usesTwelveHour = (() => {export function formatTime(hours: number, minutes: number): string {const d = new Date(2000, 0, 1, hours, minutes);- return d.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });+ return timeText(d, { hour: "numeric", minute: "2-digit" });}/** `[hours, minutes]`, or null when the text is not a time. */diff --git a/src/lib/when.ts b/src/lib/when.tsnew file mode 100644index 0000000..b321b20--- /dev/null+++ b/src/lib/when.ts@@ -0,0 +1,31 @@+/**+ * Dates and times written out in this machine's language, with each kind of format built+ * once and kept.+ *+ * `Date.toLocaleDateString(undefined, options)` builds a new formatter on every call, and a+ * formatter is not cheap — the locale's data is looked up and compiled each time. A calendar+ * week writes out hundreds of dates and times on every redraw, and those builds were most of+ * what made opening a new event stutter. A formatter made once per set of options and kept+ * gives the same text for a fraction of the cost.+ */+const made = new Map<string, Intl.DateTimeFormat>();++function formatter(options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {+ const key = JSON.stringify(options);+ let f = made.get(key);+ if (!f) {+ f = new Intl.DateTimeFormat(undefined, options);+ made.set(key, f);+ }+ return f;+}++/** As `date.toLocaleDateString(undefined, options)`, without building a formatter. */+export function dateText(date: Date, options: Intl.DateTimeFormatOptions): string {+ return formatter(options).format(date);+}++/** As `date.toLocaleTimeString(undefined, options)`, without building a formatter. */+export function timeText(date: Date, options: Intl.DateTimeFormatOptions): string {+ return formatter(options).format(date);+}diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsxindex d7fc8a8..21d5746 100644--- a/src/screens/ContactsView.tsx+++ b/src/screens/ContactsView.tsx@@ -15,6 +15,7 @@ import { Picker } from "../components/Picker";import { RowMenu, type MenuEntry } from "../components/RowMenu";import { Portal } from "../components/Portal";import { open as openFileDialog } from "@tauri-apps/plugin-dialog";+import { dateText } from "../lib/when";/** The sidebar row that is every contact rather than a list. */const ALL = "";@@ -989,7 +990,7 @@ function birthdayText(raw: string): string {const [y, m, d] = raw.slice(0, 10).split("-").map(Number);if (!m || !d) return raw;const date = new Date(y === Number(NO_YEAR) ? 2000 : y, m - 1, d);- return date.toLocaleDateString(undefined, y === Number(NO_YEAR) ? { day: "numeric", month: "long" } : { dateStyle: "long" });+ return dateText(date, y === Number(NO_YEAR) ? { day: "numeric", month: "long" } : { dateStyle: "long" });}/**diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsxindex abdafe1..7145b6f 100644--- a/src/screens/DriveView.tsx+++ b/src/screens/DriveView.tsx@@ -20,6 +20,7 @@ import { UploadTray } from "../components/UploadTray";import { listen } from "@tauri-apps/api/event";import { Picker } from "../components/Picker";import { RowMenu } from "../components/RowMenu";+import { dateText } from "../lib/when";/** iCloud Drive's own four orders, as its "by Name" menu offers them. */const SORTS = [@@ -68,7 +69,7 @@ function fileSize(bytes: number | null): string {const modified = (seconds: number | null) =>seconds === null? ""- : new Date(seconds * 1000).toLocaleDateString(undefined, {+ : dateText(new Date(seconds * 1000), {day: "numeric",month: "short",year: "numeric",diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsxindex 8f91eed..8f1e171 100644--- a/src/screens/RemindersView.tsx+++ b/src/screens/RemindersView.tsx@@ -17,6 +17,7 @@ import {import { useSync } from "../lib/sync";import { Picker } from "../components/Picker";import { Glyph, emblemGlyph, type GlyphName } from "../components/Glyph";+import { dateText, timeText } from "../lib/when";/** 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 }[] = [@@ -76,9 +77,9 @@ function dueLabel(seconds: number, dated = false, allDay = false): { text: strinif (allDay) {if (dated || days === 0) return { text: dated ? "" : "Today", overdue: false };if (days === 1) return { text: "Tomorrow", overdue: false };- return { text: due.toLocaleDateString(undefined, { day: "numeric", month: "short" }), overdue: days < 0 };+ return { text: dateText(due, { day: "numeric", month: "short" }), overdue: days < 0 };}- const time = due.toLocaleTimeString(undefined, {+ const time = timeText(due, {hour: "numeric",minute: "2-digit",});@@ -87,7 +88,7 @@ function dueLabel(seconds: number, dated = false, allDay = false): { text: strin}if (days < 0)return {- text: due.toLocaleDateString(undefined, {+ text: dateText(due, {day: "numeric",month: "short",}),@@ -97,7 +98,7 @@ function dueLabel(seconds: number, dated = false, allDay = false): { text: strinreturn { text: `Today ${time}`, overdue: due.getTime() < now.getTime() };if (days === 1) return { text: `Tomorrow ${time}`, overdue: false };return {- text: due.toLocaleDateString(undefined, { day: "numeric", month: "short" }),+ text: dateText(due, { day: "numeric", month: "short" }),overdue: false,};}@@ -744,7 +745,7 @@ export function RemindersView() {? "Today": days === 1? "Tomorrow"- : when.toLocaleDateString(undefined, {+ : dateText(when, {weekday: "short",day: "numeric",month: "short",diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsxindex 133b280..a381ac8 100644--- a/src/screens/calendar/CalendarView.tsx+++ b/src/screens/calendar/CalendarView.tsx@@ -29,6 +29,7 @@ import {startOfWeek,weekSpans,} from "./model";+import { dateText, timeText } from "../../lib/when";const ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";@@ -183,7 +184,7 @@ const toLocalInput = (s: number, dateOnly: boolean) => {};const fromLocalInput = (value: string) => seconds(new Date(value.length === 10 ? `${value}T00:00` : value));-const weekdayShort = (d: Date) => d.toLocaleDateString(undefined, { weekday: "short" });+const weekdayShort = (d: Date) => dateText(d, { weekday: "short" });/** The colour a calendar is drawn in, or Apple's blue when it has none. */const tint = (c: Calendar | undefined) =>@@ -573,7 +574,7 @@ export function CalendarView() {/** The title, and the shorter one a narrow calendar shows in its place ("Sep 2026"). */const title = useMemo(() => {- const short = (d: Date) => d.toLocaleDateString(undefined, { month: "short" });+ const short = (d: Date) => dateText(d, { month: "short" });if (view === "year") {const year = String(selected.getFullYear());return { strong: year, rest: "", brief: year };@@ -589,7 +590,7 @@ export function CalendarView() {return {strong: `${strong}${sep.trimEnd()}`,rest: parts.slice(at).map((p) => p.value).join(""),- brief: selected.toLocaleDateString(undefined, { day: "numeric", month: "short" }),+ brief: dateText(selected, { day: "numeric", month: "short" }),};}// A week across two months is named for both, as Calendar does: "Sep – Oct 2026".@@ -600,7 +601,7 @@ export function CalendarView() {}const base = view === "week" ? week[6] : selected;return {- strong: base.toLocaleDateString(undefined, { month: "long" }),+ strong: dateText(base, { month: "long" }),rest: String(base.getFullYear()),brief: `${short(base)} ${base.getFullYear()}`,};@@ -745,7 +746,7 @@ export function CalendarView() {<span className="cx-dot" aria-hidden="true" /><span className="cx-found-title">{e.title}</span><span className="cx-found-when">- {dateOf(e.startsAt).toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short", year: "numeric" })}+ {dateText(dateOf(e.startsAt), { weekday: "short", day: "numeric", month: "short", year: "numeric" })}{e.allDay ? "" : ` · ${clock(e.startsAt)}`}</span></button>@@ -919,7 +920,7 @@ function MiniMonth({return (<div className="cx-minimonth"><div className="cx-minimonth-head">- <span>{shown.toLocaleDateString(undefined, { month: "long", year: "numeric" })}</span>+ <span>{dateText(shown, { month: "long", year: "numeric" })}</span><span><buttonclassName="cx-icon small"@@ -949,7 +950,7 @@ function MiniMonth({className={`cx-minimonth-day${d.getMonth() !== shown.getMonth() ? " is-out" : ""}${sameDay(d, today) ? " is-today" : ""}${sameDay(d, selected) ? " is-selected" : ""}${busy(d) ? " is-busy" : ""}`}- aria-label={d.toLocaleDateString(undefined, { dateStyle: "full" })}+ aria-label={dateText(d, { dateStyle: "full" })}onClick={() => onPick(d)}>{d.getDate()}@@ -1075,7 +1076,7 @@ function MonthView({ref={isSelected ? cell : undefined}className="cx-day-hit"tabIndex={isSelected ? 0 : -1}- aria-label={`${day.toLocaleDateString(undefined, { dateStyle: "full" })}${+ aria-label={`${dateText(day, { dateStyle: "full" })}${list.length ? `, ${list.length} item${list.length === 1 ? "" : "s"}` : ""}`}onClick={() => onSelect(day)}@@ -1085,7 +1086,7 @@ function MonthView({/><span className={`cx-daynum${sameDay(day, today) ? " is-today" : ""}`}>{day.getDate() === 1 && day.getMonth() !== inMonth- ? day.toLocaleDateString(undefined, { month: "short", day: "numeric" })+ ? dateText(day, { month: "short", day: "numeric" }): day.getDate()}</span><ul className={`cx-items${dots ? " is-dots" : ""}`} style={{ marginTop: `${lanesHere * LANE}px` }}>@@ -1368,7 +1369,7 @@ function TimeGrid({className={`cal-col-head${sameDay(d, today) ? " is-today" : ""}`}key={dayKey(d)}onClick={() => onPickDay(d)}- aria-label={d.toLocaleDateString(undefined, { dateStyle: "full" })}+ aria-label={dateText(d, { dateStyle: "full" })}><span className="cx-col-weekday">{weekdayShort(d)}</span><span className="cx-col-num">{d.getDate()}</span>@@ -1598,9 +1599,9 @@ function YearView({const days = monthDays(first);const current = today.getFullYear() === year && today.getMonth() === m;return (- <section className="cal-mini" key={m} aria-label={first.toLocaleDateString(undefined, { month: "long" })}>+ <section className="cal-mini" key={m} aria-label={dateText(first, { month: "long" })}><h2 className={`cx-year-month${current ? " is-current" : ""}`}>- {first.toLocaleDateString(undefined, { month: "long" })}+ {dateText(first, { month: "long" })}</h2><div className="cx-minimonth-grid">{days.slice(0, 7).map((d) => (@@ -1615,7 +1616,7 @@ function YearView({<buttonkey={dayKey(d)}className={`cx-minimonth-day${sameDay(d, today) ? " is-today" : ""}${busy(d) ? " is-busy" : ""}`}- aria-label={d.toLocaleDateString(undefined, { dateStyle: "full" })}+ aria-label={dateText(d, { dateStyle: "full" })}onClick={() => onPick(d)}>{d.getDate()}@@ -1754,8 +1755,8 @@ function EventPopover({if (!editable) {const start = dateOf(draft.startsAt);const end = dateOf(Math.max(draft.startsAt, draft.endsAt - (draft.allDay ? 86_400 : 0)));- const day = (d: Date) => d.toLocaleDateString(undefined, { weekday: "long", day: "numeric", month: "long", year: "numeric" });- const time = (d: Date) => d.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });+ const day = (d: Date) => dateText(d, { weekday: "long", day: "numeric", month: "long", year: "numeric" });+ const time = (d: Date) => timeText(d, { hour: "numeric", minute: "2-digit" });const sameDay = start.toDateString() === end.toDateString();const when = draft.allDay? sameDay ? day(start) : `${day(start)} – ${day(end)}`@@ -1999,10 +2000,10 @@ function DayPane({);const nothing = allDay.length + timed.length + due.length === 0;return (- <aside className="cx-pane" aria-label={day.toLocaleDateString(undefined, { dateStyle: "full" })}>+ <aside className="cx-pane" aria-label={dateText(day, { dateStyle: "full" })}>{children && <div className="cx-pane-month">{children}</div>}- <h2 className="cx-pane-day">{day.toLocaleDateString(undefined, { weekday: "long" })}</h2>- <p className="cx-pane-date">{day.toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric" })}</p>+ <h2 className="cx-pane-day">{dateText(day, { weekday: "long" })}</h2>+ <p className="cx-pane-date">{dateText(day, { day: "numeric", month: "long", year: "numeric" })}</p>{nothing ? (<p className="cx-pane-empty">Nothing on this day.</p>) : (diff --git a/src/screens/calendar/model.ts b/src/screens/calendar/model.tsindex 2888eb0..af0e61c 100644--- a/src/screens/calendar/model.ts+++ b/src/screens/calendar/model.ts@@ -6,6 +6,7 @@* moves, which is why nothing here adds a fixed 86,400 seconds.*/import type { CalendarEvent } from "../../lib/ipc";+import { timeText } from "../../lib/when.ts";export const midnight = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());export const addDays = (d: Date, n: number) =>@@ -184,11 +185,10 @@ export const snap = (minutes: number, step = 15) => Math.round(minutes / step) *export function hourLabel(hour: number): string {if (hour === 12) return "Noon";const d = new Date(2024, 0, 1, hour);- return d.toLocaleTimeString(undefined, { hour: "numeric" });+ return timeText(d, { hour: "numeric" });}/** "9:30 AM", with ":00" left off, as Calendar writes a time. */export const clock = (s: number) =>- dateOf(s)- .toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })+ timeText(dateOf(s), { hour: "numeric", minute: "2-digit" }).replace(/:00(?=\D|$)/, "");diff --git a/src/screens/notes/model.ts b/src/screens/notes/model.tsindex 0701ead..0efe2a7 100644--- a/src/screens/notes/model.ts+++ b/src/screens/notes/model.ts@@ -2,6 +2,7 @@* The rules Notes' list and editor follow, kept apart from drawing them so they can be tested.*/import type { Note } from "../../lib/ipc";+import { dateText, timeText } from "../../lib/when.ts";const midnight = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());const daysBetween = (from: Date, to: Date) =>@@ -39,7 +40,7 @@ export function groupNotes(notes: Note[], now = new Date()): Section[] {else if (ago <= 7) add("week", "Previous 7 Days", note);else if (ago <= 30) add("month", "Previous 30 Days", note);else if (when.getFullYear() === now.getFullYear())- add(`m${when.getMonth()}`, when.toLocaleDateString(undefined, { month: "long" }), note);+ add(`m${when.getMonth()}`, dateText(when, { month: "long" }), note);else add(`y${when.getFullYear()}`, String(when.getFullYear()), note);}// Map keeps insertion order, and notes went in newest first, so groups already run@@ -54,18 +55,18 @@ export function listDate(seconds: number | null, now = new Date()): string {if (seconds === null) return "";const when = new Date(seconds * 1000);const ago = daysBetween(when, now);- if (ago <= 0) return when.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });+ if (ago <= 0) return timeText(when, { hour: "numeric", minute: "2-digit" });if (ago === 1) return "Yesterday";- if (ago < 7) return when.toLocaleDateString(undefined, { weekday: "long" });- return when.toLocaleDateString(undefined, { day: "numeric", month: "numeric", year: "numeric" });+ if (ago < 7) return dateText(when, { weekday: "long" });+ return dateText(when, { day: "numeric", month: "numeric", year: "numeric" });}/** The date at the top of the editor: "30 September 2026 at 10:02 PM". */export function editorDate(seconds: number | null): string {if (seconds === null) return "";const when = new Date(seconds * 1000);- const day = when.toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric" });- const time = when.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });+ const day = dateText(when, { day: "numeric", month: "long", year: "numeric" });+ const time = timeText(when, { hour: "numeric", minute: "2-digit" });return `${day} at ${time}`;}@@ -91,17 +92,48 @@ export function joinTitle(title: string, rest: string, hadBreak: boolean): strinexport function mergeEdits(base: string, mine: string, theirs: string): string | null {if (mine === theirs || base === theirs) return mine;if (base === mine) return theirs;- const b = [...base], m = [...mine], t = [...theirs];- const span = (o: string[]): [number, number, string[]] => {- let pre = 0;- while (pre < b.length && pre < o.length && b[pre] === o[pre]) pre++;- let suf = 0;- const max = Math.min(b.length, o.length) - pre;- while (suf < max && b[b.length - 1 - suf] === o[o.length - 1 - suf]) suf++;- return [pre, b.length - suf, o.slice(pre, o.length - suf)];- };- const x = span(m), y = span(t);- const [first, second] = x[1] < y[0] ? [x, y] : y[1] < x[0] ? [y, x] : [null, null];- if (!first || !second) return null;- return [...b.slice(0, first[0]), ...first[2], ...b.slice(first[1], second[0]), ...second[2], ...b.slice(second[1])].join("");+ const b = [...base];+ const m = script(b, [...mine]);+ const t = script(b, [...theirs]);+ let out = "";+ for (let gap = 0; gap <= b.length; gap++) {+ const ta = t.added[gap].join(""), ma = m.added[gap].join("");+ out += ta;+ if (ma !== ta) out += ma;+ if (gap < b.length && !m.removed[gap] && !t.removed[gap]) out += b[gap];+ }+ return out;+}++/**+ * One edit of `base`, character by character: what it removed, and what it put in each gap+ * (gap i is just before character i). The same rule the backend merges by, so the screen and+ * Apple agree on what a merge says.+ */+function script(b: string[], o: string[]): { removed: boolean[]; added: string[][] } {+ const removed = Array<boolean>(b.length).fill(false);+ const added: string[][] = Array.from({ length: b.length + 1 }, () => []);+ let pre = 0;+ while (pre < b.length && pre < o.length && b[pre] === o[pre]) pre++;+ let suf = 0;+ const max = Math.min(b.length, o.length) - pre;+ while (suf < max && b[b.length - 1 - suf] === o[o.length - 1 - suf]) suf++;+ const bm = b.slice(pre, b.length - suf), om = o.slice(pre, o.length - suf);+ if (bm.length * om.length <= 4_000_000) {+ const w = om.length + 1;+ const lcs = new Uint32Array((bm.length + 1) * w);+ for (let i = bm.length - 1; i >= 0; i--)+ for (let j = om.length - 1; j >= 0; j--)+ lcs[i * w + j] = bm[i] === om[j] ? lcs[(i + 1) * w + j + 1] + 1 : Math.max(lcs[(i + 1) * w + j], lcs[i * w + j + 1]);+ let i = 0, j = 0;+ while (i < bm.length || j < om.length) {+ if (i < bm.length && j < om.length && bm[i] === om[j]) { i++; j++; }+ else if (j < om.length && (i === bm.length || lcs[i * w + j + 1] >= lcs[(i + 1) * w + j])) { added[pre + i].push(om[j]); j++; }+ else { removed[pre + i] = true; i++; }+ }+ } else {+ for (let k = pre; k < pre + bm.length; k++) removed[k] = true;+ added[pre + bm.length] = om;+ }+ return { removed, added };}