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 can be searched
Yashwanth Kamireddifec53945c45a
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex 86eab38..bd43476 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -369,6 +369,47 @@ let failures = 0;await page.close();}+// ── Notes can be searched ─────────────────────────────────────────────────────────────+{+ const page = await ctx.newPage();+ await page.addInitScript(() => {+ const n = (guid, title) => ({ guid, folderGuid: "F", title, snippet: null, body: null,+ locked: false, editable: true, pinned: false, createdAt: 1, modifiedAt: 1, etag: null });+ window.__TAURI_INTERNALS__ = {+ transformCallback: (cb) => cb,+ invoke: async (cmd, args) => {+ if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };+ if (cmd === "auth_resume") return true;+ if (cmd === "account_services") return ["notes"];+ if (cmd === "note_folders") return [{ guid: "F", title: "Notes", sortOrder: 0, parentGuid: null }];+ if (cmd === "notes_in") return [n("A", "Curtains"), n("B", "Shopping")];+ if (cmd === "notes_search") return args.query.toLowerCase().includes("curt") ? [n("A", "Curtains")] : [];+ if (cmd === "note_body") return "";+ if (cmd === "sync_all" || cmd === "sync_status") return { services: [], asOf: 1, tookMs: 0 };+ if (cmd === "plugin:event|listen") return 0;+ return [];+ },+ };+ });+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+ await page.getByRole("button", { name: "Notes", exact: true }).click();+ await page.waitForTimeout(300);+ await page.fill('input[aria-label="Search notes"]', "curt");+ await page.waitForTimeout(300);+ const shown = await page.locator(".notes-list").innerText();+ const narrowed = shown.includes("Curtains") && !shown.includes("Shopping");+ await page.press('input[aria-label="Search notes"]', "Escape");+ await page.waitForTimeout(300);+ const back = (await page.locator(".notes-list").innerText()).includes("Shopping");+ console.log(+ narrowed && back+ ? "PASS searching narrows the notes, and Escape brings them back"+ : `FAIL search: narrowed=${narrowed} back=${back}`+ );+ if (!(narrowed && back)) failures++;+ await page.close();+}+// ── A list shows its own sections ─────────────────────────────────────────────────────// Inside a real list, reminders outside any section come first with no heading, then each// section under its own heading — how Apple shows it, and how the phone showed "🌅".diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rsindex 157d05f..e918000 100644--- a/crates/quince-core/src/notes.rs+++ b/crates/quince-core/src/notes.rs@@ -258,6 +258,152 @@ impl Library {})?;Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)}++ /// Notes whose title or text holds every word of `query`, in the list's own order.+ ///+ /// Matched here rather than in SQL, because SQLite folds case for ASCII alone: a search+ /// for "Café" would miss "café", and so would anything written in a script with case of+ /// its own. Every word has to appear, in any order, which is how Apple's search behaves.+ /// Recently Deleted is left out, as it is on the phone. Bodies are read to match against+ /// and never returned — the results cross into the window like any other list.+ pub fn search_notes(&self, query: &str) -> Result<Vec<Note>> {+ let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();+ if words.is_empty() {+ return Ok(Vec::new());+ }+ let mut stmt = self.conn.prepare(+ "SELECT guid, folder_guid, title,+ coalesce(snippet, substr(body, 1, 200)), locked, pinned,+ created_at, modified_at, editable, etag, coalesce(body, '')+ FROM notes+ WHERE folder_guid IS NULL OR folder_guid != ?1+ ORDER BY pinned DESC, modified_at DESC, title",+ )?;+ let rows = stmt.query_map(params![TRASH_FOLDER], |row| {+ let body: String = row.get(10)?;+ Ok((+ Note {+ guid: row.get(0)?,+ folder_guid: row.get(1)?,+ title: row.get(2)?,+ snippet: row.get(3)?,+ body: None,+ locked: row.get::<_, i64>(4)? != 0,+ pinned: row.get::<_, i64>(5)? != 0,+ created_at: row.get(6)?,+ modified_at: row.get(7)?,+ editable: row.get::<_, i64>(8)? != 0,+ etag: row.get(9)?,+ },+ body,+ ))+ })?;+ let mut found = Vec::new();+ for row in rows {+ let (note, body) = row?;+ let haystack = format!("{}\n{}", note.title, body).to_lowercase();+ if words.iter().all(|w| haystack.contains(w.as_str())) {+ found.push(note);+ }+ }+ Ok(found)+ }+}++#[cfg(test)]+mod search_tests {+ use super::*;++ fn note(guid: &str, folder: &str, title: &str, body: &str) -> Note {+ Note {+ guid: guid.into(),+ folder_guid: Some(folder.into()),+ title: title.into(),+ snippet: None,+ body: Some(body.into()),+ locked: false,+ editable: true,+ pinned: false,+ created_at: Some(1),+ modified_at: Some(1),+ etag: None,+ }+ }++ fn library() -> Library {+ let mut lib = Library::in_memory().unwrap();+ lib.put_note_folders(&[+ NoteFolder {+ guid: "F".into(),+ title: "Notes".into(),+ sort_order: 0,+ parent_guid: None,+ },+ NoteFolder {+ guid: TRASH_FOLDER.into(),+ title: "Recently Deleted".into(),+ sort_order: 1,+ parent_guid: None,+ },+ ])+ .unwrap();+ lib.put_notes(&[+ note("A", "F", "Curtains", "Bathroom accessories like mirrors"),+ note("B", "F", "Café list", "Flat white, then a croissant"),+ note("C", "F", "తెలుగు", "Notes written in Telugu"),+ note(+ "D",+ TRASH_FOLDER,+ "Curtains old",+ "deleted draft about mirrors",+ ),+ ])+ .unwrap();+ lib+ }++ fn found(lib: &Library, q: &str) -> Vec<String> {+ lib.search_notes(q)+ .unwrap()+ .into_iter()+ .map(|n| n.guid)+ .collect()+ }++ #[test]+ fn a_word_in_the_body_finds_the_note() {+ assert_eq!(found(&library(), "mirrors"), vec!["A"]);+ }++ /// SQLite folds ASCII only; this is the case that made matching live in Rust.+ #[test]+ fn case_is_folded_beyond_ascii() {+ assert_eq!(found(&library(), "CAFÉ"), vec!["B"]);+ assert_eq!(found(&library(), "తెలుగు"), vec!["C"]);+ }++ /// Every word must be there, in any order.+ #[test]+ fn every_word_has_to_appear() {+ assert_eq!(found(&library(), "croissant flat"), vec!["B"]);+ assert!(found(&library(), "croissant mirrors").is_empty());+ }++ /// Recently Deleted is not searched, as on the phone.+ #[test]+ fn deleted_notes_are_not_found() {+ assert!(!found(&library(), "draft").contains(&"D".to_string()));+ }++ #[test]+ fn nothing_typed_finds_nothing_and_nothing_carries_a_body() {+ assert!(found(&library(), " ").is_empty());+ assert!(library()+ .search_notes("mirrors")+ .unwrap()+ .iter()+ .all(|n| n.body.is_none()));+ }}#[cfg(test)]diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 80b7477..ae77f07 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -808,6 +808,13 @@ async fn note_folders(data: State<'_, Data>) -> UiResult<Vec<NoteFolder>> {library.note_folders().map_err(|e| e.to_string())}+/// Notes holding every word of `query`, from every folder but Recently Deleted.+#[tauri::command]+async fn notes_search(query: String, data: State<'_, Data>) -> UiResult<Vec<Note>> {+ let library = data.0.lock().await;+ library.search_notes(&query).map_err(|e| e.to_string())+}+/// Notes in a folder, or every note when no folder is given.#[tauri::command]async fn notes_in(folder_guid: Option<String>, data: State<'_, Data>) -> UiResult<Vec<Note>> {@@ -1436,6 +1443,7 @@ fn main() {note_delete,note_move,notes_in,+ notes_search,contacts_list,contact_save,contact_delete,diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex d358fd3..20ba8c8 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -89,6 +89,8 @@ export const api = {noteFolders: () => invoke<NoteFolder[]>("note_folders"),notesIn: (folderGuid: string | null) => invoke<Note[]>("notes_in", { folderGuid }),+ /** Notes holding every word typed, from every folder but Recently Deleted. */+ notesSearch: (query: string) => invoke<Note[]>("notes_search", { query }),/*** One note's text, whole. Null when there is no such note any more.*diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 7f5d383..5b234f1 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -39,15 +39,20 @@ export function NotesView() {const [busy, setBusy] = useState(false);const [saved, setSaved] = useState(false);+ /** What is typed in the search field. While it holds anything, the list is the results. */+ const [query, setQuery] = useState("");+ const searching = query.trim().length > 0;+const read = useCallback(async () => {const [found, list] = await Promise.all([api.noteFolders(),- api.notesIn(folder === ALL ? null : folder),+ // Search reaches every folder, as Apple's does — a note is found wherever it is filed.+ searching ? api.notesSearch(query) : api.notesIn(folder === ALL ? null : folder),]);setFolders(Array.isArray(found) ? found : []);setNotes(Array.isArray(list) ? list : []);setLoaded(true);- }, [folder]);+ }, [folder, query, searching]);// Reads the library and nothing else. `revision` ticks when a refresh finishes, whether// someone pressed for it or the timer came round, and that is the screen's whole@@ -305,7 +310,13 @@ export function NotesView() {<section className="notes-list" aria-label="Notes"><header className="cal-bar"><div className="cal-nav">- <h1>{folder === ALL ? "All Notes" : folders.find((f) => f.guid === folder)?.title}</h1>+ <h1>+ {searching+ ? "Search"+ : folder === ALL+ ? "All Notes"+ : folders.find((f) => f.guid === folder)?.title}+ </h1><span className="badge">{notes.length} {notes.length === 1 ? "note" : "notes"}</span>@@ -316,6 +327,17 @@ export function NotesView() {</button></div></header>+ <input+ className="notes-search"+ type="search"+ placeholder="Search"+ aria-label="Search notes"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Escape") setQuery("");+ }}+ />{/* Shown only when the folder column has folded away. */}<div className="notes-folder-picker">diff --git a/src/styles/app.css b/src/styles/app.cssindex 143f364..c7a4118 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -2431,3 +2431,18 @@ button.cal-day-item:hover { background: color-mix(in srgb, var(--sheet) 92%, varborder-radius: 4px;background: color-mix(in srgb, var(--text) 8%, transparent);}++/* Search above the list, where Apple puts it: quiet until typed in. */+.notes-search {+ width: 100%;+ margin: 0 0 8px;+ padding: 6px 10px;+ border: 0;+ border-radius: var(--r-field);+ background: color-mix(in srgb, var(--text) 7%, transparent);+ color: var(--text);+ font: inherit;+ font-size: var(--t-13);+}+.notes-search::placeholder { color: var(--text-3); }+.notes-search:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--gold-ring); }