: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): quote-aware toolbar, quoted list editing, cut and log fixes (#69727)
Marius Andraa64dcf1d491c
diff --git a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsxindex a4ffa8026d84..6ca1471f79f3 100644--- a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx@@ -40,6 +40,7 @@ export const TEXT_BLOCK_STYLE_BUTTONS: {export function FormattingToolbar({selectedBlockStyle,+ selectedBlockQuoted,placement,top,left,@@ -57,6 +58,8 @@ export function FormattingToolbar({returnFocusToEditor,}: {selectedBlockStyle: TextBlockStyle | null+ /** Whether every selected block sits inside a blockquote — orthogonal to the text style. */+ selectedBlockQuoted: booleanplacement: 'above' | 'below'top: numberleft: number@@ -240,21 +243,30 @@ export function FormattingToolbar({role="group"aria-label="Text style">- {TEXT_BLOCK_STYLE_BUTTONS.map((button) => (- <LemonButton- key={button.label}- size="xsmall"- icon={button.icon}- tooltip={button.label}- aria-label={button.label}- aria-pressed={selectedBlockStyle === button.style}- active={selectedBlockStyle === button.style}- className="MarkdownNotebook__format-style-button"- onClick={() => setBlockStyle(selectedBlockStyle === button.style ? 'paragraph' : button.style)}- >- {button.content}- </LemonButton>- ))}+ {TEXT_BLOCK_STYLE_BUTTONS.map((button) => {+ // Quote membership is orthogonal to the text style, so a quoted heading lights up+ // both its heading button and the quote button. The quote button always dispatches+ // 'blockquote' — the editor toggles membership based on the selection's current state.+ const isActive =+ button.style === 'blockquote' ? selectedBlockQuoted : selectedBlockStyle === button.style+ return (+ <LemonButton+ key={button.label}+ size="xsmall"+ icon={button.icon}+ tooltip={button.label}+ aria-label={button.label}+ aria-pressed={isActive}+ active={isActive}+ className="MarkdownNotebook__format-style-button"+ onClick={() =>+ setBlockStyle(button.style === 'blockquote' || !isActive ? button.style : 'paragraph')+ }+ >+ {button.content}+ </LemonButton>+ )+ })}</div>{showInlineActions ? (<>@@ -393,6 +405,22 @@ export function getSelectedBlockStyle(return [...styles][0]}+/** True when the selection is non-empty and every selected block sits inside a blockquote. */+export function getSelectedBlocksQuoted(+ textRanges: FloatingToolbarTextRange[],+ codeRanges: FloatingToolbarCodeRange[],+ listItemRanges: FloatingToolbarListItemRange[] = []+): boolean {+ if (codeRanges.length || (!textRanges.length && !listItemRanges.length)) {+ return false+ }++ return (+ textRanges.every(({ node }) => node.type === 'blockquote' || !!node.blockquote) &&+ listItemRanges.every(({ node }) => !!node.blockquote)+ )+}+export function getSelectedTextBlockStyle(textRanges: FloatingToolbarTextRange[]): TextBlockStyle | null {const firstTextRange = textRanges[0]if (!firstTextRange) {diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.tsindex bdc12cb73c72..25c2233a3666 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts@@ -4538,6 +4538,34 @@ Body text`)expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n> ## Quoted text`)})+ it('shows both the heading and blockquote buttons active for a quoted heading selection', () => {+ const { container } = render(+ createElement(MarkdownNotebook, { value: withNotebookTitle('> ## Quoted heading') })+ )+ const headingBlock = getEditableTextBlocks(container)[1]++ selectTextNode(getFirstTextNode(headingBlock), 0, 'Quoted'.length, true)++ expect(getFormattingStyleButton(container, 'Heading 2').classList.contains('LemonButton--active')).toBe(true)+ expect(getFormattingStyleButton(container, 'Blockquote').classList.contains('LemonButton--active')).toBe(true)+ })++ it.each([+ ['Heading 2', '> Quoted heading'],+ ['Blockquote', '## Quoted heading'],+ ])('toggling %s off a quoted heading keeps the other style dimension', (buttonLabel, expectedMarkdown) => {+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, { value: withNotebookTitle('> ## Quoted heading'), onChange })+ )+ const headingBlock = getEditableTextBlocks(container)[1]++ selectTextNode(getFirstTextNode(headingBlock), 0, 'Quoted'.length, true)+ fireEvent.click(getFormattingStyleButton(container, buttonLabel))++ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n${expectedMarkdown}`)+ })+it('downgrades a quoted heading to quote text with Backspace at its start', () => {const onChange = jest.fn()const { container } = render(@@ -4554,6 +4582,39 @@ Body text`)expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n> Quoted heading`)})+ it.each([+ ['- ', '> -', 'ul'],+ ['1. ', '> 1.', 'ol'],+ ])('converts a list shortcut "%s" typed inside a quote into a quoted list', (shortcut, markdown, listTag) => {+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, { value: withNotebookTitle('> Quoted text'), onChange })+ )+ const quoteBlock = getEditableTextBlocks(container)[1]++ quoteBlock.textContent = shortcut+ fireEvent.input(quoteBlock)++ const quotedList = container.querySelector(+ `.MarkdownNotebook__blockquote-group .MarkdownNotebook__list-block ${listTag}`+ )+ expect(quotedList).toBeInstanceOf(HTMLElement)+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n${markdown}`)+ })++ it('downgrades a quoted list item to quote text with Backspace at its start', () => {+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, { value: withNotebookTitle('> - First item\n> - Second item'), onChange })+ )+ const listItems = getEditableListItems(container)++ selectTextInElement(listItems[0], 0, 0)+ fireEvent.keyDown(listItems[0], { key: 'Backspace' })++ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n> First item\n\n> - Second item`)+ })+it('renders blockquoted lists inside the blockquote group', () => {const { container } = render(createElement(MarkdownNotebook, {@@ -6370,6 +6431,28 @@ Closing`expect(onChange).toHaveBeenLastCalledWith('# Intro paragraph')})+ it('deletes the selected text when cutting a selection across list items', () => {+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, { value: withNotebookTitle('- First item\n- Second item'), onChange })+ )+ const notebook = container.querySelector('.MarkdownNotebook') as HTMLElement+ const listItems = getEditableListItems(container)++ selectTextAcrossNodes(+ getFirstTextNode(listItems[0]),+ 'First'.length,+ getFirstTextNode(listItems[1]),+ 'Second'.length+ )++ const clipboardData = { setData: jest.fn() }+ fireEvent.cut(notebook, { clipboardData })++ expect(clipboardData.setData).toHaveBeenCalledWith('text/markdown', '- item\n- Second')+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n- First item`)+ })+it('lets native copy handle text selected inside a focused component', () => {expect.hasAssertions()const registry = createMarkdownNotebookRegistry([diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsxindex f4b66097a24a..db69e979583b 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx@@ -26,6 +26,7 @@ import { IconCode, IconComment, IconDrag } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import { Spinner } from 'lib/lemon-ui/Spinner'+import { downloadFile } from 'lib/utils/dom'// Monaco is heavy, so the markdown source editor only loads when the source drawer opens.const LazyCodeEditor = lazy(() => import('lib/monaco/CodeEditor').then((module) => ({ default: module.CodeEditor })))@@ -59,6 +60,7 @@ import {getDiscussionCommentRefId,isBlankInsertMenuButtonRow,isDiscussionCommentNode,+ isGroupedBlockquoteNode,isPromptComponentNode,isTextBlockNode,makeEmptyNotebookTitle,@@ -130,7 +132,12 @@ import {TextSelectionPointerStartEvent,TextSelectionPointerState,} from './editorTypes'-import { FormattingToolbar, getFloatingToolbarLinkHref, getSelectedBlockStyle } from './FormattingToolbar'+import {+ FormattingToolbar,+ getFloatingToolbarLinkHref,+ getSelectedBlockStyle,+ getSelectedBlocksQuoted,+} from './FormattingToolbar'import { markNotebookNodeFreshlyInserted } from './freshlyInserted'import {InlineMarkSelection,@@ -687,13 +694,15 @@ function MarkdownNotebookEditor({}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)+ // downloadFile appends the anchor to the DOM and defers the object-URL revoke, which+ // Firefox needs for the download to actually start.+ downloadFile(+ new File(+ [log.entries.join('\n') + '\n'],+ `markdown-notebook-debug-${new Date().toISOString().replace(/[:.]/g, '-')}.log`,+ { type: 'text/plain' }+ )+ )}, [])const stopDebugLoggingAndDownload = (): void => {@@ -1878,7 +1887,7 @@ function MarkdownNotebookEditor({// 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 => {+ (replacementText: string = '', claimSingleItemRange: boolean = false): boolean => {const notebookElement = notebookRef.currentconst selection = window.getSelection()if (!notebookElement || !selection || selection.rangeCount === 0 || selection.isCollapsed) {@@ -1912,10 +1921,11 @@ function MarkdownNotebookEditor({}// 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.+ // browser: only that item's manually synced innerHTML changes. Cut still claims it,+ // because cut prevents the browser default that would otherwise delete the text.const startElement = getClosestEditableBlockElement(getElementForNode(range.startContainer))const endElement = getClosestEditableBlockElement(getElementForNode(range.endContainer))- if (startElement === element && endElement === element) {+ if (!claimSingleItemRange && startElement === element && endElement === element) {return false}@@ -3340,7 +3350,7 @@ function MarkdownNotebookEditor({event.preventDefault()notebookClipboardMarkdownRef.current = markdownsetClipboardMarkdown(event.clipboardData, markdown)- if (!deleteSelectedNotebookBlocks()) {+ if (!deleteSelectedNotebookBlocks() && !deleteListItemRangeAtCurrentSelection('', true)) {deleteTextAtCurrentSelection('forward')}return@@ -3604,6 +3614,14 @@ function MarkdownNotebookEditor({const currentDocument = documentRef.currentconst nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]+ // The quote button toggles quote membership: unquote only when the whole selection is already quoted.+ const selectedNodes = nodes.filter(+ (node) =>+ selectedTextNodeIds.has(node.id) || selectedCodeNodeIds.has(node.id) || selectedListNodeIds.has(node.id)+ )+ const shouldUnquote =+ style === 'blockquote' && selectedNodes.length > 0 && selectedNodes.every(isGroupedBlockquoteNode)+const inlineRangesByNodeId = new Map([...(activeTextRanges ?? []), ...(activeCodeRanges ?? [])].map(({ range }) => [range.nodeId, range]))@@ -3641,8 +3659,8 @@ function MarkdownNotebookEditor({}if (selectedListNodeIds.has(node.id) && node.type === 'list') {// Lists only toggle blockquote membership; heading and code styles do not apply to them.- if (style === 'blockquote' && !node.blockquote) {- return { ...node, blockquote: true }+ if (style === 'blockquote') {+ return { ...node, blockquote: shouldUnquote ? undefined : true }}if (style === 'paragraph' && node.blockquote) {return { ...node, blockquote: undefined }@@ -3669,9 +3687,19 @@ function MarkdownNotebookEditor({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 }+ if (style === 'blockquote') {+ if (node.type === 'heading') {+ // Quote membership toggles without touching the heading level+ return { ...node, blockquote: shouldUnquote ? undefined : true }+ }+ if (shouldUnquote) {+ return { ...node, type: 'paragraph', level: undefined, blockquote: undefined }+ }+ return { ...node, type: 'blockquote', level: undefined, blockquote: undefined }+ }+ if (style === 'paragraph' && node.type === 'heading' && node.blockquote) {+ // Removing the heading style inside a quote downgrades to quote text, not plain text+ return { ...node, type: 'blockquote', level: undefined, blockquote: undefined }}return { ...node, type: style, level: undefined, blockquote: undefined }}),@@ -5959,6 +5987,11 @@ function MarkdownNotebookEditor({floatingToolbar.codeRanges,floatingToolbar.listItemRanges)}+ selectedBlockQuoted={getSelectedBlocksQuoted(+ floatingToolbar.textRanges,+ floatingToolbar.codeRanges,+ floatingToolbar.listItemRanges+ )}placement={floatingToolbar.placement}top={floatingToolbar.top}left={floatingToolbar.left}diff --git a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts b/frontend/src/lib/components/MarkdownNotebook/documentModel.tsindex 5285281dc61e..fb237c4ae392 100644--- a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts+++ b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts@@ -470,49 +470,53 @@ export function getTextBlockShortcutReplacement(}}- if (isTitleBlock || node.type !== 'paragraph') {+ if (isTitleBlock || (node.type !== 'paragraph' && node.type !== 'blockquote')) {return null}- if (getBlockquoteShortcut(text)) {- return {- nodes: [- {- id: node.id,- type: 'blockquote',- children: [],- },- ],- restoreSelection: { nodeId: node.id, start: 0, end: 0 },+ // Only the list shortcut applies inside a quote: code blocks and dividers have no quoted+ // form, and a quote marker typed in a quote stays literal text.+ if (node.type === 'paragraph') {+ if (getBlockquoteShortcut(text)) {+ return {+ nodes: [+ {+ id: node.id,+ type: 'blockquote',+ children: [],+ },+ ],+ restoreSelection: { nodeId: node.id, start: 0, end: 0 },+ }}- }- if (getCodeBlockShortcut(text)) {- return {- nodes: [- {- id: node.id,- type: 'code',- text: '',- },- ],- restoreSelection: { nodeId: node.id, start: 0, end: 0 },+ if (getCodeBlockShortcut(text)) {+ return {+ nodes: [+ {+ id: node.id,+ type: 'code',+ text: '',+ },+ ],+ restoreSelection: { nodeId: node.id, start: 0, end: 0 },+ }}- }- if (getDividerShortcut(text)) {- const trailingParagraph = makeEmptyParagraph(`divider-${node.id}`)- return {- nodes: [- {- id: node.id,- type: 'component',- tagName: DIVIDER_COMPONENT_TAG,- props: {},- },- trailingParagraph,- ],- restoreSelection: { nodeId: trailingParagraph.id, start: 0, end: 0 },+ if (getDividerShortcut(text)) {+ const trailingParagraph = makeEmptyParagraph(`divider-${node.id}`)+ return {+ nodes: [+ {+ id: node.id,+ type: 'component',+ tagName: DIVIDER_COMPONENT_TAG,+ props: {},+ },+ trailingParagraph,+ ],+ restoreSelection: { nodeId: trailingParagraph.id, start: 0, end: 0 },+ }}}@@ -526,6 +530,8 @@ export function getTextBlockShortcutReplacement(type: 'list',ordered: listShortcut.ordered,start: listShortcut.start,+ // A list typed inside a quote stays part of the quote+ blockquote: node.type === 'blockquote' ? true : undefined,items: [{id: listItemId,diff --git a/frontend/src/lib/components/MarkdownNotebook/listModel.test.ts b/frontend/src/lib/components/MarkdownNotebook/listModel.test.tsindex c5227ea3537e..7e47516678e8 100644--- a/frontend/src/lib/components/MarkdownNotebook/listModel.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/listModel.test.ts@@ -82,6 +82,20 @@ describe('listModel', () => {).toBeNull()})+ it('clamps a surviving deeper item when its depth bridge is deleted', () => {+ const items = [makeItem('parent', 0), makeItem('bridge', 1), makeItem('nested', 2), makeItem('tail', 0)]++ const deletion = deleteListItemSelectionRange(items, {+ firstItemIndex: 0,+ firstStart: 3,+ lastItemIndex: 1,+ lastEnd: 3,+ })++ expect(deletion?.items.map((item) => getInlineText(item.children))).toEqual(['pardge', 'nested', 'tail'])+ expect(deletion?.items.map((item) => item.depth)).toEqual([0, 1, 0])+ })+it('keeps the first item identity and depth when merging', () => {const items = [makeItem('parent', 0, 'item-a'), makeItem('child', 1, 'item-b')]diff --git a/frontend/src/lib/components/MarkdownNotebook/listModel.ts b/frontend/src/lib/components/MarkdownNotebook/listModel.tsindex 6722b2b5f44b..cbe62501abd7 100644--- a/frontend/src/lib/components/MarkdownNotebook/listModel.ts+++ b/frontend/src/lib/components/MarkdownNotebook/listModel.ts@@ -64,16 +64,22 @@ export function getOrderedListStart(export function normalizeListItemDepths(items: NotebookListItem[]): NotebookListItem[] {const minimumDepth = Math.min(...items.map((item) => Math.max(0, item.depth)))- if (!Number.isFinite(minimumDepth) || minimumDepth <= 0) {- return items.map((item) => ({ ...item, depth: Math.max(0, item.depth) }))- }-- return items.map((item) => ({ ...item, depth: Math.max(0, item.depth - minimumDepth) }))+ const baseDepth = Number.isFinite(minimumDepth) ? Math.max(0, minimumDepth) : 0++ // Clamp each item to at most one level deeper than its predecessor, mirroring the parser:+ // deleting a mid-depth item must not leave a deeper survivor orphaned across a depth jump.+ let previousDepth = -1+ return items.map((item) => {+ const depth = Math.min(Math.max(0, item.depth) - baseDepth, previousDepth + 1)+ previousDepth = depth+ return { ...item, depth }+ })}/**- * Builds the nodes that replace a list when one of its items is unwrapped into a paragraph:- * the items before it stay a list, its children move one depth up, and trailing items become a new list.+ * Builds the nodes that replace a list when one of its items is unwrapped into a paragraph+ * (or quote text when the list is quoted): the items before it stay a list, its children move+ * one depth up, and trailing items become a new list.*/export function getListItemParagraphReplacement(node: NotebookListBlockNode,@@ -108,7 +114,7 @@ export function getListItemParagraphReplacement(const beforeListNode = makeListNode(node.items.slice(0, targetItemIndex), `before-list-${node.id}`, node.id)const paragraph: NotebookTextBlockNode = {id: beforeListNode ? makeEmptyParagraph(`unlisted-${node.id}`).id : node.id,- type: 'paragraph',+ type: node.blockquote ? 'blockquote' : 'paragraph',children: item.children,}const childItems = node.items