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
Typing in a note can no longer lose the note
Yashwanth Kamireddi075d4a80d987
diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rsindex c59c39e..157d05f 100644--- a/crates/quince-core/src/notes.rs+++ b/crates/quince-core/src/notes.rs@@ -170,14 +170,34 @@ impl Library {pub fn note_body(&self, guid: &str) -> Result<Option<String>> {let mut stmt = self.conn- .prepare("SELECT body FROM notes WHERE guid = ?1")?;+ .prepare("SELECT body, title, snippet FROM notes WHERE guid = ?1")?;let mut rows = stmt.query(params![guid])?;- match rows.next()? {- // The note exists but has nothing in it — which is not the same as no such note,- // and the difference decides whether an editor may open.- Some(row) => Ok(Some(row.get::<_, Option<String>>(0)?.unwrap_or_default())),- None => Ok(None),+ let Some(row) = rows.next()? else {+ return Ok(None);+ };+ let body: Option<String> = row.get(0)?;+ if body.is_some() {+ return Ok(body);}++ // No body stored. That is either a note with nothing in it, or one whose text could+ // not be read — and the two must not be confused, because an editor opened over the+ // second shows an empty box, and the first keystroke saves that emptiness over+ // whatever was really there. A five-line note became a single letter that way.+ //+ // A note with a name or a line of preview has something in it, so no body means it+ // was not read. Answering "not known" keeps the editor shut.+ let title: Option<String> = row.get(1)?;+ let snippet: Option<String> = row.get(2)?;+ let has_content = [title, snippet]+ .into_iter()+ .flatten()+ .any(|s| !s.trim().is_empty());+ Ok(if has_content {+ None+ } else {+ Some(String::new())+ })}pub fn note_folders(&self) -> Result<Vec<NoteFolder>> {@@ -419,8 +439,10 @@ mod body_tests {},Note {guid: "N2".into(),+ // A note with nothing in it has no name either — a name with no body means+ // the text was not read, which is a different thing and answered differently.folder_guid: Some("F1".into()),- title: "Empty one".into(),+ title: String::new(),snippet: None,body: None,locked: false,@@ -473,3 +495,60 @@ mod body_tests {assert_eq!(lib.note_body("nothing-like-this").unwrap(), None);}}++/// Telling an empty note from one whose text could not be read.+#[cfg(test)]+mod unreadable_tests {+ use super::*;++ fn note(guid: &str, title: &str, snippet: Option<&str>, body: Option<&str>) -> Note {+ Note {+ guid: guid.into(),+ folder_guid: None,+ title: title.into(),+ snippet: snippet.map(ToString::to_string),+ body: body.map(ToString::to_string),+ locked: false,+ editable: true,+ pinned: false,+ created_at: Some(1),+ modified_at: Some(1),+ etag: None,+ }+ }++ /// The difference decides whether an editor opens. Over a note whose text was not read,+ /// an empty box is shown and the first keystroke saves that emptiness over whatever was+ /// really there — which is how a five-line note became a single letter.+ #[test]+ fn a_note_whose_text_was_not_read_answers_that_it_is_not_known() {+ let mut lib = Library::in_memory().unwrap();+ lib.put_notes(&[+ note("EMPTY", "", None, None),+ note("UNREAD", "Shopping list", Some("Milk"), None),+ note(+ "READ",+ "Shopping list",+ Some("Milk"),+ Some("Shopping list\nMilk"),+ ),+ ])+ .unwrap();++ assert_eq!(+ lib.note_body("EMPTY").unwrap(),+ Some(String::new()),+ "a note with nothing in it is empty, and may be typed into"+ );+ assert_eq!(+ lib.note_body("UNREAD").unwrap(),+ None,+ "a note with a name but no text was not read, and must not be typed into"+ );+ assert_eq!(+ lib.note_body("READ").unwrap().as_deref(),+ Some("Shopping list\nMilk")+ );+ assert_eq!(lib.note_body("no-such-note").unwrap(), None);+ }+}diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex c02e4a5..d9c3ef9 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -15,6 +15,15 @@ use serde_json::Value;const CONTAINER: &str = "com.apple.notes";const ZONE: &str = "Notes";+/// The first folder in a note's `Folders` list, where it has one.+fn first_folder(record: &Value) -> Option<String> {+ record+ .pointer("/fields/Folders/value")?+ .as_array()?+ .iter()+ .find_map(|entry| entry.get("recordName")?.as_str().map(ToString::to_string))+}+fn folder_from_record(record: &Value) -> Option<NoteFolder> {Some(NoteFolder {guid: field::record_name(record)?,@@ -58,7 +67,15 @@ fn note_from_record(record: &Value) -> Option<Note> {Some(Note {guid,- folder_guid: field::reference(record, "Folder"),+ // `Folders` first, `Folder` only if there is no list.+ //+ // Apple carries both, and on one note on this account they disagree: Curtains has+ // Folder pointing at Recently Deleted and Folders naming the real one. The phone+ // shows it where Folders says, so the list is what counts and the singular is a+ // leftover. Reading the leftover put a note the owner had taken back out of the+ // trash straight back into it here — and hid it, because deleted notes are filtered+ // from every folder view.+ folder_guid: first_folder(record).or_else(|| field::reference(record, "Folder")),title: title.unwrap_or_else(|| "Untitled".into()),snippet: field::document_text(record, "SnippetEncrypted"),body,@@ -1160,3 +1177,90 @@ mod title_tests {assert_eq!(title_and_snippet("\n\n\n"), (String::new(), String::new()));}}++/// Which folder a note is in, when Apple's two answers disagree.+#[cfg(test)]+mod folder_of_tests {+ use super::*;+ use serde_json::json;++ fn note_in(folder: Option<&str>, folders: Option<&[&str]>) -> Value {+ let mut fields = json!({+ "TextDataEncrypted": {+ "type": "ENCRYPTED_BYTES",+ "value": crate::ckdocument::text_to_base64("Curtains\nBathroom accessories"),+ },+ });+ if let Some(one) = folder {+ fields["Folder"] = json!({+ "type": "REFERENCE",+ "value": { "action": "NONE", "recordName": one },+ });+ }+ if let Some(list) = folders {+ fields["Folders"] = json!({+ "type": "REFERENCE_LIST",+ "value": list.iter().map(|n| json!({ "action": "NONE", "recordName": n }))+ .collect::<Vec<_>>(),+ });+ }+ json!({ "recordName": "N1", "recordType": "Note", "fields": fields })+ }++ /// The case this was found on: one note where the two fields disagree. The phone shows it+ /// where the list says, so the list is what counts. Believing the other one put a note the+ /// owner had taken back out of the trash straight back into it — and hid it, because+ /// deleted notes are filtered out of every folder view.+ #[test]+ fn the_list_wins_over_the_leftover() {+ let parsed = note_from_record(¬e_in(+ Some("TrashFolder-CloudKit"),+ Some(&["DefaultFolder-CloudKit"]),+ ))+ .unwrap();+ assert_eq!(+ parsed.folder_guid.as_deref(),+ Some("DefaultFolder-CloudKit")+ );+ }++ /// Where they agree, nothing changes.+ #[test]+ fn agreement_is_left_alone() {+ let parsed = note_from_record(¬e_in(+ Some("DefaultFolder-CloudKit"),+ Some(&["DefaultFolder-CloudKit"]),+ ))+ .unwrap();+ assert_eq!(+ parsed.folder_guid.as_deref(),+ Some("DefaultFolder-CloudKit")+ );+ }++ /// A note with no list still has to be filed somewhere.+ #[test]+ fn without_a_list_the_single_field_is_used() {+ let parsed = note_from_record(¬e_in(Some("TrashFolder-CloudKit"), None)).unwrap();+ assert_eq!(parsed.folder_guid.as_deref(), Some("TrashFolder-CloudKit"));+ }++ /// And a note with neither is in no folder rather than in a wrong one.+ #[test]+ fn with_neither_it_is_in_no_folder() {+ assert_eq!(+ note_from_record(¬e_in(None, None)).unwrap().folder_guid,+ None+ );+ }++ /// An empty list is not an answer; the other field still is.+ #[test]+ fn an_empty_list_falls_back() {+ let parsed = note_from_record(¬e_in(Some("DefaultFolder-CloudKit"), Some(&[]))).unwrap();+ assert_eq!(+ parsed.folder_guid.as_deref(),+ Some("DefaultFolder-CloudKit")+ );+ }+}diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 7def71c..7f5d383 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -127,7 +127,13 @@ export function NotesView() {api.noteBody(openGuid).then((text) => {- if (!cancelled && text !== null) setLoadedBody({ guid: openGuid, text });+ if (cancelled || text === null) return;+ // Never over what is being typed. A refresh follows every save, and adopting its+ // answer under someone's cursor is how a half-saved note replaced a whole one.+ setDraft((typing) => {+ if (typing === null) setLoadedBody({ guid: openGuid, text });+ return typing;+ });}).catch((e) => {if (!cancelled) setError(messageOf(e));@@ -157,8 +163,14 @@ export function NotesView() {if (!next) return;pending.current = null;if (await write(() => api.noteSave(next.guid, next.body))) {- // The draft has served its purpose: the library now holds what was typed.- setDraft((current) => (current === next.body ? null : current));+ // The draft is kept, not cleared. Clearing it handed the box back to whatever the+ // library last handed over, and a save is followed by a refresh — so for a moment the+ // box showed text older than what had just been typed, and the next keystroke was+ // typed onto that and saved over the real note. A note went from five lines to a+ // single letter that way.+ //+ // While someone is in a note, what is on their screen is the note. It is given up only+ // when they leave it.setSaved(true);}}, [write]);