diff --git a/src-tauri/src/vault/frontmatter.rs b/src-tauri/src/vault/frontmatter.rs index 4fd0e16..50d0819 100644 --- a/src-tauri/src/vault/frontmatter.rs +++ b/src-tauri/src/vault/frontmatter.rs @@ -184,18 +184,15 @@ pub fn parse_note(raw: &str, filename: &str) -> (NoteMeta, String) { (meta, content) } -/// Ensure the body starts with `# Title` heading for external app compatibility. -/// If the body already starts with `# Title`, leave it as-is. +/// Ensure the body starts with a top-level heading for external app compatibility, adding +/// `# Title` when it has none. A body that already opens with a top-level heading is left alone +/// even when that heading differs from the title: adding another one above it stacked a new +/// heading on every title change (`# New`, `# Old`, ...). fn ensure_title_heading(body: &str, title: &str) -> String { let trimmed = body.trim_start(); - // Check if body already starts with `# Title` - if let Some(rest) = trimmed.strip_prefix("# ") { - let first_line_end = rest.find('\n').unwrap_or(rest.len()); - let heading_text = rest[..first_line_end].trim(); - if heading_text.eq_ignore_ascii_case(title.trim()) { - return body.to_string(); - } + if trimmed.starts_with("# ") { + return body.to_string(); } // Don't add heading to empty notes (new/blank notes) @@ -686,4 +683,49 @@ mod tests { assert!(content.ends_with("body")); } } + + #[test] + fn a_title_heading_is_added_only_when_the_body_has_no_top_level_heading() { + let meta = |title: &str| NoteMeta { + id: "id".into(), + title: title.into(), + tags: vec![], + pinned: false, + created: Utc::now(), + modified: Utc::now(), + }; + let body_of = |raw: String| parse_note(&raw, "x.md").1; + // No heading yet: the title becomes one. + assert_eq!( + body_of(update_note_raw(&meta("New"), "Text.\n")), + "# New\n\nText." + ); + // A heading that differs from the title is not buried under a second one. + assert_eq!( + body_of(update_note_raw(&meta("New"), "# Old\n\nText.\n")), + "# Old\n\nText." + ); + let original = "---\nid: id\ntitle: Old\n---\n# Old\n\nText.\n"; + assert_eq!( + body_of(merge_frontmatter( + original, + &meta("New"), + "# Old\n\nText.\n" + )), + "# Old\n\nText." + ); + // Saving again and again never grows the note. + let once = merge_frontmatter(original, &meta("New"), "# Old\n\nText.\n"); + let (_, body) = parse_note(&once, "x.md"); + assert_eq!( + body_of(merge_frontmatter(&once, &meta("Newer"), &body)), + "# Old\n\nText." + ); + // Lower-level headings and empty notes behave as before. + assert_eq!( + body_of(update_note_raw(&meta("New"), "## Section\n")), + "# New\n\n## Section" + ); + assert!(update_note_raw(&meta("New"), "\n").ends_with("---\n\n")); + } } diff --git a/src-tauri/src/vault/operations.rs b/src-tauri/src/vault/operations.rs index 24bffe5..4f99fbb 100644 --- a/src-tauri/src/vault/operations.rs +++ b/src-tauri/src/vault/operations.rs @@ -840,7 +840,9 @@ pub fn save_note( } updated_meta.modified = Utc::now(); - let raw = frontmatter::merge_frontmatter(&existing.raw, &updated_meta, body); + // The heading that carried the old title follows the title. + let body = retitle_leading_heading(body, &existing.meta.title, &updated_meta.title); + let raw = frontmatter::merge_frontmatter(&existing.raw, &updated_meta, &body); replace_file_atomically(&target, raw.as_bytes())?; Ok(Some(SavedNote { @@ -1279,6 +1281,8 @@ pub fn rename_note(path: &str, new_title: &str, vault_path: &str) -> Result String { mod rename_link_tests { use super::*; + #[test] + fn renaming_and_retitling_keep_a_single_title_heading() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path().to_str().unwrap(); + let note = vault.path().join("Alpha.md"); + fs::write( + ¬e, + "---\nid: the-id\ntitle: Alpha\n---\n# Alpha\n\nText.\n", + ) + .unwrap(); + + // Renamed twice from the sidebar: the heading follows, nothing stacks. + let renamed = rename_note(note.to_str().unwrap(), "Beta", root).unwrap(); + let renamed = rename_note(&renamed.path, "Gamma", root).unwrap(); + let raw = fs::read_to_string(&renamed.path).unwrap(); + assert!(raw.trim_end().ends_with("---\n# Gamma\n\nText."), "{raw}"); + assert_eq!(raw.matches("\n# ").count(), 1, "{raw}"); + + // A heading the user worded differently is theirs and stays. + let other = vault.path().join("Other.md"); + fs::write( + &other, + "---\nid: other\ntitle: Other\n---\n# My own heading\n\nText.\n", + ) + .unwrap(); + let renamed = rename_note(other.to_str().unwrap(), "Renamed", root).unwrap(); + let raw = fs::read_to_string(&renamed.path).unwrap(); + assert!( + raw.trim_end().ends_with("---\n# My own heading\n\nText."), + "{raw}" + ); + + // The save path: a body still carrying the old title's heading is retitled with the title. + assert_eq!( + retitle_leading_heading("# Gamma\n\nText.\n", "Gamma", "Delta"), + "# Delta\n\nText.\n" + ); + assert_eq!( + retitle_leading_heading("# Gamma\n\nText.\n", "Gamma", "Gamma"), + "# Gamma\n\nText.\n" + ); + assert_eq!( + retitle_leading_heading("# Mine\n\nText.\n", "Gamma", "Delta"), + "# Mine\n\nText.\n" + ); + } + #[test] fn a_rename_updates_links_to_the_note_and_leaves_other_aliases_alone() { let vault = tempfile::tempdir().unwrap(); diff --git a/src/lib/components/Editor.svelte b/src/lib/components/Editor.svelte index bfac8ff..a198916 100644 --- a/src/lib/components/Editor.svelte +++ b/src/lib/components/Editor.svelte @@ -4164,6 +4164,27 @@ return restoreTitleHeading(md, hiddenTitleHeading); } + /** + * With the title heading shown in the body, the heading and the title field are the same text. + * When the field changes, the leading heading that still reads as the old title follows it; + * left behind, it was saved under a second heading carrying the new title. + */ + function syncVisibleTitleHeading(previous: string, next: string) { + if (hiddenTitleHeading || !next.trim()) return; + const same = (text: string) => text.trim().toLowerCase() === previous.trim().toLowerCase(); + if ($sourceMode) { + const text = source.state.doc.toString(); + const heading = /^(\s*# )([^\n]*)/.exec(text); + if (heading && same(heading[2])) source.replace(next.trim(), heading[1].length, heading[0].length); + return; + } + if (!editor) return; + finishProgressiveLoad(); + const first = editor.state.doc.firstChild; + if (first?.type.name !== 'heading' || first.attrs.level !== 1 || !same(first.textContent)) return; + editor.view.dispatch(editor.state.tr.insertText(next.trim(), 1, 1 + first.content.size)); + } + function editorToMarkdown(): string { if (!editor) return ''; finishProgressiveLoad(); @@ -7541,6 +7562,7 @@ if (!$activeNote) return; const title = e.currentTarget.value; if ($activeNote.meta.title === title) return; + syncVisibleTitleHeading($activeNote.meta.title, title); $activeNote.meta.title = title; if (hiddenTitleHeading) hiddenTitleHeading = { ...hiddenTitleHeading, title }; markEdited(); @@ -7563,6 +7585,7 @@ if (!newTitle) return; const oldPath = $activeNotePath; if ($activeNote.meta.title !== newTitle) { + syncVisibleTitleHeading($activeNote.meta.title, newTitle); $activeNote.meta.title = newTitle; if (hiddenTitleHeading) hiddenTitleHeading = { ...hiddenTitleHeading, title: newTitle }; markEdited();