Skip to content

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

Notes: lists typed as on the phone, a numbered list's start, table rows and columns added

Yashwanth Kamireddi65a78e0f8fb9
diff --git a/.uiverify/notes-autoformat.mjs b/.uiverify/notes-autoformat.mjs
new file mode 100644
index 0000000..131374f
--- /dev/null
+++ b/.uiverify/notes-autoformat.mjs
@@ -0,0 +1,72 @@
+// Lists typed as on the phone: "- " starts a dashed list, "* " a bulleted one, "1. " a
+// numbered one, and "[ ] " / "[x] " in a dashed line make a checklist item. The marker typed
+// goes, and the line takes the style Apple stores.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Notes");
+await page.locator(".note-row", { hasText: "Curtains" }).click();
+await page.locator(".note-rich .nf-p", { hasText: "Washing Machine cover" }).waitFor();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const styleOf = (text) => page.locator(".note-rich .nf-p", { hasText: text }).last().evaluate((p) => [p.dataset.style, p.dataset.checked ?? null, p.textContent]);
+
+// A fresh line after the note's last one, out of any list.
+await page.locator(".note-rich .nf-p").last().click();
+await page.keyboard.press("End");
+// Chromium tells the editor of a moved cursor a moment later; a key sent at once used the old one.
+await page.waitForTimeout(150);
+// Out of the note's own list: Return, then Return on the empty item ends the list.
+await page.keyboard.press("Enter");
+await page.keyboard.press("Enter");
+const plain = await page.evaluate(() => {
+ const sel = getSelection().anchorNode;
+ return (sel?.nodeType === 1 ? sel : sel?.parentElement)?.closest(".nf-p")?.dataset.style;
+});
+ok(plain === "none" || plain === "3", `starts on a plain line ${plain}`);
+
+await page.keyboard.type("- milk");
+let [style, , text] = await styleOf("milk");
+ok(style === "101" && text === "milk", `"- " makes a dashed list, the dash gone ${style} ${JSON.stringify(text)}`);
+
+await page.keyboard.press("Enter");
+await page.keyboard.type("[x] eggs");
+let checked;
+[style, checked, text] = await styleOf("eggs");
+ok(style === "103" && checked === "true" && text === "eggs", `"[x] " in a dashed line makes a ticked checklist item ${style} ${checked} ${JSON.stringify(text)}`);
+
+await page.keyboard.press("Enter");
+await page.keyboard.press("Enter");
+await page.keyboard.type("1. first");
+[style, , text] = await styleOf("first");
+ok(style === "102" && text === "first", `"1. " makes a numbered list ${style} ${JSON.stringify(text)}`);
+
+await page.keyboard.press("Enter");
+await page.keyboard.press("Enter");
+await page.keyboard.type("5. fifth");
+await page.keyboard.press("Enter");
+await page.keyboard.type("sixth");
+const counters = await page.locator(".note-rich .nf-p", { hasText: /fifth|sixth/ }).evaluateAll((ps) => ps.map((p) => [p.dataset.style, p.style.counterSet || ""]));
+ok(JSON.stringify(counters) === JSON.stringify([["102", "nf-num 5"], ["102", ""]]), `"5. " starts the list at 5; the next item counts on from it ${JSON.stringify(counters)}`);
+await page.waitForTimeout(1300);
+const saved = await page.evaluate(() => window.__noteSaves?.at(-1)?.runs?.filter((r) => r.start));
+ok(Array.isArray(saved) && saved.length === 1 && saved[0].start === 5, `and Apple is sent start 5, on that line only ${JSON.stringify(saved)}`);
+
+await page.keyboard.press("Enter");
+await page.keyboard.press("Enter");
+await page.keyboard.type("* dot");
+[style, , text] = await styleOf("dot");
+ok(style === "100" && text === "dot", `"* " makes a bulleted list ${style} ${JSON.stringify(text)}`);
+
+await page.keyboard.press("Enter");
+await page.keyboard.press("Enter");
+await page.keyboard.type("a - b");
+[style, , text] = await styleOf("a - b");
+ok(style !== "101" && text === "a - b", "a dash in the middle of a line is just a dash");
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/notes-table.mjs b/.uiverify/notes-table.mjs
index 742bc60..d614c3c 100644
--- a/.uiverify/notes-table.mjs
+++ b/.uiverify/notes-table.mjs
@@ -66,5 +66,17 @@ await page.keyboard.press("Enter");
await page.waitForTimeout(400);
const w2 = await page.evaluate(() => window.__cellWrites);
ok((await empty.textContent()) === "Bread" && w2?.length === 1 && w2[0].row === 2 && w2[0].column === 0 && w2[0].text === "Bread", `typing in an empty cell saves it ${JSON.stringify(w2)}`);
+// Right-click a cell: a row added below it, as Notes adds one.
+await page.locator(".nf-table tr").nth(1).locator("td").first().click({ button: "right" });
+await page.getByRole("menuitem", { name: "Add Row Below" }).click();
+await page.waitForTimeout(300);
+const grown = await page.locator(".nf-table tr").evaluateAll((rows) => rows.map((r) => [...r.cells].map((c) => c.textContent)));
+const asked = await page.evaluate(() => window.__rowAdds?.at(-1));
+ok(grown.length === 4 && grown[2].every((c) => c === "") && asked?.at === 2, `Add Row Below adds an empty row under the one clicked ${JSON.stringify(grown)} ${JSON.stringify(asked)}`);
+await page.locator(".nf-table tr").first().locator("td").nth(1).click({ button: "right" });
+await page.getByRole("menuitem", { name: "Add Column Before" }).click();
+await page.waitForTimeout(300);
+const wider = await page.locator(".nf-table tr").first().evaluate((r) => [...r.cells].map((c) => c.textContent));
+ok(JSON.stringify(wider) === JSON.stringify(["Item", "", "Qty"]), `Add Column Before adds an empty column before the one clicked ${JSON.stringify(wider)}`);
await b.close();
process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 20a8fc5..17b8452 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -300,6 +300,13 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
: { id: "M2", uti: "org.openxmlformats.spreadsheetml.sheet", kind: "file", filename: "Budget.xlsx", title: null, width: null, height: null, size: 9100, hasPreview: false };
case "note_attachment_open": (window.__opened ??= []).push(args.id); return null;
case "note_table": if (String(args.id).startsWith("M")) return null; return (window.__table ??= [["Item", "Qty"], ["Milk", "2"], ["", ""]]).map((r) => r.slice());
+ case "note_table_add_row": {
+ const t = (window.__table ??= [["Item", "Qty"], ["Milk", "2"], ["", ""]]);
+ if (args.column) t.forEach((r) => r.splice(args.at, 0, ""));
+ else t.splice(args.at, 0, t[0].map(() => ""));
+ (window.__rowAdds ??= []).push(args);
+ return t.map((r) => r.slice());
+ }
case "note_table_set_cell": {
(window.__cellWrites ??= []).push(args);
await new Promise((r) => setTimeout(r, 300));
diff --git a/check.sh b/check.sh
index a13bbca..8c0b3f5 100755
--- a/check.sh
+++ b/check.sh
@@ -52,6 +52,7 @@ step "contact labels" node .uiverify/contacts-labels.mjs
step "calendar go to date" node .uiverify/calendar-goto.mjs
step "calendar calendars" node .uiverify/calendar-collections.mjs
step "drive names" node .uiverify/drive-names.mjs
+step "notes autoformat" node .uiverify/notes-autoformat.mjs
step "empty today" node .uiverify/reminders-empty.mjs
step "calendar keys" node .uiverify/calendar-keys.mjs
step "reminders instant" node .uiverify/reminders-instant.mjs
@@ -86,6 +87,7 @@ step "webkit: labels" env ENGINE=webkit node .uiverify/contacts-labels.mjs
step "webkit: go to date" env ENGINE=webkit node .uiverify/calendar-goto.mjs
step "webkit: calendars" env ENGINE=webkit node .uiverify/calendar-collections.mjs
step "webkit: drive names" env ENGINE=webkit node .uiverify/drive-names.mjs
+step "webkit: autoformat" env ENGINE=webkit node .uiverify/notes-autoformat.mjs
step "webkit: row hover" env ENGINE=webkit node .uiverify/row-hover.mjs
step "webkit: fold" env ENGINE=webkit node .uiverify/sidebar-fold.mjs
step "reminder colours" node .uiverify/calendar-reminder-colour.mjs
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rs
index 0bfbec6..c3d0b69 100644
--- a/crates/quince-icloud/src/ckdocument.rs
+++ b/crates/quince-icloud/src/ckdocument.rs
@@ -984,6 +984,11 @@ pub fn set_runs(original: &[u8], runs: &[Run]) -> Option<Vec<u8>> {
} else {
without_field(&p, 4)?
};
+ // Where a numbered list starts, on its line only, as Notes keeps it.
+ p = match para.start {
+ Some(n) if para.style == Some(102) && n != 1 => set_varint_field(&p, 7, n)?,
+ _ => without_field(&p, 7)?,
+ };
if para.style == Some(103) {
let item = match &paragraph_item {
Some((e, item)) if *e == end => item.clone(),
@@ -1692,6 +1697,10 @@ pub struct Run {
pub style: Option<u64>,
pub indent: u64,
pub checked: Option<bool>,
+ /// The number a numbered list starts at, when not 1 (paragraph field 7,
+ /// `startingListItemNumber`, set on the list's first item).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub start: Option<u64>,
pub bold: bool,
pub italic: bool,
pub underline: bool,
@@ -1764,6 +1773,7 @@ fn parse_paragraph(bytes: &[u8], run: &mut Run) -> Option<()> {
match (field, wire) {
(1, WIRE_VARINT) => run.style = Some(reader.varint()?),
(4, WIRE_VARINT) => run.indent = reader.varint()?,
+ (7, WIRE_VARINT) => run.start = Some(reader.varint()?).filter(|&n| n != 1),
(5, WIRE_LEN) => {
let n = usize::try_from(reader.varint()?).ok()?;
let mut item = Reader::new(reader.take(n)?);
@@ -2777,6 +2787,30 @@ mod run_tests {
assert!(cleared.iter().all(|r| r.emphasis.is_none()));
}
+ /// A numbered list starting at 5 (paragraph field 7) is read, kept through a save, and
+ /// dropped when the line stops being numbered.
+ #[test]
+ fn a_numbered_lists_start_is_read_kept_and_dropped() {
+ let mut para = Vec::new();
+ varint(1 << 3, &mut para);
+ varint(102, &mut para);
+ varint(7 << 3, &mut para);
+ varint(5, &mut para);
+ let mut extra = Vec::new();
+ len_field(2, &para, &mut extra);
+ let doc = doc_with("five\n", &[(5, extra)]);
+ let read = runs_from_base64(&B64.encode(&doc));
+ assert_eq!((read[0].style, read[0].start), (Some(102), Some(5)));
+ let kept = runs_from_base64(&B64.encode(set_runs(&doc, &read).unwrap()));
+ assert_eq!(kept[0].start, Some(5), "a save dropped the start");
+ let plain = vec![Run {
+ style: None,
+ ..read[0].clone()
+ }];
+ let cleared = runs_from_base64(&B64.encode(set_runs(&doc, &plain).unwrap()));
+ assert_eq!(cleared[0].start, None, "a plain line kept a list's start");
+ }
+
/// A style is the line's: one set on half a line covers all of it, from its newline.
#[test]
fn a_paragraph_style_covers_its_whole_line() {
diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rs
index 7485842..9862ead 100644
--- a/crates/quince-icloud/src/notes.rs
+++ b/crates/quince-icloud/src/notes.rs
@@ -2453,6 +2453,59 @@ mod derived_title_tests {
/// written over. Only a cell already typed in can be changed — see
/// [`crate::table::with_cell`] — and a table this cannot rewrite exactly is refused, not
/// written. Answers the cells as Apple now holds them.
+pub async fn add_table_row_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ attachment: &str,
+ at: usize,
+) -> Result<Vec<Vec<String>>> {
+ add_table_line_cloudkit(http, ckdatabasews_root, params, attachment, false, at).await
+}
+
+/// A table with an empty row (`column` false) or column added at `at`, written against Apple's
+/// exact version as a cell edit is, and read back.
+pub async fn add_table_line_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ attachment: &str,
+ column: bool,
+ at: usize,
+) -> Result<Vec<Vec<String>>> {
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ client
+ .edit_record(ZONE, attachment, "Attachment", |record| {
+ let current = record
+ .pointer("/fields/MergeableDataEncrypted/value")?
+ .as_str()?;
+ let edited = if column {
+ crate::table::with_column_in_base64(current, at)?
+ } else {
+ crate::table::with_row_in_base64(current, at)?
+ };
+ Some(serde_json::json!({
+ "MergeableDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": edited }
+ }))
+ })
+ .await?
+ .ok_or_else(|| {
+ Error::Refused(format!(
+ "A {} can’t be added to this table here: it holds something Quince can’t rewrite exactly.",
+ if column { "column" } else { "row" }
+ ))
+ })?;
+ client
+ .lookup_record(ZONE, attachment)
+ .await?
+ .ok_or(Error::NotFound)?
+ .pointer("/fields/MergeableDataEncrypted/value")
+ .and_then(Value::as_str)
+ .and_then(crate::table::cells_from_base64)
+ .ok_or_else(|| Error::Protocol("Apple kept a table this cannot read back".into()))
+}
+
+/// A table cell set to `text`.
pub async fn set_table_cell_cloudkit(
http: &reqwest::Client,
ckdatabasews_root: &str,
@@ -2475,9 +2528,7 @@ pub async fn set_table_cell_cloudkit(
})
.await?
.ok_or_else(|| {
- Error::Refused(
- "That cell can’t be changed here yet — only cells already typed in can.".into(),
- )
+ Error::Refused("That cell can’t be changed here: this table holds something Quince can’t rewrite exactly.".into())
})?;
// Apple's answer to the write does not carry the table back (measured), so what it now
// holds is read from it.
diff --git a/crates/quince-icloud/src/table.rs b/crates/quince-icloud/src/table.rs
index 1af1ec0..f383648 100644
--- a/crates/quince-icloud/src/table.rs
+++ b/crates/quince-icloud/src/table.rs
@@ -344,10 +344,431 @@ pub fn with_cell(document: &[u8], row: usize, column: usize, text: &str) -> Opti
(read.get(row)?.get(column)? == text).then_some(out)
}
+/// Each field of a message with its whole encoding (key, length and payload), in order.
+fn raw_fields(b: &[u8]) -> Option<Vec<(u64, &[u8])>> {
+ let mut out = Vec::new();
+ let mut at = 0;
+ while at < b.len() {
+ let start = at;
+ let (key, next) = varint(b, at)?;
+ at = next;
+ match key & 7 {
+ 0 => at = varint(b, at)?.1,
+ 2 => {
+ let (n, next) = varint(b, at)?;
+ at = next.checked_add(usize::try_from(n).ok()?)?;
+ b.get(..at)?;
+ }
+ 1 => at = at.checked_add(8).filter(|&e| e <= b.len())?,
+ 5 => at = at.checked_add(4).filter(|&e| e <= b.len())?,
+ _ => return None,
+ }
+ out.push((key >> 3, b.get(start..at)?));
+ }
+ Some(out)
+}
+
+fn put_len(tag: u64, payload: &[u8], out: &mut Vec<u8>) {
+ put_varint((tag << 3) | 2, out);
+ put_varint(payload.len() as u64, out);
+ out.extend_from_slice(payload);
+}
+
+fn put_int(tag: u64, v: u64, out: &mut Vec<u8>) {
+ put_varint(tag << 3, out);
+ put_varint(v, out);
+}
+
+fn object_id(index: usize) -> Vec<u8> {
+ let mut id = Vec::new();
+ put_int(6, index as u64, &mut id);
+ id
+}
+
+/// A dictionary element as Apple writes one: key and value objects, stamped by one replica.
+fn dictionary_element(key: usize, value: usize, replica: u64, clock: u64) -> Vec<u8> {
+ let mut stamp_one = Vec::new();
+ put_int(1, replica, &mut stamp_one);
+ put_int(2, clock, &mut stamp_one);
+ let mut stamp = Vec::new();
+ put_len(1, &stamp_one, &mut stamp);
+ let mut e = Vec::new();
+ put_len(1, &object_id(key), &mut e);
+ put_len(2, &object_id(value), &mut e);
+ put_len(3, &stamp, &mut e);
+ e
+}
+
+/// An `NSUUID` custom object naming uuid number `uuid_index`, in the shape `template` (an
+/// existing one) has.
+fn nsuuid_object(template: &[u8], uuid_index: usize) -> Option<Vec<u8>> {
+ let custom = bytes(&fields(template)?, 13).next()?;
+ let cf = fields(custom)?;
+ let entry = bytes(&cf, 3).next()?;
+ let ef = fields(entry)?;
+ let mut value = Vec::new();
+ put_int(2, uuid_index as u64, &mut value);
+ let mut new_entry = Vec::new();
+ put_int(1, int(&ef, 1)?, &mut new_entry);
+ put_len(2, &value, &mut new_entry);
+ let mut new_custom = Vec::new();
+ put_int(1, int(&cf, 1)?, &mut new_custom);
+ put_len(3, &new_entry, &mut new_custom);
+ let mut object = Vec::new();
+ put_len(13, &new_custom, &mut object);
+ Some(object)
+}
+
+/// The table's document with an empty row added at `at` (0 is the top), as Notes adds one:
+/// a new member of the ordered row set, written as this installation's replica, and an
+/// empty text in every column so its cells can be typed in at once.
+///
+/// Nothing is returned unless it is proven: the pieces this writes are first rebuilt from
+/// the table's own and must come out byte for byte as Apple wrote them, and the result must
+/// read back as the same grid with one empty row at `at`.
+#[must_use]
+pub fn with_row(document: &[u8], at: usize) -> Option<Vec<u8>> {
+ with_member(document, false, at)
+}
+
+/// The table's document with an empty column added at `at` (0 is the leading edge), as Notes
+/// adds one: a new member of the ordered column set and an empty text in it for every row,
+/// proven as [`with_row`] is.
+#[must_use]
+pub fn with_column(document: &[u8], at: usize) -> Option<Vec<u8>> {
+ with_member(document, true, at)
+}
+
+fn with_member(document: &[u8], column: bool, at: usize) -> Option<Vec<u8>> {
+ let before = cells(document)?;
+ let width = before.first().map_or(0, Vec::len);
+ let count = if column { width } else { before.len() };
+ if at > count {
+ return None;
+ }
+ let top = fields(document)?;
+ let version_bytes = bytes(&top, 2).next()?;
+ let version = fields(version_bytes)?;
+ let data_bytes = bytes(&version, 3).next()?;
+ let data = fields(data_bytes)?;
+ let objects: Vec<&[u8]> = bytes(&data, 3).collect();
+ let uuids: Vec<&[u8]> = bytes(&data, 6).collect();
+ let doc = Doc {
+ objects: objects.clone(),
+ keys: bytes(&data, 4)
+ .map(|k| String::from_utf8_lossy(k).into_owned())
+ .collect(),
+ uuids: uuids.clone(),
+ };
+ let root = doc.custom(0)?;
+ let at_key = |name: &str| root.get(name).and_then(|id| object_index(id));
+ let rows_object = at_key(if column { "crColumns" } else { "crRows" })?;
+ let cells_object = at_key("cellColumns")?;
+
+ // This installation as a replica of the document, and the clock its writes carry.
+ let me = crate::topotext::writer_bytes();
+ let mut new_uuids: Vec<Vec<u8>> = Vec::new();
+ let replica = match uuids.iter().position(|u| *u == me) {
+ Some(i) => i,
+ None => {
+ new_uuids.push(me.to_vec());
+ uuids.len()
+ }
+ };
+ let versions: Vec<(u64, u64)> = bytes(&fields(bytes(&data, 1).next()?)?, 1)
+ .filter_map(|e| {
+ let f = fields(e)?;
+ Some((int(&f, 1).unwrap_or(0), int(&f, 2).unwrap_or(0)))
+ })
+ .collect();
+ let clock = versions
+ .iter()
+ .find(|(r, _)| *r == replica as u64)
+ .map_or(1, |(_, c)| c + 1);
+
+ // The new row's element and identity: two uuids and an NSUUID object for each.
+ let template = (0..objects.len()).find_map(|i| {
+ let entries = doc.custom(i)?;
+ entries.contains_key("UUIDIndex").then_some(objects[i])
+ })?;
+ // Proof the NSUUID shape is Apple's: an existing one rebuilt comes out the same.
+ let template_index = usize::try_from(int(
+ &fields(
+ bytes(
+ &fields(bytes(&fields(bytes(&fields(template)?, 13).next()?)?, 3).next()?)?,
+ 2,
+ )
+ .next()?,
+ )?,
+ 2,
+ )?)
+ .ok()?;
+ if nsuuid_object(template, template_index)? != template {
+ return None;
+ }
+ let element_uuid = *uuid::Uuid::new_v4().as_bytes();
+ let identity_uuid = *uuid::Uuid::new_v4().as_bytes();
+ let element_uuid_index = uuids.len() + new_uuids.len();
+ new_uuids.push(element_uuid.to_vec());
+ new_uuids.push(identity_uuid.to_vec());
+ let element_object = objects.len();
+ let identity_object = objects.len() + 1;
+ let mut new_objects = vec![
+ nsuuid_object(template, element_uuid_index)?,
+ nsuuid_object(template, element_uuid_index + 1)?,
+ ];
+
+ // The ordered row set: the text gains a character at `at`, the attachments make room for
+ // it, and the element joins both dictionaries.
+ let (kind, set_body) = doc.object(rows_object)?;
+ if kind != 16 {
+ return None;
+ }
+ let set_fields = raw_fields(set_body)?;
+ let sf = fields(set_body)?;
+ let array_body = bytes(&sf, 1).next()?;
+ let af = fields(array_body)?;
+ let string_array = bytes(&af, 1).next()?;
+ let saf = fields(string_array)?;
+ let text = bytes(&saf, 1).next()?;
+ let live = count;
+ let old_text: String = std::iter::repeat_n('\u{FFFC}', live).collect();
+ let mut new_text = old_text.clone();
+ let byte_at = old_text
+ .char_indices()
+ .nth(at)
+ .map_or(old_text.len(), |(i, _)| i);
+ new_text.insert(byte_at, '\u{FFFC}');
+ let new_string = crate::ckdocument::rewrite_text_object(text, &old_text, &new_text)?;
+ let mut attachments: Vec<(u64, Vec<u8>)> = Vec::new();
+ for a in bytes(&saf, 2) {
+ let f = fields(a)?;
+ let index = int(&f, 1).unwrap_or(0);
+ attachments.push((
+ if index >= at as u64 { index + 1 } else { index },
+ bytes(&f, 2).next()?.to_vec(),
+ ));
+ }
+ attachments.push((at as u64, element_uuid.to_vec()));
+ attachments.sort_by_key(|(i, _)| *i);
+ let mut new_string_array = Vec::new();
+ for (tag, raw) in raw_fields(string_array)? {
+ match tag {
+ 1 => put_len(1, &new_string, &mut new_string_array),
+ 2 => {}
+ _ => new_string_array.extend_from_slice(raw),
+ }
+ }
+ for (index, uuid) in &attachments {
+ let mut a = Vec::new();
+ put_int(1, *index, &mut a);
+ put_len(2, uuid, &mut a);
+ put_len(2, &a, &mut new_string_array);
+ }
+ let with_element = |dictionary: &[u8], value: usize| -> Option<Vec<u8>> {
+ // Proof the element shape is Apple's: the dictionary's last element, rebuilt from its
+ // key and value with its own stamp copied, is the same.
+ if let Some(last) = bytes(&fields(dictionary)?, 1).last() {
+ let f = fields(last)?;
+ let mut rebuilt = Vec::new();
+ put_len(
+ 1,
+ &object_id(object_index(bytes(&f, 1).next()?)?),
+ &mut rebuilt,
+ );
+ put_len(
+ 2,
+ &object_id(object_index(bytes(&f, 2).next()?)?),
+ &mut rebuilt,
+ );
+ put_len(3, bytes(&f, 3).next()?, &mut rebuilt);
+ if rebuilt != last {
+ return None;
+ }
+ }
+ let mut out = dictionary.to_vec();
+ put_len(
+ 1,
+ &dictionary_element(element_object, value, replica as u64, clock),
+ &mut out,
+ );
+ Some(out)
+ };
+ let mut new_array = Vec::new();
+ for (tag, raw) in raw_fields(array_body)? {
+ match tag {
+ 1 => put_len(1, &new_string_array, &mut new_array),
+ 2 => put_len(
+ 2,
+ &with_element(bytes(&fields(raw)?, 2).next()?, identity_object)?,
+ &mut new_array,
+ ),
+ _ => new_array.extend_from_slice(raw),
+ }
+ }
+ let mut new_set = Vec::new();
+ for (tag, raw) in set_fields {
+ match tag {
+ 1 => put_len(1, &new_array, &mut new_set),
+ 2 => put_len(
+ 2,
+ &with_element(bytes(&fields(raw)?, 2).next()?, element_object)?,
+ &mut new_set,
+ ),
+ _ => new_set.extend_from_slice(raw),
+ }
+ }
+ let mut new_rows_object = Vec::new();
+ put_len(16, &new_set, &mut new_rows_object);
+
+ // An empty text in each new cell, in the shape a phone gives an empty cell.
+ let empty_cell = (0..objects.len())
+ .find(|&i| doc.object(i).is_some_and(|(k, _)| k == 10) && doc.text(i).is_empty())?;
+ let (cells_kind, cells_body) = doc.object(cells_object)?;
+ let by_column = Doc::dictionary(cells_body)?;
+ let mut changed_objects: HashMap<usize, Vec<u8>> = HashMap::new();
+ if column {
+ // A dictionary for the new column, a cell in it for every row, and the column in
+ // `cellColumns`.
+ let row_identities = doc.ordered(at_key("crRows")?, &doc.uuid_objects())?;
+ let column_dictionary = objects.len() + new_objects.len();
+ new_objects.push(Vec::new()); // filled once its cells have places
+ let mut dictionary = Vec::new();
+ for row in row_identities {
+ let cell = objects.len() + new_objects.len();
+ new_objects.push(objects[empty_cell].to_vec());
+ put_len(
+ 1,
+ &dictionary_element(row, cell, replica as u64, clock),
+ &mut dictionary,
+ );
+ }
+ let mut object = Vec::new();
+ put_len(6, &dictionary, &mut object);
+ new_objects[column_dictionary - objects.len()] = object;
+ let mut grown = with_element(cells_body, column_dictionary)?;
+ // `with_element` keys the element by the new member's element object; `cellColumns`
+ // is keyed by its identity.
+ grown.truncate(cells_body.len());
+ put_len(
+ 1,
+ &dictionary_element(identity_object, column_dictionary, replica as u64, clock),
+ &mut grown,
+ );
+ let mut object = Vec::new();
+ put_len(cells_kind, &grown, &mut object);
+ changed_objects.insert(cells_object, object);
+ } else {
+ for &column_dictionary in by_column.values() {
+ let (k, body) = doc.object(column_dictionary)?;
+ if k != 6 {
+ return None;
+ }
+ let cell = objects.len() + new_objects.len();
+ new_objects.push(objects[empty_cell].to_vec());
+ let mut dictionary = body.to_vec();
+ put_len(
+ 1,
+ &dictionary_element(identity_object, cell, replica as u64, clock),
+ &mut dictionary,
+ );
+ let mut object = Vec::new();
+ put_len(6, &dictionary, &mut object);
+ changed_objects.insert(column_dictionary, object);
+ }
+ }
+
+ // The document: changed objects in place, new ones and new uuids after the last of their
+ // kind, and this replica's clock raised.
+ // Every other replica's entry copied as it is (some carry a subclock); this one's set.
+ let mut new_version_vector = Vec::new();
+ let mut seen_me = false;
+ for (_, raw) in raw_fields(bytes(&data, 1).next()?)? {
+ let f = fields(bytes(&fields(raw)?, 1).next()?)?;
+ if int(&f, 1).unwrap_or(0) == replica as u64 {
+ let mut e = Vec::new();
+ put_int(1, replica as u64, &mut e);
+ put_int(2, clock, &mut e);
+ put_len(1, &e, &mut new_version_vector);
+ seen_me = true;
+ } else {
+ new_version_vector.extend_from_slice(raw);
+ }
+ }
+ if !seen_me {
+ let mut e = Vec::new();
+ put_int(1, replica as u64, &mut e);
+ put_int(2, clock, &mut e);
+ put_len(1, &e, &mut new_version_vector);
+ }
+ let raw = raw_fields(data_bytes)?;
+ let last_object = raw.iter().rposition(|(t, _)| *t == 3)?;
+ let last_uuid = raw.iter().rposition(|(t, _)| *t == 6)?;
+ let mut new_data = Vec::with_capacity(data_bytes.len() + 512);
+ let mut object_n = 0usize;
+ for (i, (tag, field)) in raw.iter().enumerate() {
+ match *tag {
+ 1 => put_len(1, &new_version_vector, &mut new_data),
+ 3 => {
+ if object_n == rows_object {
+ put_len(3, &new_rows_object, &mut new_data);
+ } else if let Some(o) = changed_objects.get(&object_n) {
+ put_len(3, o, &mut new_data);
+ } else {
+ new_data.extend_from_slice(field);
+ }
+ object_n += 1;
+ }
+ _ => new_data.extend_from_slice(field),
+ }
+ if i == last_object {
+ for o in &new_objects {
+ put_len(3, o, &mut new_data);
+ }
+ }
+ if i == last_uuid {
+ for u in &new_uuids {
+ put_len(6, u, &mut new_data);
+ }
+ }
+ }
+ let new_version = splice(version_bytes, 3, 0, &new_data)?;
+ let out = splice(document, 2, 0, &new_version)?;
+
+ // And it reads back as the same table with one empty row or column at `at`.
+ let mut expected = before;
+ if column {
+ for row in &mut expected {
+ row.insert(at, String::new());
+ }
+ } else {
+ expected.insert(at, vec![String::new(); width]);
+ }
+ (cells(&out)? == expected).then_some(out)
+}
+
/// [`with_cell`] over the attachment's `MergeableDataEncrypted` as Apple sends it (base64,
/// compressed), answered in the same compression it came in.
#[must_use]
pub fn with_cell_in_base64(value: &str, row: usize, column: usize, text: &str) -> Option<String> {
+ edit_in_base64(value, |plain| with_cell(plain, row, column, text))
+}
+
+/// [`with_row`] over the attachment's `MergeableDataEncrypted` as Apple sends it, answered in
+/// the same compression it came in.
+#[must_use]
+pub fn with_row_in_base64(value: &str, at: usize) -> Option<String> {
+ edit_in_base64(value, |plain| with_row(plain, at))
+}
+
+/// [`with_column`] over the attachment's `MergeableDataEncrypted` as Apple sends it.
+#[must_use]
+pub fn with_column_in_base64(value: &str, at: usize) -> Option<String> {
+ edit_in_base64(value, |plain| with_column(plain, at))
+}
+
+/// A table edit made to the inflated document, packed back as it came: gzip, zlib or plain.
+fn edit_in_base64(value: &str, edit: impl FnOnce(&[u8]) -> Option<Vec<u8>>) -> Option<String> {
use base64::Engine;
use std::io::Write;
let raw = base64::engine::general_purpose::STANDARD
@@ -355,7 +776,7 @@ pub fn with_cell_in_base64(value: &str, row: usize, column: usize, text: &str) -
.ok()?;
let gz = raw.starts_with(&[0x1f, 0x8b]);
let plain = inflate(&raw)?;
- let edited = with_cell(&plain, row, column, text)?;
+ let edited = edit(&plain)?;
let packed = if gz {
let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
e.write_all(&edited).ok()?;
diff --git a/crates/quince-icloud/src/topotext.rs b/crates/quince-icloud/src/topotext.rs
index 9c8f600..ca4e9a5 100644
--- a/crates/quince-icloud/src/topotext.rs
+++ b/crates/quince-icloud/src/topotext.rs
@@ -42,6 +42,11 @@ pub fn writer_id() -> String {
uuid::Uuid::from_bytes(writer()).to_string().to_uppercase()
}
+/// This installation's writer id as bytes, for the CRDT writers beside the text's own.
+pub(crate) fn writer_bytes() -> [u8; 16] {
+ writer()
+}
+
fn writer() -> [u8; 16] {
*WRITER.get_or_init(|| *uuid::Uuid::new_v4().as_bytes())
}
diff --git a/probe/examples/table_row_live.rs b/probe/examples/table_row_live.rs
new file mode 100644
index 0000000..984df76
--- /dev/null
+++ b/probe/examples/table_row_live.rs
@@ -0,0 +1,62 @@
+//! Live, on a throwaway table only: rows added at the top and at the end, a column in the
+//! middle, read back from Apple, and the new row and column typed in. Refuses any attachment one of his notes still uses
+//! outside Recently Deleted (checked by the caller against the local library first).
+use anyhow::{anyhow, Result};
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let id = std::env::args()
+ .nth(1)
+ .ok_or_else(|| anyhow!("attachment id"))?;
+ 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 ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let before = quince_icloud::table::cells_from_base64(
+ quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone())
+ .lookup_record("Notes", &id)
+ .await?
+ .ok_or_else(|| anyhow!("gone"))?["fields"]["MergeableDataEncrypted"]["value"]
+ .as_str()
+ .unwrap_or(""),
+ )
+ .ok_or_else(|| anyhow!("not a table"))?;
+ println!("before: {before:?}");
+ let top = quince_icloud::notes::add_table_row_cloudkit(&http, &root, p.clone(), &id, 0).await?;
+ println!("row at top, Apple holds: {top:?}");
+ let end = quince_icloud::notes::add_table_row_cloudkit(&http, &root, p.clone(), &id, top.len())
+ .await?;
+ println!("row at end, Apple holds: {end:?}");
+ let typed = quince_icloud::notes::set_table_cell_cloudkit(
+ &http,
+ &root,
+ p.clone(),
+ &id,
+ 0,
+ 0,
+ "Quince row test",
+ )
+ .await?;
+ println!("typed in the new top row: {typed:?}");
+ let col = quince_icloud::notes::add_table_line_cloudkit(&http, &root, p.clone(), &id, true, 1)
+ .await?;
+ println!("column at 1, Apple holds: {col:?}");
+ let typed = quince_icloud::notes::set_table_cell_cloudkit(
+ &http,
+ &root,
+ p.clone(),
+ &id,
+ 0,
+ 1,
+ "Quince column test",
+ )
+ .await?;
+ println!("typed in the new column: {typed:?}");
+ Ok(())
+}
diff --git a/probe/examples/table_row_offline.rs b/probe/examples/table_row_offline.rs
new file mode 100644
index 0000000..f85a26a
--- /dev/null
+++ b/probe/examples/table_row_offline.rs
@@ -0,0 +1,60 @@
+//! Offline: a row added to saved copies of his tables, in memory only, never sent. For each
+//! table, a row at the top, the middle and the end must read back as the same grid with an
+//! empty row there, and its first cell must take text.
+fn main() {
+ for path in std::env::args().skip(1) {
+ let doc = std::fs::read(&path).expect("read");
+ let name = std::path::Path::new(&path)
+ .file_stem()
+ .unwrap()
+ .to_string_lossy()[..8]
+ .to_string();
+ let Some(grid) = quince_icloud::table::cells(&doc) else {
+ println!("{name}: not a table this reads");
+ continue;
+ };
+ let width = grid.first().map_or(0, Vec::len);
+ for at in [0, width / 2, width] {
+ let out = quince_icloud::table::with_column(&doc, at);
+ let typed = out
+ .as_deref()
+ .and_then(|o| quince_icloud::table::with_cell(o, 0, at, "col"));
+ let back = typed.as_deref().and_then(quince_icloud::table::cells);
+ println!(
+ "{name}: column at {at} {}; typing in it: {}",
+ if out.is_some() { "ok" } else { "REFUSED" },
+ match back {
+ Some(b) if b[0][at] == "col" && b.iter().all(|r| r.len() == width + 1) =>
+ "reads back",
+ Some(_) => "WRONG",
+ None => "REFUSED",
+ }
+ );
+ }
+ for at in [0, grid.len() / 2, grid.len()] {
+ match quince_icloud::table::with_row(&doc, at) {
+ None => println!(
+ "{name} {}x{}: row at {at} REFUSED",
+ grid.len(),
+ grid.first().map_or(0, Vec::len)
+ ),
+ Some(out) => {
+ let typed = quince_icloud::table::with_cell(&out, at, 0, "new");
+ let back = typed.as_deref().and_then(quince_icloud::table::cells);
+ println!(
+ "{name} {}x{}: row at {at} ok ({} → {} bytes); typing in it: {}",
+ grid.len(),
+ grid.first().map_or(0, Vec::len),
+ doc.len(),
+ out.len(),
+ match back {
+ Some(b) if b[at][0] == "new" => "reads back",
+ Some(_) => "WRONG",
+ None => "REFUSED",
+ }
+ );
+ }
+ }
+ }
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 811199f..fa34471 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1575,6 +1575,37 @@ async fn note_runs(guid: String, data: State<'_, Data>) -> UiResult<serde_json::
}
/// A table's cells, row by row, as the last pass read them — `None` when none are known.
+/// Add an empty row to a Notes table at `at` (0 is the top), as Notes does, and keep the
+/// table as Apple now holds it.
+#[tauri::command]
+async fn note_table_add_row(
+ id: String,
+ at: usize,
+ column: Option<bool>,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<Vec<Vec<String>>> {
+ let (http, root, params) = cloudkit_context(&auth).await?;
+ let cells = quince_icloud::notes::add_table_line_cloudkit(
+ &http,
+ &root,
+ params,
+ &id,
+ column.unwrap_or(false),
+ at,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ if let Ok(json) = serde_json::to_string(&cells) {
+ data.0
+ .lock()
+ .await
+ .set_state(&quince_icloud::table::state_key(&id), &json)
+ .map_err(|e| e.to_string())?;
+ }
+ Ok(cells)
+}
+
/// Change one cell of a Notes table, and keep the table as Apple now holds it.
#[tauri::command]
async fn note_table_set_cell(
@@ -3612,6 +3643,7 @@ fn main() {
note_runs,
note_table,
note_table_set_cell,
+ note_table_add_row,
note_attachment_info,
note_attachment_open,
diagnostics_save,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index f7919e2..810af37 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -141,6 +141,10 @@ export const api = {
noteAttachmentOpen: (id: string) => invoke<void>("note_attachment_open", { id }),
noteTableSetCell: (id: string, row: number, column: number, text: string) =>
invoke<string[][]>("note_table_set_cell", { id, row, column, text }),
+ /** An empty row added at `at` (0 the top); answers the table as Apple now holds it. */
+ noteTableAddRow: (id: string, at: number) => invoke<string[][]>("note_table_add_row", { id, at, column: false }),
+ /** An empty column added at `at` (0 the leading edge). */
+ noteTableAddColumn: (id: string, at: number) => invoke<string[][]>("note_table_add_row", { id, at, column: true }),
noteRuns: (guid: string) => invoke<import("../screens/notes/Formatted").Run[]>("note_runs", { guid }),
noteFolderCreate: (title: string, parent: string | null) =>
invoke<string>("note_folder_create", { title, parent }),
diff --git a/src/screens/notes/Formatted.tsx b/src/screens/notes/Formatted.tsx
index 5540e26..3023ee0 100644
--- a/src/screens/notes/Formatted.tsx
+++ b/src/screens/notes/Formatted.tsx
@@ -13,6 +13,8 @@ export type Run = {
style: number | null;
indent: number;
checked: boolean | null;
+ /** Where a numbered list starts, when not 1: set on its first item. */
+ start?: number | null;
bold: boolean;
italic: boolean;
underline: boolean;
@@ -140,7 +142,7 @@ export function FormattedBody({
<div className="note-formatted">
{all.map((p, i) => {
const style = p.run?.style ?? STYLE.body;
- number = style === STYLE.numbered ? number + 1 : 0;
+ number = style === STYLE.numbered ? (p.run?.start ?? number + 1) : 0;
const indent = { paddingInlineStart: `${(p.run?.indent ?? 0) * 1.5}em` };
const at = { "data-start": p.start } as Record<string, number>;
const content = p.spans.length ? p.spans.map((s, j) => <Inline key={j} span={s} />) : <br />;
diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsx
index 89a494e..536153b 100644
--- a/src/screens/notes/NoteEditor.tsx
+++ b/src/screens/notes/NoteEditor.tsx
@@ -1,5 +1,5 @@
import "prosemirror-view/style/prosemirror.css";
-import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
+import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import { EditorState, TextSelection, type Command, type Transaction } from "prosemirror-state";
import { EditorView } from "prosemirror-view";
import { history, undo, redo } from "prosemirror-history";
@@ -9,6 +9,11 @@ import type { Node as PMNode } from "prosemirror-model";
import type { Run } from "./Formatted";
import { fromDoc, LIST_STYLES, schema, STYLE, tableCells, toDoc } from "./rich";
import { api, noteMediaSrc, type NoteAttachment } from "../../lib/ipc";
+import { RowMenu, type MenuEntry } from "../../components/RowMenu";
+
+/** A table's right-click menu: drawn by the editor that holds the table, opened by a cell. */
+type CellMenu = { at: { x: number; y: number; alignRight: boolean }; entries: MenuEntry[] };
+let openCellMenu: ((menu: CellMenu) => void) | null = null;
/**
* An attachment in the note: a table drawn as the grid it is, with the cells Apple holds;
@@ -122,6 +127,27 @@ function attachmentView(node: PMNode) {
td.className = "nf-cell-empty";
return;
}
+ // Right-click, as in Notes: a row added above or below this one.
+ td.addEventListener("contextmenu", (e) => {
+ e.preventDefault();
+ const add = (at: number, column = false) => () => {
+ dom.classList.add("is-saving");
+ (column ? api.noteTableAddColumn(id, at) : api.noteTableAddRow(id, at)).then(
+ (next) => { dom.classList.remove("is-saving"); draw(next); },
+ (err) => { dom.classList.remove("is-saving"); dom.title = String(err); },
+ );
+ };
+ openCellMenu?.({
+ at: { x: e.clientX, y: e.clientY, alignRight: false },
+ entries: [
+ { label: "Add Row Above", run: add(r) },
+ { label: "Add Row Below", run: add(r + 1) },
+ null,
+ { label: "Add Column Before", run: add(c, true) },
+ { label: "Add Column After", run: add(c + 1, true) },
+ ],
+ });
+ });
const field = document.createElement("div");
field.className = "nf-cell-edit";
field.contentEditable = "plaintext-only";
@@ -279,7 +305,8 @@ const enter: Command = (state, dispatch) => {
return splitBlockAs((node, atEnd) => {
const style = node.attrs.style as number | null;
if (LIST_STYLES.includes(style as number)) {
- return { type: schema.nodes.paragraph, attrs: { ...node.attrs, checked: style === STYLE.checklist ? false : null } };
+ // The next item counts on from this one; only a list's first item holds where it starts.
+ return { type: schema.nodes.paragraph, attrs: { ...node.attrs, checked: style === STYLE.checklist ? false : null, start: null } };
}
if (atEnd && (style === STYLE.title || style === STYLE.heading || style === STYLE.subheading)) {
return { type: schema.nodes.paragraph, attrs: { style: null, indent: 0, checked: null } };
@@ -414,6 +441,33 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
if (tr.docChanged) reportSoon();
callbacks.current.onStatus?.(statusOf(next));
},
+ // Lists typed as on the phone: "- " a dashed list, "* " a bulleted one, "1. " a numbered
+ // one; in a dashed line "[ ] " or "[x] " makes it a checklist item, so "- [ ] " works
+ // (icloud.com's notes3 userDidInsert). The typed marker goes; one undo brings it back.
+ handleTextInput(view, from, to, text) {
+ if (text !== " " || from !== to) return false;
+ const $from = view.state.doc.resolve(from);
+ const line = $from.parent;
+ if (line.type !== schema.nodes.paragraph) return false;
+ const typed = line.textBetween(0, $from.parentOffset, undefined, "\ufffc") + " ";
+ const style = line.attrs.style as number | null;
+ const inList = style !== null && LIST_STYLES.includes(style);
+ let next: { style: number; checked: boolean | null; start?: number | null } | null = null;
+ const numbered = /^([0-9]{1,6})\. $/.exec(typed);
+ if (style === STYLE.dashed && (typed === "[ ] " || typed === "[x] ")) {
+ next = { style: STYLE.checklist, checked: typed === "[x] " };
+ } else if (!inList) {
+ if (typed === "- ") next = { style: STYLE.dashed, checked: null };
+ else if (typed === "* ") next = { style: STYLE.bulleted, checked: null };
+ // "5. " starts the list at 5, as Notes keeps it.
+ else if (numbered) next = { style: STYLE.numbered, checked: null, start: Number(numbered[1]) === 1 ? null : Number(numbered[1]) };
+ }
+ if (!next) return false;
+ const tr = view.state.tr.delete($from.start(), from);
+ tr.setNodeMarkup($from.before(), undefined, { ...line.attrs, style: next.style, checked: next.checked, start: next.start ?? null });
+ view.dispatch(tr.scrollIntoView());
+ return true;
+ },
handleDOMEvents: {
blur: () => {
if (later.current !== null) report();
@@ -496,7 +550,20 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
},
}));
- return <div ref={host} className="note-rich-host" />;
+ const [cellMenu, setCellMenu] = useState<CellMenu | null>(null);
+ useEffect(() => {
+ openCellMenu = setCellMenu;
+ return () => {
+ if (openCellMenu === setCellMenu) openCellMenu = null;
+ };
+ }, []);
+
+ return (
+ <>
+ <div ref={host} className="note-rich-host" />
+ {cellMenu && <RowMenu at={cellMenu.at} entries={cellMenu.entries} onClose={() => setCellMenu(null)} />}
+ </>
+ );
});
const toggleChecklistCmd: Command = (state, dispatch) => {
diff --git a/src/screens/notes/rich.ts b/src/screens/notes/rich.ts
index fa81cd7..1c36974 100644
--- a/src/screens/notes/rich.ts
+++ b/src/screens/notes/rich.ts
@@ -43,6 +43,8 @@ export const schema = new Schema({
style: { default: null as number | null },
indent: { default: 0 },
checked: { default: null as boolean | null },
+ /** A numbered list's first number, when not 1. */
+ start: { default: null as number | null },
},
parseDOM: [{ tag: "p" }],
toDOM: (node) => [
@@ -51,7 +53,11 @@ export const schema = new Schema({
class: "nf-p",
"data-style": node.attrs.style === null ? "none" : String(node.attrs.style),
...(node.attrs.checked ? { "data-checked": "true" } : {}),
- style: node.attrs.indent ? `--indent: ${node.attrs.indent}` : "",
+ style: [
+ node.attrs.indent ? `--indent: ${node.attrs.indent}` : "",
+ // CSS sets a counter after counting the line, so this line shows the start.
+ node.attrs.style === 102 && node.attrs.start ? `counter-set: nf-num ${node.attrs.start}` : "",
+ ].filter(Boolean).join("; "),
},
0,
],
@@ -169,6 +175,7 @@ export function toDoc(text: string, runs: Run[] | null): PMNode {
style: own?.style ?? null,
indent: own?.indent ?? 0,
checked: own?.style === STYLE.checklist ? Boolean(own.checked) : null,
+ start: own?.style === STYLE.numbered ? (own.start ?? null) : null,
},
inline,
),
@@ -182,7 +189,8 @@ export function toDoc(text: string, runs: Run[] | null): PMNode {
const same = (a: Run, b: Run) =>
a.style === b.style && a.indent === b.indent && a.checked === b.checked && a.bold === b.bold &&
a.italic === b.italic && a.underline === b.underline && a.strike === b.strike && a.link === b.link &&
- (a.attachment ?? null) === (b.attachment ?? null) && (a.emphasis ?? null) === (b.emphasis ?? null);
+ (a.attachment ?? null) === (b.attachment ?? null) && (a.emphasis ?? null) === (b.emphasis ?? null) &&
+ (a.start ?? null) === (b.start ?? null);
/** A document as Apple's text and runs. */
export function fromDoc(doc: PMNode): { text: string; runs: Run[] } {
@@ -200,6 +208,7 @@ export function fromDoc(doc: PMNode): { text: string; runs: Run[] } {
style: para.attrs.style as number | null,
indent: para.attrs.indent as number,
checked: para.attrs.style === STYLE.checklist ? Boolean(para.attrs.checked) : null,
+ ...(para.attrs.style === STYLE.numbered && para.attrs.start ? { start: para.attrs.start as number } : {}),
};
const base: Run = { ...plain(0), ...p };
para.forEach((child) => {