From 09fe5d67853563db45047fdcd22aefc4d995f70c Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 5 Apr 2026 17:54:54 -0400 Subject: [PATCH] feat: Auto-collapse tall code blocks (#11967) * Styling finetuning * test * Refactor collapsible code blocks: line-based collapse, styling fixes, use EditorStyleHelper - Use line count (12+) instead of DOM height measurement for collapse threshold - Handle missing dictionary gracefully for server-side rendering - Add addToHistory:false to toggleCodeBlockCollapse command - Move .code-block class name to EditorStyleHelper - Use neutral button variant for collapse toggle, show on hover/focus - Fix fade overlay border-radius and inset, clip line numbers via clip-path - Remove suppressAutoExpand hack; preventDefault already handles it --- app/hooks/useDictionary.ts | 2 + shared/editor/components/Styles.ts | 92 ++++++- shared/editor/nodes/CodeFence.ts | 322 ++++++++++++++++++++-- shared/editor/queries/findParentNode.ts | 4 +- shared/editor/styles/EditorStyleHelper.ts | 5 + 5 files changed, 395 insertions(+), 30 deletions(-) diff --git a/app/hooks/useDictionary.ts b/app/hooks/useDictionary.ts index 7a518e9a97..649e74e96d 100644 --- a/app/hooks/useDictionary.ts +++ b/app/hooks/useDictionary.ts @@ -125,6 +125,8 @@ export default function useDictionary() { formattingControls: t("Formatting controls"), distributeColumns: t("Distribute columns"), wrapText: t("Wrap text"), + collapseCode: t("Collapse"), + expandCode: t("Expand"), }), [t] ); diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index 994bfc13cf..48bc054630 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -1747,20 +1747,27 @@ mark { height: 16px; } -.code-block { +.${EditorStyleHelper.codeBlock} { position: relative; font-size: 90%; + + &:hover + .${EditorStyleHelper.codeBlockToggle}, + &:focus-within + .${EditorStyleHelper.codeBlockToggle}, + & + .${EditorStyleHelper.codeBlockToggle}:hover, + & + .${EditorStyleHelper.codeBlockToggle}:focus { + opacity: 1; + } } -.code-block[data-language=none], -.code-block[data-language=markdown] { +.${EditorStyleHelper.codeBlock}[data-language=none], +.${EditorStyleHelper.codeBlock}[data-language=markdown] { pre code { color: ${props.theme.text}; } } -.code-block[data-language=mermaid], -.code-block[data-language=mermaidjs] { +.${EditorStyleHelper.codeBlock}[data-language=mermaid], +.${EditorStyleHelper.codeBlock}[data-language=mermaidjs] { ${ !props.staticHTML && css` @@ -1797,8 +1804,8 @@ mark { } } -.ProseMirror[contenteditable="false"] .code-block[data-language=mermaid], -.ProseMirror[contenteditable="false"] .code-block[data-language=mermaidjs] { +.ProseMirror[contenteditable="false"] .${EditorStyleHelper.codeBlock}[data-language=mermaid], +.ProseMirror[contenteditable="false"] .${EditorStyleHelper.codeBlock}[data-language=mermaidjs] { height: 0; overflow: hidden; @@ -1808,8 +1815,8 @@ mark { } .ProseMirror.exported { - .code-block[data-language=mermaid], - .code-block[data-language=mermaidjs] { + .${EditorStyleHelper.codeBlock}[data-language=mermaid], + .${EditorStyleHelper.codeBlock}[data-language=mermaidjs] { height: auto; overflow: visible; @@ -1823,14 +1830,14 @@ mark { } } -.code-block.with-line-wrap { +.${EditorStyleHelper.codeBlock}.with-line-wrap { pre { white-space: pre-wrap; word-break: break-all; } } -.code-block.with-line-numbers { +.${EditorStyleHelper.codeBlock}.with-line-numbers { pre { padding-left: calc(var(--line-number-gutter-width, 0) * 1em + 1.5em); } @@ -1854,6 +1861,69 @@ mark { } } +.${EditorStyleHelper.codeBlock}.collapsed { + pre { + pointer-events: none; + max-height: calc(10 * 1.4em + 0.75em); + overflow: hidden; + } + + &::after { + clip-path: inset(0 0 calc(100% - 10 * 1.4em - 0.75em) 0); + } + + &::before { + content: ""; + position: absolute; + bottom: 1px; + left: 1px; + right: 1px; + height: 120px; + z-index: 1; + pointer-events: none; + border-radius: 0 0 4px 4px; + background: linear-gradient( + to bottom, + ${transparentize(1, props.theme.codeBackground)} 0%, + ${transparentize(0.2, props.theme.codeBackground)} 70%, + ${props.theme.codeBackground} 100% + ); + } +} + +.${EditorStyleHelper.codeBlockToggle} { + display: inline-flex; + align-items: center; + position: absolute; + z-index: 2; + left: 50%; + transform: translate3d(-50%, -50px, 0); + margin: 0; + padding: 0 8px; + border: 0; + border-radius: 100px; + background: ${props.theme.background}; + color: ${props.theme.buttonNeutralText}; + box-shadow: rgba(0, 0, 0, 0.07) 0px 1px 2px, ${props.theme.buttonNeutralBorder} 0 0 0 1px inset; + font-size: 13px; + font-weight: 500; + height: 24px; + cursor: var(--pointer); + user-select: none; + appearance: none !important; + opacity: 0; + transition: opacity 150ms ease; + pointer-events: auto; + + &:hover { + background: ${props.theme.backgroundSecondary}; + } + + @media print { + display: none !important; + } +} + .mermaid-diagram-wrapper { display: flex; align-items: center; diff --git a/shared/editor/nodes/CodeFence.ts b/shared/editor/nodes/CodeFence.ts index 93ba081074..f0a0339c2e 100644 --- a/shared/editor/nodes/CodeFence.ts +++ b/shared/editor/nodes/CodeFence.ts @@ -14,7 +14,7 @@ import { PluginKey, TextSelection, } from "prosemirror-state"; -import { Decoration, DecorationSet } from "prosemirror-view"; +import { Decoration, DecorationSet, type EditorView } from "prosemirror-view"; import { toast } from "sonner"; import type { Primitive } from "utility-types"; import type { Dictionary } from "~/hooks/useDictionary"; @@ -42,16 +42,115 @@ import { setRecentlyUsedCodeLanguage, } from "../lib/code"; import { isCode, isMermaid } from "../lib/isCode"; +import { findBlockNodes } from "../queries/findChildren"; import type { MarkdownSerializerState } from "../lib/markdown/serializer"; import { findNextNewline, findPreviousNewline } from "../queries/findNewlines"; -import { findParentNode } from "../queries/findParentNode"; +import { + findParentNode, + findParentNodeClosestToPos, +} from "../queries/findParentNode"; +import { EditorStyleHelper } from "../styles/EditorStyleHelper"; import { getMarkRange } from "../queries/getMarkRange"; import { isInCode } from "../queries/isInCode"; import Node from "./Node"; const DEFAULT_LANGUAGE = "javascript"; +const COLLAPSE_LINE_THRESHOLD = 12; + +interface CollapseState { + /** Positions of code blocks with more than COLLAPSE_LINE_THRESHOLD lines. */ + tallBlocks: Set; + /** Positions of code blocks currently collapsed by the user or auto-collapse. */ + collapsedBlocks: Set; + /** Node decorations that add the `collapsed` CSS class. */ + decorations: DecorationSet; +} + +/** + * Find all code block positions in the document that exceed the line threshold. + * + * @param doc - the document to scan. + * @returns set of positions of tall code blocks. + */ +function findTallBlocks(doc: ProsemirrorNode): Set { + const tall = new Set(); + for (const block of findBlockNodes(doc, true)) { + if (isCode(block.node)) { + const lines = (block.node.textContent.match(/\n/g)?.length ?? 0) + 1; + if (lines > COLLAPSE_LINE_THRESHOLD) { + tall.add(block.pos); + } + } + } + return tall; +} + +/** + * Build a CollapseState with node decorations for the collapsed class and + * widget decorations for toggle buttons on all tall blocks. + */ +function buildCollapseState( + doc: ProsemirrorNode, + tallBlocks: Set, + collapsedBlocks: Set, + expandLabel: string, + collapseLabel: string +): CollapseState { + const decorations: Decoration[] = []; + for (const pos of tallBlocks) { + const node = doc.nodeAt(pos); + if (!node || !isCode(node)) { + continue; + } + + const isCollapsed = collapsedBlocks.has(pos); + + if (isCollapsed) { + const totalLines = (node.textContent.match(/\n/g)?.length ?? 0) + 1; + const cappedLines = Math.min(totalLines, COLLAPSE_LINE_THRESHOLD); + const gutterWidth = String(totalLines).length; + const lineNumberText = Array.from({ length: cappedLines }, (_, i) => + String(i + 1).padStart(gutterWidth, " ") + ).join("\n"); + + decorations.push( + Decoration.node( + pos, + pos + node.nodeSize, + { class: "collapsed", "data-line-numbers": lineNumberText }, + { collapsed: true } + ) + ); + } + + const label = isCollapsed ? expandLabel : collapseLabel; + decorations.push( + Decoration.widget( + pos + node.nodeSize, + () => { + const button = document.createElement("button"); + button.className = EditorStyleHelper.codeBlockToggle; + button.contentEditable = "false"; + button.type = "button"; + button.textContent = label; + return button; + }, + { side: 1, key: `toggle-${pos}-${isCollapsed}` } + ) + ); + } + return { + tallBlocks, + collapsedBlocks, + decorations: DecorationSet.create(doc, decorations), + }; +} export default class CodeFence extends Node { + /** Plugin key for the collapse state, shared with the command. */ + private static readonly collapseKey = new PluginKey( + "collapse-code-block" + ); constructor(options: { dictionary: Dictionary; userPreferences?: UserPreferences | null; @@ -87,7 +186,7 @@ export default class CodeFence extends Node { draggable: false, parseDOM: [ { - tag: ".code-block", + tag: `.${EditorStyleHelper.codeBlock}`, preserveWhitespace: "full", contentElement: (node: HTMLElement) => node.querySelector("code") || node, @@ -109,20 +208,27 @@ export default class CodeFence extends Node { }, }, ], - toDOM: (node) => [ - "div", - { - class: `code-block ${ - node.attrs.wrap - ? "with-line-wrap" - : this.showLineNumbers - ? "with-line-numbers" - : "" - }`, - "data-language": node.attrs.language, - }, - ["pre", ["code", { spellCheck: "false" }, 0]], - ], + 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]], + ]; + }, }; } @@ -137,6 +243,23 @@ export default class CodeFence extends Node { ...attrs, }); }, + toggleCodeBlockCollapse: (): Command => (state, dispatch) => { + const codeBlock = findParentNode(isCode)(state.selection); + if (!codeBlock) { + return false; + } + + if (dispatch) { + dispatch( + state.tr + .setMeta(CodeFence.collapseKey, { + toggle: codeBlock.pos, + }) + .setMeta("addToHistory", false) + ); + } + return true; + }, toggleCodeBlockWrap: (): Command => (state, dispatch) => { const codeBlock = findParentNode(isCode)(state.selection); if (!codeBlock) { @@ -251,6 +374,169 @@ export default class CodeFence extends Node { return output; } + /** Plugins for collapsible code block behavior. */ + private collapsePlugins(): Plugin[] { + const collapseKey = CodeFence.collapseKey; + const options = this.options; + const build = ( + doc: ProsemirrorNode, + tall: Set, + collapsed: Set + ) => + buildCollapseState( + doc, + tall, + collapsed, + options.dictionary?.expandCode ?? "", + options.dictionary?.collapseCode ?? "" + ); + + return [ + // Main collapse plugin: manages state and decorations + new Plugin({ + key: collapseKey, + state: { + init: (_config, state) => { + const tallBlocks = findTallBlocks(state.doc); + return build(state.doc, tallBlocks, new Set(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 build(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 build(newState.doc, prev.tallBlocks, next); + } + return prev; + } + + // Recompute tall blocks on doc changes, preserving + // user collapse/expand choices where possible. + if (tr.docChanged) { + const tallBlocks = findTallBlocks(newState.doc); + const collapsedBlocks = new Set(); + + const inverse = tr.mapping.invert(); + for (const pos of tallBlocks) { + const oldPos = inverse.map(pos); + if (!prev.tallBlocks.has(oldPos)) { + // Newly tall blocks start collapsed + collapsedBlocks.add(pos); + } else if (prev.collapsedBlocks.has(oldPos)) { + // Preserve previous collapsed state + collapsedBlocks.add(pos); + } + } + + return build(newState.doc, tallBlocks, collapsedBlocks); + } + + return prev; + }, + }, + props: { + decorations(state) { + return this.getState(state)?.decorations ?? DecorationSet.empty; + }, + }, + }), + // 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; + } + + 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.previousElementSibling?.classList.contains( + EditorStyleHelper.codeBlock + ) + ? button.previousElementSibling + : null; + 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); @@ -363,6 +649,8 @@ export default class CodeFence extends Node { }, }, }), + // Collapse plugins - only on code_fence (not CodeBlock subclass) + ...(this.name === "code_fence" ? this.collapsePlugins() : []), ].filter(Boolean) as Plugin[]; } diff --git a/shared/editor/queries/findParentNode.ts b/shared/editor/queries/findParentNode.ts index d0f370e43d..eed2afc5b1 100644 --- a/shared/editor/queries/findParentNode.ts +++ b/shared/editor/queries/findParentNode.ts @@ -28,11 +28,11 @@ export const findParentNodeClosestToPos = ( $pos: ResolvedPos, predicate: Predicate ): ContentNodeWithPos | undefined => { - for (let i = $pos.depth; i > 0; i--) { + for (let i = $pos.depth; i >= 0; i--) { const node = $pos.node(i); if (predicate(node)) { return { - pos: $pos.before(i), + pos: i > 0 ? $pos.before(i) : 0, start: $pos.start(i), depth: i, node, diff --git a/shared/editor/styles/EditorStyleHelper.ts b/shared/editor/styles/EditorStyleHelper.ts index 03440a7057..9344e8e636 100644 --- a/shared/editor/styles/EditorStyleHelper.ts +++ b/shared/editor/styles/EditorStyleHelper.ts @@ -24,8 +24,13 @@ export class EditorStyleHelper { // Code + static readonly codeBlock = "code-block"; + static readonly codeWord = "code-word"; + /** Toggle button for collapsible code blocks */ + static readonly codeBlockToggle = "code-block-toggle"; + // Diffs static readonly diffInsertion = "diff-insertion";