import { authoredVeto, BaseParagraphPlugin, ContentSlice, DebugPlugin, definePlugin, type DefinitionOf, editorCommands, type Element, ElementApi, type ElementOf, inputRuleVeto, type Location, NodeApi, type NodeEntry, type NodeKey, type NodeSelection, PathApi, type BlockInsertOptions, type BlockUpsertOptions, PLUGINS, property, type Range, RangeApi, schema, SelectionApi, txLocate, locateAt, } from '../../../core'; import { domCommands } from '../../../dom/plite-dom.internal'; import { canPlaceBlocksAtPath, isDocumentView } from '../../../facade'; import { failInvariant } from '../../../internal/failInvariant'; import { applyBlockInsertion } from '../../../internal/plugin/blockInsertion'; import { applyBlockReleases, canReplaceContainers, readBlockReleases, } from '../../../internal/plugin/blockRelease'; import { createBrowserHtmlDocument, MATHML_FIRST_CHILD_DRAWN, materializeHtmlAst, parseHtmlAst, } from '../../../lib/plugins/html/htmlAst'; const CODE_LANGUAGE_CLASS_RE = /(?:^|\s)language-([^\s]+)/; const NON_WHITESPACE = /\S/; const NON_WHITESPACE_OR_END = /\S|$/; const TRAILING_NEWLINES = /\n+$/; export type HighlightNode = { children?: HighlightNode[]; properties?: Record; type: string; value?: string; }; export type HighlightResult = { children: HighlightNode[]; type: string; }; export type CodeHighlightLowlight = { highlight( language: string, value: string, options?: Readonly<{ prefix?: string | null }> | null ): HighlightResult; listLanguages(): string[]; registered(aliasOrName: string): boolean; }; type CodeBlockDecoration = Readonly<{ attributes: Readonly<{ className: string; 'data-code-block-syntax': '' }>; key: string; range: Range; }>; type CodeHighlightWarning = | { error: unknown; kind: 'highlight'; language: string } | { kind: 'missing-language'; language: string }; type CodeHighlightCache = { attributes: ReadonlyMap; decorations: readonly CodeBlockDecoration[]; language: string | null; lowlight: CodeHighlightLowlight; text: string; }; const getLineStartOffset = (text: string, offset: number) => offset === 0 ? 0 : text.lastIndexOf('\n', offset - 1) + 1; const getLineEndOffset = (text: string, offset: number) => { const nextBreak = text.indexOf('\n', offset); return nextBreak === -1 ? text.length : nextBreak; }; const getIndentDepth = (text: string, offset: number) => { const lineStart = getLineStartOffset(text, offset); const lineEnd = getLineEndOffset(text, offset); return text.slice(lineStart, lineEnd).search(NON_WHITESPACE_OR_END); }; const countTrailingNewlines = (text: string) => text.match(TRAILING_NEWLINES)?.[0].length ?? 0; const readCodeDomText = (node: Node): string => { if (node.nodeName === 'SELECT') return ''; const parent = node.parentElement; if ( parent && MATHML_FIRST_CHILD_DRAWN.has(parent.localName) && parent.closest('math') && (node as ChildNode & NonDocumentTypeChildNode).previousElementSibling ) { return ''; } if (node.nodeName === 'BR') return '\n'; if (node.nodeType === node.TEXT_NODE) return node.textContent ?? ''; return Array.from(node.childNodes).map(readCodeDomText).join(''); }; const restoreTrailingNewlines = (text: string, element: HTMLElement) => { const encoded = element.dataset.codeTrailingNewlines; if (!encoded || !/^\d+$/.test(encoded)) return text; const expected = Number(encoded); const current = countTrailingNewlines(text); if (!Number.isSafeInteger(expected) || expected > text.length + 1) { return text; } return current < expected ? text + '\n'.repeat(expected - current) : text; }; const everyEquationTexCarrierIsOrHoldsMath = (element: HTMLElement) => Array.from( element.querySelectorAll( '[data-editor-equation], [data-editor-equation-latex]' ) ).every( (carrier) => carrier.localName === 'math' || carrier.querySelector('math') ); const getSelectedLineStarts = (text: string, start: number, end: number) => { const starts = [getLineStartOffset(text, start)]; let nextBreak = text.indexOf('\n', starts[0]); while (nextBreak !== -1 && nextBreak + 1 < end) { starts.push(nextBreak + 1); nextBreak = text.indexOf('\n', nextBreak + 1); } return starts; }; const offsetToLinePoint = (text: string, offset: number) => { const before = text.slice(0, offset); const line = before.split('\n').length - 1; const lineStart = before.lastIndexOf('\n') + 1; return { line, offset: offset - lineStart }; }; export const BaseCodeBlockPlugin = definePlugin(PLUGINS.codeBlock, { read: ({ plugin, state }) => { const entry = ({ at, }: { at?: Location | null; } = {}) => { const selection = state.selection(); const target = at === undefined ? selection : at; if (!target) return undefined; const codeBlock = state.nodes.above({ at: target, type: plugin, }); if (!codeBlock) return undefined; return { codeBlock }; }; return { entry, indentDepth: () => { const selection = state.selection(); const codeBlock = entry()?.codeBlock; if (!selection || !codeBlock) return 0; return getIndentDepth( NodeApi.string(codeBlock[0]), selection.anchor.offset ); }, isEmpty: () => { const codeBlock = entry()?.codeBlock[0]; if (!codeBlock) return false; if (codeBlock.children.length === 0) return true; if (codeBlock.children.length > 1) return false; return !NodeApi.string(codeBlock.children[0]); }, }; }, schema: { element: { content: schema.content.text({ default: 'text', min: 1, max: 1 }), ownsExit: true, properties: { language: property.string() }, slice: { preserveContext: true }, }, }, component: 'pre', formats: ({ defineFormats, schema: { type } }) => defineFormats({ plainText: { encode: ({ children }) => children, }, html: { decode: ({ element, preserve, report }) => { if (element.querySelector('math')) { report({ action: 'replaced', kind: 'element', message: 'Plate HTML decode kept only the drawn text of in a code block.', }); if (everyEquationTexCarrierIsOrHoldsMath(element)) { preserve('data-editor-equation', 'data-editor-equation-latex'); } } const languageClass = element .querySelector(':scope > code') ?.className.match(CODE_LANGUAGE_CLASS_RE)?.[1]; const language = element.dataset.language || languageClass || undefined; const text = restoreTrailingNewlines( readCodeDomText(element), element ); preserve('data-code-trailing-newlines', 'data-language'); return { children: [{ text }], ...(language ? { language } : {}), }; }, encode: ({ content, node, preserve }) => { const trailingNewlines = countTrailingNewlines(NodeApi.string(node)); preserve('language'); return { attributes: { ...(trailingNewlines > 0 ? { 'data-code-trailing-newlines': trailingNewlines } : {}), 'data-language': node.language, }, children: [{ children: content, tag: 'code' }], tag: 'pre', }; }, match: [ { tag: 'pre' }, { style: { fontFamily: 'Consolas' }, tag: 'p' }, ], priority: 10, }, markdown: { node: 'code', decode: ({ node }) => ({ ...(node.lang ? { language: node.lang } : {}), children: [{ text: node.value || '' }], type, }), encode: ({ node, preserve }) => { preserve('language'); return { lang: node.language, type: 'code', value: NodeApi.string(node), }; }, }, }), shortcuts: { selectAll: { keys: 'mod+a' }, tab: { keys: 'tab' }, untab: { keys: 'shift+tab' }, }, }) .extend(({ editor, plugin, schema: { type } }) => { type CodeBlock = ElementOf; type CodeBlockInsertInput = Pick; return { update: ({ tx }) => { const paragraphType = editor.plugin(BaseParagraphPlugin).schema.type; const codeBlockTextPath = (path: readonly number[]) => [...path, 0]; const createParagraphs = (code: string) => code.split('\n').map((text) => ({ children: [{ text }], type: paragraphType, })); const pointInBlock = ( blockPath: readonly number[], point: { path: readonly number[] } ) => PathApi.isAncestor(blockPath, point.path); const mapPointToParagraph = ( blockPath: readonly number[], code: string, point: { offset: number; path: readonly number[]; root?: string } ) => { const mapped = offsetToLinePoint(code, point.offset); const blockIndex = blockPath.at(-1); if (blockIndex === undefined) return point; return { offset: mapped.offset, path: [...blockPath.slice(0, -1), blockIndex + mapped.line, 0], ...(point.root ? { root: point.root } : {}), }; }; const unwrap = ({ at, }: { at?: Location | NodeSelection; } = {}) => { if (at === undefined && !tx.selection()) return false; let unwrapped = false; const codeBlockEntries = Array.from( tx.nodes.entries({ at, type: plugin, }) ).reverse(); for (const [codeBlock, codeBlockPath] of codeBlockEntries) { const code = NodeApi.string(codeBlock); const selection = tx.selection(); const mappedSelection = selection && pointInBlock(codeBlockPath, selection.anchor) && pointInBlock(codeBlockPath, selection.focus) ? { anchor: mapPointToParagraph( codeBlockPath, code, selection.anchor ), focus: mapPointToParagraph( codeBlockPath, code, selection.focus ), } : undefined; if ( !tx.nodes.replace(createParagraphs(code), { at: codeBlockPath }) ) { continue; } unwrapped = true; if (mappedSelection) tx.selection.set(mappedSelection); } return unwrapped; }; const codeRuns = (blocks: ReadonlyArray>) => { const runs: Array>> = []; for (const entry of blocks) { const run = runs.at(-1); const last = run?.at(-1); if ( run && last && PathApi.equals(PathApi.next(last[1]), entry[1]) ) { run.push(entry); } else { runs.push([entry]); } } const codes = runs.map((run) => ({ children: [ { text: run.map(([block]) => NodeApi.string(block)).join('\n') }, ], type, })); if ( runs.length === 0 || !runs.every((run, index) => canPlaceBlocksAtPath(tx.schema, run[0][1], [codes[index]], { removing: run.map(([, path]) => path.at(-1) ?? 0), root: tx.view.root(), }) ) ) { return false; } const keys: NodeKey[] = []; for (const [index, run] of [...runs.entries()].toReversed()) { const [, at] = run[0]; if (!tx.nodes.replace(codes[index], { at })) { failInvariant('A checked code block conversion refused.'); } const key = tx.key(at); if (key) keys.push(key); for (const [, path] of run.slice(1).toReversed()) { tx.nodes.remove({ at: path }); } } const [first, ...rest] = keys.flatMap((key) => { const entry = tx.nodes.get(key); return entry ? [entry[1]] : []; }); if (first) { tx.selection.set( SelectionApi.nodes([first, ...rest], { mode: 'block', root: tx.view.root(), }) ); } return true; }; const insertCodeBlock = ( input: CodeBlockInsertInput = {}, options: BlockInsertOptions = {} ) => (tx.selection() !== null || options.at !== undefined || options.after !== undefined || options.before !== undefined) && tx.blocks.insert(tx.schema.create(type, input), { ...options, select: options.select ?? true, }) !== undefined; const applyCodeBlockInsertion = ( mode: 'insert' | 'upsert', input: CodeBlockInsertInput = {}, options: BlockInsertOptions | BlockUpsertOptions = {} ) => applyBlockInsertion({ editor, insert: (insertOptions) => insertCodeBlock(input, insertOptions), matches: (block) => block.type === type && block.listType === undefined, mode, onReuse: (block, key) => { if ( input.language !== undefined && block.language !== input.language ) { tx.nodes.set({ language: input.language }, { at: key }); } }, options, tx, }); const tab = (reverse = false) => { const selection = tx.selection(); if (!selection) return false; const codeBlock = tx.nodes.above({ at: selection.anchor, type: plugin, }); if (!codeBlock || !pointInBlock(codeBlock[1], selection.focus)) { return false; } const text = NodeApi.string(codeBlock[0]); const textPath = codeBlockTextPath(codeBlock[1]); const value = ' '; if (!tx.selection.isExpanded()) { const lineStart = getLineStartOffset(text, selection.anchor.offset); const beforeCursor = text.slice(lineStart, selection.anchor.offset); const offset = NON_WHITESPACE.test(beforeCursor) ? selection.anchor.offset : lineStart; if (reverse) { const removable = text .slice(lineStart, lineStart + value.length) .match(/^[ \t]{1,2}/)?.[0].length; if (!removable) return true; tx.text.delete({ at: { anchor: { offset: lineStart, path: textPath }, focus: { offset: lineStart + removable, path: textPath }, }, }); } else { tx.text.insert(value, { at: { offset, path: textPath } }); } return true; } const [start, end] = RangeApi.edges(selection); const lineStarts = getSelectedLineStarts( text, start.offset, end.offset ).reverse(); for (const lineStart of lineStarts) { if (reverse) { const removable = text .slice(lineStart, lineStart + value.length) .match(/^[ \t]{1,2}/)?.[0].length; if (!removable) continue; tx.text.delete({ at: { anchor: { offset: lineStart, path: textPath }, focus: { offset: lineStart + removable, path: textPath }, }, }); } else { tx.text.insert(value, { at: { offset: lineStart, path: textPath }, }); } } return true; }; return { insert: txLocate( locateAt(1, 'at', 'after', 'before'), ( input: CodeBlockInsertInput = {}, options: BlockInsertOptions = {} ) => applyCodeBlockInsertion('insert', input, options) ), resetBlock: () => { if (!tx.nodes.block({ type: plugin })) return false; return unwrap(); }, selectAll: () => { const codeBlock = tx.nodes.above({ type: plugin, }); if (!codeBlock) return false; const selection = tx.selection(); const blockRange = tx.ranges.get(codeBlock[1]); if ( selection && blockRange && RangeApi.equals(selection, blockRange) ) { return false; } tx.selection.set(codeBlock[1]); return true; }, tab: txLocate( false, ({ reverse = false }: { reverse?: boolean } = {}) => tab(reverse) ), toggle: (): boolean => { const initial = tx.selection(); if (!initial) return false; const selected = tx.nodes.blocks({ mode: 'lowest' }); const releases = readBlockReleases( editor, tx, selected, () => true ); const [release] = releases; if (release) { const [start, end] = RangeApi.edges(initial); const startBlock = tx.nodes.block({ at: start }); const endBlock = tx.nodes.block({ at: end }); // The released block converts alone; the rest of its container // never joins the code. if ( releases.length > 1 || !startBlock || !endBlock || tx.key(startBlock[1]) !== release.key || tx.key(endBlock[1]) !== release.key ) { return false; } } if (tx.nodes.some({ type: plugin })) return unwrap(); if (!release && tx.selection.nodes().length > 0) { return codeRuns(selected); } if (release) { const code = { children: [{ text: NodeApi.string(release.block) }], type, }; const fit = release.fit.map((child) => child === release.block ? code : child ); if (!canReplaceContainers(tx, new Map([[release, fit]]))) { return false; } applyBlockReleases(tx, releases); } const selection = tx.selection(); if (!selection) return false; const [start, end] = RangeApi.edges(selection); const startBlock = tx.nodes.block({ at: start }); const endBlock = tx.nodes.block({ at: end }); if (!startBlock || !endBlock) return false; const startParent = startBlock[1].slice(0, -1); const endParent = endBlock[1].slice(0, -1); const startIndex = startBlock[1].at(-1); const endIndex = endBlock[1].at(-1); if ( startIndex === undefined || endIndex === undefined || !PathApi.equals(startParent, endParent) ) { return tx.blocks.set({ type }, { at: startBlock[1] }); } const blocks: Array> = []; for (let index = startIndex; index <= endIndex; index++) { const block = tx.nodes.get([...startParent, index], { match: ElementApi.isElement, }); if (block) blocks.push(block); } if (blocks.length === 0) return false; const values = blocks.map(([block]) => NodeApi.string(block)); const mapSelectionPoint = (point: typeof selection.anchor) => { let offset = 0; for (let index = 0; index < blocks.length; index++) { const [, blockPath] = blocks[index]; if (pointInBlock(blockPath, point)) { const blockStart = tx.points.start(blockPath); const range = blockStart && tx.ranges.get(blockStart, point); offset += range ? tx.text.string(range).length : 0; return { offset, path: codeBlockTextPath(blocks[0][1]), ...(point.root ? { root: point.root } : {}), }; } offset += values[index].length + 1; } return point; }; const mappedSelection = { anchor: mapSelectionPoint(selection.anchor), focus: mapSelectionPoint(selection.focus), }; // The replacement goes first: a refused one leaves the other // blocks in place. if ( !tx.nodes.replace( { children: [{ text: values.join('\n') }], type }, { at: blocks[0][1] } ) ) { return false; } for (const [, blockPath] of blocks.slice(1).reverse()) { tx.nodes.remove({ at: blockPath }); } tx.selection.set(mappedSelection); return true; }, untab: () => tab(true), upsert: txLocate( locateAt(1, 'after', 'before'), ( input: CodeBlockInsertInput = {}, options: BlockUpsertOptions = {} ) => applyCodeBlockInsertion('upsert', input, options) ), }; }, }; }) .extend((context) => ({ contributions: [ authoredVeto.of((element) => element.type === context.schema.type ? 'code-block' : null ), inputRuleVeto.of(context.schema.type), ], dataTransferFormats: [ { accept: ({ state }) => { const selection = state.selection(); return ( !!selection && state.nodes.some({ at: selection, type: context.schema.type }) ); }, decode: ({ data, snapshot }) => { const plainText = snapshot.getData('text/plain'); const parsed = parseHtmlAst(data, 'slice'); if (!parsed.ok) return null; const htmlText = materializeHtmlAst(parsed.ast, createBrowserHtmlDocument()) .textContent || ''; const text = plainText && plainText !== data ? plainText : htmlText; return ContentSlice.closed([{ text }]); }, mimeType: 'text/html', priority: 200, }, ], commands: ({ around, handle }) => [ around(domCommands.insertData, ({ input, next, state }) => { const text = input.getData('text/plain'); const vscodeDataString = input.getData('vscode-editor-data'); const block = state.nodes.block(); const isInCodeBlock = block?.[0].type === context.schema.type; if (vscodeDataString) { try { const vscodeData: unknown = JSON.parse(vscodeDataString); const language = typeof vscodeData === 'object' && vscodeData !== null && 'mode' in vscodeData && typeof vscodeData.mode === 'string' ? vscodeData.mode : undefined; if (isInCodeBlock) { return state.transaction((tx) => { tx.text.insert(text); }); } if (!block) return next(); return state.transaction((tx) => { tx.fragment.replace( [ { children: [{ text }], language, type: context.schema.type, }, ], { at: PathApi.next(block[1]), } ); }); } catch { // Ignore malformed syntax nodes and keep scanning candidates. } } const textIsHtmlMarkup = text === input.getData('text/html'); if (isInCodeBlock && text && !textIsHtmlMarkup) { return state.transaction((tx) => { tx.text.insert(text); }); } return next(); }), handle(editorCommands.delete, ({ input, state }) => { if (input.direction !== 'backward') return false; const selection = state.selection(); if (!selection || state.selection.isExpanded()) { return false; } const codeBlock = state.nodes.above({ type: context.plugin }); if ( !codeBlock || codeBlock[0].type !== context.schema.type || selection.anchor.offset !== 0 ) { return false; } if (NodeApi.string(codeBlock[0]).length > 0) { return state.transaction(() => {}); } return state.transaction((tx) => { tx.nodes.set( { type: context.editor.plugin(BaseParagraphPlugin).schema.type, }, { at: codeBlock[1] } ); }); }), handle(editorCommands.insertBreak, ({ state }) => { const selection = state.selection(); const codeBlock = selection ? state.nodes.above({ at: selection, type: context.plugin, }) : undefined; if ( !selection || !codeBlock || codeBlock[0].type !== context.schema.type || !PathApi.isAncestor(codeBlock[1], selection.focus.path) ) { return false; } const code = NodeApi.string(codeBlock[0]); const [start, end] = RangeApi.edges(selection); const indentDepth = getIndentDepth(code, start.offset); const suffixIndent = code.slice(end.offset).match(/^[ \t]*/)?.[0].length ?? 0; const indent = ' '.repeat(Math.max(0, indentDepth - suffixIndent)); return state.transaction((tx) => { tx.text.insert(`\n${indent}`, { at: selection }); }); }), around(editorCommands.replaceSlice, ({ input, state, next }) => { const { options, slice } = input; const fragment = [...slice.content]; const target = options?.at; const currentSelection = state.selection(); if (target === undefined && !currentSelection) { return next(); } const at = target === undefined ? (currentSelection ?? undefined) : NodeApi.isNode(target) ? state.nodes.path(target) : target; if (target !== undefined && at === undefined) { return next(); } if (!state.nodes.block({ at, type: context.schema.type })) { return next(); } const separator = fragment.every((node) => !ElementApi.isElement(node)) ? '' : '\n'; const text = fragment .map((node) => NodeApi.string(node)) .join(separator); return next({ ...input, slice: ContentSlice.withContent(slice, [{ text }], { open: 'closed', }), }); }), ], })); export type CodeBlockElement = ElementOf; export type CodeHighlightPluginState = { defaultLanguage: string | null; lowlight: CodeHighlightLowlight | null; }; export const BaseCodeHighlightPlugin = definePlugin(PLUGINS.codeSyntax, { dependencies: [BaseCodeBlockPlugin], initialState: (): CodeHighlightPluginState => ({ defaultLanguage: null, lowlight: null, }), }).extend(({ editor, store }) => { const blockDecorations = new Map(); // Documents rendered one after another share unchanged blocks, so their // highlighting is found by block identity without a key lookup. let decorationsByBlock = new WeakMap(); // Every node's decoration read checks the code block type, and resolving a // portal costs more than the rest of that check; the portal stays live. const resolveCodeBlock = () => editor.plugin(BaseCodeBlockPlugin); let codeBlock: ReturnType | undefined; let nextSyntaxKey = 0; let observers = 0; const parseNodes = ( nodes: HighlightNode[], className: string[] = [], result: Array<{ classes: string[]; text: string }> = [] ) => { for (const node of nodes) { if (node.type === 'element') { const nodeClassName = node.properties?.className; const classes = [ ...className, ...(Array.isArray(nodeClassName) ? nodeClassName.map(String) : typeof nodeClassName === 'string' ? [nodeClassName] : []), ]; parseNodes(node.children ?? [], classes, result); } else if (node.type === 'text' && typeof node.value === 'string') { result.push({ classes: className, text: node.value }); } } return result; }; return { decorate: { observe: ({ refresh }) => { observers += 1; const unsubscribe = store.subscribe(() => { blockDecorations.clear(); decorationsByBlock = new WeakMap(); refresh({ nodeKeys: 'all' }); }); return () => { unsubscribe(); observers -= 1; if (observers === 0) { blockDecorations.clear(); decorationsByBlock = new WeakMap(); } }; }, // Reads the code block itself: its decorations cover its text, and a // change to that text invalidates the block too. read: ({ editor: view, entry: [block, blockPath], }): readonly CodeBlockDecoration[] => { if (!ElementApi.isElement(block)) return []; codeBlock ??= resolveCodeBlock(); if (block.type !== codeBlock.schema.type) return []; const { defaultLanguage, lowlight } = store.get(); if (!lowlight) return []; const language = (typeof block.language === 'string' ? block.language : undefined) || defaultLanguage; const atBlockPath = (cached: CodeHighlightCache) => { const cachedPath = cached.decorations[0]?.range.anchor.path; if (cachedPath && !PathApi.isParent(blockPath, cachedPath)) { const textPath = Object.freeze([...blockPath, 0]); cached.decorations = Object.freeze( cached.decorations.map((decoration) => Object.freeze({ ...decoration, range: Object.freeze({ anchor: Object.freeze({ ...decoration.range.anchor, path: textPath, }), focus: Object.freeze({ ...decoration.range.focus, path: textPath, }), }), }) ) ); } return cached.decorations; }; const sameBlock = decorationsByBlock.get(block); if ( sameBlock?.language === language && sameBlock.lowlight === lowlight ) { return atBlockPath(sameBlock); } const text = NodeApi.string(block); // A key follows a block across the live editor's edits. Nodes of a // document view get new keys, and resolving one indexes the whole // document, so there only identity finds a block's highlighting. const blockKey = isDocumentView(view) ? '' : (view.key(blockPath) ?? ''); const previous = blockKey ? blockDecorations.get(blockKey) : undefined; if ( previous?.language === language && previous.text === text && previous.lowlight === lowlight ) { decorationsByBlock.set(block, previous); return atBlockPath(previous); } let highlighted: HighlightResult; let warning: CodeHighlightWarning | undefined; try { if (!language || language === 'plaintext') { highlighted = { children: [], type: 'root' }; } else highlighted = lowlight.highlight(language, text); } catch (error) { const languageName = language ?? 'unknown'; warning = language && lowlight.listLanguages().includes(language) ? { error, kind: 'highlight', language: languageName } : { kind: 'missing-language', language: languageName }; highlighted = { children: [], type: 'root' }; } const decorations: CodeBlockDecoration[] = []; const attributesByClass = new Map< string, CodeBlockDecoration['attributes'] >(); const textPath = Object.freeze([...blockPath, 0]); const previousTokens = previous?.decorations ?? []; let retainedPrefix = 0; let matchingPrefix = true; let start = 0; for (const token of parseNodes(highlighted.children)) { const end = start + token.text.length; if (end > start && token.classes.length > 0) { const className = token.classes.join(' '); let attributes = attributesByClass.get(className); if (!attributes) { attributes = previous?.attributes.get(className) ?? Object.freeze({ className, 'data-code-block-syntax': '' }); attributesByClass.set(className, attributes); } const before = previousTokens[decorations.length]; if ( matchingPrefix && before && before.attributes === attributes && before.range.anchor.offset === start && before.range.focus.offset === end && PathApi.equals(before.range.anchor.path, textPath) ) { decorations.push(before); retainedPrefix += 1; } else { matchingPrefix = false; decorations.push({ attributes, key: '', range: { anchor: { offset: start, path: textPath }, focus: { offset: end, path: textPath }, }, }); } } start = end; } const delta = text.length - (previous?.text.length ?? 0); let beforeEnd = previousTokens.length; let afterEnd = decorations.length; while (beforeEnd > retainedPrefix && afterEnd > retainedPrefix) { const before = previousTokens[beforeEnd - 1]; const after = decorations[afterEnd - 1]; if ( before.attributes !== after.attributes || before.range.anchor.offset + delta !== after.range.anchor.offset || before.range.focus.offset + delta !== after.range.focus.offset ) { break; } decorations[afterEnd - 1] = delta === 0 && PathApi.equals(before.range.anchor.path, textPath) ? before : { ...after, key: before.key }; beforeEnd -= 1; afterEnd -= 1; } for (let index = retainedPrefix; index < afterEnd; index++) { decorations[index] = { ...decorations[index], key: `${blockKey}:${nextSyntaxKey}`, }; nextSyntaxKey += 1; } for (let index = retainedPrefix; index < decorations.length; index++) { const decoration = decorations[index]; if (Object.isFrozen(decoration)) continue; Object.freeze(decoration.range.anchor); Object.freeze(decoration.range.focus); Object.freeze(decoration.range); Object.freeze(decoration); } Object.freeze(decorations); const cache = { attributes: attributesByClass, decorations, language, lowlight, text, }; if (blockKey) blockDecorations.set(blockKey, cache); decorationsByBlock.set(block, cache); if (warning?.kind === 'highlight') { editor .plugin(DebugPlugin) .api.warn( `Could not highlight with Highlight.js for language "${warning.language}". Falling back to plaintext`, 'CODE_HIGHLIGHT', warning.error ); } else if (warning) { editor .plugin(DebugPlugin) .api.warn( `Language "${warning.language}" is not registered. Falling back to plaintext` ); } return decorations; }, }, on: { commit({ commit }) { if (blockDecorations.size === 0) return; const structure = commit.changed.hasAny('structure') || commit.changed.hasAny('replace'); if (!structure && !commit.changed.hasAny('properties')) return; const codeBlockType = editor.plugin(BaseCodeBlockPlugin).schema.type; const keys = new Set([ ...commit.changed.nodeKeysAll('node'), ...(structure ? commit.changed.nodeKeysAll('presence') : []), ]); for (const key of keys) { if (!blockDecorations.has(key)) continue; const entry = editor.read.nodes.get(key); if (!entry || !ElementApi.isElementType(entry[0], codeBlockType)) { blockDecorations.delete(key); } } }, }, }; }); export type CodeBlockDefinition = DefinitionOf; export type CodeHighlightDefinition = DefinitionOf< typeof BaseCodeHighlightPlugin >;