From 851fafe4876216f83b1b9391621d0c4772e72885 Mon Sep 17 00:00:00 2001 From: Jonas Date: Thu, 5 Nov 2026 13:14:59 +0100 Subject: [PATCH] perf(editor): derive heading ids from the doc instead of plugin state Heading ids are now computed by getHeadings(doc), which caches the result per doc node. The headingAnchor plugin only keeps its DecorationSet, mapping it through transactions while heading ids stay the same and rebuilding it otherwise. Anchor widgets are keyed by heading id, so ProseMirror reuses their DOM without looking up existing anchors. That lookup ran once per heading on every rebuild, making edits that change a heading id quadratic in the number of headings (~280 ms vs ~5.6 ms per keystroke with 500 headings in jsdom). Signed-off-by: Jonas Assisted-by: ClaudeCode:claude-opus-5-5 --- src/composables/useEditorHeadings.ts | 5 +- src/plugins/extractHeadings.ts | 18 ++- src/plugins/headingAnchor.ts | 111 ++++-------------- .../composables/useEditorHeadings.spec.js | 9 ++ src/tests/plugins/extractHeadings.spec.js | 19 ++- src/tests/plugins/headingAnchor.spec.ts | 90 ++++++++++++++ 6 files changed, 162 insertions(+), 90 deletions(-) create mode 100644 src/tests/plugins/headingAnchor.spec.ts diff --git a/src/composables/useEditorHeadings.ts b/src/composables/useEditorHeadings.ts index 61666070a61..089ef6c1747 100644 --- a/src/composables/useEditorHeadings.ts +++ b/src/composables/useEditorHeadings.ts @@ -8,7 +8,7 @@ import type { InjectionKey, Ref, ShallowRef } from 'vue' import { emit, subscribe, unsubscribe } from '@nextcloud/event-bus' import { inject, onUnmounted, provide, ref, shallowRef } from 'vue' -import { headingAnchorPluginKey } from '../plugins/headingAnchor.js' +import { getHeadings } from '../plugins/extractHeadings.js' export type Heading = { id: string @@ -32,8 +32,7 @@ export function provideEditorHeadings(editor: Editor) { const displayToc = ref(false) const updateHeadings = () => { - headings.value - = headingAnchorPluginKey.getState(editor.state)?.headings ?? [] + headings.value = getHeadings(editor.state.doc) } updateHeadings() // Initial sync on setup editor.on('update', ({ transaction }) => { diff --git a/src/plugins/extractHeadings.ts b/src/plugins/extractHeadings.ts index fa037bd686a..7d815d64ce9 100644 --- a/src/plugins/extractHeadings.ts +++ b/src/plugins/extractHeadings.ts @@ -8,13 +8,29 @@ import type { Heading } from '../composables/useEditorHeadings.ts' import { slugify } from './slug.js' +const cache = new WeakMap() + +/** + * Headings of the doc, cached per doc node. + * + * @param doc - the prosemirror doc + */ +export function getHeadings(doc: Node): Heading[] { + let headings = cache.get(doc) + if (!headings) { + headings = extractHeadings(doc) + cache.set(doc, headings) + } + return headings +} + /** * Extract heading data structure from doc * * @param doc - the prosemirror doc * @return headings found in the doc */ -export default function extractHeadings(doc: Node) { +export function extractHeadings(doc: Node) { const counter = new Map() const headings: Heading[] = [] diff --git a/src/plugins/headingAnchor.ts b/src/plugins/headingAnchor.ts index 766299adc87..aa9d77e9688 100644 --- a/src/plugins/headingAnchor.ts +++ b/src/plugins/headingAnchor.ts @@ -4,21 +4,14 @@ */ import type { Node } from '@tiptap/pm/model' -import type { Transaction } from '@tiptap/pm/state' -import type { EditorView } from '@tiptap/pm/view' import type { Heading } from '../composables/useEditorHeadings.ts' import { t } from '@nextcloud/l10n' import { Plugin, PluginKey } from '@tiptap/pm/state' import { Decoration, DecorationSet } from '@tiptap/pm/view' -import extractHeadings from './extractHeadings.ts' +import { getHeadings } from './extractHeadings.ts' -export const headingAnchorPluginKey = new PluginKey('headingAnchor') - -interface HeadingAnchorState { - headings: Heading[] - decorations: DecorationSet -} +const headingAnchorPluginKey = new PluginKey('headingAnchor') /** * Heading anchor decorations ProseMirror plugin @@ -29,98 +22,49 @@ interface HeadingAnchorState { export default function headingAnchor() { return new Plugin({ key: headingAnchorPluginKey, - state: { - init(_, { doc }) { - const headings = extractHeadings(doc) - return { - headings, - decorations: anchorDecorations(doc, headings), - } - }, - apply(tr, value, _oldState, newState) { + init: (_, { doc }) => anchorDecorations(doc), + apply(tr, decorations, oldState, newState) { if (!tr.docChanged) { - return value + return decorations + } + if (!sameIds(getHeadings(oldState.doc), getHeadings(newState.doc))) { + return anchorDecorations(newState.doc) } - const headings = extractHeadings(newState.doc) - const decorations - = mapDecorations(value, tr, headings) - || anchorDecorations(newState.doc, headings) - return { headings, decorations } + let removed = false + const mapped = decorations.map(tr.mapping, tr.doc, { + onRemove: () => { + removed = true + }, + }) + return removed ? anchorDecorations(newState.doc) : mapped }, }, - props: { decorations(state) { - return this.getState(state)!.decorations + return this.getState(state) }, }, }) } /** - * Map the previous decorations to current document state. + * Check if both heading lists have the same ids in the same order. * - * Return false if headings changed or decorations would get removed. - * The latter prevents lost decorations in case of replacements. - * - * @param value - previous plugin state - * @param tr - current transaction - * @param headings - array of headings - * - * @return + * @param a - headings + * @param b - headings to compare against */ -function mapDecorations( - value: HeadingAnchorState, - tr: Transaction, - headings: Heading[], -) { - if (headingsChanged(headings, value.headings)) { - return false - } - let removedDecorations = false - const decorations = value.decorations.map(tr.mapping, tr.doc, { - onRemove: () => { - removedDecorations = true - }, - }) - return removedDecorations ? false : decorations -} - -/** - * Check if the headings provided are equivalent. - * - * @param current - array of headings - * @param prev - headings to compare against - */ -function headingsChanged(current: Heading[], prev: Heading[]) { - return current.length !== prev.length || current.some(isDifferentFrom(prev)) -} - -/** - * Check if headings are different - i.e. have different id or level - * - * @param other - headings to compare against - * - * Returns a function to be used in a call to Array#some. - * The returned function takes a heading and an index (as provided by iterators) - * and compares the id and level of the heading to the one in `other` with the same index. - */ -function isDifferentFrom(other: Heading[]) { - return (heading: Heading, i: number) => { - return heading.id !== other[i].id || heading.level !== other[i].level - } +function sameIds(a: Heading[], b: Heading[]) { + return a.length === b.length && a.every((heading, i) => heading.id === b[i].id) } /** - * Create anchor decorations for the given headings + * Create anchor decorations for all headings in the doc * * @param doc - prosemirror doc - * @param headings - headings structure in the doc */ -function anchorDecorations(doc: Node, headings: Heading[]) { - const decorations = headings.map(decorationForHeading) - return DecorationSet.create(doc, decorations) +function anchorDecorations(doc: Node) { + return DecorationSet.create(doc, getHeadings(doc).map(decorationForHeading)) } /** @@ -131,6 +75,7 @@ function anchorDecorations(doc: Node, headings: Heading[]) { function decorationForHeading(heading: Heading) { return Decoration.widget(heading.offset + 1, headingToDom(heading), { side: -1, + key: heading.id, }) } @@ -140,11 +85,7 @@ function decorationForHeading(heading: Heading) { * @param heading to generate anchor for */ function headingToDom(heading: Heading) { - return (view: EditorView) => { - const existing = view.dom.querySelector(`#${heading.id}`) - if (existing) { - return existing - } + return () => { const el = document.createElement('a') const symbol = document.createTextNode('#') el.appendChild(symbol) diff --git a/src/tests/composables/useEditorHeadings.spec.js b/src/tests/composables/useEditorHeadings.spec.js index b32c2883924..9ddd4afb9cf 100644 --- a/src/tests/composables/useEditorHeadings.spec.js +++ b/src/tests/composables/useEditorHeadings.spec.js @@ -64,3 +64,12 @@ test('updates headings', async () => { expect(injected.headings).toEqual(headingsForContent) editor.destroy() }) + +test('updates heading level', async () => { + const editor = createCustomEditor(content, [Heading]) + const wrapper = createWrapper(editor) + editor.chain().setTextSelection(1).setHeading({ level: 3 }).run() + await nextTick() + expect(wrapper.vm.headings.map((h) => h.level)).toEqual([3, 2]) + editor.destroy() +}) diff --git a/src/tests/plugins/extractHeadings.spec.js b/src/tests/plugins/extractHeadings.spec.js index 52a8caa7598..d7de4e941de 100644 --- a/src/tests/plugins/extractHeadings.spec.js +++ b/src/tests/plugins/extractHeadings.spec.js @@ -6,7 +6,7 @@ import { Blockquote } from '@tiptap/extension-blockquote' import Details from '../../nodes/Details.js' import Heading from '../../nodes/Heading.js' -import extractHeadings from '../../plugins/extractHeadings.ts' +import { extractHeadings, getHeadings } from '../../plugins/extractHeadings.ts' import createCustomEditor from '../testHelpers/createCustomEditor.ts' describe('extractHeadings', () => { @@ -75,6 +75,23 @@ describe('extractHeadings', () => { }) }) +describe('getHeadings', () => { + it('returns the cached headings for the same doc', () => { + const doc = prepareDoc('

Heading

') + expect(getHeadings(doc)).toBe(getHeadings(doc)) + }) + + it('extracts headings again for a changed doc', () => { + const editor = createCustomEditor('

Heading

', [Heading]) + const before = getHeadings(editor.state.doc) + editor.commands.insertContentAt(1, 'New ') + const after = getHeadings(editor.state.doc) + editor.destroy() + expect(after).not.toBe(before) + expect(after[0].id).toBe('h-new-heading') + }) +}) + function prepareDoc(content, extraExtensions = []) { const editor = createCustomEditor(content, [Heading, ...extraExtensions]) const doc = editor.state.doc diff --git a/src/tests/plugins/headingAnchor.spec.ts b/src/tests/plugins/headingAnchor.spec.ts new file mode 100644 index 00000000000..1d1795035ee --- /dev/null +++ b/src/tests/plugins/headingAnchor.spec.ts @@ -0,0 +1,90 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { Editor } from '@tiptap/core' +import type { DecorationSet } from '@tiptap/pm/view' + +import { TextSelection } from '@tiptap/pm/state' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import Heading from '../../nodes/Heading.js' +import createCustomEditor from '../testHelpers/createCustomEditor.ts' + +const content = '

First

Some text

Second

' + +describe('headingAnchor plugin', () => { + let editor: Editor + + beforeEach(() => { + editor = createCustomEditor(content, [Heading]) + }) + + afterEach(() => { + editor.destroy() + }) + + it('adds an anchor for each heading', () => { + expect(anchorIds(editor)).toEqual(['h-first', 'h-second']) + }) + + it('keeps decorations on selection change', () => { + const before = decorations(editor) + const { tr, doc } = editor.state + editor.view.dispatch(tr.setSelection(TextSelection.create(doc, 10))) + expect(decorations(editor)).toBe(before) + }) + + it('maps anchors when editing text outside headings', () => { + editor.commands.insertContentAt(8, 'More ') + expect(anchorIds(editor)).toEqual(['h-first', 'h-second']) + expect(anchorPositions(editor)).toEqual(headingPositions(editor)) + }) + + it('updates anchors when a heading changes', () => { + editor.commands.insertContentAt(1, 'New ') + expect(anchorIds(editor)).toEqual(['h-new-first', 'h-second']) + expect(anchorPositions(editor)).toEqual(headingPositions(editor)) + }) + + it('keeps the anchor element of unchanged headings', () => { + const second = editor.view.dom.querySelector('#h-second') + expect(second).not.toBeNull() + editor.commands.insertContentAt(1, 'New ') + expect(editor.view.dom.querySelector('#h-second')).toBe(second) + }) +}) + +/** + * @param editor - tiptap editor + */ +function decorations(editor: Editor) { + return editor.view.someProp('decorations', (f) => f.call(editor.view, editor.state)) as DecorationSet +} + +/** + * @param editor - tiptap editor + */ +function anchorIds(editor: Editor) { + return decorations(editor).find().map((d) => d.spec.key) +} + +/** + * @param editor - tiptap editor + */ +function anchorPositions(editor: Editor) { + return decorations(editor).find().map((d) => d.from) +} + +/** + * @param editor - tiptap editor + */ +function headingPositions(editor: Editor) { + const positions: number[] = [] + editor.state.doc.descendants((node, pos) => { + if (node.type.name === 'heading') { + positions.push(pos + 1) + } + }) + return positions +}