summaryrefslogtreecommitdiff
path: root/src/browser.rs
diff options
context:
space:
mode:
authorChristopher Warner <cwarner@kernelcode.com>2026-10-10 18:49:01 -0400
committerChristopher Warner <cwarner@kernelcode.com>2026-10-10 18:49:01 -0400
commitbe0d09e2cb91ef391d7455334fc5ed15d6f5649a (patch)
treebc3b8d3c3b79de695761b750789aeb2ddaf8df49 /src/browser.rs
parentb5e522306f3f4153f633618b8d1e36dc8bbf6371 (diff)
downloadiphone-notes-be0d09e2cb91ef391d7455334fc5ed15d6f5649a.tar.gz
iphone-notes-be0d09e2cb91ef391d7455334fc5ed15d6f5649a.tar.bz2
iphone-notes-be0d09e2cb91ef391d7455334fc5ed15d6f5649a.tar.xz
iphone-notes-be0d09e2cb91ef391d7455334fc5ed15d6f5649a.zip
feat: update existing Apple Notes by title instead of duplicating
Add `icloud-note update` that finds a note by title and replaces its content in place so revision requests do not create a second note. Co-authored-by: Cursor <cursoragent@cursor.com>
Diffstat (limited to 'src/browser.rs')
-rw-r--r--src/browser.rs122
1 files changed, 119 insertions, 3 deletions
diff --git a/src/browser.rs b/src/browser.rs
index 187b535..b3b72d8 100644
--- a/src/browser.rs
+++ b/src/browser.rs
@@ -185,13 +185,50 @@ async fn wait_for_notes_app(page: &Page, timeout: Duration, allow_login_wait: bo
bail!("NotesApp did not become ready. Run: icloud-note login");
}
+fn note_list_helpers_js() -> &'static str {
+ r#"
+ function noteLen(list) {
+ if (!list) return 0;
+ if (typeof list.get === "function" && typeof list.get("length") === "number")
+ return list.get("length");
+ return list.length || 0;
+ }
+ function noteAt(list, i) {
+ if (!list) return null;
+ if (typeof list.objectAt === "function") return list.objectAt(i);
+ if (typeof list.get === "function") return list.objectAt?.(i) ?? list[i];
+ return list[i];
+ }
+ function findByTitle(list, want) {
+ const norm = (s) => String(s || "").trim().toLowerCase();
+ const target = norm(want);
+ let best = null;
+ let bestMod = -1;
+ const n = noteLen(list);
+ for (let i = 0; i < n; i++) {
+ const note = noteAt(list, i);
+ if (!note) continue;
+ const title = note.Title ?? note.title ?? "";
+ if (norm(title) !== target) continue;
+ const mod = Number(note.ModificationDate || note.modificationDate || 0);
+ if (!best || mod >= bestMod) {
+ best = note;
+ bestMod = mod;
+ }
+ }
+ return best;
+ }
+ "#
+}
+
async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result<CreatedNote> {
let full = format_note_text(title, body);
- // Pass text via JSON.stringify embedded in JS to avoid injection issues
let text_js = serde_json::to_string(&full)?;
+ let helpers = note_list_helpers_js();
let expr = format!(
r#"async () => {{
const text = {text_js};
+ {helpers}
const iframe = document.querySelector("iframe");
const w = iframe?.contentWindow;
const app = w?.NotesApp;
@@ -201,7 +238,7 @@ async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result<Cr
const noteList = dataManager.allNotes || dataManager.__CW__allNotes;
const sample =
mv?.selectedNote ||
- (noteList?.objectAt ? noteList.objectAt(0) : noteList?.[0]) ||
+ noteAt(noteList, 0) ||
null;
const Note = sample?.constructor;
if (!Note?.createNoteWithTitleText && !Note?.createEmptyNote) {{
@@ -213,7 +250,7 @@ async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result<Cr
mv?.selectedFolder ||
dataManager.defaultFolder ||
dataManager.inboxFolder ||
- (folderList?.objectAt ? folderList.objectAt(0) : folderList?.[0]) ||
+ noteAt(folderList, 0) ||
null;
if (!folder) throw new Error("Could not resolve a Notes folder");
let note;
@@ -238,6 +275,57 @@ async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result<Cr
Ok(note)
}
+/// Find an existing note by title and replace its content (does not create).
+async fn update_via_notes_app(page: &Page, match_title: &str, title: &str, body: &str) -> Result<CreatedNote> {
+ let full = format_note_text(title, body);
+ let text_js = serde_json::to_string(&full)?;
+ let match_js = serde_json::to_string(match_title)?;
+ let helpers = note_list_helpers_js();
+ let expr = format!(
+ r#"async () => {{
+ const text = {text_js};
+ const matchTitle = {match_js};
+ {helpers}
+ const iframe = document.querySelector("iframe");
+ const w = iframe?.contentWindow;
+ const app = w?.NotesApp;
+ if (!app?.dataManager) throw new Error("NotesApp unavailable");
+ const dataManager = app.dataManager;
+ const mv = app.mainViewModel;
+ const noteList = dataManager.allNotes || dataManager.__CW__allNotes;
+ const note = findByTitle(noteList, matchTitle);
+ if (!note) {{
+ throw new Error("No note titled " + JSON.stringify(matchTitle));
+ }}
+ const Note = note.constructor;
+ // Preferred path: replace TopoText via NotesApp helpers
+ if (typeof Note.createInitialTopoTextString === "function"
+ && dataManager.topoTextManager
+ && typeof dataManager.topoTextManager.load === "function") {{
+ const replacement = Note.createInitialTopoTextString(text);
+ dataManager.topoTextManager.load(note.id, replacement);
+ if (typeof note.userDidChangeTopoText === "function") {{
+ note.userDidChangeTopoText();
+ }}
+ }} else if (typeof note.userDidChangeTopoText === "function") {{
+ note.userDidChangeTopoText(text);
+ }} else {{
+ throw new Error("No supported update path on Note model");
+ }}
+ if (note.Title !== undefined) {{
+ note.Title = text.split("\n")[0] || matchTitle;
+ }}
+ await note.save(true);
+ return {{
+ title: String(note.Title || text.split("\n")[0] || matchTitle),
+ record_name: String(note.recordName || note.id || "")
+ }};
+ }}"#
+ );
+ let note: CreatedNote = page.evaluate(expr).await?.into_value()?;
+ Ok(note)
+}
+
fn mark_session(paths: &Paths) -> Result<()> {
std::fs::write(&paths.marker_path, b"ok\n")?;
#[cfg(unix)]
@@ -300,3 +388,31 @@ pub async fn cmd_create(paths: &Paths, title: &str, body: &str) -> Result<()> {
Ok(())
}
+/// Update an existing note matched by title. Never creates a new note.
+pub async fn cmd_update(
+ paths: &Paths,
+ match_title: &str,
+ title: &str,
+ body: &str,
+) -> Result<()> {
+ if !paths.has_session() {
+ bail!("No saved session. Run: icloud-note login");
+ }
+ let (mut browser, handle) = launch(paths, false).await?;
+ let page = browser.new_page("about:blank").await?;
+ wait_for_notes_app(&page, Duration::from_secs(90), false).await?;
+ let note = update_via_notes_app(&page, match_title, title, body)
+ .await
+ .context("update note via NotesApp")?;
+ sleep(Duration::from_secs(2)).await;
+ mark_session(paths)?;
+ if note.record_name.is_empty() {
+ println!("updated: {}", note.title);
+ } else {
+ println!("updated: {} ({})", note.title, note.record_name);
+ }
+ browser.close().await?;
+ let _ = handle.await;
+ Ok(())
+}
+