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: pin and unpin, written to Apple's per-user record

Yashwanth Kamireddi604706db1d30
diff --git a/.uiverify/notes-pin.mjs b/.uiverify/notes-pin.mjs
new file mode 100644
index 0000000..f9e7eb0
--- /dev/null
+++ b/.uiverify/notes-pin.mjs
@@ -0,0 +1,44 @@
+// Pinning a note, as on the phone: it moves to Pinned at the top of the list and back again.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 820 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,
+ calendarFixture: false, notesFixture: true, contactsFixture: false, driveFixture: false, remindersFixture: false });
+const page = await ctx.newPage();
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.locator(".nav-item", { hasText: "Notes" }).click();
+await page.waitForTimeout(400);
+
+let failures = 0;
+const ok = (pass, yes, no) => { console.log(pass ? `PASS ${yes}` : `FAIL ${no}`); if (!pass) failures++; };
+
+/** The titles under the Pinned heading, in order. */
+const pinned = () => page.evaluate(() => {
+ const out = [];
+ let inPinned = false;
+ for (const el of document.querySelectorAll(".note-rows .notes-section, .note-rows .note-row-title")) {
+ if (el.classList.contains("notes-section")) inPinned = el.textContent.trim() === "Pinned";
+ else if (inPinned) out.push(el.textContent.trim());
+ }
+ return out;
+});
+
+await page.locator(".note-row", { hasText: "Curtains" }).click();
+await page.waitForTimeout(300);
+await page.getByRole("button", { name: "Pin Note" }).click();
+await page.waitForTimeout(500);
+const after = await pinned();
+ok(after.includes("Curtains"), "a pinned note moves to Pinned", `Pinned holds ${JSON.stringify(after)}`);
+const sent = await page.evaluate(() => window.__pins ?? []);
+ok(JSON.stringify(sent) === JSON.stringify([["n1", true]]), "and the pin is sent to iCloud for that note",
+ `sent ${JSON.stringify(sent)}`);
+
+await page.getByRole("button", { name: "Unpin Note" }).click();
+await page.waitForTimeout(500);
+const back = await pinned();
+ok(!back.includes("Curtains"), "unpinned, it leaves Pinned", `Pinned still holds ${JSON.stringify(back)}`);
+
+await b.close();
+process.exitCode = failures === 0 ? 0 : 1;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index ffea462..68db17e 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -141,8 +141,14 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
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_pin": {
+ const n = noteList.find((x) => x.guid === args?.guid);
+ if (n) n.pinned = args.pinned;
+ (window.__pins ??= []).push([args?.guid, args?.pinned]);
+ return null;
+ }
case "note_create": return "Note/new";
- case "notes_in": return !notesFixture ? [] : noteList;
+ case "notes_in": return !notesFixture ? [] : noteList.map((n) => ({ ...n }));
case "note_body": return (noteList.find((n) => n.guid === args?.guid) ?? {}).body ?? null;
case "note_counts": {
const per = new Map();
diff --git a/check.sh b/check.sh
index af66ad2..780cf97 100755
--- a/check.sh
+++ b/check.sh
@@ -36,6 +36,7 @@ step "keyboard only" node .uiverify/keyboard.mjs
step "somewhere else" node .uiverify/elsewhere.mjs
step "writing a note" node .uiverify/notes-compose.mjs
step "deleting a note" node .uiverify/notes-trash.mjs
+step "pinning a note" node .uiverify/notes-pin.mjs
step "uploading" node .uiverify/drive-upload.mjs
step "calendar grids" node .uiverify/calendar.mjs
step "every size" node .uiverify/sizes.mjs
@@ -46,7 +47,7 @@ export PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS=1
step "webkit: set up" .uiverify/webkit-libs.sh
step "webkit: nav" env ENGINE=webkit node .uiverify/assert.mjs
step "webkit: keyboard" env ENGINE=webkit node .uiverify/keyboard.mjs
-step "webkit: notes" bash -c 'ENGINE=webkit node .uiverify/notes-compose.mjs && ENGINE=webkit node .uiverify/notes-trash.mjs'
+step "webkit: notes" bash -c 'ENGINE=webkit node .uiverify/notes-compose.mjs && ENGINE=webkit node .uiverify/notes-trash.mjs && ENGINE=webkit node .uiverify/notes-pin.mjs'
step "webkit: drive" env ENGINE=webkit node .uiverify/drive-upload.mjs
step "webkit: calendar" env ENGINE=webkit node .uiverify/calendar.mjs
step "webkit: sizes" env ENGINE=webkit node .uiverify/sizes.mjs
diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rs
index e6d1460..c0008b0 100644
--- a/crates/quince-icloud/src/notes.rs
+++ b/crates/quince-icloud/src/notes.rs
@@ -575,6 +575,61 @@ fn filed_in(client: &ZoneClient<'_>, folder: &str) -> Value {
"ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },
})
}
+/// The name of the record that holds one person's state for a note — whether it is pinned.
+///
+/// Measured on the account: `Note_UserSpecific::<owner>/Private::Notes::<owner>::<note>`,
+/// where the owner is the zone's. Apple validates it, so it is built exactly, never guessed.
+fn user_specific_name(owner: &str, note_guid: &str) -> String {
+ format!("Note_UserSpecific::{owner}/Private::Notes::{owner}::{note_guid}")
+}
+
+/// Pin a note, or unpin it, the way the phone does.
+///
+/// Pinning is not on the note: it is `IsPinned` on the per-user record beside it. That
+/// record is updated where Apple already made one, and made — under the name Apple would
+/// give it — for a note that has none yet. The note itself is not touched.
+pub async fn pin_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ note: &Note,
+ pinned: bool,
+) -> Result<()> {
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ let record = client
+ .lookup_record(ZONE, &note.guid)
+ .await?
+ .ok_or_else(|| Error::Protocol("that note is no longer in iCloud".into()))?;
+ let owner = record
+ .pointer("/zoneID/ownerRecordName")
+ .or_else(|| record.pointer("/created/userRecordName"))
+ .and_then(Value::as_str)
+ .ok_or_else(|| Error::Protocol("iCloud did not say whose note this is".into()))?
+ .to_string();
+ let name = user_specific_name(&owner, &note.guid);
+ let flag = serde_json::json!({ "IsPinned": { "type": "INT64", "value": i64::from(pinned) } });
+
+ if let Some(existing) = client.lookup_record(ZONE, &name).await? {
+ let tag = existing.get("recordChangeTag").and_then(Value::as_str);
+ client
+ .update_record(ZONE, &name, "Note_UserSpecific", tag, flag)
+ .await?;
+ } else {
+ let mut fields = flag;
+ fields["Note"] = client.reference_to(ZONE, &note.guid);
+ fields["Note"]["value"]["action"] = Value::from("NONE");
+ fields["Folder"] =
+ client.reference_to(ZONE, note.folder_guid.as_deref().unwrap_or(DEFAULT_FOLDER));
+ fields["Folder"]["value"]["action"] = Value::from("NONE");
+ fields["Deleted"] = serde_json::json!({ "type": "INT64", "value": 0 });
+ fields["IsSystemPaper"] = serde_json::json!({ "type": "INT64", "value": 0 });
+ client
+ .create_record(ZONE, &name, "Note_UserSpecific", fields)
+ .await?;
+ }
+ Ok(())
+}
+
/// Delete a note the way the phone does.
///
/// This used to remove the record outright, which on iCloud is final: no Recently Deleted, no
@@ -608,6 +663,19 @@ pub async fn delete_cloudkit(
#[cfg(test)]
mod tests {
use super::*;
+
+ #[test]
+ fn a_notes_own_record_is_named_as_apple_names_it() {
+ // Copied from a pinned note on the account.
+ assert_eq!(
+ user_specific_name(
+ "_909a7c35ff0feea469084c60822e0cfd",
+ "C454914D-6726-4216-ADDC-E441B9BB8952"
+ ),
+ "Note_UserSpecific::_909a7c35ff0feea469084c60822e0cfd/Private::Notes::\
+ _909a7c35ff0feea469084c60822e0cfd::C454914D-6726-4216-ADDC-E441B9BB8952"
+ );
+ }
use quince_core::Library;
use serde_json::json;
use wiremock::matchers::{method, path_regex};
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index ecac45e..61e80ee 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -818,6 +818,22 @@ async fn note_move(
resync_notes(&http, &root, params, &data).await
}
+/// Pin a note to the top of its list, or unpin it.
+#[tauri::command]
+async fn note_pin(
+ guid: String,
+ pinned: bool,
+ 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::pin_cloudkit(&http, &root, params.clone(), &note, pinned)
+ .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;
@@ -831,7 +847,6 @@ async fn notes_search(query: String, data: State<'_, Data>) -> UiResult<Vec<Note
library.search_notes(&query).map_err(|e| e.to_string())
}
-/// Notes in a folder, or every note when no folder is given.
/// How many notes each folder holds, and all of them but Recently Deleted.
#[tauri::command]
async fn note_counts(data: State<'_, Data>) -> UiResult<(i64, Vec<(String, i64)>)> {
@@ -839,6 +854,7 @@ async fn note_counts(data: State<'_, Data>) -> UiResult<(i64, Vec<(String, i64)>
library.note_counts().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>> {
let library = data.0.lock().await;
@@ -1715,6 +1731,7 @@ fn main() {
note_create,
note_delete,
note_move,
+ note_pin,
notes_in,
notes_search,
note_counts,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index b489386..c6f509f 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -127,6 +127,9 @@ export const api = {
noteMove: (guid: string, folderGuid: string | null) =>
invoke<void>("note_move", { guid, folderGuid }),
+ /** Pinned notes lead their list, here and on every device. */
+ notePin: (guid: string, pinned: boolean) => invoke<void>("note_pin", { guid, pinned }),
+
/** Create when the guid is empty, otherwise save changes. Returns Apple's id for it. */
contactSave: (contact: Contact) => invoke<string>("contact_save", { contact }),
contactDelete: (guid: string) => invoke<void>("contact_delete", { guid }),
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index 9380aed..2088632 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -1,6 +1,6 @@
import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { flushSync } from "react-dom";
-import { Folder, FolderOpen, SquarePen, Trash2 } from "lucide-react";
+import { Folder, FolderOpen, Pin, PinOff, SquarePen, Trash2 } from "lucide-react";
import { editorDate, groupNotes, joinTitle, listDate, splitTitle } from "./notes/model";
import { api, messageOf, nestFolders, type Note, type NoteFolder } from "../lib/ipc";
import { useSync } from "../lib/sync";
@@ -349,6 +349,11 @@ export function NotesView() {
[open, write]
);
+ const pin = useCallback(async () => {
+ if (!open) return;
+ await write(() => api.notePin(open.guid, !open.pinned));
+ }, [open, write]);
+
// A save confirmation is a moment, not a state.
useEffect(() => {
if (!saved) return undefined;
@@ -536,6 +541,22 @@ export function NotesView() {
.map((f) => ({ value: f.guid, label: f.title })),
]}
/>
+ {!inTrash && (
+ <button
+ className="notes-icon"
+ aria-label={open.pinned ? "Unpin Note" : "Pin Note"}
+ aria-pressed={open.pinned}
+ title={open.pinned ? "Unpin Note" : "Pin Note"}
+ onClick={() => void pin()}
+ disabled={busy}
+ >
+ {open.pinned ? (
+ <PinOff size={17} strokeWidth={2} aria-hidden="true" />
+ ) : (
+ <Pin size={17} strokeWidth={2} aria-hidden="true" />
+ )}
+ </button>
+ )}
{inTrash && (
<button className="quiet" onClick={() => void recover()} disabled={busy}>
Recover