Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src/composables/useEditorHeadings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -32,8 +32,7 @@ export function provideEditorHeadings(editor: Editor) {
const displayToc = ref<boolean>(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 }) => {
Expand Down
18 changes: 17 additions & 1 deletion src/plugins/extractHeadings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,29 @@ import type { Heading } from '../composables/useEditorHeadings.ts'

import { slugify } from './slug.js'

const cache = new WeakMap<Node, Heading[]>()

/**
* 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[] = []

Expand Down
111 changes: 26 additions & 85 deletions src/plugins/headingAnchor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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))
}

/**
Expand All @@ -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,
})
}

Expand All @@ -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)
Expand Down
9 changes: 9 additions & 0 deletions src/tests/composables/useEditorHeadings.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
19 changes: 18 additions & 1 deletion src/tests/plugins/extractHeadings.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -75,6 +75,23 @@ describe('extractHeadings', () => {
})
})

describe('getHeadings', () => {
it('returns the cached headings for the same doc', () => {
const doc = prepareDoc('<h1>Heading</h1>')
expect(getHeadings(doc)).toBe(getHeadings(doc))
})

it('extracts headings again for a changed doc', () => {
const editor = createCustomEditor('<h1>Heading</h1>', [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
Expand Down
90 changes: 90 additions & 0 deletions src/tests/plugins/headingAnchor.spec.ts
Original file line number Diff line number Diff line change
@@ -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 = '<h1>First</h1><p>Some text</p><h2>Second</h2>'

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
}
Loading