From c0058f43f499ff79a12847bcdc7fecc982e012ec Mon Sep 17 00:00:00 2001 From: Yuri Karamian Date: Tue, 13 Oct 2026 14:19:27 +0200 Subject: [PATCH] perf: reuse the wiki title index, parsed note dates and skip grammar guessing Opening a note rebuilt the wiki-link title lookup every time; it is now built once per titles list and the list is replaced, not mutated, when a title changes. Re-sorting the note list on each external file change re-parsed every note's date; parsed dates are now kept per entry. A code block naming a language without a grammar (mermaid, a typo) ran every registered grammar on each keystroke; it is now left plain. --- src/lib/components/Editor.svelte | 11 ++++++++--- src/lib/editor/extensions/cachedCodeBlockLowlight.ts | 8 +++++--- src/lib/editor/markdownParser.ts | 8 ++++---- src/lib/stores/app.ts | 9 +++++++-- src/lib/utils/note-list-updates.ts | 5 +++-- tests/code-block-highlighting.test.mjs | 6 ++++++ tests/markdown-parser.test.mjs | 8 +++++--- 7 files changed, 38 insertions(+), 17 deletions(-) diff --git a/src/lib/components/Editor.svelte b/src/lib/components/Editor.svelte index b479784..ea6f49a 100644 --- a/src/lib/components/Editor.svelte +++ b/src/lib/components/Editor.svelte @@ -2675,7 +2675,8 @@ let wikiLinkMenu = $state<{ x: number; y: number; query: string; from: number } | null>(null); let wikiLinkSelectedIndex = $state(0); - let wikiLinkTitlesCache = $state([]); + // Replaced, never mutated: the markdown parser keeps one lookup index per array. + let wikiLinkTitlesCache = $state.raw([]); let wikiLinkTypedByUser = false; // Disambiguation state: when ]] auto-close finds multiple matches let wikiLinkDisambigEntries = $state(null); @@ -2811,9 +2812,13 @@ const entry = { path, title: event.note.meta.title }; const index = wikiLinkTitlesCache.findIndex(note => note.path === path); if (index >= 0) { - if (wikiLinkTitlesCache[index].title !== entry.title) wikiLinkTitlesCache[index] = entry; + if (wikiLinkTitlesCache[index].title !== entry.title) { + const updated = wikiLinkTitlesCache.slice(); + updated[index] = entry; + wikiLinkTitlesCache = updated; + } } else { - wikiLinkTitlesCache.push(entry); + wikiLinkTitlesCache = [...wikiLinkTitlesCache, entry]; } if (wikiTitleRefresh) pendingWikiTitleChanges.set(path, entry); } else if (event.event_type === 'remove') { diff --git a/src/lib/editor/extensions/cachedCodeBlockLowlight.ts b/src/lib/editor/extensions/cachedCodeBlockLowlight.ts index 2f6dad9..2e449d7 100644 --- a/src/lib/editor/extensions/cachedCodeBlockLowlight.ts +++ b/src/lib/editor/extensions/cachedCodeBlockLowlight.ts @@ -35,9 +35,11 @@ export function createCodeBlockHighlightPlugin({ const cached = cache.get(node); if (cached) return cached; const language = node.attrs.language || defaultLanguage; - const tree = language && lowlight.registered(language) - ? lowlight.highlight(language, node.textContent) - : lowlight.highlightAuto(node.textContent); + // A named language without a grammar (mermaid, a typo) stays plain: guessing would run + // every registered grammar over the block on each edit. + const tree = !language ? lowlight.highlightAuto(node.textContent) + : lowlight.registered(language) ? lowlight.highlight(language, node.textContent) + : { children: [] }; const spans: HighlightSpan[] = []; let offset = 0; function visit(nodes: HighlightNode[], inheritedClass: string) { diff --git a/src/lib/editor/markdownParser.ts b/src/lib/editor/markdownParser.ts index be36def..7a7924f 100644 --- a/src/lib/editor/markdownParser.ts +++ b/src/lib/editor/markdownParser.ts @@ -10,8 +10,9 @@ import { IMG_GRID_CLOSER, parseImgGridHeader, splitTrailingCloser } from './imag interface WikiTitle { path: string; title: string } export interface MarkdownEnvironment { wikiLinkTitles?: readonly WikiTitle[] } -const wikiIndexKey = Symbol('wiki-index'); type WikiIndex = { paths: Map; titles: Map }; +// One index per titles array: callers replace the array, never mutate it, when a title changes. +const wikiIndexes = new WeakMap(); function displayMath(state: StateBlock, startLine: number, endLine: number, silent: boolean): boolean { const start = state.bMarks[startLine] + state.tShift[startLine]; @@ -98,7 +99,7 @@ function wikiLink(state: StateInline, silent: boolean): boolean { const raw = state.src.slice(state.pos + 2, end); if (!raw || raw.includes(']')) return false; if (!silent) { - let index: WikiIndex | undefined = state.env[wikiIndexKey]; + let index = wikiIndexes.get(notes); if (!index) { index = { paths: new Map(), titles: new Map() }; for (const note of notes) { @@ -109,7 +110,7 @@ function wikiLink(state: StateInline, silent: boolean): boolean { const previous = index.titles.get(title); if (!previous || depth < previous.depth) index.titles.set(title, { path: note.path, depth }); } - state.env[wikiIndexKey] = index; + wikiIndexes.set(notes, index); } const pipe = raw.indexOf('|'); const reference = (pipe < 0 ? raw : raw.slice(0, pipe)).trim(); @@ -397,7 +398,6 @@ export function createEditorMarkdownParser(): MarkdownIt { md.renderer.rules.helix_empty = () => '

