Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(notebooks): list delete crash, crash log download, quoted headings (#69294)

Marius Andra972f4c6dfe69
diff --git a/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx
index f03abfca08cc..0529ef208599 100644
--- a/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx
@@ -182,8 +182,10 @@ export function EditableTextBlock({
return {
...currentNode,
- type: 'paragraph',
+ // A quoted heading downgrades to quote text, staying in the quote
+ type: currentNode.blockquote ? 'blockquote' : 'paragraph',
level: undefined,
+ blockquote: undefined,
children: currentNode.children,
}
})
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index ecc288a89ae8..bdc12cb73c72 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -407,6 +407,39 @@ function fireSelectAllShortcut(element: HTMLElement): void {
fireEvent.keyDown(element, { key: 'a', metaKey: true })
}
+// jsdom has no URL.createObjectURL, so the debug-log download needs stubs; restore() puts the
+// original (usually absent) properties back so the stubs never leak into other tests.
+function stubNotebookLogDownload(): {
+ createObjectURL: jest.Mock<string, [Blob]>
+ anchorClick: jest.SpyInstance
+ restore: () => void
+} {
+ const originalCreateObjectURL = Object.getOwnPropertyDescriptor(window.URL, 'createObjectURL')
+ const originalRevokeObjectURL = Object.getOwnPropertyDescriptor(window.URL, 'revokeObjectURL')
+ const createObjectURL = jest.fn((_blob: Blob) => 'blob:notebook-debug-log')
+ Object.defineProperty(window.URL, 'createObjectURL', { value: createObjectURL, configurable: true })
+ Object.defineProperty(window.URL, 'revokeObjectURL', { value: jest.fn(), configurable: true })
+ const anchorClick = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+
+ const restoreUrlProperty = (name: 'createObjectURL' | 'revokeObjectURL', descriptor?: PropertyDescriptor): void => {
+ if (descriptor) {
+ Object.defineProperty(window.URL, name, descriptor)
+ } else {
+ delete (window.URL as unknown as Record<string, unknown>)[name]
+ }
+ }
+
+ return {
+ createObjectURL,
+ anchorClick,
+ restore: () => {
+ anchorClick.mockRestore()
+ restoreUrlProperty('createObjectURL', originalCreateObjectURL)
+ restoreUrlProperty('revokeObjectURL', originalRevokeObjectURL)
+ },
+ }
+}
+
function expectNoDuplicateKeyWarnings(callback: () => void): void {
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined)
let thrownError: unknown
@@ -2395,11 +2428,7 @@ Intro paragraph
})
it('records keystrokes, mouse events, and commits into a downloadable debug log', async () => {
- const createObjectURL = jest.fn((_blob: Blob) => 'blob:notebook-debug-log')
- const revokeObjectURL = jest.fn()
- Object.defineProperty(window.URL, 'createObjectURL', { value: createObjectURL, configurable: true })
- Object.defineProperty(window.URL, 'revokeObjectURL', { value: revokeObjectURL, configurable: true })
- const anchorClick = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+ const { createObjectURL, anchorClick, restore } = stubNotebookLogDownload()
try {
const { container } = render(
@@ -2446,7 +2475,82 @@ Intro paragraph
const keydownEntry = entries.find((entry) => entry.type === 'keydown')
expect(keydownEntry?.key).toEqual('a')
} finally {
- anchorClick.mockRestore()
+ restore()
+ }
+ })
+
+ it('downloads the debug log automatically when an uncaught error fires while recording', async () => {
+ const { createObjectURL, anchorClick, restore } = stubNotebookLogDownload()
+
+ try {
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('Hello there'), showDebug: true })
+ )
+ fireEvent.click(container.querySelector('button[aria-label="Edit markdown source"]') as HTMLButtonElement)
+ const logButton = container.querySelector(
+ '[data-attr="markdown-notebook-debug-log-toggle"]'
+ ) as HTMLButtonElement
+ fireEvent.click(logButton)
+ expect(logButton.textContent).toEqual('Stop')
+
+ act(() => {
+ window.dispatchEvent(new ErrorEvent('error', { error: new Error('boom') }))
+ })
+
+ expect(anchorClick).toHaveBeenCalledTimes(1)
+ expect(logButton.textContent).toEqual('Log')
+ const blobText = await createObjectURL.mock.calls[0][0].text()
+ const entries = blobText
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line) as Record<string, unknown>)
+ const crashEntry = entries[entries.length - 1]
+ expect(crashEntry.type).toEqual('crash')
+ expect(crashEntry.error).toEqual('Error: boom')
+ expect(crashEntry.markdown).toEqual(withNotebookTitle('Hello there'))
+ } finally {
+ restore()
+ }
+ })
+
+ it('downloads the debug log when a React commit crash hits the editor', async () => {
+ const { createObjectURL, anchorClick, restore } = stubNotebookLogDownload()
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined)
+
+ try {
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('1. one\n2. two\n3. three'),
+ showDebug: true,
+ })
+ )
+ fireEvent.click(container.querySelector('button[aria-label="Edit markdown source"]') as HTMLButtonElement)
+ fireEvent.click(
+ container.querySelector('[data-attr="markdown-notebook-debug-log-toggle"]') as HTMLButtonElement
+ )
+
+ // Reproduce the production crash class: the DOM is restructured behind React's
+ // back, then a model commit makes React unmount an <li> that is no longer where
+ // React left it, throwing a removeChild NotFoundError mid-commit.
+ const listItems = getEditableListItems(container)
+ const li = listItems[1].closest('li') as HTMLElement
+ li.parentNode?.removeChild(li)
+ selectTextAcrossNodes(getFirstTextNode(listItems[0]), 0, getFirstTextNode(listItems[2]), 5)
+
+ expect(() => fireEvent.keyDown(listItems[0], { key: 'Backspace' })).toThrow()
+
+ expect(anchorClick).toHaveBeenCalledTimes(1)
+ const blobText = await createObjectURL.mock.calls[0][0].text()
+ const entries = blobText
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line) as Record<string, unknown>)
+ const crashEntry = entries[entries.length - 1]
+ expect(crashEntry.type).toEqual('crash')
+ expect(String(crashEntry.error)).toContain('not a child of this node')
+ } finally {
+ consoleError.mockRestore()
+ restore()
}
})
@@ -4382,6 +4486,74 @@ Body text`)
> Quote outro`)
})
+ it('round-trips headings inside blockquotes as quoted headings', () => {
+ const markdown = `> Quote intro
+> ## Quoted heading
+> Quote outro`
+
+ const document = parseMarkdownNotebook(markdown)
+
+ expect(document.nodes.map((node) => node.type)).toEqual(['blockquote', 'heading', 'blockquote'])
+ expect(document.nodes[1].type === 'heading' && document.nodes[1].level).toEqual(2)
+ expect(document.nodes[1].type === 'heading' && document.nodes[1].blockquote).toBe(true)
+ expect(serializeMarkdownNotebook(document)).toEqual(`> Quote intro
+
+> ## Quoted heading
+
+> Quote outro`)
+ })
+
+ it('keeps quote text that looks like a heading as escaped literal text', () => {
+ const document = parseMarkdownNotebook('> \\## literal marker')
+
+ expect(document.nodes.map((node) => node.type)).toEqual(['blockquote'])
+ expect(serializeMarkdownNotebook(document)).toEqual('> \\## literal marker')
+ })
+
+ it('renders blockquoted headings inside the blockquote group', () => {
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('> Quote intro\n> ## Quoted heading'),
+ })
+ )
+ const quotedHeading = container.querySelector('.MarkdownNotebook__blockquote-group h2')
+
+ expect(quotedHeading).toBeInstanceOf(HTMLElement)
+ expect(quotedHeading?.textContent).toEqual('Quoted heading')
+ })
+
+ it('applies a heading style inside a blockquote without leaving the quote', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('> Quoted text'),
+ onChange,
+ })
+ )
+ const quoteBlock = getEditableTextBlocks(container)[1]
+
+ selectTextNode(getFirstTextNode(quoteBlock), 0, 'Quoted'.length, true)
+ fireEvent.click(getFormattingStyleButton(container, 'Heading 2'))
+
+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n> ## Quoted text`)
+ })
+
+ it('downgrades a quoted heading to quote text with Backspace at its start', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('> ## Quoted heading'),
+ onChange,
+ })
+ )
+ const headingBlock = getEditableTextBlocks(container)[1]
+
+ selectTextInElement(headingBlock, 0, 0)
+ fireEvent.keyDown(headingBlock, { key: 'Backspace' })
+
+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n> Quoted heading`)
+ })
+
it('renders blockquoted lists inside the blockquote group', () => {
const { container } = render(
createElement(MarkdownNotebook, {
@@ -5546,6 +5718,75 @@ Keep after`),
expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nKeep before\n\nKeep after`)
})
+ it('deletes a fully selected list item through the model when the selection reaches the next item', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('1. one\n2. two\n3. three'), onChange })
+ )
+ const listItems = getEditableListItems(container)
+
+ // A triple-click style selection: the whole first item, ending at the next item's start.
+ selectTextAcrossNodes(getFirstTextNode(listItems[0]), 0, getFirstTextNode(listItems[1]), 0)
+ const event = beforeInputInContentEditable(listItems[0], 'deleteContentBackward')
+
+ // The edit must go through the model: the browser default merges the React-managed
+ // <li> elements in place and the next React commit crashes with a removeChild error.
+ expect(event.defaultPrevented).toBe(true)
+ expect(getEditableListItems(container).map((item) => item.textContent)).toEqual(['', 'two', 'three'])
+ expect(container.querySelectorAll('li')).toHaveLength(3)
+ expect(onChange).toHaveBeenCalled()
+ })
+
+ it('merges a selection spanning list items into one item with Backspace', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('1. alpha\n2. beta\n3. gamma'), onChange })
+ )
+ const listItems = getEditableListItems(container)
+
+ selectTextAcrossNodes(getFirstTextNode(listItems[0]), 2, getFirstTextNode(listItems[2]), 3)
+ fireEvent.keyDown(listItems[0], { key: 'Backspace' })
+
+ expect(getEditableListItems(container).map((item) => item.textContent)).toEqual(['alma'])
+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n1. alma`)
+ })
+
+ it('replaces a selection spanning list items with the typed character', () => {
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('1. alpha\n2. beta\n3. gamma') })
+ )
+ const listItems = getEditableListItems(container)
+
+ selectTextAcrossNodes(getFirstTextNode(listItems[0]), 2, getFirstTextNode(listItems[2]), 3)
+ const event = fireInsertTextBeforeInput(listItems[0], 'X')
+
+ expect(event.defaultPrevented).toBe(true)
+ expect(getEditableListItems(container).map((item) => item.textContent)).toEqual(['alXma'])
+ })
+
+ it('blocks unclaimed native range edits that cross inline-editable boundaries', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('| a | b |\n| --- | --- |\n| one | two |'),
+ onChange,
+ })
+ )
+ const cells = Array.from(container.querySelectorAll('.MarkdownNotebook__table-cell-content')) as HTMLElement[]
+ const bodyCells = cells.filter((cell) => cell.textContent === 'one' || cell.textContent === 'two')
+ expect(bodyCells).toHaveLength(2)
+
+ onChange.mockClear()
+ selectTextAcrossNodes(getFirstTextNode(bodyCells[0]), 1, getFirstTextNode(bodyCells[1]), 1)
+ const event = beforeInputInContentEditable(bodyCells[0], 'deleteContentBackward')
+
+ // No model handler claims a cross-cell range yet, so the native edit (which would
+ // merge React-managed cells and crash the next commit) must be dropped.
+ expect(event.defaultPrevented).toBe(true)
+ expect(bodyCells.map((cell) => cell.textContent)).toEqual(['one', 'two'])
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
it('deletes a Cmd+A selection that includes component blocks', () => {
const onChange = jest.fn()
const registry = createMarkdownNotebookRegistry([
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 2ed1ada3f676..f4b66097a24a 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -3,12 +3,14 @@ import './MarkdownNotebook.scss'
import clsx from 'clsx'
import {
ClipboardEvent as ReactClipboardEvent,
+ Component,
DragEvent as ReactDragEvent,
FocusEvent as ReactFocusEvent,
FormEvent,
Fragment,
KeyboardEvent,
MouseEvent as ReactMouseEvent,
+ ReactNode,
Suspense,
lazy,
useCallback,
@@ -74,9 +76,11 @@ import {
} from './documentModel'
import {
findTextPosition,
+ getClosestEditableBlockElement,
getCollapsedSelectionRange,
getCollapsedSelectionRestoreRequest,
getComponentNodeForSelection,
+ getElementForNode,
getElementLineHeight,
getFocusedComponentNode,
getInlineEditableElementForSelection,
@@ -90,6 +94,7 @@ import {
getSelectedTextRanges,
getSelectionClientRect,
getSelectionRange,
+ inputEventCrossesInlineEditableBoundary,
isFormattingToolbarFocused,
isNativeEditableElement,
isSelectionInsideElement,
@@ -152,6 +157,7 @@ import {
getNextInsertMenuSelectedIndex,
} from './InsertMenu'
import {
+ deleteListItemSelectionRange,
getListItemIndex,
getListItemParagraphReplacement,
getListItemRefKey,
@@ -400,6 +406,31 @@ function componentNodeErrorsKey(node: NotebookComponentBlockNode): string {
return node.errors?.join('\n') ?? ''
}
+/** Input types whose browser default edits the DOM across the current selection/target range. */
+const NATIVE_RANGE_EDIT_INPUT_TYPES = new Set([
+ 'insertText',
+ 'insertParagraph',
+ 'insertLineBreak',
+ 'insertFromPaste',
+ 'insertFromPasteAsQuotation',
+ 'insertFromDrop',
+ 'insertFromYank',
+ 'insertReplacementText',
+ 'insertTranspose',
+ 'deleteContent',
+ 'deleteContentBackward',
+ 'deleteContentForward',
+ 'deleteWordBackward',
+ 'deleteWordForward',
+ 'deleteSoftLineBackward',
+ 'deleteSoftLineForward',
+ 'deleteHardLineBackward',
+ 'deleteHardLineForward',
+ 'deleteEntireSoftLine',
+ 'deleteByCut',
+ 'deleteByDrag',
+])
+
/** A debug recording session: JSONL entries downloaded as a .log file on stop. */
type NotebookDebugLog = {
startedAt: number
@@ -451,7 +482,57 @@ function getDebugSelectionSummary(): Record<string, unknown> {
}
}
-export function MarkdownNotebook({
+// Debug recordings currently in flight, so a crash anywhere in the editor can flush them
+// before the component (and its refs) unmounts.
+const activeDebugLogCrashFlushers = new Set<(error: unknown) => void>()
+
+function flushMarkdownNotebookDebugLogsOnCrash(error: unknown): void {
+ for (const flush of activeDebugLogCrashFlushers) {
+ flush(error)
+ }
+}
+
+type MarkdownNotebookCrashReporterState = { error: Error | null; reported: boolean }
+
+/**
+ * Downloads any in-flight debug recording before a render/commit crash unmounts the editor.
+ * The error is rethrown so the surrounding error boundary still renders its usual fallback —
+ * by then the log download has already been triggered.
+ */
+class MarkdownNotebookCrashReporter extends Component<{ children: ReactNode }, MarkdownNotebookCrashReporterState> {
+ override state: MarkdownNotebookCrashReporterState = { error: null, reported: false }
+
+ static getDerivedStateFromError(error: Error): Partial<MarkdownNotebookCrashReporterState> {
+ return { error }
+ }
+
+ override componentDidCatch(error: Error): void {
+ flushMarkdownNotebookDebugLogsOnCrash(error)
+ this.setState({ reported: true })
+ }
+
+ override render(): ReactNode {
+ if (this.state.error) {
+ if (this.state.reported) {
+ throw this.state.error
+ }
+ // One empty pass: componentDidCatch runs after it commits, flushes the log, and
+ // flips `reported` so the next render rethrows into the surrounding boundary.
+ return null
+ }
+ return this.props.children
+ }
+}
+
+export function MarkdownNotebook(props: MarkdownNotebookProps): JSX.Element {
+ return (
+ <MarkdownNotebookCrashReporter>
+ <MarkdownNotebookEditor {...props} />
+ </MarkdownNotebookCrashReporter>
+ )
+}
+
+function MarkdownNotebookEditor({
value,
onChange,
onAskAI,
@@ -605,6 +686,16 @@ export function MarkdownNotebook({
setIsDebugLogging(true)
}
+ const downloadDebugLog = useCallback((log: NotebookDebugLog): void => {
+ const blob = new Blob([log.entries.join('\n') + '\n'], { type: 'text/plain' })
+ const url = URL.createObjectURL(blob)
+ const anchor = window.document.createElement('a')
+ anchor.href = url
+ anchor.download = `markdown-notebook-debug-${new Date().toISOString().replace(/[:.]/g, '-')}.log`
+ anchor.click()
+ URL.revokeObjectURL(url)
+ }, [])
+
const stopDebugLoggingAndDownload = (): void => {
const log = debugLogRef.current
logDebugEntry('stop', { markdown: lastSerializedValueRef.current })
@@ -614,15 +705,59 @@ export function MarkdownNotebook({
return
}
- const blob = new Blob([log.entries.join('\n') + '\n'], { type: 'text/plain' })
- const url = URL.createObjectURL(blob)
- const anchor = window.document.createElement('a')
- anchor.href = url
- anchor.download = `markdown-notebook-debug-${new Date().toISOString().replace(/[:.]/g, '-')}.log`
- anchor.click()
- URL.revokeObjectURL(url)
+ downloadDebugLog(log)
}
+ // A crash can unmount the editor or leave its DOM unusable, which would silently discard
+ // an in-flight recording — the moment the editor did something worth debugging. Download
+ // the log immediately instead of losing it.
+ const flushDebugLogOnCrash = useCallback(
+ (error: unknown): void => {
+ const log = debugLogRef.current
+ if (!log) {
+ return
+ }
+
+ logDebugEntry('crash', {
+ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error),
+ stack: error instanceof Error ? truncateForDebugLog(error.stack, 4000) : undefined,
+ markdown: lastSerializedValueRef.current,
+ })
+ debugLogRef.current = null
+ setIsDebugLogging(false)
+ downloadDebugLog(log)
+ },
+ [downloadDebugLog, logDebugEntry]
+ )
+
+ // While recording, an uncaught error anywhere flushes the log: crashes in event handlers
+ // and DOM listeners never reach the crash reporter boundary below. Unhandled rejections
+ // are recorded but don't end the session — they are usually background noise (a failed
+ // fetch), not an editor crash.
+ useEffect(() => {
+ if (!isDebugLogging) {
+ return
+ }
+
+ const handleWindowError = (event: ErrorEvent): void => {
+ flushDebugLogOnCrash(event.error ?? event.message)
+ }
+ const handleUnhandledRejection = (event: PromiseRejectionEvent): void => {
+ const reason: unknown = event.reason
+ logDebugEntry('unhandledrejection', {
+ error: reason instanceof Error ? `${reason.name}: ${reason.message}` : String(reason),
+ })
+ }
+ activeDebugLogCrashFlushers.add(flushDebugLogOnCrash)
+ window.addEventListener('error', handleWindowError)
+ window.addEventListener('unhandledrejection', handleUnhandledRejection)
+ return () => {
+ activeDebugLogCrashFlushers.delete(flushDebugLogOnCrash)
+ window.removeEventListener('error', handleWindowError)
+ window.removeEventListener('unhandledrejection', handleUnhandledRejection)
+ }
+ }, [isDebugLogging, flushDebugLogOnCrash, logDebugEntry])
+
// While recording, capture-phase listeners mirror every keyboard, mouse, input, and
// clipboard event into the log, plus deduplicated selection snapshots — together with
// the commit entries this reconstructs an editing session for offline debugging.
@@ -1738,6 +1873,116 @@ export function MarkdownNotebook({
[commitDocument]
)
+ // A ranged selection that reaches a list item's edge (e.g. the whole item selected up to
+ // the next item's start) must be deleted through the model: the browser's native delete
+ // merges `<li>` elements in place, and React then crashes on its next commit because the
+ // list structure it manages no longer matches the DOM (removeChild NotFoundError).
+ const deleteListItemRangeAtCurrentSelection = useCallback(
+ (replacementText: string = ''): boolean => {
+ const notebookElement = notebookRef.current
+ const selection = window.getSelection()
+ if (!notebookElement || !selection || selection.rangeCount === 0 || selection.isCollapsed) {
+ return false
+ }
+
+ const element = getSelectedInlineEditableElementOfType(
+ notebookElement,
+ 'MarkdownNotebook__list-item-content'
+ )
+ const nodeId = element?.dataset.markdownNotebookNodeId
+ if (!element || !nodeId) {
+ return false
+ }
+
+ const currentDocument = documentRef.current
+ const nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]
+ const node = nodes.find((currentNode) => currentNode.id === nodeId)
+ if (!node || node.type !== 'list') {
+ return false
+ }
+
+ const range = selection.getRangeAt(0)
+ const listBlockElement = blockRefs.current[node.id]
+ if (
+ !listBlockElement ||
+ !listBlockElement.contains(range.startContainer) ||
+ !listBlockElement.contains(range.endContainer)
+ ) {
+ return false
+ }
+
+ // A range confined to a single item's content element is safe to leave to the
+ // browser: only that item's manually synced innerHTML changes.
+ const startElement = getClosestEditableBlockElement(getElementForNode(range.startContainer))
+ const endElement = getClosestEditableBlockElement(getElementForNode(range.endContainer))
+ if (startElement === element && endElement === element) {
+ return false
+ }
+
+ const itemRanges = node.items.flatMap((_, itemIndex) => {
+ const itemElement = listItemRefs.current[getListItemRefKey(node.id, itemIndex)]
+ const itemRange = itemElement ? getSelectionRange(itemElement, node.id) : null
+ if (!itemRange) {
+ return []
+ }
+ return [
+ {
+ itemIndex,
+ start: Math.min(itemRange.start, itemRange.end),
+ end: Math.max(itemRange.start, itemRange.end),
+ },
+ ]
+ })
+
+ // A zero-length range at the selection's edge is a boundary touch that selects
+ // nothing in that item.
+ while (itemRanges.length > 1 && itemRanges[0].start === itemRanges[0].end) {
+ itemRanges.shift()
+ }
+ while (
+ itemRanges.length > 1 &&
+ itemRanges[itemRanges.length - 1].start === itemRanges[itemRanges.length - 1].end
+ ) {
+ itemRanges.pop()
+ }
+ const firstRange = itemRanges[0]
+ const lastRange = itemRanges[itemRanges.length - 1]
+ if (!firstRange || !lastRange) {
+ return false
+ }
+
+ const deletion = deleteListItemSelectionRange(
+ node.items,
+ {
+ firstItemIndex: firstRange.itemIndex,
+ firstStart: firstRange.start,
+ lastItemIndex: lastRange.itemIndex,
+ lastEnd: lastRange.end,
+ },
+ replacementText
+ )
+ if (!deletion) {
+ return false
+ }
+
+ restoreSelectionRef.current = {
+ nodeId: node.id,
+ listItemIndex: deletion.caretItemIndex,
+ listItemId: deletion.caretItemId,
+ start: deletion.caretOffset,
+ end: deletion.caretOffset,
+ }
+ commitDocument({
+ ...currentDocument,
+ nodes: nodes.map((currentNode) =>
+ currentNode.id === node.id ? { ...node, items: deletion.items } : currentNode
+ ),
+ })
+ return true
+ },
+ [commitDocument]
+ )
+
const insertTableRowAtCurrentSelection = useCallback((): boolean => {
const element = getSelectedInlineEditableElementOfType(
notebookRef.current,
@@ -2089,7 +2334,13 @@ export function MarkdownNotebook({
...currentDocument,
nodes: nodes.map((currentNode) =>
currentNode.id === node.id && isTextBlockNode(currentNode)
- ? { ...currentNode, type: 'paragraph', level: undefined }
+ ? {
+ ...currentNode,
+ // A quoted heading downgrades to quote text, staying in the quote
+ type: currentNode.blockquote ? 'blockquote' : 'paragraph',
+ level: undefined,
+ blockquote: undefined,
+ }
: currentNode
),
})
@@ -2216,7 +2467,8 @@ export function MarkdownNotebook({
nativeEvent.inputType === 'insertText' &&
typeof nativeEvent.data === 'string' &&
nativeEvent.data.length > 0 &&
- deleteSelectedNotebookBlocks(nativeEvent.data)
+ (deleteSelectedNotebookBlocks(nativeEvent.data) ||
+ deleteListItemRangeAtCurrentSelection(nativeEvent.data))
) {
event.preventDefault()
event.stopPropagation()
@@ -2236,9 +2488,10 @@ export function MarkdownNotebook({
if (
(nativeEvent.inputType === 'deleteContentBackward' ||
nativeEvent.inputType === 'deleteContentForward') &&
- (deleteListItemAtCurrentSelection(
- nativeEvent.inputType === 'deleteContentBackward' ? 'backward' : 'forward'
- ) ||
+ (deleteListItemRangeAtCurrentSelection() ||
+ deleteListItemAtCurrentSelection(
+ nativeEvent.inputType === 'deleteContentBackward' ? 'backward' : 'forward'
+ ) ||
deleteTextAtCurrentSelection(
nativeEvent.inputType === 'deleteContentBackward' ? 'backward' : 'forward'
))
@@ -2248,6 +2501,19 @@ export function MarkdownNotebook({
return
}
+ // A native edit whose range crosses inline-editable boundaries would restructure
+ // React-managed DOM and crash the next React commit. If no handler above claimed
+ // the edit, dropping it is the safe outcome.
+ if (
+ NATIVE_RANGE_EDIT_INPUT_TYPES.has(nativeEvent.inputType) &&
+ inputEventCrossesInlineEditableBoundary(nativeEvent, notebookElement)
+ ) {
+ logDebugEntry('blocked-cross-boundary-edit', { inputType: nativeEvent.inputType })
+ event.preventDefault()
+ event.stopPropagation()
+ return
+ }
+
if (nativeEvent.inputType !== 'historyUndo' && nativeEvent.inputType !== 'historyRedo') {
return
}
@@ -2266,8 +2532,10 @@ export function MarkdownNotebook({
return () => notebookElement.removeEventListener('beforeinput', handleBeforeInput, true)
}, [
deleteListItemAtCurrentSelection,
+ deleteListItemRangeAtCurrentSelection,
deleteSelectedNotebookBlocks,
deleteTextAtCurrentSelection,
+ logDebugEntry,
insertNewlineInCodeBlockAtCurrentSelection,
insertTableRowAtCurrentSelection,
mode,
@@ -3393,9 +3661,19 @@ export function MarkdownNotebook({
}
}
if (typeof style === 'number') {
- return { ...node, type: 'heading', level: style }
+ // A heading applied inside a quote keeps its quote membership
+ return {
+ ...node,
+ type: 'heading',
+ level: style,
+ blockquote: node.type === 'blockquote' || node.blockquote ? true : undefined,
+ }
+ }
+ if (style === 'blockquote' && node.type === 'heading') {
+ // Quoting a heading keeps it a heading, mirroring list quote membership
+ return { ...node, blockquote: true }
}
- return { ...node, type: style, level: undefined }
+ return { ...node, type: style, level: undefined, blockquote: undefined }
}),
})
}
@@ -5143,7 +5421,8 @@ export function MarkdownNotebook({
!event.altKey &&
!event.metaKey &&
!event.ctrlKey &&
- (deleteListItemAtCurrentSelection(event.key === 'Backspace' ? 'backward' : 'forward') ||
+ (deleteListItemRangeAtCurrentSelection() ||
+ deleteListItemAtCurrentSelection(event.key === 'Backspace' ? 'backward' : 'forward') ||
deleteEmptyCodeBlockAtCurrentSelection())
) {
event.preventDefault()
diff --git a/frontend/src/lib/components/MarkdownNotebook/README.md b/frontend/src/lib/components/MarkdownNotebook/README.md
index 1d9889b68cf0..72a26aa11903 100644
--- a/frontend/src/lib/components/MarkdownNotebook/README.md
+++ b/frontend/src/lib/components/MarkdownNotebook/README.md
@@ -24,7 +24,7 @@ See [COMPONENTS.md](./COMPONENTS.md) for how to register embeddable components (
## Supported markdown
-Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported), hard breaks, ref anchors (`<ref id="x">highlighted text</ref>`, lowercase inline tags so they can never collide with uppercase component tags), and mentions (`<mention id="5">@Name</mention>`; the text is the display label, the id is the member). Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted lists), ordered/unordered lists with nesting, GFM task lists (`- [ ]`/`- [x]` on bullet items; the checkbox replaces the bullet and `1. [x]` stays literal), GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (`![alt](src)`, stored as the `Image` component), and JSX-like component tags.
+Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported), hard breaks, ref anchors (`<ref id="x">highlighted text</ref>`, lowercase inline tags so they can never collide with uppercase component tags), and mentions (`<mention id="5">@Name</mention>`; the text is the display label, the id is the member). Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted headings — `> ## Heading` — and quoted lists), ordered/unordered lists with nesting, GFM task lists (`- [ ]`/`- [x]` on bullet items; the checkbox replaces the bullet and `1. [x]` stays literal), GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (`![alt](src)`, stored as the `Image` component), and JSX-like component tags.
### Round-trip guarantee
@@ -43,7 +43,7 @@ The canvas (`.MarkdownNotebook__canvas`) is a single `contenteditable` editing h
Because of this, all editing behavior must be dispatched from root-level handlers based on the current selection:
- `handleRootEditableKeyDown` (canvas `onKeyDown`) — Tab indentation, Enter splits, Backspace/Delete semantics, ArrowDown below a trailing code block
-- the native `beforeinput` capture listener — `insertParagraph`/`insertLineBreak` (inside code blocks these insert a literal `\n` through the model, since the browser default inserts `<br>` elements that are invisible to `textContent`), `deleteContent*`, `historyUndo/Redo`
+- the native `beforeinput` capture listener — `insertParagraph`/`insertLineBreak` (inside code blocks these insert a literal `\n` through the model, since the browser default inserts `<br>` elements that are invisible to `textContent`), `deleteContent*`, `historyUndo/Redo`, and a last-resort guard that cancels any unclaimed native range edit crossing inline-editable boundaries — the browser would otherwise restructure React-managed elements in place (e.g. merge two `<li>`s) and the next React commit would crash with `removeChild` DOM exceptions
- `handleRootEditableInput` (canvas `onInput`) — syncing typed text back into the document model
- `handleNotebookKeyDown` (notebook root `onKeyDownCapture`) — Cmd/Ctrl shortcuts: bold/italic/underline (`B`/`I`/`U`), strikethrough (`Shift+X`), scoped select-all (`A`), copy of a focused component (`C`)
@@ -64,6 +64,8 @@ Save conflicts (HTTP 409) are resolved through the same path: `notebookLogic` re
The debug drawer (`showDebug`) has a Log button that records an editing session as JSONL: every keystroke, mouse, input, and clipboard event on the notebook (capture phase), deduplicated selection snapshots, and every document commit with the resulting markdown — plus remote merges with their base/local/remote inputs and conflicts. Stop downloads the session as a `.log` file, built to be handed to an agent (or a human) to reconstruct exactly what the editor did and why.
+If the editor crashes while a recording is in flight, the log downloads itself instead of being lost: a `crash` entry (error, stack, current markdown) is appended and the file is saved immediately — whether the crash is an uncaught error in an event handler (window `error` listener) or a React render/commit error (`MarkdownNotebookCrashReporter`, which flushes the log and rethrows so the app's error boundary still takes over). Unhandled promise rejections are logged as entries but don't end the session.
+
## Inline discussion comments
A Google Docs-style comment thread is two paired pieces of markdown: an inline `<ref id="banana">highlighted text</ref>` anchor (a multi-block selection wraps each block's range in the same id) and a `<Comment ref="banana" replies={[…]} />` block placed right above the first block holding the highlight. When threads are present and the container is wide enough, the canvas reserves a right gutter (`--markdown-notebook-comment-gutter`) and pushes the text column left; each thread row keeps zero height so the card hangs in the gutter level with its content. Below `COMMENT_GUTTER_MIN_CONTAINER_WIDTH_PX` the threads flow inline as right-aligned cards. Replies live in the markdown itself as an id-keyed array, so two people replying at the same time merge by union (`mergeIdKeyedArrayPropValues` in `collaboration.ts`) instead of clobbering each other.
diff --git a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
index 3a47a2d42efc..5285281dc61e 100644
--- a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
@@ -122,7 +122,10 @@ export function isTextBlockNode(node: NotebookBlockNode): node is NotebookTextBl
export function isGroupedBlockquoteNode(
node: NotebookBlockNode
): node is NotebookTextBlockNode | NotebookListBlockNode {
- return (isTextBlockNode(node) && node.type === 'blockquote') || (node.type === 'list' && !!node.blockquote)
+ return (
+ (isTextBlockNode(node) && (node.type === 'blockquote' || !!node.blockquote)) ||
+ (node.type === 'list' && !!node.blockquote)
+ )
}
export function isPromptComponentNode(node: NotebookBlockNode): node is NotebookComponentBlockNode {
@@ -318,7 +321,7 @@ export function getPromptSource(value: NotebookPropValue | undefined): 'slash' |
}
export function textBlocksShareContinuationStyle(left: NotebookTextBlockNode, right: NotebookTextBlockNode): boolean {
- if (left.type !== right.type) {
+ if (left.type !== right.type || !!left.blockquote !== !!right.blockquote) {
return false
}
@@ -458,6 +461,8 @@ export function getTextBlockShortcutReplacement(
id: node.id,
type: 'heading',
level: headingShortcut,
+ // A heading typed inside a quote stays part of the quote
+ blockquote: node.type === 'blockquote' || node.blockquote ? true : undefined,
children: [],
},
],
diff --git a/frontend/src/lib/components/MarkdownNotebook/domSelection.ts b/frontend/src/lib/components/MarkdownNotebook/domSelection.ts
index 23a4abc8535d..8405ffc99121 100644
--- a/frontend/src/lib/components/MarkdownNotebook/domSelection.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/domSelection.ts
@@ -222,6 +222,42 @@ export function getInlineEditableElementForSelection(
return getClosestEditableBlockElement(getElementForNode(selection.anchorNode))
}
+/** The subset of Range that StaticRange (from InputEvent.getTargetRanges) also implements. */
+type EditTargetRange = Pick<Range, 'collapsed' | 'startContainer' | 'endContainer'>
+
+/**
+ * Whether a native input event would edit content across inline-editable element boundaries.
+ * The browser implements such edits by restructuring the DOM in place (merging two `<li>`
+ * elements, joining table cells), which desyncs the React-managed element tree and makes the
+ * next React commit throw removeChild/insertBefore DOM exceptions — so these browser defaults
+ * must never be allowed to run.
+ */
+export function inputEventCrossesInlineEditableBoundary(event: InputEvent, rootElement: HTMLElement): boolean {
+ const eventWithTargetRanges = event as InputEvent & { getTargetRanges?: () => EditTargetRange[] }
+ const targetRanges =
+ typeof eventWithTargetRanges.getTargetRanges === 'function' ? eventWithTargetRanges.getTargetRanges() : []
+ if (targetRanges.length) {
+ return targetRanges.some((targetRange) => rangeCrossesInlineEditableBoundary(targetRange, rootElement))
+ }
+
+ const selection = window.getSelection()
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
+ return false
+ }
+
+ return rangeCrossesInlineEditableBoundary(selection.getRangeAt(0), rootElement)
+}
+
+function rangeCrossesInlineEditableBoundary(range: EditTargetRange, rootElement: HTMLElement): boolean {
+ if (range.collapsed || !rootElement.contains(range.startContainer) || !rootElement.contains(range.endContainer)) {
+ return false
+ }
+
+ const startElement = getClosestEditableBlockElement(getElementForNode(range.startContainer))
+ const endElement = getClosestEditableBlockElement(getElementForNode(range.endContainer))
+ return !startElement || !endElement || startElement !== endElement
+}
+
export function getCollapsedSelectionRestoreRequest(
selection: Selection | null,
rootElement: HTMLElement
diff --git a/frontend/src/lib/components/MarkdownNotebook/listModel.test.ts b/frontend/src/lib/components/MarkdownNotebook/listModel.test.ts
new file mode 100644
index 000000000000..c5227ea3537e
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/listModel.test.ts
@@ -0,0 +1,102 @@
+import { deleteListItemSelectionRange } from './listModel'
+import { NotebookListItem } from './types'
+import { getInlineText } from './utils'
+
+function makeItem(text: string, depth: number = 0, id?: string): NotebookListItem {
+ return { id, children: text ? [{ type: 'text', text }] : [], depth }
+}
+
+describe('listModel', () => {
+ describe('deleteListItemSelectionRange', () => {
+ test.each([
+ {
+ name: 'deletes a range within a single item',
+ items: ['alpha'],
+ range: { firstItemIndex: 0, firstStart: 1, lastItemIndex: 0, lastEnd: 3 },
+ replacementText: '',
+ expectedTexts: ['aha'],
+ expectedCaret: { itemIndex: 0, offset: 1 },
+ },
+ {
+ name: 'empties a fully selected item but keeps it in the list',
+ items: ['one', 'two', 'three'],
+ range: { firstItemIndex: 0, firstStart: 0, lastItemIndex: 0, lastEnd: 3 },
+ replacementText: '',
+ expectedTexts: ['', 'two', 'three'],
+ expectedCaret: { itemIndex: 0, offset: 0 },
+ },
+ {
+ name: 'merges across items and removes the ones in between',
+ items: ['alpha', 'beta', 'gamma'],
+ range: { firstItemIndex: 0, firstStart: 2, lastItemIndex: 2, lastEnd: 3 },
+ replacementText: '',
+ expectedTexts: ['alma'],
+ expectedCaret: { itemIndex: 0, offset: 2 },
+ },
+ {
+ name: 'inserts replacement text where the selection started',
+ items: ['alpha', 'beta', 'gamma'],
+ range: { firstItemIndex: 0, firstStart: 2, lastItemIndex: 2, lastEnd: 3 },
+ replacementText: 'X',
+ expectedTexts: ['alXma'],
+ expectedCaret: { itemIndex: 0, offset: 3 },
+ },
+ {
+ name: 'clamps offsets that overshoot the item text',
+ items: ['ab', 'cd'],
+ range: { firstItemIndex: 0, firstStart: 5, lastItemIndex: 1, lastEnd: 9 },
+ replacementText: '',
+ expectedTexts: ['ab'],
+ expectedCaret: { itemIndex: 0, offset: 2 },
+ },
+ ])('$name', ({ items, range, replacementText, expectedTexts, expectedCaret }) => {
+ const deletion = deleteListItemSelectionRange(
+ items.map((text) => makeItem(text)),
+ range,
+ replacementText
+ )
+
+ expect(deletion).not.toBeNull()
+ expect(deletion?.items.map((item) => getInlineText(item.children))).toEqual(expectedTexts)
+ expect(deletion?.caretItemIndex).toEqual(expectedCaret.itemIndex)
+ expect(deletion?.caretOffset).toEqual(expectedCaret.offset)
+ })
+
+ test.each([
+ {
+ name: 'a collapsed range without replacement text',
+ items: ['alpha'],
+ range: { firstItemIndex: 0, firstStart: 2, lastItemIndex: 0, lastEnd: 2 },
+ },
+ {
+ name: 'an out-of-bounds item index',
+ items: ['alpha'],
+ range: { firstItemIndex: 0, firstStart: 0, lastItemIndex: 3, lastEnd: 1 },
+ },
+ ])('returns null for $name', ({ items, range }) => {
+ expect(
+ deleteListItemSelectionRange(
+ items.map((text) => makeItem(text)),
+ range
+ )
+ ).toBeNull()
+ })
+
+ it('keeps the first item identity and depth when merging', () => {
+ const items = [makeItem('parent', 0, 'item-a'), makeItem('child', 1, 'item-b')]
+
+ const deletion = deleteListItemSelectionRange(items, {
+ firstItemIndex: 0,
+ firstStart: 3,
+ lastItemIndex: 1,
+ lastEnd: 2,
+ })
+
+ expect(deletion?.items).toHaveLength(1)
+ expect(deletion?.items[0].id).toEqual('item-a')
+ expect(deletion?.items[0].depth).toEqual(0)
+ expect(deletion?.caretItemId).toEqual('item-a')
+ expect(getInlineText(deletion?.items[0].children ?? [])).toEqual('parild')
+ })
+ })
+})
diff --git a/frontend/src/lib/components/MarkdownNotebook/listModel.ts b/frontend/src/lib/components/MarkdownNotebook/listModel.ts
index 075478b28853..6722b2b5f44b 100644
--- a/frontend/src/lib/components/MarkdownNotebook/listModel.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/listModel.ts
@@ -1,5 +1,13 @@
+import { splitInlineNodesAt } from './inlineContent'
import { makeEmptyParagraph } from './markdown'
-import { NotebookBlockNode, NotebookListBlockNode, NotebookListItem, NotebookTextBlockNode } from './types'
+import {
+ NotebookBlockNode,
+ NotebookInlineNode,
+ NotebookListBlockNode,
+ NotebookListItem,
+ NotebookTextBlockNode,
+} from './types'
+import { getInlineText, normalizeInlineNodes } from './utils'
export type RenderedListItem = NotebookListItem & {
index: number
@@ -119,6 +127,66 @@ export function getListItemParagraphReplacement(
return { replacementNodes, paragraphId: paragraph.id }
}
+export type ListItemSelectionRange = {
+ firstItemIndex: number
+ firstStart: number
+ lastItemIndex: number
+ lastEnd: number
+}
+
+export type ListItemSelectionDeletion = {
+ items: NotebookListItem[]
+ caretItemIndex: number
+ caretItemId: string | undefined
+ caretOffset: number
+}
+
+/**
+ * Deletes a text selection that lives inside one list block: the first selected item keeps its
+ * text before the selection (plus the optional replacement text) and inherits the last selected
+ * item's text after it, the items in between are removed, and the caret lands where the
+ * selection started. Returns null when the range describes no change.
+ */
+export function deleteListItemSelectionRange(
+ items: NotebookListItem[],
+ range: ListItemSelectionRange,
+ replacementText: string = ''
+): ListItemSelectionDeletion | null {
+ const firstItem = items[range.firstItemIndex]
+ const lastItem = items[range.lastItemIndex]
+ if (!firstItem || !lastItem || range.lastItemIndex < range.firstItemIndex) {
+ return null
+ }
+
+ const firstTextLength = getInlineText(firstItem.children).length
+ const lastTextLength = getInlineText(lastItem.children).length
+ const firstStart = Math.max(0, Math.min(range.firstStart, firstTextLength))
+ const lastEnd = Math.max(0, Math.min(range.lastEnd, lastTextLength))
+ if (range.firstItemIndex === range.lastItemIndex && firstStart >= lastEnd && !replacementText) {
+ return null
+ }
+
+ const [beforeSelection] = splitInlineNodesAt(firstItem.children, firstStart)
+ const [, afterSelection] = splitInlineNodesAt(lastItem.children, lastEnd)
+ const insertedChildren: NotebookInlineNode[] = replacementText ? [{ type: 'text', text: replacementText }] : []
+ const mergedItem: NotebookListItem = {
+ ...firstItem,
+ children: normalizeInlineNodes([...beforeSelection, ...insertedChildren, ...afterSelection]),
+ }
+ const nextItems = normalizeListItemDepths([
+ ...items.slice(0, range.firstItemIndex),
+ mergedItem,
+ ...items.slice(range.lastItemIndex + 1),
+ ])
+
+ return {
+ items: nextItems,
+ caretItemIndex: range.firstItemIndex,
+ caretItemId: mergedItem.id,
+ caretOffset: getInlineText(beforeSelection).length + replacementText.length,
+ }
+}
+
/** Shifts a list item and its subtree one depth step in or out, or returns null when the shift is not allowed. */
export function shiftListItemSubtreeDepth(
items: NotebookListItem[],
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
index 540c4e9325ce..40ceee863703 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
@@ -180,9 +180,11 @@ export function serializeNode(node: NotebookBlockNode): string {
function serializeNodeUncached(node: NotebookBlockNode): string {
if (node.type === 'heading') {
const [firstLine, ...followingLines] = serializeInlineNodes(node.children).split('\n')
- return [`${'#'.repeat(node.level ?? 1)} ${firstLine}`, ...followingLines.map(escapeMarkdownLineStart)].join(
- '\n'
- )
+ const linePrefix = node.blockquote ? '> ' : ''
+ return [
+ `${linePrefix}${'#'.repeat(node.level ?? 1)} ${firstLine}`,
+ ...followingLines.map((followingLine) => `${linePrefix}${escapeMarkdownLineStart(followingLine)}`),
+ ].join('\n')
}
if (node.type === 'paragraph') {
return escapeMarkdownBlockLines(serializeInlineNodes(node.children))
@@ -612,12 +614,28 @@ function parseBlock(lines: string[], lineIndex: number): BlockParseResult {
return parseBlockquotedComponentBlock(lines, lineIndex)
}
+ // The heading marker needs its trailing space (`> ## `), which stripBlockquoteMarker trims.
+ const quotedHeadingMatch = line.replace(/^\s*>\s?/, '').match(HEADING_REGEX)
+ if (quotedHeadingMatch) {
+ return {
+ node: {
+ id: '',
+ type: 'heading',
+ level: quotedHeadingMatch[1].length as NotebookTextBlockNode['level'],
+ blockquote: true,
+ children: parseInlineMarkdown(quotedHeadingMatch[2]),
+ },
+ nextLineIndex: lineIndex + 1,
+ }
+ }
+
const quoteLines: string[] = []
let nextLineIndex = lineIndex
while (
nextLineIndex < lines.length &&
lines[nextLineIndex].trim().startsWith('>') &&
!isListLine(stripBlockquoteMarker(lines[nextLineIndex])) &&
+ !HEADING_REGEX.test(lines[nextLineIndex].replace(/^\s*>\s?/, '')) &&
!COMPONENT_START_REGEX.test(stripAllBlockquoteMarkers(lines[nextLineIndex]))
) {
quoteLines.push(stripBlockquoteMarker(lines[nextLineIndex]))
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
index 35ccd8c2528c..801bf54eddea 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
@@ -131,6 +131,7 @@ describe('markdown round trip', () => {
id: '',
type: 'heading',
level: count(6) as NotebookTextBlockNode['level'],
+ blockquote: random() < 0.25 ? true : undefined,
children: [makeInlineRun(false)],
}
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/types.ts b/frontend/src/lib/components/MarkdownNotebook/types.ts
index bf2255ceb92c..f8d9fb3b952a 100644
--- a/frontend/src/lib/components/MarkdownNotebook/types.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/types.ts
@@ -40,6 +40,8 @@ export type NotebookTextBlockNode = {
id: string
type: 'paragraph' | 'heading' | 'blockquote'
level?: 1 | 2 | 3 | 4 | 5 | 6
+ /** A heading that is part of a blockquote: serialized with a `> ` prefix on every line. */
+ blockquote?: boolean
children: NotebookInlineNode[]
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/utils.ts b/frontend/src/lib/components/MarkdownNotebook/utils.ts
index 8e9247d3b640..6f8d21b205bf 100644
--- a/frontend/src/lib/components/MarkdownNotebook/utils.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/utils.ts
@@ -123,6 +123,7 @@ function getUncachedNodeFingerprint(node: NotebookBlockNode): string {
return JSON.stringify({
type: node.type,
level: node.level,
+ blockquote: node.blockquote,
children: node.children,
})
}
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts
index 5d034e792b4c..8e1b78d07c5c 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts
@@ -45,6 +45,20 @@ describe('markdownNotebookDowngrade', () => {
})
})
+ it('wraps quoted headings in a blockquote', () => {
+ expect(convertMarkdownToNotebookContent('> ## Quoted heading')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'blockquote',
+ content: [
+ { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Quoted heading' }] },
+ ],
+ },
+ ],
+ })
+ })
+
it.each<[string, string, JSONContentMarks]>([
['**bold**', 'bold', [{ type: 'bold' }]],
['*italic*', 'italic', [{ type: 'italic' }]],
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
index f47512ad8dfc..f78423fa44c9 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
@@ -65,7 +65,12 @@ function convertBlockNode(node: NotebookBlockNode): JSONContent | JSONContent[]
}
if (node.type === 'heading') {
const content = convertInlineNodes(node.children)
- return { type: 'heading', attrs: { level: node.level ?? 1 }, ...(content.length ? { content } : {}) }
+ const heading: JSONContent = {
+ type: 'heading',
+ attrs: { level: node.level ?? 1 },
+ ...(content.length ? { content } : {}),
+ }
+ return node.blockquote ? { type: 'blockquote', content: [heading] } : heading
}
if (node.type === 'blockquote') {
return { type: 'blockquote', content: [makeParagraph(convertInlineNodes(node.children))] }
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
index ec778ea1970c..5d1dc77453db 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
@@ -529,7 +529,7 @@ after`)
expect(parsed.nodes.map((node) => node.type)).toEqual(['heading', 'list', 'component', 'blockquote'])
})
- it('splits embedded cards and headings out of blockquotes instead of quoting their tags', () => {
+ it('splits embedded cards out of blockquotes while keeping headings quoted', () => {
const content: JSONContent = {
type: 'doc',
content: [
@@ -564,7 +564,7 @@ after`)
expect(markdown).toContain('> Quoted context')
expect(markdown).toContain('\n\n<Query ')
- expect(markdown).toContain('\n\n## Where to improve')
+ expect(markdown).toContain('> ## Where to improve')
expect(markdown).toContain('\n\n<Python ')
expect(markdown).not.toContain('> <')
@@ -574,6 +574,8 @@ after`)
'Query',
'Python',
])
+ const quotedHeading = parsed.nodes.find((node) => node.type === 'heading')
+ expect(quotedHeading?.type === 'heading' && quotedHeading.blockquote).toBe(true)
})
it('splits embedded cards out of callouts while keeping the emoji and text quoted', () => {
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
index 522e2b45642e..3e7b2ba82ec2 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
@@ -689,6 +689,11 @@ function isBlockquotableRichContentNode(node: JSONContent, serialized: string):
if (nodeType === 'paragraph' || nodeType === 'text') {
return true
}
+ // Blockquoted headings parse back (`> ## Heading`), but only as a single line — a heading
+ // whose content spilled onto extra lines splits out of the quote instead.
+ if (nodeType === 'heading') {
+ return !serialized.includes('\n')
+ }
// Blockquoted lists parse back (`> - item`), but only while every line is a list line — a
// list that spilled block content into standalone blocks splits out of the quote with them.
if (LIST_NODE_TYPES.has(nodeType ?? '')) {