import copy from "copy-to-clipboard"; import { t } from "i18next"; import type Token from "markdown-it/lib/token.mjs"; import { chainCommands } from "prosemirror-commands"; import { textblockTypeInputRule } from "prosemirror-inputrules"; import type { NodeSpec, NodeType, Schema, Node as ProsemirrorNode, } from "prosemirror-model"; import type { Command, EditorState } from "prosemirror-state"; import { NodeSelection, Plugin, PluginKey, TextSelection, } from "prosemirror-state"; import { Decoration, DecorationSet, type EditorView, type NodeViewConstructor, } from "prosemirror-view"; import type { Primitive } from "utility-types"; import type { UserPreferences } from "../../types"; import { isBrowser, isMac } from "../../utils/browser"; import backspaceToParagraph from "../commands/backspaceToParagraph"; import { newlineInCode, indentInCode, moveToNextNewline, moveToPreviousNewline, outdentInCode, enterInCode, backspaceInCode, deleteInCode, arrowLeftInCode, splitCodeBlockOnTripleBackticks, } from "../commands/codeFence"; import { selectAll } from "../commands/selectAll"; import toggleBlockType from "../commands/toggleBlockType"; import { CodeHighlighting } from "../plugins/CodeHighlightingPlugin"; import Mermaid, { pluginKey as mermaidPluginKey, type MermaidState, } from "../extensions/Mermaid"; import { codeLanguages, getRecentlyUsedCodeLanguage, setRecentlyUsedCodeLanguage, } from "../lib/code"; import { isCode, isMermaid } from "../lib/isCode"; import { isRemoteTransaction, mapDecorations } from "../lib/multiplayer"; import { findBlockNodes } from "../queries/findChildren"; import type { MarkdownSerializerState } from "../lib/markdown/serializer"; import { escapeRawTableCell } from "../lib/markdown/tableCell"; import { findNextNewline, findPreviousNewline } from "../queries/findNewlines"; import { findParentNode, findParentNodeClosestToPos, } from "../queries/findParentNode"; import { EditorStyleHelper } from "../styles/EditorStyleHelper"; import { getMarkRange } from "../queries/getMarkRange"; import { isInCode } from "../queries/isInCode"; import { CodeFenceView } from "./CodeFenceView"; import Node from "./Node"; const DEFAULT_LANGUAGE = "javascript"; /** Fraction of the viewport height above which a code block is collapsible. */ const COLLAPSE_HEIGHT_RATIO = 0.5; /** Approximate rendered line height of a code block, in pixels. */ const CODE_LINE_HEIGHT = 20; /** * Fraction of the document text above which a code block is not * auto-collapsed, as collapsing it would hide most of the document. */ const AUTO_COLLAPSE_MAX_DOC_RATIO = 0.5; const collapseKey = new PluginKey("collapse-code-block"); /** * Reduce a language attribute or fence info string to a single safe token, so * it cannot break the fence line when written back to markdown. * * @param language - the language attribute or fence info string. * @returns the first whitespace-separated token with backticks removed. */ function sanitizeLanguage(language: string | null | undefined): string { return String(language ?? "") .replace(/`/g, "") .trim() .split(/\s/)[0]; } interface CollapseState { /** Positions of code blocks taller than COLLAPSE_HEIGHT_RATIO of the viewport. */ tallBlocks: Set; /** Positions of code blocks currently collapsed by the user or auto-collapse. */ collapsedBlocks: Set; /** Node decorations that mark collapsible and collapsed blocks. */ decorations: DecorationSet; } /** * Expand the collapsed code block that contains a document position. * * @param pos - the document position inside the code block. * @returns a command that expands the code block when it is collapsed. */ export function expandCodeBlockAt(pos: number): Command { return (state, dispatch) => { const $pos = state.doc.resolve(pos); const codeBlock = findParentNodeClosestToPos($pos, isCode); if (!codeBlock) { return false; } const collapseState = collapseKey.getState(state); if (!collapseState?.collapsedBlocks.has(codeBlock.pos)) { return false; } dispatch?.( state.tr .setMeta(collapseKey, { expand: codeBlock.pos }) .setMeta("addToHistory", false) ); return true; }; } /** * Find all code block positions whose estimated height exceeds * COLLAPSE_HEIGHT_RATIO of the viewport height. * * @param doc - the document to scan. * @returns set of positions of tall code blocks. */ function findTallBlocks(doc: ProsemirrorNode): Set { const tall = new Set(); if (!isBrowser) { return tall; } const maxLines = (window.innerHeight * COLLAPSE_HEIGHT_RATIO) / CODE_LINE_HEIGHT; for (const block of findBlockNodes(doc, true)) { if (isCode(block.node)) { const lines = (block.node.textContent.match(/\n/g)?.length ?? 0) + 1; if (lines > maxLines) { tall.add(block.pos); } } } return tall; } /** * Find the tall code blocks that should start collapsed. A block that makes * up the majority of the document text is left expanded. * * @param doc - the document to scan. * @param tallBlocks - positions of tall code blocks in the document. * @returns set of positions of code blocks to auto-collapse. */ function findAutoCollapsedBlocks( doc: ProsemirrorNode, tallBlocks: Set ): Set { const docLength = doc.textContent.length; const collapsed = new Set(); for (const pos of tallBlocks) { const node = doc.nodeAt(pos); if (!node || !isCode(node)) { continue; } if (node.textContent.length <= docLength * AUTO_COLLAPSE_MAX_DOC_RATIO) { collapsed.add(pos); } } return collapsed; } /** * Build a CollapseState with node decorations that mark tall blocks as * collapsible and add the collapsed class to collapsed blocks. */ function buildCollapseState( doc: ProsemirrorNode, tallBlocks: Set, collapsedBlocks: Set ): CollapseState { const decorations: Decoration[] = []; for (const pos of tallBlocks) { const node = doc.nodeAt(pos); if (!node || !isCode(node)) { continue; } const isCollapsed = collapsedBlocks.has(pos); decorations.push( Decoration.node( pos, pos + node.nodeSize, isCollapsed ? { class: "collapsed" } : {}, { collapsible: true, collapsed: isCollapsed } ) ); } return { tallBlocks, collapsedBlocks, decorations: DecorationSet.create(doc, decorations), }; } /** * Options for the CodeFence node. */ type CodeFenceOptions = { /** Display preferences for the logged in user, if any. */ userPreferences?: UserPreferences | null; }; export default class CodeFence extends Node { get showLineNumbers(): boolean { return this.options.userPreferences?.codeBlockLineNumbers ?? true; } get name() { return "code_fence"; } get schema(): NodeSpec { return { attrs: { language: { default: DEFAULT_LANGUAGE, // Null is permitted as existing documents can contain code blocks // written before a language was always recorded. validate: "string|null", }, wrap: { default: false, validate: "boolean", }, }, content: "text*", marks: "comment", group: "block", code: true, defining: true, draggable: false, parseDOM: [ { tag: `.${EditorStyleHelper.codeBlock}`, preserveWhitespace: "full", contentElement: (node: HTMLElement) => node.querySelector("code") || node, getAttrs: (dom: HTMLDivElement) => ({ language: dom.dataset.language, wrap: dom.classList.contains("with-line-wrap"), }), }, { tag: "code", preserveWhitespace: "full", getAttrs: (dom) => { // Only parse code blocks that contain newlines for code fences, // otherwise the code mark rule will be applied. if (!dom.textContent?.includes("\n")) { return false; } return { language: dom.dataset.language }; }, }, ], toDOM: (node) => { const classes = [ EditorStyleHelper.codeBlock, node.attrs.wrap ? "with-line-wrap" : "", this.showLineNumbers ? "with-line-numbers" : "", ] .filter(Boolean) .join(" "); return [ "div", { class: classes, "data-language": node.attrs.language, }, ["pre", ["code", { spellCheck: "false" }, 0]], ]; }, }; } commands({ type, schema }: { type: NodeType; schema: Schema }) { return { code_block: (attrs: Record) => { if (attrs?.language) { setRecentlyUsedCodeLanguage(attrs.language as string); } return toggleBlockType(type, schema.nodes.paragraph, { language: getRecentlyUsedCodeLanguage() ?? DEFAULT_LANGUAGE, ...attrs, }); }, expandCodeBlockAt: (pos: number) => expandCodeBlockAt(pos), toggleCodeBlockCollapse: (): Command => (state, dispatch) => { const codeBlock = findParentNode(isCode)(state.selection); if (!codeBlock) { return false; } if (dispatch) { dispatch( state.tr .setMeta(collapseKey, { toggle: codeBlock.pos, }) .setMeta("addToHistory", false) ); } return true; }, toggleCodeBlockWrap: (): Command => (state, dispatch) => { const codeBlock = findParentNode(isCode)(state.selection); if (!codeBlock) { return false; } if (dispatch) { dispatch( state.tr.setNodeMarkup(codeBlock.pos, undefined, { ...codeBlock.node.attrs, wrap: !codeBlock.node.attrs.wrap, }) ); } return true; }, edit_mermaid: (): Command => (state, dispatch) => { const codeBlock = state.selection instanceof NodeSelection && isCode(state.selection.node) ? { pos: state.selection.from, node: state.selection.node } : findParentNode(isCode)(state.selection); if (!codeBlock || !isMermaid(codeBlock.node)) { return false; } const mermaidState = mermaidPluginKey.getState(state) as MermaidState; const decorations = mermaidState?.decorationSet.find( codeBlock.pos, codeBlock.pos + codeBlock.node.nodeSize ); const nodeDecoration = decorations?.find( (d) => d.spec.diagramId && d.from === codeBlock.pos ); const diagramId = nodeDecoration?.spec.diagramId; if (dispatch && diagramId) { dispatch( state.tr .setMeta(mermaidPluginKey, { editingId: mermaidState?.editingId === diagramId ? undefined : diagramId, }) .setSelection(TextSelection.create(state.doc, codeBlock.pos + 1)) .scrollIntoView() ); } return true; }, copyToClipboard: (attrs?: { pos?: number }): Command => (state, dispatch) => { const node = attrs?.pos !== undefined ? state.doc.nodeAt(attrs.pos) : null; const codeBlock = node && isCode(node) ? node : findParentNode(isCode)(state.selection)?.node; if (codeBlock) { copy(codeBlock.textContent); this.editor.props.onNotice?.(t("Copied to clipboard")); return true; } const { doc, tr } = state; const range = getMarkRange( doc.resolve(state.selection.from), this.editor.schema.marks.code_inline ) || getMarkRange( doc.resolve(state.selection.to), this.editor.schema.marks.code_inline ); if (range) { const $end = doc.resolve(range.to); tr.setSelection(new TextSelection($end, $end)); dispatch?.(tr); copy(tr.doc.textBetween(state.selection.from, state.selection.to)); this.editor.props.onNotice?.(t("Copied to clipboard")); return true; } return false; }, }; } get allowInReadOnly() { return true; } keys({ type, schema }: { type: NodeType; schema: Schema }) { const output: Record = { // Both shortcuts work, but Shift-Ctrl-c matches the one in the menu "Shift-Ctrl-c": toggleBlockType(type, schema.nodes.paragraph), "Shift-Ctrl-\\": toggleBlockType(type, schema.nodes.paragraph), "Shift-Tab": outdentInCode, Tab: indentInCode, Enter: enterInCode, Backspace: chainCommands(backspaceInCode, backspaceToParagraph(type)), Delete: deleteInCode, ArrowLeft: arrowLeftInCode, "Shift-Enter": newlineInCode, "Mod-a": selectAll(type), "Mod-]": indentInCode, "Mod-[": outdentInCode, }; if (isMac) { return { ...output, "Ctrl-a": moveToPreviousNewline, "Ctrl-e": moveToNextNewline, }; } return output; } /** Plugins for collapsible code block behavior. */ private collapsePlugins(): Plugin[] { const createCodeFenceView: NodeViewConstructor = ( node, _view, _getPos, decorations ) => new CodeFenceView(node, decorations); return [ // Main collapse plugin: manages state and decorations new Plugin({ key: collapseKey, state: { init: (_config, state) => { const tallBlocks = findTallBlocks(state.doc); return buildCollapseState( state.doc, tallBlocks, findAutoCollapsedBlocks(state.doc, tallBlocks) ); }, apply: (tr, prev, oldState, newState) => { const meta = tr.getMeta(collapseKey); // Toggle collapsed state if (meta?.toggle !== undefined) { const next = new Set(prev.collapsedBlocks); if (next.has(meta.toggle)) { next.delete(meta.toggle); } else { next.add(meta.toggle); } return buildCollapseState(newState.doc, prev.tallBlocks, next); } // Expand a specific block (auto-expand on focus) if (meta?.expand !== undefined) { if (prev.collapsedBlocks.has(meta.expand)) { const next = new Set(prev.collapsedBlocks); next.delete(meta.expand); return buildCollapseState(newState.doc, prev.tallBlocks, next); } return prev; } // Recompute tall blocks on doc changes. Newly tall blocks are only // auto-collapsed when content arrives via load/remote sync — never // while the user is typing, which would collapse the block under // the cursor. if (tr.docChanged) { const tallBlocks = findTallBlocks(newState.doc); const collapsedBlocks = new Set(); const isRemote = isRemoteTransaction(tr, newState); const autoCollapsedBlocks = isRemote ? findAutoCollapsedBlocks(newState.doc, tallBlocks) : new Set(); const previousBlockDecorations: Decoration[] = []; for (const pos of prev.tallBlocks) { const node = oldState.doc.nodeAt(pos); if (!node || !isCode(node)) { continue; } previousBlockDecorations.push( Decoration.node( pos, pos + node.nodeSize, {}, { collapsed: prev.collapsedBlocks.has(pos), trackedCodeBlock: true, } ) ); } const mappedTallBlocks = new Set(); const mappedCollapsedBlocks = new Set(); const previousBlocks = DecorationSet.create( oldState.doc, previousBlockDecorations ); for (const decoration of mapDecorations( previousBlocks, tr, newState ).find()) { if (!decoration.spec.trackedCodeBlock) { continue; } mappedTallBlocks.add(decoration.from); if (decoration.spec.collapsed) { mappedCollapsedBlocks.add(decoration.from); } } for (const pos of tallBlocks) { if (!mappedTallBlocks.has(pos)) { // Newly tall blocks start collapsed only on load/remote sync if (autoCollapsedBlocks.has(pos)) { collapsedBlocks.add(pos); } } else if (mappedCollapsedBlocks.has(pos)) { // Preserve previous collapsed state collapsedBlocks.add(pos); } } return buildCollapseState( newState.doc, tallBlocks, collapsedBlocks ); } return prev; }, }, props: { decorations(state) { return this.getState(state)?.decorations ?? DecorationSet.empty; }, // Collapse applies to every code node type, see isCode. nodeViews: { code_fence: createCodeFenceView, code_block: createCodeFenceView, }, }, }), // Click handler for toggle button + auto-expand on focus new Plugin({ key: new PluginKey("collapse-toggle"), appendTransaction: (transactions, oldState, newState) => { const hasCollapseMeta = transactions.some((tr) => tr.getMeta(collapseKey) ); const hasSelectionSet = transactions.some((tr) => tr.selectionSet); if (hasCollapseMeta || !hasSelectionSet) { return null; } const codeBlock = findParentNode(isCode)(newState.selection); const collapseState = collapseKey.getState(newState); if ( !codeBlock || !collapseState?.collapsedBlocks.has(codeBlock.pos) ) { return null; } // Only auto-expand when the selection moved INTO the block. If the // selection was already inside this block (e.g. after the user just // clicked Collapse while the cursor was inside), don't re-expand. const oldCodeBlock = findParentNode(isCode)(oldState.selection); if (oldCodeBlock?.pos === codeBlock.pos) { return null; } return newState.tr .setMeta(collapseKey, { expand: codeBlock.pos }) .setMeta("addToHistory", false); }, props: { handleDOMEvents: { mousedown: (view: EditorView, event: MouseEvent) => { const target = event.target as HTMLElement; const button = target.closest( `.${EditorStyleHelper.codeBlockToggle}` ); if (!button) { return false; } const codeBlockEl = button.closest( `.${EditorStyleHelper.codeBlock}` ); if (!codeBlockEl) { return false; } const codeEl = codeBlockEl.querySelector("code"); if (!codeEl) { return false; } const pos = view.posAtDOM(codeEl, 0); const $pos = view.state.doc.resolve(pos); const parent = findParentNodeClosestToPos($pos, isCode); if (!parent) { return false; } const collapseState = collapseKey.getState(view.state); const isCollapsing = !collapseState?.collapsedBlocks.has( parent.pos ); view.dispatch( view.state.tr .setMeta(collapseKey, { toggle: parent.pos }) .setMeta("addToHistory", false) ); if (isCollapsing) { codeBlockEl.scrollIntoView({ block: "nearest" }); } event.preventDefault(); event.stopPropagation(); return true; }, }, }, }), ]; } get plugins() { const createActiveCodeBlockDecoration = (state: EditorState) => { const codeBlock = findParentNode(isCode)(state.selection); if (!codeBlock) { return DecorationSet.empty; } if (isMermaid(codeBlock.node)) { const mermaidState = mermaidPluginKey.getState(state) as MermaidState; const decorations = mermaidState?.decorationSet.find( codeBlock.pos, codeBlock.pos + codeBlock.node.nodeSize ); const nodeDecoration = decorations?.find( (d) => d.spec.diagramId && d.from === codeBlock.pos ); const diagramId = nodeDecoration?.spec.diagramId; if (!diagramId || mermaidState?.editingId !== diagramId) { return DecorationSet.empty; } } const decoration = Decoration.node( codeBlock.pos, codeBlock.pos + codeBlock.node.nodeSize, { class: "code-active" } ); return DecorationSet.create(state.doc, [decoration]); }; return [ CodeHighlighting({ name: this.name, lineNumbers: this.showLineNumbers, }), this.name === "code_fence" ? Mermaid({ editor: this.editor }) : undefined, new Plugin({ key: new PluginKey("code-fence-split"), props: { handleTextInput: (view, _from, _to, text) => { if (text === "`") { const { state, dispatch } = view; return splitCodeBlockOnTripleBackticks(state, dispatch); } return false; }, }, }), new Plugin({ key: new PluginKey("triple-click"), props: { handleDOMEvents: { mousedown(view, event) { const { dispatch, state } = view; const { selection: { $from, $to }, } = state; if ( $from.sameParent($to) && event.detail === 3 && isInCode(view.state, { onlyBlock: true }) ) { dispatch?.( state.tr .setSelection( TextSelection.create( state.doc, findPreviousNewline($from), findNextNewline($from) ) ) .scrollIntoView() ); event.preventDefault(); return true; } return false; }, }, }, }), new Plugin({ key: new PluginKey("code-fence-active"), state: { init: (_, state) => createActiveCodeBlockDecoration(state), apply: (tr, pluginState, oldState, newState) => { // Only recompute if selection or document changed if ( !tr.selectionSet && !tr.docChanged && !tr.getMeta(mermaidPluginKey) ) { return pluginState; } return createActiveCodeBlockDecoration(newState); }, }, props: { decorations(state) { return this.getState(state); }, }, }), // Collapse plugins - only on code_fence (not CodeBlock subclass) ...(this.name === "code_fence" ? this.collapsePlugins() : []), ].filter(Boolean) as Plugin[]; } inputRules({ type }: { type: NodeType }) { return [ textblockTypeInputRule(/^```([a-zA-Z0-9+#-]*)\s$/, type, (match) => { const language = match[1].toLowerCase(); return { language: Object.prototype.hasOwnProperty.call( codeLanguages, language ) ? language : (getRecentlyUsedCodeLanguage() ?? DEFAULT_LANGUAGE), }; }), ]; } toMarkdown(state: MarkdownSerializerState, node: ProsemirrorNode) { // Fence content bypasses esc(), so when inside a table cell escape it here // so it cannot break out of the column. const content = state.inTable ? escapeRawTableCell(node.textContent) : node.textContent; // The fence must be longer than any backtick run in the content, or the // content could terminate the fence early when the markdown is parsed. const backticks = content.match(/`{3,}/g); const fence = "`".repeat( backticks ? Math.max(...backticks.map((run) => run.length)) + 1 : 3 ); state.write(fence + sanitizeLanguage(node.attrs.language) + "\n"); state.text(content, false); state.ensureNewLine(); state.write(fence); state.closeBlock(node); } get markdownToken() { return "fence"; } parseMarkdown() { return { block: "code_block", getAttrs: (tok: Token) => ({ language: sanitizeLanguage(tok.info) }), noCloseToken: true, }; } }