\n'; md.renderer.rules.helix_wiki = (tokens, index, _options, _env, renderer) => `${md.utils.escapeHtml(tokens[index].content)}`; - md.core.ruler.before('block', 'helix_wiki_index', state => { delete state.env[wikiIndexKey]; }); md.core.ruler.after('inline', 'helix_literal_html', literalHtml); diff --git a/src/lib/stores/app.ts b/src/lib/stores/app.ts index b3b76ef..48577b4 100644 --- a/src/lib/stores/app.ts +++ b/src/lib/stores/app.ts @@ -278,6 +278,9 @@ export function activateVaultData(vaultPath: string | null): void { } // Derived +// Entries are replaced, not mutated, when a note changes, so a parsed date stays valid for its entry. +const noteTimestamps = { created: new WeakMap(), modified: new WeakMap() }; + export const sortedNotes = derived( [notes, sortMode, viewMode, noteOrder], ([$notes, $sortMode, $viewMode, $noteOrder]) => { @@ -291,9 +294,11 @@ export const sortedNotes = derived( const dateField = $sortMode === "title" || ($sortMode === "custom" && customSortable) ? null : $sortMode === "created" ? "created" : "modified"; - const timestamps = dateField ? new Map() : null; + const timestamps = dateField ? noteTimestamps[dateField] : null; if (dateField && timestamps) { - for (const note of $notes) timestamps.set(note, Date.parse(note.meta[dateField])); + for (const note of $notes) { + if (!timestamps.has(note)) timestamps.set(note, Date.parse(note.meta[dateField])); + } } const sortFn = (a: NoteEntry, b: NoteEntry) => { diff --git a/src/lib/utils/note-list-updates.ts b/src/lib/utils/note-list-updates.ts index b613a63..c236ce9 100644 --- a/src/lib/utils/note-list-updates.ts +++ b/src/lib/utils/note-list-updates.ts @@ -1,6 +1,6 @@ import type { FileEvent, NoteEntry } from '../types'; -const normalize = (path: string) => path.replace(/\\/g, '/'); +const normalize = (path: string) => path.includes('\\') ? path.replace(/\\/g, '/') : path; /** A delayed watcher/sync batch must not update a different (even nested) vault. */ export function isCurrentVaultEvent(event: FileEvent, vaultPath: string | null): boolean { @@ -27,7 +27,8 @@ function belongsToList(note: NoteEntry, key: string, quickAccess: string[]): boo /** Patch one note without rescanning the vault, including changes to tag membership. */ export function updateNoteList(list: NoteEntry[], note: NoteEntry, key: string, quickAccess: string[]): NoteEntry[] { if (key === 'trash') return list; - const index = list.findIndex((entry) => normalize(entry.path) === normalize(note.path)); + const notePath = normalize(note.path); + const index = list.findIndex((entry) => normalize(entry.path) === notePath); if (!belongsToList(note, key, quickAccess)) { return index < 0 ? list : list.filter((_, i) => i !== index); } diff --git a/tests/code-block-highlighting.test.mjs b/tests/code-block-highlighting.test.mjs index c76dfa2..5b3a312 100644 --- a/tests/code-block-highlighting.test.mjs +++ b/tests/code-block-highlighting.test.mjs @@ -148,3 +148,9 @@ test('cache ownership respects highlighter/default-language boundaries and empty assert.deepEqual(fixture.calls, [{ language: 'javascript', text: 'const x = 1;' }]); assert.deepEqual(keywordRanges(fixture.plugin, state), expectedKeywords(state.doc)); }); + +test('a named language without a grammar is left plain instead of guessed', () => { + const { plugin, state, calls } = setup([codeBlock('graph TD; A-->B;', 'mermaid'), codeBlock('const a = 1;', null)], null); + assert.deepEqual(calls, [{ language: 'auto', text: 'const a = 1;' }]); + assert.equal(plugin.getState(state).decorations.find(0, 'graph TD; A-->B;'.length + 2).length, 0); +}); diff --git a/tests/markdown-parser.test.mjs b/tests/markdown-parser.test.mjs index 267e028..77c2c40 100644 --- a/tests/markdown-parser.test.mjs +++ b/tests/markdown-parser.test.mjs @@ -100,7 +100,7 @@ test('wiki lookup preserves path precedence, shallowest title and escaped attrib assert.doesNotMatch(parser.render('[[Note]]'), /data-wiki-link/); }); -test('wiki lookup reads titles once per render and refreshes after in-place cache changes', () => { +test('wiki lookup reads titles once per titles array and refreshes when the array is replaced', () => { let reads = 0; const notes = Array.from({ length: 250 }, (_, index) => ({ path: `folder/Note ${index}.md`, get title() { reads++; return `Note ${index}`; }, @@ -108,9 +108,11 @@ test('wiki lookup reads titles once per render and refreshes after in-place cach const env = { wikiLinkTitles: notes }; const source = '[[Note 249]] '.repeat(100); parser.render(source, env); + parser.render(source, env); assert.equal(reads, notes.length); - notes[249] = { path: 'Moved.md', title: 'Note 249' }; - assert.match(parser.render(source, env), /data-path="Moved\.md"/); + const updated = notes.slice(); + updated[249] = { path: 'Moved.md', title: 'Note 249' }; + assert.match(parser.render(source, { wikiLinkTitles: updated }), /data-path="Moved\.md"/); }); test('ordinary and legacy links/images remain functional while unsafe schemes remain rejected', () => {