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: read tables and draw them as grids in the note

Yashwanth Kamireddi043c41dc993d
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rs
index 1c0c0d6..baafb92 100644
--- a/crates/quince-icloud/src/ckdocument.rs
+++ b/crates/quince-icloud/src/ckdocument.rs
@@ -1680,6 +1680,10 @@ pub struct Run {
pub underline: bool,
pub strike: bool,
pub link: Option<String>,
+ /// The attachment this run's one character stands for — a table, a picture — by id.
+ /// Read only: an attachment's place is kept from Apple's own run, never written from this.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub attachment: Option<String>,
}
/// Every run of a note document, in order. Empty for anything that is not one.
@@ -1719,6 +1723,11 @@ fn parse_run(bytes: &[u8]) -> Option<Run> {
.ok()
.map(ToString::to_string);
}
+ (12, WIRE_LEN) => {
+ let n = usize::try_from(reader.varint()?).ok()?;
+ let info = reader.take(n)?;
+ run.attachment = bytes_field(info, 1).and_then(|id| String::from_utf8(id).ok());
+ }
_ => reader.skip(wire)?,
}
}
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index db4d181..099338a 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -13,6 +13,7 @@ pub mod notes;
pub mod occasions;
pub mod reminders;
pub mod sync;
+pub mod table;
pub mod topotext;
#[derive(Debug, thiserror::Error)]
diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rs
index 4af3154..55a3ee0 100644
--- a/crates/quince-icloud/src/notes.rs
+++ b/crates/quince-icloud/src/notes.rs
@@ -269,6 +269,8 @@ pub fn apply_cloudkit(
// Apple names this record type outright, so locking is something we read rather than guess.
let mut locked_notes: std::collections::HashSet<String> = std::collections::HashSet::new();
+ // Tables found in this pass: id and cells (None when gone or unreadable).
+ let mut tables: Vec<(String, Option<Vec<Vec<String>>>)> = Vec::new();
for record in &records {
let removed = record
.get("deleted")
@@ -324,6 +326,22 @@ pub fn apply_cloudkit(
folders.extend(folder_from_record(record));
}
}
+ // A table: its cells, kept beside the library's settings under its id, which is
+ // what the note's text names it by.
+ "Attachment" => {
+ let Some(name) = field::record_name(record) else { continue };
+ let uti = record
+ .pointer("/fields/UTI/value")
+ .and_then(Value::as_str)
+ .unwrap_or_default();
+ if uti == crate::table::UTI {
+ let cells = (!removed)
+ .then(|| record.pointer("/fields/MergeableDataEncrypted/value").and_then(Value::as_str))
+ .flatten()
+ .and_then(crate::table::cells_from_base64);
+ tables.push((name, cells));
+ }
+ }
// Per-user state. The note it refers to is what matters, not this record's name.
"Note_UserSpecific" | "PasswordProtectedNote_UserSpecific" => {
if let Some(target) = field::reference(record, "Note") {
@@ -342,6 +360,10 @@ pub fn apply_cloudkit(
}
}
+ for (name, cells) in &tables {
+ let value = cells.as_ref().and_then(|c| serde_json::to_string(c).ok()).unwrap_or_default();
+ library.set_state(&crate::table::state_key(name), &value)?;
+ }
// A note the owner deleted is still present as a Note record; only the per-user record
// says so. Without this, deleted notes would keep showing.
notes.retain(|n| !deleted_notes.contains(&n.guid));
diff --git a/crates/quince-icloud/src/table.rs b/crates/quince-icloud/src/table.rs
new file mode 100644
index 0000000..645502a
--- /dev/null
+++ b/crates/quince-icloud/src/table.rs
@@ -0,0 +1,261 @@
+//! A Notes table, read from the attachment that holds it.
+//!
+//! A table is an `Attachment` record of type `com.apple.notes.table` whose
+//! `MergeableDataEncrypted` is a versioned CRDT document (gzip or zlib, then protobuf):
+//!
+//! - `Document{2: Version{3: data}}`; `data` is `{3: object*, 4: key*, 5: type*, 6: uuid*}`.
+//! - Object 0 is a custom object of type `com.apple.notes.ICTable` whose entries name, by
+//! object index, `crRows`, `crColumns` and `cellColumns`.
+//! - `crRows` and `crColumns` are ordered sets (object kind 16): a list of elements — each an
+//! index and a uuid — and a dictionary from each element's own `NSUUID` object to the row's
+//! or column's `NSUUID` object. The elements in index order are the rows (or columns) in
+//! reading order.
+//! - `cellColumns` is a dictionary: column object → dictionary: row object → a text object
+//! (kind 10) whose field 2 is the cell's text. A cell never typed in may be missing; it is
+//! empty.
+//!
+//! Measured on tables made on a phone and on icloud.com: a 2×2 never typed in, and an 11×2
+//! with text in its cells, read back exactly as Notes shows them.
+
+use std::collections::HashMap;
+
+/// The attachment type a table is.
+pub const UTI: &str = "com.apple.notes.table";
+
+/// Where a table's cells are kept in the library, by attachment id.
+#[must_use]
+pub fn state_key(id: &str) -> String {
+ format!("notes.table.{id}")
+}
+
+/// A table's cells as the last pass stored them; `None` when none are known.
+#[must_use]
+pub fn stored(library: &quince_core::Library, id: &str) -> Option<Vec<Vec<String>>> {
+ library
+ .state(&state_key(id))
+ .ok()
+ .flatten()
+ .filter(|s| !s.is_empty())
+ .and_then(|s| serde_json::from_str(&s).ok())
+}
+
+fn varint(b: &[u8], mut at: usize) -> Option<(u64, usize)> {
+ let mut v = 0u64;
+ for shift in 0..10 {
+ let byte = *b.get(at)?;
+ at += 1;
+ v |= u64::from(byte & 0x7f) << (shift * 7);
+ if byte & 0x80 == 0 {
+ return Some((v, at));
+ }
+ }
+ None
+}
+
+#[derive(Clone, Copy)]
+enum Wire<'a> {
+ Int(u64),
+ Bytes(&'a [u8]),
+}
+
+fn fields(b: &[u8]) -> Option<Vec<(u64, Wire<'_>)>> {
+ let mut out = Vec::new();
+ let mut at = 0;
+ while at < b.len() {
+ let (key, next) = varint(b, at)?;
+ at = next;
+ match key & 7 {
+ 0 => {
+ let (v, next) = varint(b, at)?;
+ at = next;
+ out.push((key >> 3, Wire::Int(v)));
+ }
+ 2 => {
+ let (n, next) = varint(b, at)?;
+ let end = next.checked_add(usize::try_from(n).ok()?)?;
+ out.push((key >> 3, Wire::Bytes(b.get(next..end)?)));
+ at = end;
+ }
+ 1 => at = at.checked_add(8).filter(|&e| e <= b.len())?,
+ 5 => at = at.checked_add(4).filter(|&e| e <= b.len())?,
+ _ => return None,
+ }
+ }
+ Some(out)
+}
+
+fn bytes<'a, 'f>(fs: &'f [(u64, Wire<'a>)], tag: u64) -> impl Iterator<Item = &'a [u8]> + 'f {
+ fs.iter().filter_map(move |(t, w)| match (t, w) {
+ (t, Wire::Bytes(b)) if *t == tag => Some(*b),
+ _ => None,
+ })
+}
+
+fn int(fs: &[(u64, Wire<'_>)], tag: u64) -> Option<u64> {
+ fs.iter().find_map(|(t, w)| match (t, w) {
+ (t, Wire::Int(v)) if *t == tag => Some(*v),
+ _ => None,
+ })
+}
+
+/// An object id's object index, where it is one (field 6).
+fn object_index(id: &[u8]) -> Option<usize> {
+ usize::try_from(int(&fields(id)?, 6)?).ok()
+}
+
+fn inflate(data: &[u8]) -> Option<Vec<u8>> {
+ use std::io::Read;
+ let mut out = Vec::new();
+ if data.starts_with(&[0x1f, 0x8b]) {
+ flate2::read::GzDecoder::new(data).read_to_end(&mut out).ok()?;
+ } else if flate2::read::ZlibDecoder::new(data).read_to_end(&mut out).is_ok() {
+ } else {
+ return Some(data.to_vec());
+ }
+ Some(out)
+}
+
+struct Doc<'a> {
+ objects: Vec<&'a [u8]>,
+ keys: Vec<String>,
+ uuids: Vec<&'a [u8]>,
+}
+
+impl<'a> Doc<'a> {
+ /// An object's kind (its one field's number) and payload.
+ fn object(&self, i: usize) -> Option<(u64, &'a [u8])> {
+ let fs = fields(self.objects.get(i)?)?;
+ match fs.first()? {
+ (kind, Wire::Bytes(b)) => Some((*kind, *b)),
+ _ => None,
+ }
+ }
+
+ /// A custom object's entries: key name → the object id's bytes.
+ fn custom(&self, i: usize) -> Option<HashMap<String, &'a [u8]>> {
+ let (kind, body) = self.object(i)?;
+ if kind != 13 {
+ return None;
+ }
+ let mut out = HashMap::new();
+ for entry in bytes(&fields(body)?, 3) {
+ let e = fields(entry)?;
+ let key = usize::try_from(int(&e, 1)?).ok()?;
+ let value = bytes(&e, 2).next()?;
+ out.insert(self.keys.get(key)?.clone(), value);
+ }
+ Some(out)
+ }
+
+ /// A dictionary object (kind 6, or a dictionary message itself): object → object.
+ fn dictionary(body: &[u8]) -> Option<HashMap<usize, usize>> {
+ let mut out = HashMap::new();
+ for element in bytes(&fields(body)?, 1) {
+ let e = fields(element)?;
+ let (Some(k), Some(v)) = (bytes(&e, 1).next(), bytes(&e, 2).next()) else { continue };
+ if let (Some(k), Some(v)) = (object_index(k), object_index(v)) {
+ out.insert(k, v);
+ }
+ }
+ Some(out)
+ }
+
+ /// The `NSUUID` object holding each uuid.
+ fn uuid_objects(&self) -> HashMap<&'a [u8], usize> {
+ let mut out = HashMap::new();
+ for i in 0..self.objects.len() {
+ if let Some(entries) = self.custom(i) {
+ if let Some(at) = entries.get("UUIDIndex").and_then(|id| int(&fields(id)?, 2).or_else(|| int(&fields(id)?, 1))) {
+ if let Some(u) = usize::try_from(at).ok().and_then(|at| self.uuids.get(at)) {
+ out.insert(*u, i);
+ }
+ }
+ }
+ }
+ out
+ }
+
+ /// An ordered set's members, in order, as the objects the table keys its cells by.
+ fn ordered(&self, i: usize, by_uuid: &HashMap<&[u8], usize>) -> Option<Vec<usize>> {
+ let (_, body) = self.object(i)?;
+ let top = fields(body)?;
+ let array = fields(bytes(&top, 1).next()?)?;
+ let list = fields(bytes(&array, 1).next()?)?;
+ let mut elements: Vec<(u64, &[u8])> = Vec::new();
+ for element in bytes(&list, 2) {
+ let e = fields(element)?;
+ elements.push((int(&e, 1).unwrap_or(0), bytes(&e, 2).next()?));
+ }
+ elements.sort_by_key(|(at, _)| *at);
+ let mut members: HashMap<usize, usize> = HashMap::new();
+ for d in bytes(&array, 2) {
+ members.extend(Self::dictionary(d)?);
+ }
+ Some(
+ elements
+ .into_iter()
+ .filter_map(|(_, u)| {
+ let own = *by_uuid.get(u)?;
+ Some(members.get(&own).copied().unwrap_or(own))
+ })
+ .collect(),
+ )
+ }
+
+ fn text(&self, i: usize) -> String {
+ self.object(i)
+ .filter(|(kind, _)| *kind == 10)
+ .and_then(|(_, body)| fields(body))
+ .and_then(|fs| bytes(&fs, 2).next().map(|b| String::from_utf8_lossy(b).into_owned()))
+ .unwrap_or_default()
+ }
+}
+
+/// The table's cells, row by row, from the attachment's `MergeableDataEncrypted` (base64).
+/// `None` for data that is not a table this understands.
+#[must_use]
+pub fn cells_from_base64(value: &str) -> Option<Vec<Vec<String>>> {
+ use base64::Engine;
+ let raw = base64::engine::general_purpose::STANDARD.decode(value.trim()).ok()?;
+ cells(&inflate(&raw)?)
+}
+
+/// [`cells_from_base64`] over the inflated document.
+#[must_use]
+pub fn cells(document: &[u8]) -> Option<Vec<Vec<String>>> {
+ let top = fields(document)?;
+ let version = fields(bytes(&top, 2).next()?)?;
+ let data = fields(bytes(&version, 3).next()?)?;
+ let doc = Doc {
+ objects: bytes(&data, 3).collect(),
+ keys: bytes(&data, 4).map(|k| String::from_utf8_lossy(k).into_owned()).collect(),
+ uuids: bytes(&data, 6).collect(),
+ };
+ let root = doc.custom(0)?;
+ let at = |name: &str| root.get(name).and_then(|id| object_index(id));
+ let by_uuid = doc.uuid_objects();
+ let rows = doc.ordered(at("crRows")?, &by_uuid)?;
+ let columns = doc.ordered(at("crColumns")?, &by_uuid)?;
+ let (_, cells_body) = doc.object(at("cellColumns")?)?;
+ let by_column = Doc::dictionary(cells_body)?;
+ let column_cells: HashMap<usize, HashMap<usize, usize>> = by_column
+ .iter()
+ .filter_map(|(col, inner)| Some((*col, Doc::dictionary(doc.object(*inner)?.1)?)))
+ .collect();
+ Some(
+ rows.iter()
+ .map(|row| {
+ columns
+ .iter()
+ .map(|col| {
+ column_cells
+ .get(col)
+ .and_then(|cells| cells.get(row))
+ .map(|&cell| doc.text(cell))
+ .unwrap_or_default()
+ })
+ .collect()
+ })
+ .collect(),
+ )
+}
diff --git a/crates/quince-icloud/tests/data/table-empty-2x2.bin b/crates/quince-icloud/tests/data/table-empty-2x2.bin
new file mode 100644
index 0000000..47880d2
Binary files /dev/null and b/crates/quince-icloud/tests/data/table-empty-2x2.bin differ
diff --git a/crates/quince-icloud/tests/table.rs b/crates/quince-icloud/tests/table.rs
new file mode 100644
index 0000000..bb89b13
--- /dev/null
+++ b/crates/quince-icloud/tests/table.rs
@@ -0,0 +1,7 @@
+//! A table made on a phone and never typed in reads as the 2×2 of empty cells Notes shows.
+#[test]
+fn an_empty_table_reads_as_two_by_two() {
+ let doc = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/table-empty-2x2.bin")).unwrap();
+ let cells = quince_icloud::table::cells(&doc).expect("a table");
+ assert_eq!(cells, vec![vec![String::new(), String::new()], vec![String::new(), String::new()]]);
+}
diff --git a/probe/examples/notes_table_chain.rs b/probe/examples/notes_table_chain.rs
new file mode 100644
index 0000000..be78c29
--- /dev/null
+++ b/probe/examples/notes_table_chain.rs
@@ -0,0 +1,30 @@
+//! Read-only: a note's table by the chain the app follows — the note's runs name the
+//! attachment, the attachment record is fetched, its cells are read.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client.session().service_url("ckdatabasews").ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());
+ let note = zc.lookup_record("Notes", "50a80840-1931-45d9-9774-7d7ab70d9022").await?.ok_or_else(|| anyhow!("no note"))?;
+ println!("by {} / created {}", note["modified"], note["created"]);
+ println!("text {:?} modified {}", quince_icloud::ckdocument::stored_text_from_base64(note["fields"]["TextDataEncrypted"]["value"].as_str().unwrap_or("")), note["fields"]["ModificationDate"]["value"]);
+ let runs = quince_icloud::ckdocument::runs_from_base64(note["fields"]["TextDataEncrypted"]["value"].as_str().unwrap_or(""));
+ let raw = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, note["fields"]["TextDataEncrypted"]["value"].as_str().unwrap_or("").trim()).unwrap_or_default();
+ for r in quince_icloud::ckdocument::debug_attribute_runs(&raw) { println!("{}", quince_icloud::ckdocument::debug_tree(&r, 6).join(" | ")); }
+ println!("{} runs: {:?}", runs.len(), runs.iter().map(|r| (r.length, r.attachment.clone())).collect::<Vec<_>>());
+ for id in runs.iter().filter_map(|r| r.attachment.clone()) {
+ let rec = zc.lookup_record("Notes", &id).await?;
+ let cells = rec.as_ref().and_then(|r| r["fields"]["MergeableDataEncrypted"]["value"].as_str()).and_then(quince_icloud::table::cells_from_base64);
+ println!("attachment {id}:");
+ for row in cells.unwrap_or_default() {
+ println!(" {row:?}");
+ }
+ }
+ Ok(())
+}
diff --git a/probe/examples/notes_table_owner.rs b/probe/examples/notes_table_owner.rs
new file mode 100644
index 0000000..e2c0d86
--- /dev/null
+++ b/probe/examples/notes_table_owner.rs
@@ -0,0 +1,26 @@
+//! Read-only: every table attachment, the note it belongs to, whether that note's text
+//! still places it, and its cells.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client.session().service_url("ckdatabasews").ok_or_else(|| anyhow!("no ck"))?;
+ 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 a in walk.records.iter().filter(|r| r["recordType"] == "Attachment") {
+ let id = a["recordName"].as_str().unwrap_or("");
+ let owner = a["fields"]["Note"]["value"]["recordName"].as_str().unwrap_or("");
+ let note = walk.records.iter().find(|r| r["recordName"] == owner);
+ let body = note.and_then(|n| n["fields"]["TextDataEncrypted"]["value"].as_str()).unwrap_or("");
+ let placed = quince_icloud::ckdocument::runs_from_base64(body).iter().any(|r| r.attachment.as_deref() == Some(id));
+ let cells = a["fields"]["MergeableDataEncrypted"]["value"].as_str().and_then(quince_icloud::table::cells_from_base64);
+ println!("{id} → note {owner} ({:?}) placed in text: {placed} deleted: {} modified-by {}", quince_icloud::ckdocument::stored_text_from_base64(body).unwrap_or_default().chars().take(20).collect::<String>(), a["fields"]["Deleted"]["value"], a["modified"]["timestamp"]);
+ println!(" {:?}", cells.map(|c| c.into_iter().take(3).collect::<Vec<_>>()));
+ }
+ Ok(())
+}
diff --git a/probe/examples/notes_who_wrote.rs b/probe/examples/notes_who_wrote.rs
new file mode 100644
index 0000000..7b20038
--- /dev/null
+++ b/probe/examples/notes_who_wrote.rs
@@ -0,0 +1,19 @@
+//! Read-only: which device last wrote each note — to tell this app's writes from others'.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client.session().service_url("ckdatabasews").ok_or_else(|| anyhow!("no ck"))?;
+ 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 text = r["fields"]["TextDataEncrypted"]["value"].as_str().and_then(quince_icloud::ckdocument::stored_text_from_base64).unwrap_or_default();
+ println!("{:>4} {:>14} {:?}", r["modified"]["deviceID"].as_str().unwrap_or("?"), r["modified"]["timestamp"], text.lines().next().unwrap_or("").chars().take(30).collect::<String>());
+ }
+ Ok(())
+}
diff --git a/probe/examples/table_file.rs b/probe/examples/table_file.rs
new file mode 100644
index 0000000..8987a3a
--- /dev/null
+++ b/probe/examples/table_file.rs
@@ -0,0 +1,8 @@
+//! Offline: print a table's cells from an inflated attachment document on disk.
+fn main() {
+ let path = std::env::args().nth(1).expect("pass a file");
+ let doc = std::fs::read(path).unwrap();
+ for row in quince_icloud::table::cells(&doc).expect("a table") {
+ println!("{row:?}");
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 50ba0d1..5da3fe5 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1167,6 +1167,35 @@ async fn note_runs(guid: String, data: State<'_, Data>) -> UiResult<serde_json::
.unwrap_or(serde_json::Value::Array(Vec::new())))
}
+/// A table's cells, row by row, as the last pass read them — `None` when none are known.
+#[tauri::command]
+async fn note_table(
+ id: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<Option<Vec<Vec<String>>>> {
+ if let Some(cells) = quince_icloud::table::stored(&*data.0.lock().await, &id) {
+ return Ok(Some(cells));
+ }
+ // Not stored yet — a table made before this app read tables, which a pass of changes
+ // does not bring — so asked of Apple now, and kept.
+ let (http, root, params) = cloudkit_context(&auth).await?;
+ let client = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", params);
+ let record = client.lookup_record("Notes", &id).await.map_err(|e| e.to_string())?;
+ let cells = record
+ .as_ref()
+ .and_then(|r| r.pointer("/fields/MergeableDataEncrypted/value"))
+ .and_then(serde_json::Value::as_str)
+ .and_then(quince_icloud::table::cells_from_base64);
+ if let Some(cells) = &cells {
+ let mut library = data.0.lock().await;
+ if let Ok(json) = serde_json::to_string(cells) {
+ library.set_state(&quince_icloud::table::state_key(&id), &json).map_err(|e| e.to_string())?;
+ }
+ }
+ Ok(cells)
+}
+
#[tauri::command]
async fn note_save(
guid: String,
@@ -2863,6 +2892,7 @@ fn main() {
note_folder_delete,
note_body,
note_runs,
+ note_table,
note_paragraph,
note_save,
note_create,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 78feb7f..6e47f74 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -125,6 +125,8 @@ export const api = {
noteFolders: () => invoke<NoteFolder[]>("note_folders"),
noteParagraph: (guid: string, start: number, change: { style?: number; checked?: boolean; expect?: string }) =>
invoke<void>("note_paragraph", { guid, start, ...change }),
+ /** A table's cells, row by row, by the attachment id a note's text names it by. */
+ noteTable: (id: string) => invoke<string[][] | null>("note_table", { id }),
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 e808bfe..90fb813 100644
--- a/src/screens/notes/Formatted.tsx
+++ b/src/screens/notes/Formatted.tsx
@@ -18,6 +18,8 @@ export type Run = {
underline: boolean;
strike: boolean;
link: string | null;
+ /** The attachment this run's character stands for — a table, a picture — by id. */
+ attachment?: string | null;
};
/** Apple's paragraph styles. */
diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsx
index 1cf02ba..1409883 100644
--- a/src/screens/notes/NoteEditor.tsx
+++ b/src/screens/notes/NoteEditor.tsx
@@ -8,6 +8,39 @@ import { baseKeymap, splitBlockAs, toggleMark, chainCommands } from "prosemirror
import type { Node as PMNode } from "prosemirror-model";
import type { Run } from "./Formatted";
import { fromDoc, LIST_STYLES, schema, STYLE, toDoc } from "./rich";
+import { api } from "../../lib/ipc";
+
+/**
+ * An attachment in the note: a table drawn as the grid it is, with the cells Apple holds;
+ * anything else — a picture, a sketch — as a labelled placeholder that keeps its place. Not
+ * editable here, and never written from here: the note keeps the attachment exactly.
+ */
+function attachmentView(node: PMNode) {
+ const dom = document.createElement("span");
+ dom.className = "nf-attachment";
+ dom.contentEditable = "false";
+ dom.textContent = "Attachment";
+ dom.title = "Open it on an Apple device to change it";
+ const id = node.attrs.id as string | null;
+ if (id) {
+ api.noteTable(id).then(
+ (cells) => {
+ if (!cells || !cells.length) return;
+ const table = document.createElement("table");
+ table.className = "nf-table";
+ for (const row of cells) {
+ const tr = table.insertRow();
+ for (const cell of row) tr.insertCell().textContent = cell.trimEnd();
+ }
+ dom.className = "nf-attachment is-table";
+ dom.title = "A table — edit it on an Apple device for now";
+ dom.replaceChildren(table);
+ },
+ () => {},
+ );
+ }
+ return { dom, ignoreMutation: () => true, stopEvent: () => false };
+}
/** What the toolbar shows as on: the style of the line the cursor is in, and its marks. */
export type EditorStatus = {
@@ -222,6 +255,7 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
});
const v = new EditorView(host.current, {
state,
+ nodeViews: { attachment: (node) => attachmentView(node) },
editable: () => editable,
attributes: {
class: "note-rich",
diff --git a/src/screens/notes/rich.ts b/src/screens/notes/rich.ts
index ecf1133..45322a3 100644
--- a/src/screens/notes/rich.ts
+++ b/src/screens/notes/rich.ts
@@ -60,6 +60,7 @@ export const schema = new Schema({
inline: true,
atom: true,
selectable: true,
+ attrs: { id: { default: null as string | null } },
toDOM: () => ["span", { class: "nf-attachment", contenteditable: "false", title: "Attachment — open it on an Apple device" }, "Attachment"],
},
/** Shift-Return: a new line in the same paragraph. */
@@ -128,7 +129,7 @@ export function toDoc(text: string, runs: Run[] | null): PMNode {
while (i < end) {
const ch = text[i];
if (ch === ATTACHMENT) {
- inline.push(schema.nodes.attachment.create());
+ inline.push(schema.nodes.attachment.create({ id: fits ? (units[i]?.attachment ?? null) : null }));
i += 1;
continue;
}
@@ -160,7 +161,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.italic === b.italic && a.underline === b.underline && a.strike === b.strike && a.link === b.link &&
+ (a.attachment ?? null) === (b.attachment ?? null);
/** A document as Apple's text and runs. */
export function fromDoc(doc: PMNode): { text: string; runs: Run[] } {
@@ -181,7 +183,7 @@ export function fromDoc(doc: PMNode): { text: string; runs: Run[] } {
};
const base: Run = { ...plain(0), ...p };
para.forEach((child) => {
- if (child.type === schema.nodes.attachment) return push(ATTACHMENT, base);
+ if (child.type === schema.nodes.attachment) return push(ATTACHMENT, { ...base, attachment: child.attrs.id ?? null });
if (child.type === schema.nodes.line_break) return push(LINE_BREAK, base);
const has = (name: string) => child.marks.some((m) => m.type.name === name);
push(child.text ?? "", {
diff --git a/src/styles/notes.css b/src/styles/notes.css
index b21e61c..7a62bd8 100644
--- a/src/styles/notes.css
+++ b/src/styles/notes.css
@@ -398,3 +398,8 @@ textarea.note-title::placeholder { color: var(--text-3); }
.fp-subheading { font-size: 15px; font-weight: 600; }
.fp-mono { font-family: ui-monospace, "SF Mono", "JetBrains Mono", monospace; font-size: 14px; }
.fp-list-mark { width: 16px; color: var(--text-2); }
+
+/* A table in a note, as Notes draws one: hairline cells, the text set as the note's. */
+.note-rich .nf-attachment.is-table { display: block; padding: 0; margin: 6px 0; background: none; color: inherit; font-size: inherit; overflow-x: auto; }
+.nf-table { border-collapse: collapse; min-width: 50%; }
+.nf-table td { min-width: 120px; padding: 4px 8px; border: 1px solid color-mix(in srgb, var(--text) 22%, transparent); vertical-align: top; white-space: pre-wrap; }