Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Notes folders sit inside each other, the way they were filed
Yashwanth Kamireddi661a4ccf8432
diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rsindex d52e0ad..8b5dc96 100644--- a/crates/quince-core/src/notes.rs+++ b/crates/quince-core/src/notes.rs@@ -10,6 +10,9 @@ pub struct NoteFolder {pub guid: String,pub title: String,pub sort_order: i64,+ /// The folder this one sits inside, where it sits inside one at all.+ #[serde(default)]+ pub parent_guid: Option<String>,}/// Apple's identifier for the folder deleted notes go to.@@ -65,15 +68,16 @@ impl Library {let tx = self.conn.transaction()?;{let mut stmt = tx.prepare(- "INSERT INTO note_folders (guid, title, sort_order, updated_at)- VALUES (?1, ?2, ?3, ?4)+ "INSERT INTO note_folders (guid, title, sort_order, parent_guid, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5)ON CONFLICT(guid) DO UPDATE SETtitle = excluded.title, sort_order = excluded.sort_order,+ parent_guid = excluded.parent_guid,updated_at = excluded.updated_at",)?;let stamp = now();for f in folders {- stmt.execute(params![f.guid, f.title, f.sort_order, stamp])?;+ stmt.execute(params![f.guid, f.title, f.sort_order, f.parent_guid, stamp])?;}}tx.commit()?;@@ -161,13 +165,15 @@ impl Library {pub fn note_folders(&self) -> Result<Vec<NoteFolder>> {let mut stmt = self.conn.prepare(- "SELECT guid, title, sort_order FROM note_folders ORDER BY sort_order, title",+ "SELECT guid, title, sort_order, parent_guid+ FROM note_folders ORDER BY sort_order, title",)?;let rows = stmt.query_map([], |row| {Ok(NoteFolder {guid: row.get(0)?,title: row.get(1)?,sort_order: row.get(2)?,+ parent_guid: row.get(3)?,})})?;Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)@@ -214,9 +220,53 @@ mod tests {guid: guid.into(),title: title.into(),sort_order: 0,+ parent_guid: None,}}+ /// Apple Notes nests folders, and the link has to survive a round trip through the+ /// library or somebody's filing comes back as one flat list.+ #[test]+ fn a_folder_remembers_the_one_it_sits_inside() {+ let mut lib = Library::in_memory().unwrap();+ let mut inner = folder("f2", "Semester 5");+ inner.parent_guid = Some("f1".into());+ lib.put_note_folders(&[folder("f1", "University"), inner])+ .unwrap();++ let stored = lib.note_folders().unwrap();+ let nested = stored.iter().find(|f| f.guid == "f2").unwrap();+ assert_eq!(nested.parent_guid.as_deref(), Some("f1"));+ assert_eq!(+ stored.iter().find(|f| f.guid == "f1").unwrap().parent_guid,+ None,+ "a top-level folder sits inside nothing"+ );+ }++ /// A folder moved out to the top level must not keep its old parent.+ #[test]+ fn a_folder_moved_to_the_top_stops_naming_a_parent() {+ let mut lib = Library::in_memory().unwrap();+ let mut inner = folder("f2", "Semester 5");+ inner.parent_guid = Some("f1".into());+ lib.put_note_folders(&[folder("f1", "University"), inner.clone()])+ .unwrap();++ inner.parent_guid = None;+ lib.put_note_folders(&[folder("f1", "University"), inner])+ .unwrap();+ assert_eq!(+ lib.note_folders()+ .unwrap()+ .iter()+ .find(|f| f.guid == "f2")+ .unwrap()+ .parent_guid,+ None+ );+ }+fn note(guid: &str, folder: Option<&str>, pinned: bool, modified: i64) -> Note {Note {guid: guid.into(),diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rsindex 51a3666..238e152 100644--- a/crates/quince-core/src/schema.rs+++ b/crates/quince-core/src/schema.rs@@ -244,4 +244,14 @@ pub const MIGRATIONS: &[&str] = &[ALTER TABLE calendars ADD COLUMN writable INTEGER NOT NULL DEFAULT 1;ALTER TABLE calendars ADD COLUMN is_default INTEGER NOT NULL DEFAULT 0;"#,+ // 16 — a notes folder can sit inside another one.+ //+ // Apple Notes has nested folders and keeps the link on the folder record as+ // `ParentFolder`. This account has only the two Apple makes for itself, neither of which+ // is nested, so the field was never seen — but a folder created with one is accepted and+ // handed straight back, which is how it was confirmed. Flattened, somebody's filing comes+ // out as one long list with every level jumbled together.+ r#"+ ALTER TABLE note_folders ADD COLUMN parent_guid TEXT;+ "#,];diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex 5b40d08..4356259 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -20,6 +20,11 @@ fn folder_from_record(record: &Value) -> Option<NoteFolder> {guid: field::record_name(record)?,title: field::document_text(record, "TitleEncrypted").unwrap_or_else(|| "Notes".into()),sort_order: 0,+ // Apple Notes nests folders and keeps the link here. Neither folder Apple makes for+ // itself has one, so this account never shows it — but a folder created with one is+ // accepted and handed straight back, which is how it was confirmed. Without it,+ // somebody's filing comes out as one long list with every level jumbled together.+ parent_guid: field::reference(record, "ParentFolder"),})}@@ -884,3 +889,66 @@ mod write_tests {assert_eq!(sent(&server).await["fields"]["Folder"], Value::Null);}}++/// Folders other people have, that this account does not.+///+/// This account holds only the two Apple makes for itself, neither nested. A folder created+/// with a `ParentFolder` reference was accepted and handed straight back, which is how the+/// field was confirmed — these carry that shape.+#[cfg(test)]+mod folder_shape_tests {+ use super::*;+ use serde_json::json;++ fn folder(name: &str, title: &str, parent: Option<&str>) -> Value {+ let mut fields = json!({+ "TitleEncrypted": {+ "type": "ENCRYPTED_BYTES",+ "value": crate::ckdocument::bare_text_to_base64(title),+ },+ });+ if let Some(parent) = parent {+ fields["ParentFolder"] = json!({+ "type": "REFERENCE",+ "value": { "action": "VALIDATE", "recordName": parent },+ });+ }+ json!({ "recordName": name, "recordType": "Folder", "fields": fields })+ }++ #[test]+ fn a_nested_folder_keeps_the_one_it_sits_in() {+ let outer = folder_from_record(&folder("F1", "University", None)).unwrap();+ let inner = folder_from_record(&folder("F2", "Semester 5", Some("F1"))).unwrap();+ assert_eq!(outer.parent_guid, None);+ assert_eq!(inner.parent_guid.as_deref(), Some("F1"));+ assert_eq!(inner.title, "Semester 5");+ }++ /// The two Apple makes for itself have no parent and must not gain one.+ #[test]+ fn apples_own_folders_stay_at_the_top() {+ for name in ["DefaultFolder-CloudKit", "TrashFolder-CloudKit"] {+ let parsed = folder_from_record(&json!({+ "recordName": name,+ "recordType": "Folder",+ "fields": {+ "MinimumSupportedNotesVersion": { "type": "INT64", "value": 0 },+ "TitleEncrypted": { "type": "ENCRYPTED_BYTES", "value": "Tm90ZXM=" },+ }+ }))+ .unwrap();+ assert_eq!(parsed.parent_guid, None);+ assert_eq!(parsed.title, "Notes", "plain base64, which Apple also uses");+ }+ }++ /// A folder whose parent has been deleted must still appear, at the top rather than+ /// nowhere — a folder that references nothing is not a folder that does not exist.+ #[test]+ fn a_folder_whose_parent_is_gone_is_still_a_folder() {+ let orphan = folder_from_record(&folder("F3", "Odds and ends", Some("GONE"))).unwrap();+ assert_eq!(orphan.title, "Odds and ends");+ assert_eq!(orphan.parent_guid.as_deref(), Some("GONE"));+ }+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex de20f1f..dbbd5df 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -235,7 +235,47 @@ export type Reminder = {etag: string | null;};-export type NoteFolder = { guid: string; title: string; sortOrder: number };+export type NoteFolder = {+ guid: string;+ title: string;+ sortOrder: number;+ /** The folder this one sits inside, where it sits inside one at all. */+ parentGuid: string | null;+};++/**+ * Folders in the order they are filed, each with how deep it sits.+ *+ * Apple Notes nests folders, and flattening them turns somebody's filing into one long list+ * with every level jumbled together. A folder whose parent has been deleted is shown at the+ * top rather than dropped — it still holds notes.+ */+export function nestFolders(folders: NoteFolder[]): { folder: NoteFolder; depth: number }[] {+ const byParent = new Map<string | null, NoteFolder[]>();+ const known = new Set(folders.map((f) => f.guid));+ for (const f of folders) {+ const under = f.parentGuid && known.has(f.parentGuid) ? f.parentGuid : null;+ byParent.set(under, [...(byParent.get(under) ?? []), f]);+ }++ const out: { folder: NoteFolder; depth: number }[] = [];+ const seen = new Set<string>();+ const walk = (parent: string | null, depth: number) => {+ for (const folder of byParent.get(parent) ?? []) {+ // A folder cannot be its own ancestor, but nothing about the data guarantees that, and+ // a cycle here would hang the window rather than show a wrong tree.+ if (seen.has(folder.guid)) continue;+ seen.add(folder.guid);+ out.push({ folder, depth });+ walk(folder.guid, depth + 1);+ }+ };+ walk(null, 0);+ for (const folder of folders) {+ if (!seen.has(folder.guid)) out.push({ folder, depth: 0 });+ }+ return out;+}export type Note = {guid: string;diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 3db60e0..7e38220 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { api, messageOf, type Note, type NoteFolder } from "../lib/ipc";+import { api, messageOf, nestFolders, type Note, type NoteFolder } from "../lib/ipc";import { useSync } from "../lib/sync";import { Picker } from "../components/Picker";@@ -242,12 +242,14 @@ export function NotesView() {><span className="rem-list-name">All Notes</span></button>- {folders.map((f) => (+ {nestFolders(folders).map(({ folder: f, depth }) => (<buttonkey={f.guid}className="rem-list"aria-current={folder === f.guid}onClick={() => setFolder(f.guid)}+ /* A folder inside another is shown inside it, the way it was filed. */+ style={depth > 0 ? { paddingLeft: `${8 + depth * 14}px` } : undefined}><span className="rem-list-name">{f.title}</span></button>