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 can be written, not just read

Yashwanth Kamireddi75275beea198
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjs
index 1e11acd..b4d8509 100644
--- a/.uiverify/a11y.mjs
+++ b/.uiverify/a11y.mjs
@@ -36,6 +36,8 @@ function installStub({ screen, services, twoFactor }) {
return null;
case "reminders_smart": return [];
case "note_folders": return [];
+ case "note_save": case "note_delete": case "note_move": return null;
+ case "note_create": return "Note/new";
case "notes_in": return [];
case "contacts_list": return [];
case "contacts_last_synced": return Math.floor(Date.now() / 1000);
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjs
index 43584c3..3d66858 100644
--- a/.uiverify/assert.mjs
+++ b/.uiverify/assert.mjs
@@ -23,6 +23,8 @@ await ctx.addInitScript(({ services }) => {
if (cmd === "reminder_list_create" || cmd === "reminder_list_rename" || cmd === "reminder_list_delete") return null;
if (cmd === "note_folders") return [];
if (cmd === "notes_in") return [];
+ if (cmd === "note_save" || cmd === "note_delete" || cmd === "note_move") return null;
+ if (cmd === "note_create") return "Note/new";
if (cmd === "contacts_list") return [];
if (cmd === "drive_children") return [];
if (cmd === "drive_sync_folder") return 0;
diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjs
index 06c6d43..90396dd 100644
--- a/.uiverify/keyboard.mjs
+++ b/.uiverify/keyboard.mjs
@@ -35,6 +35,8 @@ function installStub({ screen, services, twoFactor }) {
return null;
case "reminders_smart": return [];
case "note_folders": return [];
+ case "note_save": case "note_delete": case "note_move": return null;
+ case "note_create": return "Note/new";
case "notes_in": return [];
case "contacts_list": return [];
case "contacts_last_synced": return Math.floor(Date.now() / 1000);
diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjs
index 2ea72c9..82b6386 100644
--- a/.uiverify/shots.mjs
+++ b/.uiverify/shots.mjs
@@ -52,16 +52,16 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
{ guid: "n1", folderGuid: "f1", title: "Curtains",
snippet: "Bathroom accessories like mirror holder…",
body: "Curtains\nBathroom accessories like mirror holder, soap holder, shampoo, clothes hanger\nFan\nwall clock\nBed\nDining table\nTea filter\nKnife\nWashing Machine cover",
- locked: false, pinned: false, createdAt: null, modifiedAt: 1788500000, etag: null },
+ locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1788500000, etag: null },
{ guid: "n2", folderGuid: "f1", title: "🔴 UNIT 1: SOFTWARE TESTING METHODOLOGIES",
snippet: "📌 SECTION A: 2-MARK HIGH-YIELD…",
body: "🔴 UNIT 1: SOFTWARE TESTING METHODOLOGIES\n\n📌 SECTION A: 2-MARK HIGH-YIELD QUESTIONS\n\nSoftware testing is the process of evaluating a system to find whether it satisfies the specified requirements, and to detect the differences between expected and actual results.",
- locked: false, pinned: true, createdAt: null, modifiedAt: 1787900000, etag: null },
+ locked: false, editable: true, pinned: true, createdAt: null, modifiedAt: 1787900000, etag: null },
{ guid: "n3", folderGuid: "f1",
title: "These sources outline the fundamental principles and methodologies",
snippet: "of **Software Testing Methodologies…",
body: "These sources outline the fundamental principles and methodologies of **Software Testing Methodologies (CSEN3311)**, emphasizing its evolution from simple debugging to a structured, process-oriented discipline. The material details the **Software Testing Life Cycle (STLC)**, covering essential phases from initial planning and test design to execution and post-implementation review.",
- locked: false, pinned: false, createdAt: null, modifiedAt: 1787800000, etag: null },
+ locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1787800000, etag: null },
];
const contactList = !contactsFixture ? [] : [
{ guid: "c1", firstName: "Zoya", lastName: "Ahuja", company: null, isCompany: false,
@@ -137,6 +137,8 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
return null;
case "reminders_smart": return !remindersFixture ? [] : reminderItems.filter(r => !r.completedAt);
case "note_folders": return !notesFixture ? [] : noteFolders;
+ case "note_save": case "note_delete": case "note_move": return null;
+ case "note_create": return "Note/new";
case "notes_in": return !notesFixture ? [] : noteList;
case "contacts_list": return !contactsFixture ? [] : contactList;
case "drive_children": return !driveFixture ? [] : driveItems;
diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rs
index 0757466..3dd055f 100644
--- a/crates/quince-core/src/notes.rs
+++ b/crates/quince-core/src/notes.rs
@@ -25,9 +25,21 @@ pub struct Note {
pub pinned: bool,
pub created_at: Option<i64>,
pub modified_at: Option<i64>,
+ /// Whether saving an edit would preserve the note.
+ ///
+ /// Apple's document carries version vectors and merge state around the text. Where that
+ /// document can be reproduced byte for byte, an edit is a safe surgical swap; where it
+ /// cannot, writing would flatten everything else in it, so the note stays read-only and
+ /// the interface says why.
+ #[serde(default = "yes")]
+ pub editable: bool,
pub etag: Option<String>,
}
+fn yes() -> bool {
+ true
+}
+
fn now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -59,13 +71,14 @@ impl Library {
{
let mut stmt = tx.prepare(
"INSERT INTO notes (guid, folder_guid, title, snippet, body, locked, pinned,
- created_at, modified_at, etag, updated_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
+ created_at, modified_at, editable, etag, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
ON CONFLICT(guid) DO UPDATE SET
folder_guid = excluded.folder_guid, title = excluded.title,
snippet = excluded.snippet, body = excluded.body,
locked = excluded.locked, pinned = excluded.pinned,
created_at = excluded.created_at, modified_at = excluded.modified_at,
+ editable = excluded.editable,
etag = excluded.etag, updated_at = excluded.updated_at",
)?;
let stamp = now();
@@ -80,6 +93,7 @@ impl Library {
i64::from(n.pinned),
n.created_at,
n.modified_at,
+ i64::from(n.editable),
n.etag,
stamp
])?;
@@ -121,7 +135,7 @@ impl Library {
pub fn notes_in(&self, folder_guid: Option<&str>) -> Result<Vec<Note>> {
let mut stmt = self.conn.prepare(
"SELECT guid, folder_guid, title, snippet, body, locked, pinned,
- created_at, modified_at, etag
+ created_at, modified_at, editable, etag
FROM notes
WHERE ?1 IS NULL OR folder_guid = ?1
ORDER BY pinned DESC, modified_at DESC, title",
@@ -137,7 +151,8 @@ impl Library {
pinned: row.get::<_, i64>(6)? != 0,
created_at: row.get(7)?,
modified_at: row.get(8)?,
- etag: row.get(9)?,
+ editable: row.get::<_, i64>(9)? != 0,
+ etag: row.get(10)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
@@ -167,6 +182,7 @@ mod tests {
pinned,
created_at: Some(1),
modified_at: Some(modified),
+ editable: true,
etag: None,
}
}
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index e1d449b..b03c5b3 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -179,4 +179,13 @@ pub const MIGRATIONS: &[&str] = &[
ALTER TABLE reminders ADD COLUMN recur_frequency INTEGER;
ALTER TABLE reminders ADD COLUMN recur_interval INTEGER;
"#,
+ // 9 — whether a note can be saved without damage.
+ //
+ // A note body is Apple's document protobuf: text surrounded by version vectors, folder
+ // links and merge state. Saving means rewriting that document in place. Where the
+ // document cannot be reproduced byte for byte, this app will not write it, and the
+ // interface has to be able to say so before someone starts typing rather than after.
+ r#"
+ ALTER TABLE notes ADD COLUMN editable INTEGER NOT NULL DEFAULT 1;
+ "#,
];
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rs
index 7a23c4d..0a337d5 100644
--- a/crates/quince-icloud/src/ckdocument.rs
+++ b/crates/quince-icloud/src/ckdocument.rs
@@ -190,6 +190,16 @@ pub fn text_to_base64(text: &str) -> String {
B64.encode(gzip(&document_bytes(text)))
}
+/// Encode text the way Apple stores a note's title and snippet: gzipped UTF-8, with no
+/// document wrapper around it.
+///
+/// The decoder already falls back to this shape on the way in; writing the wrapped form
+/// here instead would put protobuf framing into the title a phone displays.
+#[must_use]
+pub fn bare_text_to_base64(text: &str) -> String {
+ B64.encode(gzip(text.as_bytes()))
+}
+
/// A length-delimited protobuf field: `(tag << 3) | 2`, then the length, then the payload.
fn length_delimited(tag: u64, payload: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(payload.len() + 4);
@@ -230,6 +240,198 @@ fn gzip(bytes: &[u8]) -> Vec<u8> {
encoder.finish().unwrap_or_default()
}
+/// Rewrite the text inside an existing document, leaving every other field exactly as it
+/// was.
+///
+/// A note body is not just its text. Around it Apple keeps version vectors, folder links
+/// and per-device merge state, and the earlier encoder — which builds the smallest document
+/// Apple will read — would have replaced all of it with a bare string. Saving an edit that
+/// way silently throws away everything the note knew about itself.
+///
+/// So this edits in place: walk the message, swap the one field that holds the text, copy
+/// every other byte through untouched.
+///
+/// Returns `None` when the document is not one this understands well enough to rewrite,
+/// which is the point. A note whose shape cannot be reproduced exactly is left alone rather
+/// than flattened, and the interface says so instead of pretending the save worked.
+#[must_use]
+pub fn replace_text(original: &[u8], text: &str) -> Option<Vec<u8>> {
+ let plain = inflate(original)?;
+ let current = field_at(&plain, TEXT_PATH)?;
+
+ // The proof, before anything is written: putting the text back exactly as it came out
+ // has to reproduce the original byte for byte. If it does, every other field survived
+ // the walk, and swapping the text is safe. If it does not, this document has something
+ // in it this code does not model, and it is not ours to rewrite.
+ if rewrite(&plain, TEXT_PATH, current)? != plain {
+ return None;
+ }
+
+ rewrite(&plain, TEXT_PATH, text.as_bytes())
+}
+
+/// Whether [`replace_text`] would accept this document, without building the result.
+///
+/// Answers "can this note be edited?" at sync time, so the interface can say so before
+/// someone starts typing rather than after they press save.
+#[must_use]
+pub fn is_rewritable(original: &[u8]) -> bool {
+ let Some(plain) = inflate(original) else {
+ return false;
+ };
+ let Some(current) = field_at(&plain, TEXT_PATH) else {
+ return false;
+ };
+ rewrite(&plain, TEXT_PATH, current).is_some_and(|rebuilt| rebuilt == plain)
+}
+
+/// [`replace_text`] over the base64 a CloudKit field carries, gzipped on the way back.
+#[must_use]
+pub fn replace_text_in_base64(original: &str, text: &str) -> Option<String> {
+ let raw = B64.decode(original.trim()).ok()?;
+ Some(B64.encode(gzip(&replace_text(&raw, text)?)))
+}
+
+/// Copy a message through, replacing the length-delimited field at `path` with `payload`.
+///
+/// Every field that is not on the path is copied as raw bytes, so nothing is re-encoded and
+/// nothing can be lost in translation.
+fn rewrite(message: &[u8], path: &[u64], payload: &[u8]) -> Option<Vec<u8>> {
+ let (&wanted, rest) = path.split_first()?;
+ let mut reader = Reader::new(message);
+ let mut out = Vec::with_capacity(message.len() + payload.len());
+ let mut replaced = false;
+
+ while !reader.done() {
+ let start = reader.at;
+ let key = reader.varint()?;
+ let (field, wire) = (key >> 3, key & 7);
+
+ if field == wanted && wire == WIRE_LEN && !replaced {
+ let n = usize::try_from(reader.varint()?).ok()?;
+ let chunk = reader.take(n)?;
+ let inner = if rest.is_empty() {
+ payload.to_vec()
+ } else {
+ // A sibling with the same tag that does not contain the path is a different
+ // part of the document, so copy it and keep looking.
+ match rewrite(chunk, rest, payload) {
+ Some(done) => done,
+ None => {
+ out.extend_from_slice(message.get(start..reader.at)?);
+ continue;
+ }
+ }
+ };
+ out.extend_from_slice(&length_delimited(field, &inner));
+ replaced = true;
+ } else {
+ reader.skip(wire)?;
+ out.extend_from_slice(message.get(start..reader.at)?);
+ }
+ }
+
+ replaced.then_some(out)
+}
+
+/// Decompress a base64 document payload without interpreting it.
+///
+/// For measuring what Apple actually sends before writing anything back.
+#[must_use]
+pub fn debug_inflate(value: &str) -> Option<Vec<u8>> {
+ inflate(&B64.decode(value.trim()).ok()?)
+}
+
+/// A readable outline of a protobuf message: one line per field, nested.
+///
+/// Rewriting a note body means preserving every field that is not the text, so the shape
+/// has to be known rather than assumed. This is how it gets looked at.
+#[must_use]
+pub fn debug_tree(bytes: &[u8], depth_limit: usize) -> Vec<String> {
+ let mut lines = Vec::new();
+ walk(bytes, 1, depth_limit, &mut lines);
+ lines
+}
+
+fn walk(bytes: &[u8], depth: usize, limit: usize, out: &mut Vec<String>) {
+ let pad = " ".repeat(depth + 1);
+ let mut reader = Reader::new(bytes);
+ while !reader.done() {
+ let Some(key) = reader.varint() else { return };
+ let (field, wire) = (key >> 3, key & 7);
+ match wire {
+ WIRE_VARINT => {
+ let Some(value) = reader.varint() else { return };
+ out.push(format!("{pad}{field}: varint {value}"));
+ }
+ WIRE_LEN => {
+ let Some(len) = reader.varint().and_then(|n| usize::try_from(n).ok()) else {
+ return;
+ };
+ let Some(chunk) = reader.take(len) else {
+ return;
+ };
+ match std::str::from_utf8(chunk) {
+ // Printable UTF-8 of any length is text, and text is what a writer has
+ // to be able to find.
+ Ok(text) if usable_text(chunk).is_some() => out.push(format!(
+ "{pad}{field}: text {len}B {:?}",
+ text.chars().take(48).collect::<String>()
+ )),
+ _ if depth < limit && looks_like_message(chunk) => {
+ out.push(format!("{pad}{field}: message {len}B"));
+ walk(chunk, depth + 1, limit, out);
+ }
+ // Short opaque fields are shown as hex: at this size the bytes are the
+ // evidence, and a length alone says nothing.
+ _ if len <= 16 => out.push(format!(
+ "{pad}{field}: bytes {len}B {}",
+ chunk
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect::<Vec<_>>()
+ .join(" ")
+ )),
+ _ => out.push(format!("{pad}{field}: bytes {len}B")),
+ }
+ }
+ WIRE_64BIT => {
+ if reader.take(8).is_none() {
+ return;
+ }
+ out.push(format!("{pad}{field}: fixed64"));
+ }
+ WIRE_32BIT => {
+ if reader.take(4).is_none() {
+ return;
+ }
+ out.push(format!("{pad}{field}: fixed32"));
+ }
+ _ => return,
+ }
+ }
+}
+
+/// Whether a chunk parses cleanly as a protobuf message all the way to its end.
+///
+/// Length-delimited bytes are ambiguous on the wire: a nested message and an opaque blob
+/// look identical until you try to read one. Parsing to the exact end is the test.
+fn looks_like_message(bytes: &[u8]) -> bool {
+ if bytes.is_empty() {
+ return false;
+ }
+ let mut reader = Reader::new(bytes);
+ while !reader.done() {
+ let Some(key) = reader.varint() else {
+ return false;
+ };
+ if key >> 3 == 0 || reader.skip(key & 7).is_none() {
+ return false;
+ }
+ }
+ true
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -442,3 +644,148 @@ mod tests {
assert!(text_from_bytes(&wrong).is_none());
}
}
+
+#[cfg(test)]
+mod rewrite_tests {
+ use super::*;
+
+ fn varint(tag: u64, value: u64) -> Vec<u8> {
+ let mut out = Vec::new();
+ write_varint(tag << 3, &mut out);
+ write_varint(value, &mut out);
+ out
+ }
+
+ /// The shape a real note body has: the text at 2 -> 3 -> 2, with version-vector
+ /// messages and stray scalars around it that a save must not disturb.
+ fn document(text: &str) -> Vec<u8> {
+ let mut note = Vec::new();
+ note.extend(length_delimited(2, text.as_bytes()));
+ // Two of Apple's merge records, which carry no length describing the text.
+ for index in 1..=2u64 {
+ let mut run = Vec::new();
+ run.extend(length_delimited(
+ 1,
+ &[varint(1, 1), varint(2, 144_927)].concat(),
+ ));
+ run.extend(varint(2, 34_947));
+ run.extend(varint(5, index));
+ note.extend(length_delimited(3, &run));
+ }
+ note.extend(length_delimited(4, &length_delimited(1, &[0xAB; 28])));
+
+ let mut inner = Vec::new();
+ inner.extend(varint(1, 0));
+ inner.extend(varint(2, 0));
+ inner.extend(length_delimited(3, &note));
+
+ let mut doc = varint(1, 0);
+ doc.extend(length_delimited(2, &inner));
+ doc
+ }
+
+ #[test]
+ fn the_text_is_swapped_and_nothing_else_moves() {
+ let before = document("the original body");
+ let after = replace_text(&before, "a longer body than the one it replaced").unwrap();
+
+ assert_eq!(
+ text_from_bytes(&after).as_deref(),
+ Some("a longer body than the one it replaced")
+ );
+ // Everything that is not the text is still there, byte for byte.
+ assert_eq!(
+ replace_text(&after, "the original body").unwrap(),
+ before,
+ "putting the old text back must give the original document"
+ );
+ }
+
+ /// The whole point of rewriting in place rather than re-encoding. An edit of the same
+ /// length must leave the document byte-identical apart from the text itself, which is
+ /// the strongest statement available that nothing else was touched.
+ #[test]
+ fn a_same_length_edit_changes_only_the_text() {
+ let before = document("first");
+ let after = replace_text(&before, "FIRST").unwrap();
+ assert_eq!(before.len(), after.len());
+
+ let differing: Vec<usize> = before
+ .iter()
+ .zip(&after)
+ .enumerate()
+ .filter_map(|(i, (a, b))| (a != b).then_some(i))
+ .collect();
+ assert_eq!(differing.len(), 5, "only the five text bytes moved");
+ }
+
+ /// And when the length does change, the only fields that change are the lengths on the
+ /// path to the text. The version vectors keep their exact values.
+ #[test]
+ fn the_version_vectors_survive_a_save() {
+ let before = document("first");
+ let after = replace_text(&before, "second").unwrap();
+ // Sizes shift on the path by construction; the fields and their values must not.
+ let shape = |bytes: &[u8]| {
+ debug_tree(bytes, 6)
+ .into_iter()
+ .filter(|line| !line.contains("text "))
+ .map(|line| {
+ line.split_whitespace()
+ .filter(|token| !token.ends_with('B'))
+ .collect::<Vec<_>>()
+ .join(" ")
+ })
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(
+ shape(&after),
+ shape(&before),
+ "every field but the text must survive unchanged"
+ );
+ }
+
+ #[test]
+ fn an_empty_body_is_a_legitimate_edit() {
+ let after = replace_text(&document("something"), "").unwrap();
+ assert_eq!(field_at(&after, TEXT_PATH), Some(&[][..]));
+ }
+
+ /// Growing and shrinking both rewrite the enclosing lengths, which is where a naive
+ /// splice corrupts the message.
+ #[test]
+ fn lengths_are_rewritten_in_both_directions() {
+ for (from, to) in [
+ ("short", &"x".repeat(5_000)[..]),
+ (&"y".repeat(5_000), "tiny"),
+ ] {
+ let after = replace_text(&document(from), to).unwrap();
+ assert_eq!(text_from_bytes(&after).as_deref(), Some(to));
+ assert!(looks_like_message(&after), "still a valid message");
+ }
+ }
+
+ /// A document without the path is not ours to rewrite, and saying so is the safe answer.
+ #[test]
+ fn a_document_we_do_not_recognise_is_refused() {
+ assert!(replace_text(&varint(1, 0), "anything").is_none());
+ assert!(replace_text(&[0xFF, 0xFF, 0xFF], "anything").is_none());
+ assert!(replace_text(&[], "anything").is_none());
+ }
+
+ /// Real payloads arrive compressed, and a save has to survive the round trip.
+ #[test]
+ fn a_gzipped_document_round_trips() {
+ let encoded = B64.encode(gzip(&document("before")));
+ let saved = replace_text_in_base64(&encoded, "after").unwrap();
+ assert_eq!(text_from_base64(&saved).as_deref(), Some("after"));
+ }
+
+ /// Unicode is measured in bytes on the wire, not characters.
+ #[test]
+ fn emoji_and_accents_survive() {
+ let text = "🔴 UNIT 2 — Prüfung · 测试\nsecond line";
+ let after = replace_text(&document("x"), text).unwrap();
+ assert_eq!(text_from_bytes(&after).as_deref(), Some(text));
+ }
+}
diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rs
index db27924..6a1f684 100644
--- a/crates/quince-icloud/src/notes.rs
+++ b/crates/quince-icloud/src/notes.rs
@@ -8,7 +8,7 @@
//! folder names are bare UTF-8. One decoder handles both.
use crate::cloudkit::{field, ZoneClient};
-use crate::Result;
+use crate::{Error, Result};
use quince_core::notes::{Note, NoteFolder};
use serde_json::Value;
@@ -23,10 +23,33 @@ fn folder_from_record(record: &Value) -> Option<NoteFolder> {
})
}
+/// Whether this note's document can be rewritten without losing anything.
+///
+/// Apple's body is not only text: version vectors, folder links and per-device merge state
+/// sit around it. The test is exact — take the text out, put the same text back, and the
+/// bytes must come back identical. When they do, an edit is a surgical swap and everything
+/// else survives. When they do not, there is something in this document the code does not
+/// model, and saving would flatten it, so the note stays read-only.
+fn can_rewrite(record: &Value) -> bool {
+ let Some(encoded) = record
+ .pointer("/fields/TextDataEncrypted/value")
+ .and_then(Value::as_str)
+ else {
+ return false;
+ };
+ // Compares the compressed payload's own bytes, not a decoded string: the check has to
+ // cover whatever whitespace the note really ends with, which reading it as text would
+ // quietly trim away.
+ base64::Engine::decode(&base64::engine::general_purpose::STANDARD, encoded.trim())
+ .ok()
+ .is_some_and(|raw| crate::ckdocument::is_rewritable(&raw))
+}
+
fn note_from_record(record: &Value) -> Option<Note> {
let guid = field::record_name(record)?;
let title = field::document_text(record, "TitleEncrypted");
let body = field::document_text(record, "TextDataEncrypted");
+ let editable = body.is_some() && can_rewrite(record);
Some(Note {
guid,
@@ -41,6 +64,7 @@ fn note_from_record(record: &Value) -> Option<Note> {
pinned: false, // carried on the per-user record, applied below
created_at: field::timestamp_seconds(record, "CreationDate"),
modified_at: field::timestamp_seconds(record, "ModificationDate"),
+ editable,
etag: record
.get("recordChangeTag")
.and_then(Value::as_str)
@@ -174,6 +198,194 @@ pub fn apply_cloudkit(
Ok((folders.len(), notes.len(), token))
}
+/// Milliseconds since the epoch, which is how CloudKit writes timestamps.
+fn now_millis() -> i64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
+}
+
+/// Apple's own rule for a note's title and its preview: the first line is the title, and
+/// what follows it is the snippet.
+///
+/// Deriving both here rather than asking the interface for them is what keeps a note saved
+/// from this app looking, in the list on a phone, exactly like one typed on the phone.
+#[must_use]
+pub fn title_and_snippet(body: &str) -> (String, String) {
+ let mut lines = body.lines().map(str::trim).filter(|l| !l.is_empty());
+ let title = lines.next().unwrap_or_default().to_string();
+ let snippet = lines.next().unwrap_or_default().to_string();
+ (title, snippet)
+}
+
+/// Save a new body onto an existing note.
+///
+/// The document is rewritten in place against whatever Apple currently holds, not against
+/// the local copy: the note may have moved on since the last sync, and the version vectors
+/// and merge state inside it belong to that newer version. Refuses outright rather than
+/// writing a document it cannot reproduce, because the failure mode of guessing here is
+/// losing the note's history.
+pub async fn edit_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ note: &Note,
+ body: &str,
+) -> Result<()> {
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+
+ let current = client
+ .lookup_record(ZONE, &note.guid)
+ .await?
+ .ok_or_else(|| Error::Protocol("Apple no longer has that note.".into()))?;
+
+ let encoded = current
+ .pointer("/fields/TextDataEncrypted/value")
+ .and_then(Value::as_str)
+ .ok_or_else(|| Error::Protocol("That note has no body Apple will let us read.".into()))?;
+
+ let rewritten = crate::ckdocument::replace_text_in_base64(encoded, body).ok_or_else(|| {
+ Error::Protocol(
+ "This note holds formatting Quince can't rewrite safely, so it was left unchanged."
+ .into(),
+ )
+ })?;
+
+ let (title, snippet) = title_and_snippet(body);
+ let tag = current
+ .get("recordChangeTag")
+ .and_then(Value::as_str)
+ .or(note.etag.as_deref());
+
+ client
+ .update_record(
+ ZONE,
+ &note.guid,
+ "Note",
+ tag,
+ serde_json::json!({
+ "TextDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": rewritten },
+ "TitleEncrypted": {
+ "type": "ENCRYPTED_BYTES",
+ "value": crate::ckdocument::bare_text_to_base64(&title),
+ },
+ "SnippetEncrypted": {
+ "type": "ENCRYPTED_BYTES",
+ "value": crate::ckdocument::bare_text_to_base64(&snippet),
+ },
+ "ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },
+ }),
+ )
+ .await?;
+ Ok(())
+}
+
+/// Write a new note, optionally into a folder.
+///
+/// Returns the record name Apple will know it by, so the caller can open it without waiting
+/// for the next sync.
+pub async fn create_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ folder_guid: Option<&str>,
+ body: &str,
+) -> Result<String> {
+ if body.trim().is_empty() {
+ return Err(Error::Protocol("a note needs something in it".into()));
+ }
+
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ let record_name = format!("Note/{}", uuid::Uuid::new_v4().to_string().to_uppercase());
+ let stamp = now_millis();
+ let (title, snippet) = title_and_snippet(body);
+
+ let mut fields = serde_json::json!({
+ "TextDataEncrypted": {
+ "type": "ENCRYPTED_BYTES",
+ "value": crate::ckdocument::text_to_base64(body),
+ },
+ "TitleEncrypted": {
+ "type": "ENCRYPTED_BYTES",
+ "value": crate::ckdocument::bare_text_to_base64(&title),
+ },
+ "SnippetEncrypted": {
+ "type": "ENCRYPTED_BYTES",
+ "value": crate::ckdocument::bare_text_to_base64(&snippet),
+ },
+ "CreationDate": { "type": "TIMESTAMP", "value": stamp },
+ "ModificationDate": { "type": "TIMESTAMP", "value": stamp },
+ });
+ if let Some(folder) = folder_guid {
+ fields["Folder"] = client.reference_to(ZONE, folder);
+ }
+
+ client
+ .create_record(ZONE, &record_name, "Note", fields)
+ .await?;
+ Ok(record_name)
+}
+
+/// Move a note into a folder, or out of every folder.
+pub async fn move_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ note: &Note,
+ folder_guid: Option<&str>,
+) -> Result<()> {
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ let folder = match folder_guid {
+ Some(guid) => client.reference_to(ZONE, guid),
+ // CloudKit clears a reference by writing an explicit null, not by omitting it.
+ None => Value::Null,
+ };
+ client
+ .update_record(
+ ZONE,
+ &note.guid,
+ "Note",
+ note.etag.as_deref(),
+ serde_json::json!({
+ "Folder": folder,
+ "ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },
+ }),
+ )
+ .await?;
+ Ok(())
+}
+
+/// Delete a note.
+///
+/// Apple keeps the `Note` record and marks the per-user record deleted instead, which is
+/// how a note disappears from every device while its history stays recoverable. Writing the
+/// flag on the note itself would be a different, harsher thing.
+pub async fn delete_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ note: &Note,
+) -> Result<()> {
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ let record_name = format!(
+ "Note_UserSpecific/{}",
+ uuid::Uuid::new_v4().to_string().to_uppercase()
+ );
+ client
+ .create_record(
+ ZONE,
+ &record_name,
+ "Note_UserSpecific",
+ serde_json::json!({
+ "Note": client.reference_to(ZONE, &note.guid),
+ "Deleted": { "type": "NUMBER_INT64", "value": 1 },
+ "ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },
+ }),
+ )
+ .await?;
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -396,3 +608,247 @@ mod tests {
assert!(stored[0].folder_guid.is_none());
}
}
+
+#[cfg(test)]
+mod write_tests {
+ use super::*;
+ use serde_json::json;
+ use wiremock::matchers::{method, path_regex};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ fn note(guid: &str) -> Note {
+ Note {
+ guid: guid.into(),
+ folder_guid: Some("Folder/a".into()),
+ title: "Curtains".into(),
+ snippet: None,
+ body: Some("Curtains\nmeasure the bay window".into()),
+ locked: false,
+ pinned: false,
+ created_at: None,
+ modified_at: None,
+ editable: true,
+ etag: Some("tag".into()),
+ }
+ }
+
+ /// A document shaped like the real ones: text surrounded by Apple's merge state.
+ fn document(text: &str) -> String {
+ use base64::{engine::general_purpose::STANDARD as B64, Engine};
+ use std::io::Write;
+ fn framed(tag: u8, payload: &[u8]) -> Vec<u8> {
+ let mut out = vec![(tag << 3) | 2];
+ let mut len = payload.len();
+ loop {
+ let mut byte = (len & 0x7F) as u8;
+ len >>= 7;
+ if len != 0 {
+ byte |= 0x80;
+ }
+ out.push(byte);
+ if len == 0 {
+ break;
+ }
+ }
+ out.extend_from_slice(payload);
+ out
+ }
+ // Version-vector siblings alongside the text, which a save must not disturb.
+ let mut note = framed(2, text.as_bytes());
+ note.extend(framed(3, &[0x08, 0x01, 0x10, 0x83, 0x8d, 0x02]));
+ let proto = framed(2, &framed(3, &note));
+
+ let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
+ gz.write_all(&proto).unwrap();
+ B64.encode(gz.finish().unwrap())
+ }
+
+ async fn server(existing: &str) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/lookup$"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "records": [{
+ "recordName": "Note/1",
+ "recordType": "Note",
+ "recordChangeTag": "fresh",
+ "fields": {
+ "TextDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": document(existing) }
+ }
+ }]
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/modify$"))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .set_body_json(json!({ "records": [{ "recordName": "Note/1" }] })),
+ )
+ .mount(&server)
+ .await;
+ server
+ }
+
+ async fn sent(server: &MockServer) -> Value {
+ let requests = server.received_requests().await.unwrap();
+ let modify = requests
+ .iter()
+ .find(|r| r.url.path().ends_with("/records/modify"))
+ .expect("a modify was sent");
+ serde_json::from_slice::<Value>(&modify.body).unwrap()["operations"][0]["record"].clone()
+ }
+
+ #[tokio::test]
+ async fn an_edit_rewrites_the_body_in_place() {
+ let server = server("Curtains\nmeasure the bay window").await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &note("Note/1"),
+ "Curtains\nmeasure the bay window\norder the rail",
+ )
+ .await
+ .unwrap();
+
+ let record = sent(&server).await;
+ let written = record["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap();
+ assert_eq!(
+ crate::ckdocument::text_from_base64(written).as_deref(),
+ Some("Curtains\nmeasure the bay window\norder the rail")
+ );
+ // The version vector alongside the text has to have come through the save.
+ let raw = crate::ckdocument::debug_inflate(written).unwrap();
+ assert!(
+ crate::ckdocument::debug_tree(&raw, 6)
+ .iter()
+ .any(|line| line.contains("3: message")),
+ "Apple's merge state must survive an edit"
+ );
+ }
+
+ /// The change tag comes from what Apple holds now, not from the local copy, so an edit
+ /// applies to the current version rather than racing a change made on a phone.
+ #[tokio::test]
+ async fn an_edit_uses_the_change_tag_apple_just_gave_us() {
+ let server = server("before").await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &note("Note/1"),
+ "after",
+ )
+ .await
+ .unwrap();
+ assert_eq!(sent(&server).await["recordChangeTag"], "fresh");
+ }
+
+ /// Apple's list shows the first line as the title and the next as the preview.
+ #[test]
+ fn the_first_line_is_the_title() {
+ assert_eq!(
+ title_and_snippet("Shopping\n\nmilk and bread\neggs"),
+ ("Shopping".into(), "milk and bread".into())
+ );
+ assert_eq!(
+ title_and_snippet(" just one line "),
+ ("just one line".into(), String::new())
+ );
+ assert_eq!(title_and_snippet(""), (String::new(), String::new()));
+ }
+
+ #[tokio::test]
+ async fn an_empty_note_is_refused_before_anything_is_sent() {
+ let server = server("x").await;
+ let outcome = create_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ None,
+ " \n ",
+ )
+ .await;
+ assert!(outcome.is_err());
+ assert!(
+ server.received_requests().await.unwrap().is_empty(),
+ "nothing should reach Apple"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_new_note_carries_its_folder_and_a_readable_body() {
+ let server = server("x").await;
+ let name = create_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ Some("Folder/a"),
+ "Packing\npassport",
+ )
+ .await
+ .unwrap();
+ assert!(name.starts_with("Note/"));
+
+ let record = sent(&server).await;
+ assert_eq!(
+ record["fields"]["Folder"]["value"]["recordName"],
+ "Folder/a"
+ );
+ assert_eq!(
+ crate::ckdocument::text_from_base64(
+ record["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap()
+ )
+ .as_deref(),
+ Some("Packing\npassport")
+ );
+ // The title Apple shows in its list is bare text, not a wrapped document.
+ assert_eq!(
+ crate::ckdocument::text_from_base64(
+ record["fields"]["TitleEncrypted"]["value"]
+ .as_str()
+ .unwrap()
+ )
+ .as_deref(),
+ Some("Packing")
+ );
+ }
+
+ /// Deleting writes the per-user record Apple uses, leaving the note itself intact.
+ #[tokio::test]
+ async fn deleting_marks_the_per_user_record() {
+ let server = server("x").await;
+ delete_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &note("Note/1"),
+ )
+ .await
+ .unwrap();
+ let record = sent(&server).await;
+ assert_eq!(record["recordType"], "Note_UserSpecific");
+ assert_eq!(record["fields"]["Deleted"]["value"], 1);
+ assert_eq!(record["fields"]["Note"]["value"]["recordName"], "Note/1");
+ }
+
+ #[tokio::test]
+ async fn moving_out_of_every_folder_clears_the_reference() {
+ let server = server("x").await;
+ move_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &note("Note/1"),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(sent(&server).await["fields"]["Folder"], Value::Null);
+ }
+}
diff --git a/probe/src/main.rs b/probe/src/main.rs
index da5cfda..67fac70 100644
--- a/probe/src/main.rs
+++ b/probe/src/main.rs
@@ -988,6 +988,58 @@ async fn main() -> Result<()> {
}
}
+ // ---- can a note be saved without damaging it? -------------------------------
+ // Editing a note means rewriting Apple's document while keeping the version vectors,
+ // folder links and merge state around the text. This checks, for every real note on the
+ // account, whether putting the text back exactly as it came out reproduces the original
+ // bytes. Where it does, a save is safe. Read-only — nothing is sent to Apple.
+ println!("\n\x1b[1m── Notes: is every note safe to edit? ──\x1b[0m");
+ if let Some(ck) = session.service_url("ckdatabasews") {
+ let zc = quince_icloud::cloudkit::ZoneClient::new(
+ client.http(),
+ &ck,
+ "com.apple.notes",
+ client.service_params(),
+ );
+ if let Ok((records, _)) = zc.all_records("Notes", None).await {
+ let (mut safe, mut refused) = (0, 0);
+ for rec in records
+ .iter()
+ .filter(|r| r.get("recordType").and_then(|t| t.as_str()) == Some("Note"))
+ {
+ let Some(encoded) = rec
+ .pointer("/fields/TextDataEncrypted/value")
+ .and_then(|v| v.as_str())
+ else {
+ continue;
+ };
+ let title = quince_icloud::cloudkit::field::document_text(rec, "TitleEncrypted")
+ .unwrap_or_else(|| "(untitled)".into());
+ let title: String = title.chars().take(44).collect();
+ let Some(raw) = quince_icloud::ckdocument::debug_inflate(encoded) else {
+ println!(" \x1b[33mSKIP\x1b[0m {title:<46} could not decompress");
+ refused += 1;
+ continue;
+ };
+ let text = quince_icloud::ckdocument::text_from_bytes(&raw).unwrap_or_default();
+ match quince_icloud::ckdocument::replace_text(&raw, &text) {
+ Some(rebuilt) if rebuilt == raw => {
+ println!(
+ " \x1b[32mSAFE\x1b[0m {title:<46} {} byte(s) reproduced exactly",
+ raw.len()
+ );
+ safe += 1;
+ }
+ _ => {
+ println!(" \x1b[33mREAD-ONLY\x1b[0m {title:<41} shape not reproducible");
+ refused += 1;
+ }
+ }
+ }
+ println!("\n {safe} note(s) editable, {refused} left read-only");
+ }
+ }
+
// ---- CloudKit containers ----------------------------------------------------
// Apple's legacy /rd and /ca endpoints answer with a placeholder once data has been
// upgraded to the modern format. The real records live in CloudKit, so find out which
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 159d32e..7c52909 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -465,6 +465,111 @@ async fn reminder_list_delete(
resync_reminders(&http, &root, params, &data).await
}
+/// Re-read notes after a write, so what is on screen is what Apple stored.
+async fn resync_notes(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ data: &State<'_, Data>,
+) -> Result<(), String> {
+ let mut library = data.0.lock().await;
+ let since = library.sync_token("notes").map_err(|e| e.to_string())?;
+ quince_icloud::notes::sync_cloudkit(http, root, params, &mut library, since.as_deref())
+ .await
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+}
+
+/// One note, by record name. `None` once Apple no longer has it.
+async fn note_by_guid(data: &State<'_, Data>, guid: &str) -> Result<Note, String> {
+ let library = data.0.lock().await;
+ library
+ .notes_in(None)
+ .map_err(|e| e.to_string())?
+ .into_iter()
+ .find(|n| n.guid == guid)
+ .ok_or_else(|| "That note is no longer in the local library.".into())
+}
+
+/// Save a note's body.
+///
+/// Writes to Apple first and re-reads after, so the editor never shows a version Apple has
+/// not accepted. A note whose document cannot be rewritten safely is refused with the
+/// reason rather than flattened.
+#[tauri::command]
+async fn note_save(
+ guid: String,
+ body: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<()> {
+ let (http, root, params) = cloudkit_context(&auth).await?;
+ let note = note_by_guid(&data, &guid).await?;
+ if !note.editable {
+ return Err(
+ "This note holds formatting Quince can't rewrite safely, so it stays read-only.".into(),
+ );
+ }
+ quince_icloud::notes::edit_cloudkit(&http, &root, params.clone(), &note, &body)
+ .await
+ .map_err(|e| e.to_string())?;
+ resync_notes(&http, &root, params, &data).await
+}
+
+/// Write a new note and return the record name Apple gave it.
+#[tauri::command]
+async fn note_create(
+ folder_guid: Option<String>,
+ body: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<String> {
+ let (http, root, params) = cloudkit_context(&auth).await?;
+ let guid = quince_icloud::notes::create_cloudkit(
+ &http,
+ &root,
+ params.clone(),
+ folder_guid.as_deref(),
+ &body,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ resync_notes(&http, &root, params, &data).await?;
+ Ok(guid)
+}
+
+#[tauri::command]
+async fn note_delete(guid: String, auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<()> {
+ let (http, root, params) = cloudkit_context(&auth).await?;
+ let note = note_by_guid(&data, &guid).await?;
+ quince_icloud::notes::delete_cloudkit(&http, &root, params.clone(), &note)
+ .await
+ .map_err(|e| e.to_string())?;
+ resync_notes(&http, &root, params, &data).await
+}
+
+/// Move a note into a folder, or out of every folder when `folder_guid` is absent.
+#[tauri::command]
+async fn note_move(
+ guid: String,
+ folder_guid: Option<String>,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<()> {
+ let (http, root, params) = cloudkit_context(&auth).await?;
+ let note = note_by_guid(&data, &guid).await?;
+ quince_icloud::notes::move_cloudkit(
+ &http,
+ &root,
+ params.clone(),
+ &note,
+ folder_guid.as_deref(),
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ resync_notes(&http, &root, params, &data).await
+}
+
#[tauri::command]
async fn note_folders(data: State<'_, Data>) -> UiResult<Vec<NoteFolder>> {
let library = data.0.lock().await;
@@ -618,6 +723,10 @@ fn main() {
reminder_list_rename,
reminder_list_delete,
note_folders,
+ note_save,
+ note_create,
+ note_delete,
+ note_move,
notes_in,
contacts_list,
drive_sync_folder,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 2b68327..e14d069 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -81,6 +81,12 @@ export const api = {
noteFolders: () => invoke<NoteFolder[]>("note_folders"),
notesIn: (folderGuid: string | null) => invoke<Note[]>("notes_in", { folderGuid }),
+ noteSave: (guid: string, body: string) => invoke<void>("note_save", { guid, body }),
+ noteCreate: (folderGuid: string | null, body: string) =>
+ invoke<string>("note_create", { folderGuid, body }),
+ noteDelete: (guid: string) => invoke<void>("note_delete", { guid }),
+ noteMove: (guid: string, folderGuid: string | null) =>
+ invoke<void>("note_move", { guid, folderGuid }),
contactsList: (search: string | null) => invoke<Contact[]>("contacts_list", { search }),
@@ -162,6 +168,8 @@ export type Note = {
body: string | null;
/** Locked by its owner, so Apple holds it encrypted and there is nothing to show. */
locked: boolean;
+ /** False when Apple's document can't be rewritten without losing what surrounds the text. */
+ editable: boolean;
pinned: boolean;
createdAt: number | null;
modifiedAt: number | null;
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index 5958b74..2b1c848 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -33,6 +33,10 @@ export function NotesView() {
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const { revision } = useSync();
+ /** The body being typed, held apart from the note until it is saved. */
+ const [draft, setDraft] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [saved, setSaved] = useState(false);
const read = useCallback(async () => {
const [found, list] = await Promise.all([
@@ -60,6 +64,28 @@ export function NotesView() {
};
}, [read, revision]);
+ /**
+ * Every write goes to Apple first and the library is re-read after, so nothing on screen
+ * is a guess about what was stored.
+ */
+ const write = useCallback(
+ async (run: () => Promise<void>) => {
+ setBusy(true);
+ setError(null);
+ try {
+ await run();
+ await read();
+ return true;
+ } catch (e) {
+ setError(messageOf(e));
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ },
+ [read]
+ );
+
// Keep a note open across refreshes where possible; fall back to the first.
useEffect(() => {
if (notes.length === 0) return setOpenGuid(null);
@@ -73,6 +99,56 @@ export function NotesView() {
[notes, openGuid]
);
+ // A different note means a different draft. Switching away from unsaved typing would
+ // otherwise carry it into the next note and save it over that one.
+ useEffect(() => {
+ setDraft(null);
+ setSaved(false);
+ }, [openGuid]);
+
+ const dirty = draft !== null && open !== null && draft !== (open.body ?? "");
+
+ const save = useCallback(async () => {
+ if (!open || draft === null || !dirty) return;
+ const body = draft;
+ if (await write(() => api.noteSave(open.guid, body))) {
+ setDraft(null);
+ setSaved(true);
+ }
+ }, [open, draft, dirty, write]);
+
+ const create = useCallback(async () => {
+ const guid = await api
+ .noteCreate(folder === ALL ? null : folder, "New Note\n")
+ .catch((e) => {
+ setError(messageOf(e));
+ return null;
+ });
+ if (guid === null) return;
+ await read();
+ setOpenGuid(guid);
+ }, [folder, read]);
+
+ const remove = useCallback(async () => {
+ if (!open) return;
+ await write(() => api.noteDelete(open.guid));
+ }, [open, write]);
+
+ const moveTo = useCallback(
+ async (guid: string) => {
+ if (!open) return;
+ await write(() => api.noteMove(open.guid, guid === ALL ? null : guid));
+ },
+ [open, write]
+ );
+
+ // A save confirmation is a moment, not a state.
+ useEffect(() => {
+ if (!saved) return undefined;
+ const timer = window.setTimeout(() => setSaved(false), 2000);
+ return () => window.clearTimeout(timer);
+ }, [saved]);
+
return (
<div className="notes">
<aside className="notes-folders" aria-label="Note folders">
@@ -103,6 +179,11 @@ export function NotesView() {
{notes.length} {notes.length === 1 ? "note" : "notes"}
</span>
</div>
+ <div className="cal-actions">
+ <button className="quiet" onClick={() => void create()} disabled={busy}>
+ New note
+ </button>
+ </div>
</header>
{/* Shown only when the folder column has folded away. */}
@@ -163,8 +244,62 @@ export function NotesView() {
{/* Apple derives a note's title from its first line, so the body already
contains it. Rendering both shows the same sentence twice. */}
{!bodyRepeatsTitle(open) && <h2>{open.title}</h2>}
- <p className="note-when">{when(open.modifiedAt)}</p>
- <pre className="note-text">{open.body ?? ""}</pre>
+
+ <div className="note-bar">
+ <p className="note-when">
+ {saved ? "Saved" : dirty ? "Unsaved changes" : when(open.modifiedAt)}
+ </p>
+ <div className="note-bar-actions">
+ <select
+ value={open.folderGuid ?? ALL}
+ onChange={(e) => void moveTo(e.target.value)}
+ disabled={busy}
+ aria-label={`Folder for ${open.title}`}
+ >
+ <option value={ALL}>No folder</option>
+ {folders.map((f) => (
+ <option key={f.guid} value={f.guid}>
+ {f.title}
+ </option>
+ ))}
+ </select>
+ {open.editable && (
+ <button className="quiet" onClick={() => void save()} disabled={!dirty || busy}>
+ {busy ? "Saving…" : "Save"}
+ </button>
+ )}
+ <button className="quiet danger" onClick={() => void remove()} disabled={busy}>
+ Delete
+ </button>
+ </div>
+ </div>
+
+ {open.editable ? (
+ <textarea
+ className="note-text"
+ aria-label={`Body of ${open.title}`}
+ value={draft ?? open.body ?? ""}
+ disabled={busy}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ // Apple's own shortcut, and the one a keyboard user reaches for.
+ if ((e.metaKey || e.ctrlKey) && e.key === "s") {
+ e.preventDefault();
+ void save();
+ }
+ }}
+ onBlur={() => void save()}
+ spellCheck
+ />
+ ) : (
+ <>
+ <pre className="note-text">{open.body ?? ""}</pre>
+ <p className="note-readonly">
+ This note holds formatting Quince can't rewrite without losing it, so it
+ stays read-only here. Editing it on an Apple device is safe.
+ </p>
+ </>
+ )}
</>
)
) : (
diff --git a/src/styles/app.css b/src/styles/app.css
index 157e58b..701516d 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -875,6 +875,59 @@
max-width: 68ch;
}
+/* The editor is the same surface as the reader, with no border and no field chrome: typing
+ in a note should feel like writing on the page, which is how Apple's own editor reads. */
+textarea.note-text {
+ width: 100%;
+ flex: 1;
+ min-height: 40vh;
+ resize: none;
+ border: 0;
+ padding: 0;
+ background: none;
+ color: inherit;
+}
+
+textarea.note-text:focus {
+ outline: none;
+}
+
+textarea.note-text:disabled {
+ color: var(--text-2);
+}
+
+.note-bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+}
+
+.note-bar-actions {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.note-bar-actions select {
+ font-size: var(--t-11);
+ padding: 3px 6px;
+ border-radius: var(--r-field);
+ border: 0.5px solid var(--field-edge);
+ background: var(--field);
+ color: var(--text);
+}
+
+.quiet.danger { color: var(--danger); }
+
+.note-readonly {
+ margin: 14px 0 0;
+ max-width: 68ch;
+ font-size: var(--t-11);
+ color: var(--text-3);
+}
+
/* Apple gives Notes three columns; our service sidebar already takes one, so these have to
earn their width. Folders are few and short, the list carries two lines per row, and the