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.

feat(notebooks): close markdown notebook editor parity gaps (#68852)

Marius Andrabdbbd5ebe8f1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 0daa6d994c95..8244729f9357 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1217,9 +1217,9 @@ snapshots:
components-markdown-notebook--selection-toolbar-state--light:
hash: v1.k794b7964.f5c91317fef4dbd71945a2c2cc95bb37ecdf276020aa959a2745b8273e9e41b5.fsryMCCBVtHpn2nZHOTISpKXxKhCkvPnaxXcUpY5qiA
components-markdown-notebook--slash-menu-and-insertion--dark:
- hash: v1.k794b7964.a8e03cc86a51e29941d4f0305d2c042e44a766346cd1ba34207845e9660f5579.LcTMbbSSSV0fgK-DogkQr15rB76cB4d7Q6dStpnm2ho
+ hash: v1.k794b7964.226ccc85aab91ac7b729103db595c69e1ba1a01fd7d4541c7ab8790a4510e2ea.gBbTKWw9HuIhArY_kbRFcrpzn6FoIm3xyUinqK2RzT8
components-markdown-notebook--slash-menu-and-insertion--light:
- hash: v1.k794b7964.e59aa2895abf4d9ac2815b7d582be6ef32094daefef6710ca41b4690e7effff5.jwmQtjoVadLAMzej6MQE4-W8rw5_lfT35V7uwLvkw14
+ hash: v1.k794b7964.8ddf6af31b7d9b712c95ae38c11d12d301c3324e62badf18abef74717a574a1a.D-dkvZd470v-LmFak4uLdbNupq_Ijwbs4Xwtm9l3J7Q
components-markdown-notebook--text-only-notebook--dark:
hash: v1.k794b7964.180d01e7e88e19ca74879f6117c37d9f305df0ff2bb1b5582b283b73736f1937.WwPaxf-nmSkk-7TRBJBziJOQnvi437cFgh59fEMqLQ4
components-markdown-notebook--text-only-notebook--light:
diff --git a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md
index 1cc2e5489977..8494576a45c8 100644
--- a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md
+++ b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md
@@ -190,6 +190,7 @@ The internal AI tag `Prompt` is also reserved (registered by the notebooks scene
`Image` and `Divider` are special: they serialize back to plain markdown (`![alt](src)` and `---`) rather than component-tag syntax.
`Comment` is special too: its authorial-note flavor (`text` prop) serializes as a markdown `<!-- … -->` comment, while its discussion flavor (`ref` + `replies` props, a Google Docs-style thread anchored to an inline `<ref id="…">` highlight) serializes as a regular `<Comment … />` tag.
The lowercase inline tags `<ref>` and `<mention>` are part of the inline grammar, not components — component tags must start with an uppercase letter.
+Code carries no inline marks, so a comment anchored to a selection inside a code block stores its anchor as a `ref=<id>:<start>-<end>` token in the fence info string (e.g. ` ```python ref=abc123:4-17 `), with UTF-16 offsets into the code text.
Choose a specific tag name that describes the persisted block.
## Testing checklist
diff --git a/frontend/src/lib/components/MarkdownNotebook/EditableCodeBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/EditableCodeBlock.tsx
index fbaa9eec4283..c09fcca8db5c 100644
--- a/frontend/src/lib/components/MarkdownNotebook/EditableCodeBlock.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/EditableCodeBlock.tsx
@@ -5,9 +5,10 @@ import { LemonButton } from '@posthog/lemon-ui'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { updateNotebookCodeBlockText } from './documentModel'
import { findTextPosition, getElementLineHeight, isSelectionAnchoredInsideElement } from './domSelection'
import { TextSelectionPointerStartEvent } from './editorTypes'
-import { NotebookBlockNode, NotebookCodeBlockNode, NotebookMode } from './types'
+import { NotebookBlockNode, NotebookCodeBlockNode, NotebookCodeRefMark, NotebookMode } from './types'
function measureCharacterRect(element: HTMLElement, offset: number): DOMRect | null {
const startPosition = findTextPosition(element, offset)
@@ -64,6 +65,79 @@ function areNumberArraysEqual(left: number[], right: number[]): boolean {
return left.length === right.length && left.every((value, index) => value === right[index])
}
+type CodeRefRect = {
+ refId: string
+ top: number
+ left: number
+ width: number
+ height: number
+}
+
+// Code renders as plain text (input handling reads `textContent`), so comment highlights can't be
+// inline spans — they're measured from each anchor's text range and painted as an absolutely
+// positioned overlay behind the text, one box per rendered line fragment.
+function measureCodeRefRects(
+ frameElement: HTMLElement,
+ codeElement: HTMLElement,
+ refs: NotebookCodeRefMark[]
+): CodeRefRect[] {
+ if (typeof frameElement.getBoundingClientRect !== 'function') {
+ return []
+ }
+
+ const frameRect = frameElement.getBoundingClientRect()
+ const textLength = (codeElement.textContent ?? '').length
+ const rects: CodeRefRect[] = []
+ for (const ref of refs) {
+ const start = Math.min(ref.start, textLength)
+ const end = Math.min(ref.end, textLength)
+ if (end <= start) {
+ continue
+ }
+
+ const startPosition = findTextPosition(codeElement, start)
+ const endPosition = findTextPosition(codeElement, end)
+ const range = codeElement.ownerDocument.createRange()
+ range.setStart(startPosition.node, startPosition.offset)
+ range.setEnd(endPosition.node, endPosition.offset)
+ // jsdom ranges have no getClientRects; the highlight is skipped there
+ if (typeof range.getClientRects !== 'function') {
+ continue
+ }
+
+ for (const rect of Array.from(range.getClientRects())) {
+ if (!rect.width || !rect.height) {
+ continue
+ }
+ rects.push({
+ refId: ref.id,
+ top: rect.top - frameRect.top,
+ left: rect.left - frameRect.left,
+ width: rect.width,
+ height: rect.height,
+ })
+ }
+ }
+
+ return rects
+}
+
+function areCodeRefRectsEqual(left: CodeRefRect[], right: CodeRefRect[]): boolean {
+ return (
+ left.length === right.length &&
+ left.every((rect, index) => {
+ const other = right[index]
+ return (
+ rect.refId === other.refId &&
+ rect.top === other.top &&
+ rect.left === other.left &&
+ rect.width === other.width &&
+ rect.height === other.height
+ )
+ })
+ )
+}
+
// A trailing <br> makes the final empty line visible: browsers collapse a trailing "\n" in
// pre-wrap rendering, so without the sentinel trailing blank lines would not render or be
// reachable with the caret. <br> contributes nothing to textContent, so text offsets are stable.
@@ -94,10 +168,13 @@ export function EditableCodeBlock({
startTextSelectionPointer: (event: TextSelectionPointerStartEvent) => void
}): JSX.Element {
const elementRef = useRef<HTMLPreElement | null>(null)
+ const frameRef = useRef<HTMLDivElement | null>(null)
const skipDomSyncForTextRef = useRef<string | null>(null)
const [lineTops, setLineTops] = useState<number[]>([])
+ const [refRects, setRefRects] = useState<CodeRefRect[]>([])
const lines = node.text.split('\n')
+ const refs = node.refs
const setElementRef = useCallback(
(element: HTMLPreElement | null): void => {
@@ -139,9 +216,21 @@ export function EditableCodeBlock({
setLineTops((currentTops) => (areNumberArraysEqual(currentTops, nextTops) ? currentTops : nextTops))
}, [])
+ const measureRefRects = useCallback((): void => {
+ const element = elementRef.current
+ const frameElement = frameRef.current
+ if (!element || !frameElement) {
+ return
+ }
+
+ const nextRects = refs?.length ? measureCodeRefRects(frameElement, element, refs) : []
+ setRefRects((currentRects) => (areCodeRefRectsEqual(currentRects, nextRects) ? currentRects : nextRects))
+ }, [refs])
+
useLayoutEffect(() => {
measureLineTops()
- }, [measureLineTops, node.text])
+ measureRefRects()
+ }, [measureLineTops, measureRefRects, node.text])
useEffect(() => {
const element = elementRef.current
@@ -149,10 +238,13 @@ export function EditableCodeBlock({
return
}
- const observer = new ResizeObserver(() => measureLineTops())
+ const observer = new ResizeObserver(() => {
+ measureLineTops()
+ measureRefRects()
+ })
observer.observe(element)
return () => observer.disconnect()
- }, [measureLineTops])
+ }, [measureLineTops, measureRefRects])
const updateText = (text: string): void => {
skipDomSyncForTextRef.current = text
@@ -161,7 +253,7 @@ export function EditableCodeBlock({
return currentNode
}
- return { ...currentNode, text }
+ return updateNotebookCodeBlockText(currentNode, text)
})
}
@@ -177,7 +269,24 @@ export function EditableCodeBlock({
}
return (
- <div className="MarkdownNotebook__code-block-frame">
+ <div className="MarkdownNotebook__code-block-frame" ref={frameRef}>
+ {refRects.length ? (
+ <div className="MarkdownNotebook__code-ref-overlay" contentEditable={false} aria-hidden="true">
+ {refRects.map((rect, rectIndex) => (
+ <div
+ key={`${rect.refId}-${rectIndex}`}
+ className="MarkdownNotebook__code-ref-highlight"
+ data-notebook-ref={rect.refId}
+ style={{
+ top: `${rect.top}px`,
+ left: `${rect.left}px`,
+ width: `${rect.width}px`,
+ height: `${rect.height}px`,
+ }}
+ />
+ ))}
+ </div>
+ ) : null}
<div
className="MarkdownNotebook__code-block-gutter"
contentEditable={false}
diff --git a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
index d8a5dfc51022..a4ffa8026d84 100644
--- a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
@@ -1,5 +1,12 @@
import clsx from 'clsx'
-import { type CSSProperties, useEffect, useLayoutEffect, useRef, useState } from 'react'
+import {
+ KeyboardEvent as ReactKeyboardEvent,
+ type CSSProperties,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react'
import { IconCode, IconComment, IconCopy, IconQuote, IconSparkles } from '@posthog/icons'
import { LemonButton, LemonInput } from '@posthog/lemon-ui'
@@ -47,6 +54,7 @@ export function FormattingToolbar({
isAskAIDisabled,
startInlineCommentAtSelection,
lockPosition,
+ returnFocusToEditor,
}: {
selectedBlockStyle: TextBlockStyle | null
placement: 'above' | 'below'
@@ -63,6 +71,8 @@ export function FormattingToolbar({
isAskAIDisabled?: boolean
startInlineCommentAtSelection?: () => void
lockPosition: () => void
+ /** Moves focus back into the editor (Escape while the toolbar holds focus). */
+ returnFocusToEditor?: () => void
}): JSX.Element {
const [isLinkEditorOpen, setIsLinkEditorOpen] = useState(initialLinkEditorOpen)
const [linkHref, setLinkHref] = useState(currentLinkHref ?? '')
@@ -148,12 +158,66 @@ export function FormattingToolbar({
setIsLinkEditorOpen(false)
}
+ // Roving arrow-key navigation between the toolbar's buttons; Escape hands focus back to
+ // the editor. The buttons stay in the tab order, so this only augments focus movement.
+ const handleToolbarKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>): void => {
+ if (event.target instanceof HTMLElement && event.target.closest('.MarkdownNotebook__format-link-editor')) {
+ if (event.key === 'Escape') {
+ event.preventDefault()
+ event.stopPropagation()
+ setIsLinkEditorOpen(false)
+ }
+ return
+ }
+
+ if (event.key === 'Escape') {
+ event.preventDefault()
+ event.stopPropagation()
+ returnFocusToEditor?.()
+ return
+ }
+
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {
+ return
+ }
+
+ const toolbarElement = toolbarRef.current
+ if (!toolbarElement) {
+ return
+ }
+
+ const buttons = Array.from(toolbarElement.querySelectorAll<HTMLButtonElement>('button:not([disabled])'))
+ if (!buttons.length) {
+ return
+ }
+
+ const activeIndex = buttons.findIndex((button) => button === window.document.activeElement)
+ if (activeIndex === -1) {
+ return
+ }
+
+ event.preventDefault()
+ event.stopPropagation()
+ const nextIndex =
+ event.key === 'Home'
+ ? 0
+ : event.key === 'End'
+ ? buttons.length - 1
+ : (activeIndex + (event.key === 'ArrowRight' ? 1 : -1) + buttons.length) % buttons.length
+ buttons[nextIndex].focus()
+ }
+
return (
<div
className={clsx('MarkdownNotebook__format-toolbar', `MarkdownNotebook__format-toolbar--${placement}`)}
contentEditable={false}
ref={toolbarRef}
style={toolbarStyle}
+ role="toolbar"
+ aria-label="Text formatting"
+ aria-orientation="horizontal"
+ aria-keyshortcuts="Alt+F10"
+ onKeyDown={handleToolbarKeyDown}
onFocusCapture={lockPosition}
onPointerDownCapture={lockPosition}
onTouchStartCapture={lockPosition}
@@ -183,6 +247,7 @@ export function FormattingToolbar({
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)}
@@ -235,6 +300,7 @@ export function FormattingToolbar({
icon={<IconLink />}
tooltip="Link"
aria-label="Link"
+ aria-pressed={hasExistingLink || isLinkEditorOpen}
active={hasExistingLink || isLinkEditorOpen}
onClick={openLinkEditor}
/>
@@ -247,7 +313,7 @@ export function FormattingToolbar({
/>
</>
) : null}
- {showInlineActions && startInlineCommentAtSelection ? (
+ {startInlineCommentAtSelection ? (
<LemonButton
size="xsmall"
icon={<IconComment />}
diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertBoundaryButton.tsx b/frontend/src/lib/components/MarkdownNotebook/InsertBoundaryButton.tsx
index 81f617b965ea..7c2202d596c8 100644
--- a/frontend/src/lib/components/MarkdownNotebook/InsertBoundaryButton.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/InsertBoundaryButton.tsx
@@ -33,6 +33,8 @@ export function InsertBoundaryButton({
)}
contentEditable={false}
onMouseEnter={() => setActiveBoundaryIndex(boundaryIndex)}
+ // Reveal on keyboard focus, mirroring the mouse-hover reveal.
+ onFocusCapture={() => setActiveBoundaryIndex(boundaryIndex)}
onMouseDown={(event) => {
if (
!isAvailable ||
@@ -69,9 +71,8 @@ export function InsertBoundaryButton({
tooltip="Add block"
onClick={() => openInsertMenuAtBoundary(boundaryIndex)}
aria-label="Add block"
- aria-hidden={!isVisible}
data-boundary-index={boundaryIndex}
- tabIndex={isVisible ? 0 : -1}
+ tabIndex={0}
/>
) : null}
</div>
diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts
index 15ec8be05905..2ac7b9ea0873 100644
--- a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts
@@ -1,5 +1,5 @@
import { InsertCommand } from './editorTypes'
-import { buildInsertCommands } from './InsertMenu'
+import { buildInsertCommands, groupInsertCommandsByCategory } from './InsertMenu'
import { getMarkdownNotebookDefaultRegistry } from './registry'
describe('buildInsertCommands', () => {
@@ -40,4 +40,26 @@ describe('buildInsertCommands', () => {
const { commands } = build()
expect(commands.find((candidate) => candidate.key === 'custom')).toBeUndefined()
})
+
+ it('offers every insight type under the Insight category', () => {
+ const { commands } = build()
+ const insightLabels = commands
+ .filter((command) => command.category === 'Insight')
+ .map((command) => command.label)
+
+ expect(insightLabels).toEqual(['Trend', 'Funnel', 'Retention', 'Paths', 'Stickiness', 'Lifecycle'])
+ })
+
+ it('renders Products as the last category, merging caller-supplied product commands', () => {
+ // Grouping is first-occurrence order, so a command inserted in the wrong array
+ // silently pulls the Products group up the menu.
+ const { commands } = build([{ key: 'product-flag', label: 'Feature flag', category: 'Products', run: noop }])
+ const categories = Object.keys(groupInsertCommandsByCategory(commands))
+
+ expect(categories[categories.length - 1]).toEqual('Products')
+ expect(groupInsertCommandsByCategory(commands)['Products'].map((command) => command.label)).toEqual([
+ 'Session recordings',
+ 'Feature flag',
+ ])
+ })
})
diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
index 5d3e66e12429..d2d032766fe9 100644
--- a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
@@ -1,7 +1,22 @@
import clsx from 'clsx'
import { ReactNode, type CSSProperties, useEffect, useRef } from 'react'
-import { IconCode, IconDatabase, IconGraph, IconList, IconPencil, IconSparkles } from '@posthog/icons'
+import {
+ IconCode,
+ IconCursor,
+ IconDatabase,
+ IconFunnels,
+ IconLifecycle,
+ IconList,
+ IconPencil,
+ IconPeople,
+ IconRetention,
+ IconRewindPlay,
+ IconSparkles,
+ IconStickiness,
+ IconTrends,
+ IconUserPaths,
+} from '@posthog/icons'
import { Scene } from 'scenes/sceneTypes'
@@ -27,7 +42,13 @@ import {
NotebookComponentRegistry,
} from './types'
+/** DOM id of a command's option element, referenced by the editor's `aria-activedescendant`. */
+export function getInsertMenuOptionDomId(menuId: string, commandKey: string): string {
+ return `${menuId}-option-${commandKey}`
+}
+
export function InsertMenu({
+ id,
query,
commands,
targetNodeId,
@@ -35,6 +56,7 @@ export function InsertMenu({
selectedIndex,
onClose,
}: {
+ id?: string
query: string
commands: InsertCommand[]
targetNodeId: string
@@ -45,8 +67,9 @@ export function InsertMenu({
const selectedItemRef = useRef<HTMLButtonElement | null>(null)
const filteredCommands = getFilteredInsertCommands(commands, query)
const commandsByCategory = groupInsertCommandsByCategory(filteredCommands)
- const selectedCommandKey =
- filteredCommands[getClampedInsertMenuSelectedIndex(selectedIndex, filteredCommands.length)]?.key
+ const selectedCommandIndex = getClampedInsertMenuSelectedIndex(selectedIndex, filteredCommands.length)
+ const selectedCommand = filteredCommands[selectedCommandIndex]
+ const selectedCommandKey = selectedCommand?.key
const menuStyle = position
? ({
'--markdown-notebook-insert-menu-left': `${position.left}px`,
@@ -69,10 +92,20 @@ export function InsertMenu({
)}
contentEditable={false}
style={menuStyle}
+ id={id}
+ role="listbox"
+ aria-label="Insert block"
>
+ {/* Focus stays in the editor while the menu is open, so screen readers may miss the
+ aria-activedescendant change — announce the selection explicitly. */}
+ <div className="sr-only" aria-live="polite">
+ {selectedCommand
+ ? `${selectedCommand.label}, ${selectedCommandIndex + 1} of ${filteredCommands.length}`
+ : 'No components found'}
+ </div>
{Object.entries(commandsByCategory).map(([category, categoryCommands]) => (
- <div className="MarkdownNotebook__insert-category" key={category}>
- <h5>{category}</h5>
+ <div className="MarkdownNotebook__insert-category" key={category} role="group" aria-label={category}>
+ <h5 aria-hidden="true">{category}</h5>
<div className="MarkdownNotebook__insert-grid">
{categoryCommands.map((command) => (
<button
@@ -82,6 +115,8 @@ export function InsertMenu({
command.key === selectedCommandKey && 'MarkdownNotebook__insert-item--selected'
)}
key={command.key}
+ id={id ? getInsertMenuOptionDomId(id, command.key) : undefined}
+ role="option"
aria-selected={command.key === selectedCommandKey}
disabled={command.disabled}
type="button"
@@ -253,7 +288,7 @@ export function buildInsertCommands(
key: 'query-trend',
label: 'Trend',
category: 'Insight',
- icon: <IconGraph />,
+ icon: <IconTrends />,
run: (targetNodeId) =>
insertComponent(targetNodeId, 'Query', {
query: {
@@ -266,7 +301,7 @@ export function buildInsertCommands(
key: 'query-funnel',
label: 'Funnel',
category: 'Insight',
- icon: <IconGraph />,
+ icon: <IconFunnels />,
run: (targetNodeId) =>
insertComponent(targetNodeId, 'Query', {
query: {
@@ -281,6 +316,74 @@ export function buildInsertCommands(
},
}),
},
+ {
+ key: 'query-retention',
+ label: 'Retention',
+ category: 'Insight',
+ icon: <IconRetention />,
+ run: (targetNodeId) =>
+ insertComponent(targetNodeId, 'Query', {
+ query: {
+ kind: 'InsightVizNode',
+ source: {
+ kind: 'RetentionQuery',
+ retentionFilter: {
+ period: 'Day',
+ totalIntervals: 11,
+ targetEntity: { id: '$pageview', name: '$pageview', type: 'events' },
+ returningEntity: { id: '$pageview', name: '$pageview', type: 'events' },
+ },
+ },
+ },
+ }),
+ },
+ {
+ key: 'query-paths',
+ label: 'Paths',
+ category: 'Insight',
+ aliases: ['user paths'],
+ icon: <IconUserPaths />,
+ run: (targetNodeId) =>
+ insertComponent(targetNodeId, 'Query', {
+ query: {
+ kind: 'InsightVizNode',
+ source: { kind: 'PathsQuery', pathsFilter: { includeEventTypes: ['$pageview'] } },
+ },
+ }),
+ },
+ {
+ key: 'query-stickiness',
+ label: 'Stickiness',
+ category: 'Insight',
+ icon: <IconStickiness />,
+ run: (targetNodeId) =>
+ insertComponent(targetNodeId, 'Query', {
+ query: {
+ kind: 'InsightVizNode',
+ source: {
+ kind: 'StickinessQuery',
+ series: [{ kind: 'EventsNode', name: '$pageview', event: '$pageview', math: 'total' }],
+ stickinessFilter: {},
+ },
+ },
+ }),
+ },
+ {
+ key: 'query-lifecycle',
+ label: 'Lifecycle',
+ category: 'Insight',
+ icon: <IconLifecycle />,
+ run: (targetNodeId) =>
+ insertComponent(targetNodeId, 'Query', {
+ query: {
+ kind: 'InsightVizNode',
+ source: {
+ kind: 'LifecycleQuery',
+ series: [{ kind: 'EventsNode', name: '$pageview', event: '$pageview', math: 'total' }],
+ },
+ },
+ }),
+ },
]
const sqlCommands: InsertCommand[] = [
@@ -304,7 +407,7 @@ export function buildInsertCommands(
key: 'query-events',
label: 'Events',
category: 'Data',
- icon: <IconList />,
+ icon: <IconCursor />,
run: (targetNodeId) =>
insertComponent(targetNodeId, 'Query', {
query: {
@@ -317,7 +420,7 @@ export function buildInsertCommands(
key: 'data-people',
label: 'People',
category: 'Data',
- icon: <IconList />,
+ icon: <IconPeople />,
run: (targetNodeId) =>
insertComponent(targetNodeId, 'Query', {
query: {
@@ -332,11 +435,17 @@ export function buildInsertCommands(
},
}),
},
+ ]
+
+ // Appended after every other built-in category so "Products" renders as the last group
+ // (grouping preserves first-occurrence order); scene-supplied product commands merge in.
+ const productCommands: InsertCommand[] = [
{
key: 'data-session-recordings',
label: 'Session recordings',
- category: 'Data',
- icon: <IconList />,
+ category: 'Products',
+ aliases: ['replay', 'playlist'],
+ icon: <IconRewindPlay />,
run: (targetNodeId) => insertRegisteredComponent(targetNodeId, 'RecordingPlaylist'),
},
]
@@ -489,6 +598,7 @@ export function buildInsertCommands(
...mediaCommands,
...componentCommands,
...textStyleCommands,
+ ...productCommands,
...extraCommands,
]
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
index 09b480016909..d584551d99e6 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
@@ -1926,6 +1926,21 @@ button.MarkdownNotebook__component-title:focus-visible {
background: var(--color-bg-fill-highlight-200, rgb(235 145 0 / 30%));
}
+/* Code comment anchors: code carries no inline marks, so highlights are measured from each
+ anchor's text range and painted as positioned boxes behind the text. */
+.MarkdownNotebook__code-ref-overlay {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+}
+
+.MarkdownNotebook__code-ref-highlight {
+ position: absolute;
+ background: var(--color-bg-fill-highlight-100, rgb(235 145 0 / 15%));
+ border-bottom: 2px solid var(--color-border-warning, rgb(235 145 0 / 60%));
+ border-radius: 2px;
+}
+
/* Inline mentions keep their person id in the markdown; the text is the display label. */
.MarkdownNotebook__mention {
padding: 0 0.125rem;
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index e1bfce58d834..5e01aa50edb1 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -4192,6 +4192,31 @@ aXbc
Numbers <ref id="${refId}">look</ref> off here`)
})
+ it('creates a comment thread anchored to a selection inside a code block', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('```js\nconst answer = 42\n```'),
+ onChange,
+ })
+ )
+ const codeBlock = container.querySelector('.MarkdownNotebook__code-block') as HTMLElement
+
+ selectTextAcrossNodes(getFirstTextNode(codeBlock), 6, getFirstTextNode(codeBlock), 'const answer'.length, true)
+ fireEvent.click(container.querySelector('button[aria-label="Comment on selection"]') as HTMLButtonElement)
+
+ const markdown = onChange.mock.calls[onChange.mock.calls.length - 1][0] as string
+ const refId = markdown.match(/<Comment ref="([^"]+)" replies={\[\]} \/>/)?.[1]
+ expect(refId).toBeTruthy()
+ expect(markdown).toEqual(`${TEST_NOTEBOOK_TITLE_MARKDOWN}
+
+<Comment ref="${refId}" replies={[]} />
+
+\`\`\`js ref=${refId}:6-12
+const answer = 42
+\`\`\``)
+ })
+
it('places a comment on the title row below it, keeping the heading first', () => {
const onChange = jest.fn()
const { container } = render(
@@ -6237,6 +6262,46 @@ Tail with **bold** text`)
expect(onChange).toHaveBeenLastCalledWith('# Hello **bold**')
})
+ it('pastes clipboard files through the external converter after the caret block', () => {
+ const onChange = jest.fn()
+ const convertExternalDataTransferToNodes = jest.fn((dataTransfer: DataTransfer) =>
+ dataTransfer.files.length
+ ? [
+ {
+ id: 'pasted-image',
+ type: 'component' as const,
+ tagName: 'Image',
+ props: { src: 'https://example.com/pasted.png', alt: 'pasted' },
+ },
+ ]
+ : null
+ )
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('First paragraph\n\nSecond paragraph'),
+ onChange,
+ convertExternalDataTransferToNodes,
+ })
+ )
+ const firstParagraph = getBodyTextBlock(container)
+
+ fireEvent.paste(firstParagraph, {
+ clipboardData: {
+ files: [new File([''], 'pasted.png', { type: 'image/png' })],
+ getData: jest.fn(() => ''),
+ },
+ })
+
+ expect(convertExternalDataTransferToNodes).toHaveBeenCalled()
+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}
+
+First paragraph
+
+![pasted](https://example.com/pasted.png)
+
+Second paragraph`)
+ })
+
it('undoes pasted markdown blocks as one notebook history step', () => {
const onChange = jest.fn()
const { container } = render(
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 5865b868bd07..2ed1ada3f676 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -69,6 +69,7 @@ import {
setClipboardMarkdown,
setsEqual,
textBlocksShareContinuationStyle,
+ updateNotebookCodeBlockText,
writeSystemClipboardText,
} from './documentModel'
import {
@@ -146,6 +147,7 @@ import {
buildInsertCommands,
getClampedInsertMenuSelectedIndex,
getFilteredInsertCommands,
+ getInsertMenuOptionDomId,
getInsertMenuPosition,
getNextInsertMenuSelectedIndex,
} from './InsertMenu'
@@ -198,6 +200,7 @@ import {
} from './tableModel'
import {
NotebookBlockNode,
+ NotebookCodeBlockNode,
NotebookCollaborationConflict,
NotebookComponentBlockNode,
NotebookComponentProps,
@@ -236,6 +239,13 @@ export type MarkdownNotebookProps = {
/** Reports the local caret whenever it moves; null when the selection leaves the notebook. */
onCaretChange?: (position: MarkdownNotebookCaretPosition | null) => void
initialInsertMenu?: { nodeIndex?: number; query?: string }
+ /** Converts external content (dropped or pasted files, dragged app resources or URLs) into
+ * blocks inserted at the drop/caret position. Return null to ignore the transfer; return a
+ * promise when conversion needs async work (e.g. file uploads) — the insert position is
+ * captured up front. */
+ convertExternalDataTransferToNodes?: (
+ dataTransfer: DataTransfer
+ ) => NotebookBlockNode[] | Promise<NotebookBlockNode[] | null> | null
focusAIPromptRequest?: number
aiWritingNodeIndexes?: number[]
placeholder?: string
@@ -458,6 +468,7 @@ export function MarkdownNotebook({
remoteCarets,
onCaretChange,
initialInsertMenu,
+ convertExternalDataTransferToNodes,
focusAIPromptRequest,
aiWritingNodeIndexes,
placeholder = 'Start writing...',
@@ -483,6 +494,9 @@ export function MarkdownNotebook({
const [focusedRowIndex, setFocusedRowIndex] = useState<number | null>(null)
const [draggingNodeId, setDraggingNodeId] = useState<string | null>(null)
const [dropBoundaryIndex, setDropBoundaryIndex] = useState<number | null>(null)
+ const [isExternalDragOver, setIsExternalDragOver] = useState(false)
+ /** Whether the in-flight drag started inside this editor (native text/link drags included). */
+ const canvasDragOriginRef = useRef(false)
const [selectedComponentNodeIds, setSelectedComponentNodeIds] = useState<Set<string>>(() => new Set())
const [componentPanelCache, setComponentPanelCache] = useState<Record<string, ComponentPanelCacheEntry>>({})
const [internalDebugOpen, setInternalDebugOpen] = useState(false)
@@ -494,6 +508,7 @@ export function MarkdownNotebook({
const [fitsCommentGutter, setFitsCommentGutter] = useState(true)
const [debugMarkdown, setDebugMarkdown] = useState(() => serializeMarkdownNotebook(document))
const debugDrawerId = useId()
+ const insertMenuDomId = useId()
const notebookRef = useRef<HTMLDivElement | null>(null)
const mainRef = useRef<HTMLDivElement | null>(null)
const canvasRef = useRef<HTMLDivElement | null>(null)
@@ -3079,11 +3094,49 @@ export function MarkdownNotebook({
}
}
+ // Pasted files insert after the block holding the caret (or the focused component); pastes
+ // with no block context append to the end.
+ const getPasteInsertBoundaryIndex = (target: HTMLElement): number => {
+ const nodes = documentRef.current.nodes.length ? documentRef.current.nodes : [emptyNodeRef.current]
+ const focusedComponentNode = getFocusedComponentNode(target, nodes, blockRefs.current)
+ const nodeId = focusedComponentNode
+ ? focusedComponentNode.id
+ : target.closest<HTMLElement>('[data-markdown-notebook-node-id]')?.dataset.markdownNotebookNodeId
+ const nodeIndex = nodeId ? nodes.findIndex((node) => node.id === nodeId) : -1
+ return nodeIndex === -1 ? nodes.length : nodeIndex + 1
+ }
+
const handleNotebookPaste = (event: ReactClipboardEvent<HTMLDivElement>): void => {
if (mode !== 'edit' || !(event.target instanceof HTMLElement) || isNativeEditableElement(event.target)) {
return
}
+ // Pasted files (e.g. a screenshot) have no text representation the editor could insert —
+ // hand them to the external converter, mirroring the file drop path.
+ const clipboardFiles = event.clipboardData?.files
+ if (
+ convertExternalDataTransferToNodes &&
+ clipboardFiles?.length &&
+ !event.clipboardData.getData('text/plain')
+ ) {
+ const result = convertExternalDataTransferToNodes(event.clipboardData)
+ if (result) {
+ event.preventDefault()
+ event.stopPropagation()
+ const boundaryIndex = getPasteInsertBoundaryIndex(event.target)
+ if (result instanceof Promise) {
+ void result.then((insertedNodes) => {
+ if (insertedNodes?.length) {
+ insertExternalNodesAtBoundary(insertedNodes, boundaryIndex)
+ }
+ })
+ return
+ }
+ insertExternalNodesAtBoundary(result, boundaryIndex)
+ return
+ }
+ }
+
const targetComponentNode = getFocusedComponentNode(event.target, documentRef.current.nodes, blockRefs.current)
if (!targetComponentNode) {
return
@@ -3347,6 +3400,18 @@ export function MarkdownNotebook({
})
}
+ const setCodeRefMark = (
+ node: NotebookCodeBlockNode,
+ range: NotebookTextSelectionRange,
+ refId: string
+ ): NotebookCodeBlockNode => ({
+ ...node,
+ refs: [
+ ...(node.refs ?? []).filter((ref) => ref.id !== refId),
+ { id: refId, start: range.start, end: Math.min(range.end, node.text.length) },
+ ],
+ })
+
const askAIAboutSelection = (): void => {
if (!floatingToolbar || !onAskAI) {
return
@@ -3360,12 +3425,16 @@ export function MarkdownNotebook({
const currentDocument = documentRef.current
const nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]
const textRangesByNodeId = new Map(floatingToolbar.textRanges.map((entry) => [entry.node.id, entry]))
+ const codeRangesByNodeId = new Map(floatingToolbar.codeRanges.map((entry) => [entry.node.id, entry]))
const listItemRangesByNodeId = new Map<string, FloatingToolbarListItemRange[]>()
floatingToolbar.listItemRanges.forEach((entry) => {
listItemRangesByNodeId.set(entry.node.id, [...(listItemRangesByNodeId.get(entry.node.id) ?? []), entry])
})
const refId =
- floatingToolbar.textRanges.length + floatingToolbar.listItemRanges.length > 0
+ floatingToolbar.textRanges.length +
+ floatingToolbar.listItemRanges.length +
+ floatingToolbar.codeRanges.length >
+ 0
? createNotebookRefId()
: undefined
// Insert the prompt after the last selected block in document order.
@@ -3400,9 +3469,12 @@ export function MarkdownNotebook({
const nextNodes = nodes.flatMap((node, index): NotebookBlockNode[] => {
let updatedNode = node
const textRange = textRangesByNodeId.get(node.id)
+ const codeRange = codeRangesByNodeId.get(node.id)
const listItemRanges = listItemRangesByNodeId.get(node.id)
if (refId && textRange && isTextBlockNode(node)) {
updatedNode = { ...node, children: setInlineRefMark(node.children, textRange.range, refId) }
+ } else if (refId && codeRange && node.type === 'code') {
+ updatedNode = setCodeRefMark(node, codeRange.range, refId)
} else if (refId && listItemRanges && node.type === 'list') {
updatedNode = {
...node,
@@ -3445,13 +3517,18 @@ export function MarkdownNotebook({
})
}
- // Comments need at least one markable range; code blocks can't carry inline marks, so
- // a selection of only code offers nothing.
+ // Comments need at least one anchorable range: an inline `<ref>` mark for text and list
+ // selections, or a block-level `refs` anchor for selections inside code blocks.
const canStartInlineCommentAtSelection = (): boolean => {
if (!floatingToolbar) {
return false
}
- return floatingToolbar.textRanges.length + floatingToolbar.listItemRanges.length >= 1
+ return (
+ floatingToolbar.textRanges.length +
+ floatingToolbar.listItemRanges.length +
+ floatingToolbar.codeRanges.length >=
+ 1
+ )
}
const startInlineCommentAtSelection = (): void => {
@@ -3460,6 +3537,7 @@ export function MarkdownNotebook({
}
const textRangesByNodeId = new Map(floatingToolbar.textRanges.map((entry) => [entry.node.id, entry]))
+ const codeRangesByNodeId = new Map(floatingToolbar.codeRanges.map((entry) => [entry.node.id, entry]))
const listItemRangesByNodeId = new Map<string, FloatingToolbarListItemRange[]>()
floatingToolbar.listItemRanges.forEach((entry) => {
listItemRangesByNodeId.set(entry.node.id, [...(listItemRangesByNodeId.get(entry.node.id) ?? []), entry])
@@ -3468,7 +3546,10 @@ export function MarkdownNotebook({
const currentDocument = documentRef.current
const nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]
const firstSelectedIndex = nodes.findIndex(
- (node) => textRangesByNodeId.has(node.id) || listItemRangesByNodeId.has(node.id)
+ (node) =>
+ textRangesByNodeId.has(node.id) ||
+ listItemRangesByNodeId.has(node.id) ||
+ codeRangesByNodeId.has(node.id)
)
if (firstSelectedIndex === -1) {
return
@@ -3488,9 +3569,12 @@ export function MarkdownNotebook({
const nextNodes = nodes.flatMap((node, index): NotebookBlockNode[] => {
let updatedNode = node
const textRange = textRangesByNodeId.get(node.id)
+ const codeRange = codeRangesByNodeId.get(node.id)
const listItemRanges = listItemRangesByNodeId.get(node.id)
if (textRange && isTextBlockNode(node)) {
updatedNode = { ...node, children: setInlineRefMark(node.children, textRange.range, refId) }
+ } else if (codeRange && node.type === 'code') {
+ updatedNode = setCodeRefMark(node, codeRange.range, refId)
} else if (listItemRanges && node.type === 'list') {
updatedNode = {
...node,
@@ -4152,7 +4236,7 @@ export function MarkdownNotebook({
if (currentNode.type !== 'code') {
return currentNode
}
- return { ...currentNode, text: element.textContent ?? '' }
+ return updateNotebookCodeBlockText(currentNode, element.textContent ?? '')
})
return true
}, [updateNode])
@@ -4502,8 +4586,51 @@ export function MarkdownNotebook({
clearBlockDragState()
}
+ // Drags carrying an app resource (custom `node` type), files, or a URL are treated as external
+ // inserts. URL drags only count when the drag started outside this editor — dragging a link
+ // (or linked text) within the notebook stays on the browser's native contentEditable handling.
+ const isExternalNotebookDrag = (dataTransfer: DataTransfer | null): boolean =>
+ !!dataTransfer &&
+ (dataTransfer.types.includes('node') ||
+ dataTransfer.types.includes('Files') ||
+ (dataTransfer.types.includes('text/uri-list') && !canvasDragOriginRef.current))
+
+ const acceptsExternalDrag = (event: ReactDragEvent<HTMLDivElement>): boolean =>
+ mode === 'edit' && !!convertExternalDataTransferToNodes && isExternalNotebookDrag(event.dataTransfer)
+
+ const clearExternalDragState = (): void => {
+ setIsExternalDragOver(false)
+ setDropBoundaryIndex(null)
+ }
+
+ const insertExternalNodesAtBoundary = (insertedNodes: NotebookBlockNode[], boundaryIndex: number): void => {
+ if (!insertedNodes.length) {
+ return
+ }
+
+ const currentDocument = documentRef.current
+ const nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]
+ // The title block always stays first: nothing may drop before it.
+ const clampedBoundaryIndex = Math.max(1, Math.min(boundaryIndex, nodes.length))
+ insertedNodes.forEach((node) => markNotebookNodeFreshlyInserted(node.id))
+ commitDocument({
+ ...currentDocument,
+ nodes: [...nodes.slice(0, clampedBoundaryIndex), ...insertedNodes, ...nodes.slice(clampedBoundaryIndex)],
+ })
+ }
+
const handleCanvasDragOver = (event: ReactDragEvent<HTMLDivElement>): void => {
if (!blockDragNodeIdRef.current) {
+ if (!acceptsExternalDrag(event)) {
+ return
+ }
+
+ event.preventDefault()
+ if (event.dataTransfer) {
+ event.dataTransfer.dropEffect = 'copy'
+ }
+ setIsExternalDragOver(true)
+ setDropBoundaryIndex(getDropBoundaryIndexFromPointer(event.clientY))
return
}
@@ -4518,6 +4645,26 @@ export function MarkdownNotebook({
const handleCanvasDrop = (event: ReactDragEvent<HTMLDivElement>): void => {
const nodeId = blockDragNodeIdRef.current
if (!nodeId) {
+ if (!acceptsExternalDrag(event) || !event.dataTransfer) {
+ return
+ }
+
+ event.preventDefault()
+ const boundaryIndex = getDropBoundaryIndexFromPointer(event.clientY)
+ clearExternalDragState()
+ const result = convertExternalDataTransferToNodes?.(event.dataTransfer)
+ if (!result) {
+ return
+ }
+ if (result instanceof Promise) {
+ void result.then((insertedNodes) => {
+ if (insertedNodes?.length) {
+ insertExternalNodesAtBoundary(insertedNodes, boundaryIndex)
+ }
+ })
+ return
+ }
+ insertExternalNodesAtBoundary(result, boundaryIndex)
return
}
@@ -4528,7 +4675,7 @@ export function MarkdownNotebook({
}
const handleCanvasDragLeave = (event: ReactDragEvent<HTMLDivElement>): void => {
- if (!blockDragNodeIdRef.current) {
+ if (!blockDragNodeIdRef.current && !isExternalDragOver) {
return
}
@@ -4536,6 +4683,7 @@ export function MarkdownNotebook({
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) {
return
}
+ setIsExternalDragOver(false)
setDropBoundaryIndex(null)
}
@@ -4560,7 +4708,7 @@ export function MarkdownNotebook({
if (currentNode.type !== 'code') {
return currentNode
}
- return { ...currentNode, text: inlineEditableElement.textContent ?? '' }
+ return updateNotebookCodeBlockText(currentNode, inlineEditableElement.textContent ?? '')
})
return
}
@@ -4921,6 +5069,19 @@ export function MarkdownNotebook({
return
}
+ if (
+ mode === 'edit' &&
+ event.key === 'F10' &&
+ event.altKey &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ focusFormattingToolbar()
+ ) {
+ event.preventDefault()
+ event.stopPropagation()
+ return
+ }
+
if (mode === 'edit' && event.key === 'Tab' && !event.altKey && !event.metaKey && !event.ctrlKey) {
const inlineEditableElement = getInlineEditableElementForSelection(
window.getSelection(),
@@ -5055,13 +5216,50 @@ export function MarkdownNotebook({
}
}
+ // Alt+F10 moves keyboard focus into the floating toolbar (the standard editor-toolbar
+ // shortcut); Escape in the toolbar hands focus back without collapsing the selection.
+ const focusFormattingToolbar = (): boolean => {
+ if (!floatingToolbar) {
+ return false
+ }
+
+ lockFloatingToolbarPosition()
+ const button = mainRef.current?.querySelector<HTMLButtonElement>(
+ '.MarkdownNotebook__format-toolbar button:not([disabled])'
+ )
+ if (!button) {
+ return false
+ }
+
+ button.focus()
+ return true
+ }
+
+ const returnFocusFromFormattingToolbar = (): void => {
+ canvasRef.current?.focus()
+ }
+
const renderedNodeGroups = getMarkdownNotebookVisualGroups(
renderedNodes,
insertMenu?.detached ? insertMenu.nodeId : undefined
)
+ // The insert menu never takes focus (typing keeps filtering), so the canvas points at the
+ // selected option via aria-activedescendant.
+ const activeInsertMenuCommands =
+ insertMenu && (insertMenu.mode ?? 'tools') === 'tools'
+ ? getFilteredInsertCommands(insertCommands, insertMenu.query)
+ : null
+ const activeInsertMenuCommand =
+ activeInsertMenuCommands?.[
+ getClampedInsertMenuSelectedIndex(insertMenu?.selectedIndex ?? 0, activeInsertMenuCommands.length)
+ ]
+ const activeInsertMenuOptionDomId = activeInsertMenuCommand
+ ? getInsertMenuOptionDomId(insertMenuDomId, activeInsertMenuCommand.key)
+ : undefined
+
const dropIndicatorTarget: { index: number; position: 'before' | 'after' } | null =
- draggingNodeId !== null && dropBoundaryIndex !== null
+ (draggingNodeId !== null || isExternalDragOver) && dropBoundaryIndex !== null
? dropBoundaryIndex < renderedNodes.length
? { index: dropBoundaryIndex, position: 'before' }
: renderedNodes.length
@@ -5326,6 +5524,7 @@ export function MarkdownNotebook({
})}
{isToolInsertMenuOpen ? (
<InsertMenu
+ id={insertMenuDomId}
query={insertMenu.query}
commands={insertCommands}
targetNodeId={node.id}
@@ -5372,10 +5571,22 @@ export function MarkdownNotebook({
contentEditable={mode === 'edit'}
suppressContentEditableWarning
data-markdown-notebook-editor
+ role={mode === 'edit' ? 'textbox' : undefined}
+ aria-multiline={mode === 'edit' ? true : undefined}
+ aria-label={mode === 'edit' ? 'Notebook editor' : undefined}
+ aria-controls={activeInsertMenuOptionDomId ? insertMenuDomId : undefined}
+ aria-expanded={activeInsertMenuOptionDomId ? true : undefined}
+ aria-activedescendant={activeInsertMenuOptionDomId}
onInput={handleRootEditableInput}
onKeyDown={handleRootEditableKeyDown}
onMouseLeave={handleCanvasMouseLeave}
onClick={handleCanvasClick}
+ onDragStartCapture={() => {
+ canvasDragOriginRef.current = true
+ }}
+ onDragEndCapture={() => {
+ canvasDragOriginRef.current = false
+ }}
onDragOver={handleCanvasDragOver}
onDrop={handleCanvasDrop}
onDragLeave={handleCanvasDragLeave}
@@ -5488,6 +5699,7 @@ export function MarkdownNotebook({
canStartInlineCommentAtSelection() ? startInlineCommentAtSelection : undefined
}
lockPosition={lockFloatingToolbarPosition}
+ returnFocusToEditor={returnFocusFromFormattingToolbar}
/>
) : null}
</div>
diff --git a/frontend/src/lib/components/MarkdownNotebook/TODO.md b/frontend/src/lib/components/MarkdownNotebook/TODO.md
index 541b79352e17..6bbe351fe488 100644
--- a/frontend/src/lib/components/MarkdownNotebook/TODO.md
+++ b/frontend/src/lib/components/MarkdownNotebook/TODO.md
@@ -11,9 +11,7 @@ The markdown notebook rewrite (markdown storage, custom component tags, conflict
## Editor gaps
-- Accessibility: the formatting toolbar, insert menu, and component insertion flow need keyboard navigation and screen-reader coverage (focus management, roving tabindex, ARIA roles beyond the current labels).
-- Inline comments: selections inside code blocks can't be commented (code carries no inline marks).
-- Drag and drop: dropping a resource directly onto the editor canvas is not handled (the legacy editor's `DropAndPasteHandlerExtension` equivalent). The notebook panel dropzone and "add to notebook" flows work — they append to the end of the document via `notebookLogic` instead of inserting at the drop position.
+- (none currently tracked — accessibility for the toolbar/insert menu, comments on code block selections, and canvas drag-and-drop at the drop position have shipped)
## Open questions
diff --git a/frontend/src/lib/components/MarkdownNotebook/discussionComments.test.ts b/frontend/src/lib/components/MarkdownNotebook/discussionComments.test.ts
index bbeb42904c7d..05eec001d882 100644
--- a/frontend/src/lib/components/MarkdownNotebook/discussionComments.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/discussionComments.test.ts
@@ -2,10 +2,11 @@ import {
ensureEditableNotebookDocument,
getMarkdownNotebookVisualGroups,
removeNotebookNodesWithRefCleanup,
+ updateNotebookCodeBlockText,
} from './documentModel'
import { removeInlineRefMark, setInlineRefMark } from './inlineContent'
import { parseMarkdownNotebook, serializeMarkdownNotebook } from './markdown'
-import { NotebookDocument } from './types'
+import { NotebookCodeBlockNode, NotebookCodeRefMark, NotebookDocument } from './types'
describe('discussion comments', () => {
const parse = (markdown: string): NotebookDocument => parseMarkdownNotebook(markdown)
@@ -172,5 +173,57 @@ describe('discussion comments', () => {
expect(serializeMarkdownNotebook(result)).toContain('<ref id="banana">look off</ref>')
})
+
+ it('deleting a thread anchored in a code block clears the code anchor', () => {
+ const document = parse(
+ ['# Title', '', '<Comment ref="c1" replies={[]} />', '', '```js ref=c1:0-5\nconst x = 1\n```'].join(
+ '\n'
+ )
+ )
+ const commentNode = document.nodes.find((node) => node.type === 'component')
+
+ const result = removeNotebookNodesWithRefCleanup(document, new Set([commentNode!.id]))
+
+ expect(serializeMarkdownNotebook(result)).toEqual('# Title\n\n```js\nconst x = 1\n```')
+ })
+ })
+
+ describe('updateNotebookCodeBlockText', () => {
+ const codeNode = (text: string, refs?: NotebookCodeRefMark[]): NotebookCodeBlockNode => ({
+ id: 'c',
+ type: 'code',
+ text,
+ refs,
+ })
+
+ it.each<[string, string, NotebookCodeRefMark[], string, NotebookCodeRefMark[] | undefined]>([
+ [
+ 'shifts anchors past an insertion before them',
+ 'const x = 1',
+ [{ id: 'a', start: 6, end: 7 }],
+ 'let y\nconst x = 1',
+ [{ id: 'a', start: 12, end: 13 }],
+ ],
+ [
+ 'keeps anchors put when the edit happens after them',
+ 'const x = 1',
+ [{ id: 'a', start: 6, end: 7 }],
+ 'const x = 1 + 2',
+ [{ id: 'a', start: 6, end: 7 }],
+ ],
+ [
+ 'keeps insertions at the anchor edges outside the anchor',
+ 'abcd',
+ [{ id: 'a', start: 1, end: 3 }],
+ 'aXbcYd',
+ [{ id: 'a', start: 2, end: 4 }],
+ ],
+ ['drops an anchor whose range was deleted', 'abcdef', [{ id: 'a', start: 2, end: 4 }], 'abef', undefined],
+ ])('%s', (_name, baseText, refs, nextText, expectedRefs) => {
+ const result = updateNotebookCodeBlockText(codeNode(baseText, refs), nextText)
+
+ expect(result.text).toEqual(nextText)
+ expect(result.refs).toEqual(expectedRefs)
+ })
})
})
diff --git a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
index 0ad74c5a92fb..3a47a2d42efc 100644
--- a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
@@ -13,6 +13,7 @@ import { getTableCellAtPosition, getTableEdgeCellPosition } from './tableModel'
import { getTextChanges, mapTextIndex } from './textChanges'
import {
NotebookBlockNode,
+ NotebookCodeBlockNode,
NotebookComponentBlockNode,
NotebookDocument,
NotebookInlineNode,
@@ -267,17 +268,45 @@ export function removeNotebookNodesWithRefCleanup(document: NotebookDocument, no
return { ...document, nodes: stripNotebookRefMarksFromNodes(remainingNodes, removedRefIds) }
}
-/** Unwraps `<ref>` tags with the given ids across every text-bearing block, keeping the text. */
+/** Unwraps `<ref>` tags (and code block anchors) with the given ids across every block, keeping the text. */
export function stripNotebookRefMarksFromNodes(nodes: NotebookBlockNode[], refIds: Set<string>): NotebookBlockNode[] {
if (!refIds.size) {
return nodes
}
- return nodes.map((node) =>
- mapNodeInlineChildren(node, (children) =>
+ return nodes.map((node) => {
+ if (node.type === 'code') {
+ if (!node.refs?.some((ref) => refIds.has(ref.id))) {
+ return node
+ }
+ const refs = node.refs.filter((ref) => !refIds.has(ref.id))
+ return { ...node, refs: refs.length ? refs : undefined }
+ }
+ return mapNodeInlineChildren(node, (children) =>
[...refIds].reduce((current, refId) => removeInlineRefMark(current, refId), children)
)
- )
+ })
+}
+
+/** Replaces a code block's text, remapping its comment anchors through the edit and dropping
+ * anchors whose range the edit deleted. Insertions at an anchor's edges stay outside it. */
+export function updateNotebookCodeBlockText(node: NotebookCodeBlockNode, nextText: string): NotebookCodeBlockNode {
+ if (node.text === nextText) {
+ return node
+ }
+ if (!node.refs?.length) {
+ return { ...node, text: nextText }
+ }
+
+ const changes = getTextChanges(node.text, nextText)
+ const refs = node.refs
+ .map((ref) => ({
+ ...ref,
+ start: mapTextIndex(ref.start, changes, 'right'),
+ end: mapTextIndex(ref.end, changes, 'left'),
+ }))
+ .filter((ref) => ref.end > ref.start)
+ return { ...node, text: nextText, refs: refs.length ? refs : undefined }
}
export function isCommentComponentNode(node: NotebookBlockNode): node is NotebookComponentBlockNode {
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
index 4e6d0d573eee..2ecab7b4ebfa 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
@@ -1,5 +1,7 @@
import {
NotebookBlockNode,
+ NotebookCodeBlockNode,
+ NotebookCodeRefMark,
NotebookComponentBlockNode,
NotebookComponentProps,
NotebookDocument,
@@ -228,7 +230,7 @@ function serializeNodeUncached(node: NotebookBlockNode): string {
if (node.type === 'code') {
// The fence must be longer than any backtick run in the content, so the content can't close it
const fence = getCodeBlockFence(node.text)
- return `${fence}${node.language ?? ''}\n${node.text}\n${fence}`
+ return `${fence}${serializeCodeBlockInfo(node)}\n${node.text}\n${fence}`
}
if (node.type === 'component' && node.errors?.length && node.raw) {
// Props that failed to parse exist only in `raw` — re-emitting from `props` would
@@ -891,13 +893,42 @@ function serializeTableSeparatorCell(alignment: NotebookTableAlignment | undefin
return '---'
}
+/** A comment anchor in a fence info string: `ref=<id>:<start>-<end>`. */
+const CODE_BLOCK_REF_TOKEN_REGEX = /^ref=([A-Za-z0-9_-]+):(\d+)-(\d+)$/
+
+function serializeCodeBlockInfo(node: NotebookCodeBlockNode): string {
+ const refTokens = (node.refs ?? [])
+ .filter((ref) => ref.start >= 0 && ref.start < node.text.length && ref.end > ref.start)
+ .map((ref) => `ref=${ref.id}:${ref.start}-${Math.min(ref.end, node.text.length)}`)
+ return [node.language ?? '', ...refTokens].filter(Boolean).join(' ')
+}
+
+function parseCodeBlockInfo(info: string): { language?: string; refs: NotebookCodeRefMark[] } {
+ if (!info) {
+ return { language: undefined, refs: [] }
+ }
+
+ const refs: NotebookCodeRefMark[] = []
+ const languageTokens: string[] = []
+ for (const token of info.split(/\s+/)) {
+ const refMatch = token.match(CODE_BLOCK_REF_TOKEN_REGEX)
+ if (refMatch) {
+ refs.push({ id: refMatch[1], start: Number(refMatch[2]), end: Number(refMatch[3]) })
+ continue
+ }
+ languageTokens.push(token)
+ }
+
+ return { language: languageTokens.join(' ') || undefined, refs }
+}
+
function parseCodeBlock(lines: string[], lineIndex: number): BlockParseResult {
const startLine = lines[lineIndex].trim()
const fenceLength = startLine.match(/^`+/)?.[0].length ?? 3
// Only a bare fence at least as long as the opener closes the block, so shorter
// fences (or fences with info strings) inside the code stay part of the content
const closingFenceRegex = new RegExp(`^\`{${fenceLength},}$`)
- const language = startLine.slice(fenceLength).trim() || undefined
+ const { language, refs } = parseCodeBlockInfo(startLine.slice(fenceLength).trim())
const codeLines: string[] = []
let nextLineIndex = lineIndex + 1
@@ -906,12 +937,18 @@ function parseCodeBlock(lines: string[], lineIndex: number): BlockParseResult {
nextLineIndex += 1
}
+ const text = codeLines.join('\n')
+ const validRefs = refs
+ .map((ref) => ({ ...ref, end: Math.min(ref.end, text.length) }))
+ .filter((ref) => ref.start >= 0 && ref.start < text.length && ref.end > ref.start)
+
return {
node: {
id: '',
type: 'code',
language,
- text: codeLines.join('\n'),
+ text,
+ ...(validRefs.length ? { refs: validRefs } : {}),
},
nextLineIndex: nextLineIndex < lines.length ? nextLineIndex + 1 : nextLineIndex,
error:
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
index 257bcd229171..35ccd8c2528c 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
@@ -391,6 +391,46 @@ describe('markdown round trip', () => {
})
})
+ describe('code block comment anchors', () => {
+ it('round-trips ref tokens in the fence info string alongside the language', () => {
+ const document = makeDocument([
+ {
+ id: '',
+ type: 'code',
+ language: 'python',
+ text: 'a = 1\nb = 2',
+ refs: [
+ { id: 'abc123', start: 0, end: 5 },
+ { id: 'def456', start: 6, end: 11 },
+ ],
+ },
+ ])
+
+ const serialized = serializeMarkdownNotebook(document)
+ expect(serialized).toEqual('```python ref=abc123:0-5 ref=def456:6-11\na = 1\nb = 2\n```')
+ expect(stripIds(parseMarkdownNotebook(serialized))).toEqual(stripIds(document))
+ })
+
+ it('round-trips a ref token on a code block without a language', () => {
+ const document = makeDocument([
+ { id: '', type: 'code', language: undefined, text: 'select 1', refs: [{ id: 'a1', start: 0, end: 6 }] },
+ ])
+
+ expect(stripIds(roundTrip(document))).toEqual(stripIds(document))
+ })
+
+ it('drops anchors whose range the code no longer contains and clamps overlong ends', () => {
+ const nodes = parseMarkdownNotebook('```js ref=gone:90-99 ref=kept:2-99\nshort\n```').nodes
+
+ expect(nodes).toHaveLength(1)
+ expect(nodes[0]).toMatchObject({
+ type: 'code',
+ language: 'js',
+ refs: [{ id: 'kept', start: 2, end: 5 }],
+ })
+ })
+ })
+
describe('underscore and asterisk emphasis', () => {
it('parses underscore emphasis at word boundaries', () => {
const nodes = parseMarkdownNotebook('_em_ and __strong__ but not user_id or snake_case_words').nodes
diff --git a/frontend/src/lib/components/MarkdownNotebook/types.ts b/frontend/src/lib/components/MarkdownNotebook/types.ts
index b521df5b1f42..bf2255ceb92c 100644
--- a/frontend/src/lib/components/MarkdownNotebook/types.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/types.ts
@@ -77,11 +77,21 @@ export type NotebookTableBlockNode = {
alignments?: (NotebookTableAlignment | undefined)[]
}
+/** Anchors a discussion comment to a character range inside a code block. Code carries no inline
+ * marks, so anchors live on the block and serialize as `ref=<id>:<start>-<end>` tokens in the
+ * fence info string. Offsets are UTF-16 code units into `text`. */
+export type NotebookCodeRefMark = {
+ id: string
+ start: number
+ end: number
+}
+
export type NotebookCodeBlockNode = {
id: string
type: 'code'
language?: string
text: string
+ refs?: NotebookCodeRefMark[]
}
export type NotebookComponentBlockNode = {
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookEntityListPicker.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookEntityListPicker.tsx
new file mode 100644
index 000000000000..1e38135aa2fa
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookEntityListPicker.tsx
@@ -0,0 +1,151 @@
+import { useEffect, useState, type ReactNode } from 'react'
+
+import { IconPlus } from '@posthog/icons'
+import { LemonButton, LemonInput, Tooltip } from '@posthog/lemon-ui'
+
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+
+export type MarkdownNotebookEntityListPickerItem = {
+ id: string | number
+ name: string
+ description?: string | null
+}
+
+export type MarkdownNotebookEntityListPickerProps = {
+ isOpen: boolean
+ title: string
+ searchPlaceholder: string
+ entityIcon?: ReactNode
+ /** Loads the pickable entities when the modal opens; typed search filters client-side. */
+ loadItems: () => Promise<MarkdownNotebookEntityListPickerItem[]>
+ onClose: () => void
+ onSelect: (item: MarkdownNotebookEntityListPickerItem) => void
+}
+
+/** Entity picker for insert-menu commands whose entity has no taxonomic group (surveys, early
+ * access features, …): a searchable one-page list, matching the experiment picker's table feel. */
+export function MarkdownNotebookEntityListPicker({
+ isOpen,
+ title,
+ searchPlaceholder,
+ entityIcon,
+ loadItems,
+ onClose,
+ onSelect,
+}: MarkdownNotebookEntityListPickerProps): JSX.Element {
+ const [search, setSearch] = useState('')
+ const [items, setItems] = useState<MarkdownNotebookEntityListPickerItem[]>([])
+ const [isLoading, setIsLoading] = useState(false)
+
+ useEffect(() => {
+ if (!isOpen) {
+ setSearch('')
+ return
+ }
+
+ let cancelled = false
+ setIsLoading(true)
+ loadItems()
+ .then((loadedItems) => {
+ if (!cancelled) {
+ setItems(loadedItems)
+ }
+ })
+ .catch(() => {
+ if (!cancelled) {
+ setItems([])
+ }
+ })
+ .finally(() => {
+ if (!cancelled) {
+ setIsLoading(false)
+ }
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [isOpen, loadItems])
+
+ const normalizedSearch = search.trim().toLowerCase()
+ const filteredItems = normalizedSearch
+ ? items.filter((item) => item.name.toLowerCase().includes(normalizedSearch))
+ : items
+
+ const columns: LemonTableColumns<MarkdownNotebookEntityListPickerItem> = [
+ ...(entityIcon
+ ? [
+ {
+ key: 'icon',
+ width: 32,
+ render: function renderIcon() {
+ return <span className="text-secondary text-2xl">{entityIcon}</span>
+ },
+ },
+ ]
+ : []),
+ {
+ title: 'Name',
+ dataIndex: 'name',
+ key: 'name',
+ render: function renderName(_, item) {
+ return (
+ <div className="flex flex-col gap-1 min-w-0 overflow-hidden">
+ <Tooltip title={item.name}>
+ <span className="block truncate max-w-full font-medium">{item.name}</span>
+ </Tooltip>
+ {item.description ? (
+ <Tooltip title={item.description}>
+ <div className="text-xs text-tertiary line-clamp-2">{item.description}</div>
+ </Tooltip>
+ ) : null}
+ </div>
+ )
+ },
+ },
+ {
+ key: 'action',
+ width: 32,
+ render: function renderAction() {
+ return (
+ <IconPlus className="text-muted text-xl opacity-40 group-hover:opacity-100 group-hover:text-success transition-all" />
+ )
+ },
+ },
+ ]
+
+ return (
+ <LemonModal
+ title={title}
+ onClose={onClose}
+ isOpen={isOpen}
+ footer={
+ <LemonButton type="secondary" data-attr="markdown-notebook-entity-picker-cancel" onClick={onClose}>
+ Close
+ </LemonButton>
+ }
+ >
+ <div className="mb-3">
+ <LemonInput
+ type="search"
+ placeholder={searchPlaceholder}
+ autoFocus
+ value={search}
+ onChange={setSearch}
+ />
+ </div>
+ <LemonTable
+ dataSource={filteredItems}
+ columns={columns}
+ loading={isLoading}
+ rowKey="id"
+ rowClassName="group cursor-pointer hover:bg-success-highlight/30"
+ onRow={(item) => ({
+ onClick: () => onSelect(item),
+ title: 'Click to select',
+ })}
+ emptyState="Nothing found"
+ />
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookTaxonomicPicker.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookTaxonomicPicker.tsx
new file mode 100644
index 000000000000..1908987d6fa8
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookTaxonomicPicker.tsx
@@ -0,0 +1,49 @@
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
+import { TaxonomicFilterGroupType, TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+
+export type MarkdownNotebookTaxonomicPickerProps = {
+ isOpen: boolean
+ title: string
+ groupType: TaxonomicFilterGroupType
+ onClose: () => void
+ onSelect: (value: TaxonomicFilterValue) => void
+}
+
+/** Entity picker for insert-menu commands whose entity has a taxonomic group (feature flags,
+ * cohorts, …) — the taxonomic filter brings search and pagination for free. */
+export function MarkdownNotebookTaxonomicPicker({
+ isOpen,
+ title,
+ groupType,
+ onClose,
+ onSelect,
+}: MarkdownNotebookTaxonomicPickerProps): JSX.Element {
+ return (
+ <LemonModal
+ title={title}
+ onClose={onClose}
+ isOpen={isOpen}
+ footer={
+ <LemonButton type="secondary" data-attr="markdown-notebook-taxonomic-picker-cancel" onClick={onClose}>
+ Close
+ </LemonButton>
+ }
+ >
+ {/* Remount per open so a previous search query doesn't carry over */}
+ {isOpen ? (
+ <TaxonomicFilter
+ groupType={groupType}
+ taxonomicGroupTypes={[groupType]}
+ onChange={(_, value) => {
+ if (value !== null && value !== undefined && value !== '') {
+ onSelect(value)
+ }
+ }}
+ />
+ ) : null}
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
index 27b641935d9d..87203cae1704 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
@@ -1,14 +1,18 @@
import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { IconFlask, IconGraph } from '@posthog/icons'
+import { IconFlask, IconGraph, IconMessage, IconPeople, IconRocket, IconToggle } from '@posthog/icons'
+import { lemonToast } from '@posthog/lemon-ui'
+import api from 'lib/api'
import { MarkdownNotebook, parseMarkdownNotebook } from 'lib/components/MarkdownNotebook'
import type {
InsertCommand,
MarkdownNotebookAskAIRequest,
MarkdownNotebookInsertMenuApi,
} from 'lib/components/MarkdownNotebook'
+import { makeEmptyParagraph } from 'lib/components/MarkdownNotebook/markdown'
import {
insertNotebookAIFollowUpPromptAfterResponse,
rebaseNotebookAIResponseRange,
@@ -16,13 +20,19 @@ import {
streamNotebookAIResponseMarkdown,
} from 'lib/components/MarkdownNotebook/notebookAI'
import type { MarkdownNotebookCaretPosition, RemoteNotebookCaret } from 'lib/components/MarkdownNotebook/remoteCarets'
-import type { NotebookBlockNode } from 'lib/components/MarkdownNotebook/types'
+import type { NotebookBlockNode, NotebookComponentProps } from 'lib/components/MarkdownNotebook/types'
import { getInlineText } from 'lib/components/MarkdownNotebook/utils'
+import { TaxonomicFilterGroupType, TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'
+import { uploadFile } from 'lib/hooks/useUploadFiles'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { uuid } from 'lib/utils/dom'
import type { NotebookArtifactContent } from '~/queries/schema/schema-assistant-messages'
+import {
+ MarkdownNotebookEntityListPicker,
+ type MarkdownNotebookEntityListPickerItem,
+} from './MarkdownNotebookEntityListPicker'
import { MarkdownNotebookExperimentPicker } from './MarkdownNotebookExperimentPicker'
import { InlineAIAssistantMessage, InlineAICompletion, InlineNotebookAIRunner } from './MarkdownNotebookInlineAI'
import { getMarkdownRegistryForFeatureFlags } from './markdownNotebookRegistry'
@@ -35,7 +45,14 @@ import {
getInlineNotebookAIUIContext,
} from './markdownNotebookRuntime'
import { MarkdownNotebookSavedInsightPicker } from './MarkdownNotebookSavedInsightPicker'
-import { getMarkdownNotebookMarkdown, notebookArtifactContentToMarkdown } from './markdownNotebookV2'
+import { MarkdownNotebookTaxonomicPicker } from './MarkdownNotebookTaxonomicPicker'
+import {
+ buildDroppedLinkParagraphNode,
+ convertDroppedPostHogUrlToMarkdownNode,
+ convertDroppedRichContentNodeToMarkdownNode,
+ getMarkdownNotebookMarkdown,
+ notebookArtifactContentToMarkdown,
+} from './markdownNotebookV2'
import { notebookLogic } from './notebookLogic'
import {
NOTEBOOK_AI_PRESENCE_COLOR,
@@ -53,6 +70,15 @@ type MarkdownNotebookV2Props = {
onDebugOpenChange?: (isOpen: boolean) => void
}
+/** Which "Products" insert-menu picker modal is open. */
+type MarkdownNotebookEntityPickerKind =
+ | 'saved-insight'
+ | 'experiment'
+ | 'feature-flag'
+ | 'survey'
+ | 'early-access-feature'
+ | 'cohort'
+
export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotebookV2Props): JSX.Element {
const { isEditable, notebook, markdownEditorValue, markdownEditorInteractionActive, markdownRemoteCarets } =
useValues(notebookLogic)
@@ -397,53 +423,64 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
[applyNotebookArtifactMarkdown, getInlineAIRequest, updateMarkdownEditorValue]
)
- const [savedInsightPickerTargetNodeId, setSavedInsightPickerTargetNodeId] = useState<string | null>(null)
- const [experimentPickerTargetNodeId, setExperimentPickerTargetNodeId] = useState<string | null>(null)
- // Insert API + target node captured when "Saved insight" / "Experiment" is picked, so the modal's
- // async selection can insert into the right node once an entity is chosen.
- const savedInsightInsertRef = useRef<{ api: MarkdownNotebookInsertMenuApi; targetNodeId: string } | null>(null)
- const experimentInsertRef = useRef<{ api: MarkdownNotebookInsertMenuApi; targetNodeId: string } | null>(null)
-
- const buildExtraInsertCommands = useCallback(
- (api: MarkdownNotebookInsertMenuApi): InsertCommand[] => [
- {
- key: 'query-saved-insight',
- label: 'Saved insight',
- category: 'Insight',
- icon: <IconGraph />,
- run: (targetNodeId) => {
- savedInsightInsertRef.current = { api, targetNodeId }
- setSavedInsightPickerTargetNodeId(targetNodeId)
- },
- },
- {
- key: 'experiment',
- label: 'Experiment',
- category: 'Experiment',
- icon: <IconFlask />,
- run: (targetNodeId) => {
- experimentInsertRef.current = { api, targetNodeId }
- setExperimentPickerTargetNodeId(targetNodeId)
- },
+ const [openEntityPicker, setOpenEntityPicker] = useState<MarkdownNotebookEntityPickerKind | null>(null)
+ // Insert API + target node captured when a picker command runs, so the modal's async
+ // selection can insert into the right node once an entity is chosen.
+ const pendingEntityInsertRef = useRef<{ api: MarkdownNotebookInsertMenuApi; targetNodeId: string } | null>(null)
+
+ const buildExtraInsertCommands = useCallback((api: MarkdownNotebookInsertMenuApi): InsertCommand[] => {
+ const pickerCommand = (
+ key: string,
+ label: string,
+ icon: JSX.Element,
+ picker: MarkdownNotebookEntityPickerKind,
+ aliases?: string[]
+ ): InsertCommand => ({
+ key,
+ label,
+ category: 'Products',
+ icon,
+ aliases,
+ run: (targetNodeId) => {
+ pendingEntityInsertRef.current = { api, targetNodeId }
+ setOpenEntityPicker(picker)
},
- ],
- []
- )
-
- const closeSavedInsightPicker = useCallback((): void => {
- savedInsightInsertRef.current = null
- setSavedInsightPickerTargetNodeId(null)
+ })
+
+ return [
+ pickerCommand('query-saved-insight', 'Saved insight', <IconGraph />, 'saved-insight', ['insight']),
+ pickerCommand('experiment', 'Experiment', <IconFlask />, 'experiment', ['ab test']),
+ pickerCommand('product-feature-flag', 'Feature flag', <IconToggle />, 'feature-flag', ['flag']),
+ pickerCommand('product-survey', 'Survey', <IconMessage />, 'survey'),
+ pickerCommand(
+ 'product-early-access-feature',
+ 'Early access feature',
+ <IconRocket />,
+ 'early-access-feature'
+ ),
+ pickerCommand('product-cohort', 'Cohort', <IconPeople />, 'cohort'),
+ ]
}, [])
- const closeExperimentPicker = useCallback((): void => {
- experimentInsertRef.current = null
- setExperimentPickerTargetNodeId(null)
+ const closeEntityPicker = useCallback((): void => {
+ pendingEntityInsertRef.current = null
+ setOpenEntityPicker(null)
}, [])
- const handleSavedInsightPicked = useCallback((shortId: string, title: string): void => {
- const pending = savedInsightInsertRef.current
+ // Inserts the picked entity's component into the node the picker command targeted, then
+ // closes the picker.
+ const insertPickedComponent = useCallback((tagName: string, props: NotebookComponentProps): void => {
+ const pending = pendingEntityInsertRef.current
if (pending) {
- pending.api.insertComponent(pending.targetNodeId, 'Query', {
+ pending.api.insertComponent(pending.targetNodeId, tagName, props)
+ }
+ pendingEntityInsertRef.current = null
+ setOpenEntityPicker(null)
+ }, [])
+
+ const handleSavedInsightPicked = useCallback(
+ (shortId: string, title: string): void => {
+ insertPickedComponent('Query', {
query: { kind: 'SavedInsightNode', shortId },
// The insight is already configured via the picker, so render results-only — hiding the
// settings panel (the "Edit the insight" / "Detach from insight" controls) by default.
@@ -451,20 +488,138 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
// Label the node with the insight's name so the toolbar shows it instead of the short id.
...(title ? { title } : {}),
})
- }
- savedInsightInsertRef.current = null
- setSavedInsightPickerTargetNodeId(null)
+ },
+ [insertPickedComponent]
+ )
+
+ const handleExperimentPicked = useCallback(
+ (experimentId: number): void => {
+ insertPickedComponent('Experiment', { id: experimentId })
+ },
+ [insertPickedComponent]
+ )
+
+ const handleTaxonomicEntityPicked = useCallback(
+ (value: TaxonomicFilterValue): void => {
+ const tagName = openEntityPicker === 'feature-flag' ? 'FeatureFlag' : 'Cohort'
+ const id = Number(value)
+ if (!Number.isInteger(id) || id <= 0) {
+ closeEntityPicker()
+ return
+ }
+ insertPickedComponent(tagName, { id })
+ },
+ [closeEntityPicker, insertPickedComponent, openEntityPicker]
+ )
+
+ const loadSurveyPickerItems = useCallback(async (): Promise<MarkdownNotebookEntityListPickerItem[]> => {
+ const response = await api.surveys.list({ limit: 100 })
+ return response.results.map((survey) => ({
+ id: survey.id,
+ name: survey.name,
+ description: survey.description,
+ }))
}, [])
- const handleExperimentPicked = useCallback((experimentId: number): void => {
- const pending = experimentInsertRef.current
- if (pending) {
- pending.api.insertComponent(pending.targetNodeId, 'Experiment', { id: experimentId })
- }
- experimentInsertRef.current = null
- setExperimentPickerTargetNodeId(null)
+ const loadEarlyAccessFeaturePickerItems = useCallback(async (): Promise<MarkdownNotebookEntityListPickerItem[]> => {
+ const response = await api.earlyAccessFeatures.list()
+ return response.results.map((feature) => ({
+ id: feature.id,
+ name: feature.name,
+ description: feature.description,
+ }))
}, [])
+ const convertExternalDataTransferToNodes = useCallback(
+ (dataTransfer: DataTransfer): NotebookBlockNode[] | Promise<NotebookBlockNode[] | null> | null => {
+ const nodeType = dataTransfer.getData('node')
+ if (nodeType) {
+ let attrs: Record<string, unknown> = {}
+ const propertiesJson = dataTransfer.getData('properties')
+ if (propertiesJson) {
+ try {
+ attrs = JSON.parse(propertiesJson)
+ } catch {
+ return null
+ }
+ }
+
+ const node = convertDroppedRichContentNodeToMarkdownNode(nodeType, attrs)
+ if (node) {
+ posthog.capture('notebook node dropped', { node_type: nodeType, is_markdown: true })
+ }
+ return node ? [node] : null
+ }
+
+ // Entity links (`Link`) drag with only their href: map recognized PostHog resource
+ // URLs to their component node, and keep anything else as a plain link block.
+ const draggedUrl = (dataTransfer.getData('text/uri-list') ?? '')
+ .split('\n')
+ .map((line) => line.trim())
+ .find((line) => line && !line.startsWith('#'))
+ if (draggedUrl) {
+ const resourceNode = convertDroppedPostHogUrlToMarkdownNode(draggedUrl)
+ posthog.capture('notebook node dropped', {
+ node_type: resourceNode?.type === 'component' ? resourceNode.tagName : 'link',
+ is_markdown: true,
+ })
+ return [resourceNode ?? buildDroppedLinkParagraphNode(draggedUrl)]
+ }
+
+ const files = Array.from(dataTransfer.files ?? [])
+ if (files.length) {
+ const imageFiles = files.filter((file) => file.type.startsWith('image/'))
+ if (imageFiles.length < files.length) {
+ lemonToast.warning('Only images can be added to notebooks at this time.')
+ }
+ if (!imageFiles.length) {
+ return null
+ }
+
+ posthog.capture('notebook files dropped', {
+ file_types: imageFiles.map((file) => file.type),
+ is_markdown: true,
+ })
+ // allSettled so one failed upload doesn't discard the files that uploaded fine.
+ return Promise.allSettled(
+ imageFiles.map(async (file): Promise<NotebookBlockNode> => {
+ const media = await uploadFile(file)
+ return {
+ id: makeEmptyParagraph('dropped-image').id,
+ type: 'component',
+ tagName: 'Image',
+ props: { src: media.image_location, alt: media.name },
+ }
+ })
+ ).then((results): NotebookBlockNode[] | null => {
+ const uploadedNodes = results
+ .filter(
+ (result): result is PromiseFulfilledResult<NotebookBlockNode> =>
+ result.status === 'fulfilled'
+ )
+ .map((result) => result.value)
+ const firstRejection = results.find(
+ (result): result is PromiseRejectedResult => result.status === 'rejected'
+ )
+ if (firstRejection) {
+ const failedCount = results.length - uploadedNodes.length
+ const { detail, message } = (firstRejection.reason ?? {}) as {
+ detail?: string
+ message?: string
+ }
+ lemonToast.error(
+ `${failedCount === 1 ? 'Image upload' : `${failedCount} image uploads`} failed: ${detail ?? message ?? 'unknown error'}`
+ )
+ }
+ return uploadedNodes.length ? uploadedNodes : null
+ })
+ }
+
+ return null
+ },
+ []
+ )
+
const runtimeContext = useMemo<MarkdownNotebookRuntimeContextValue>(
() => ({
notebookShortId: notebook?.short_id ?? null,
@@ -586,6 +741,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
remoteCarets={remoteCarets}
onCaretChange={isEditable ? publishMarkdownCaret : undefined}
onAskAI={isEditable ? handleAskAI : undefined}
+ convertExternalDataTransferToNodes={isEditable ? convertExternalDataTransferToNodes : undefined}
isAskAIDisabled={inlineAIRequests.length > 0}
createAIConversationId={uuid}
deferRemoteValue={markdownEditorInteractionActive}
@@ -610,18 +766,53 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
))}
{isEditable && (
<MarkdownNotebookSavedInsightPicker
- isOpen={savedInsightPickerTargetNodeId !== null}
- onClose={closeSavedInsightPicker}
+ isOpen={openEntityPicker === 'saved-insight'}
+ onClose={closeEntityPicker}
onSelect={handleSavedInsightPicked}
/>
)}
{isEditable && (
<MarkdownNotebookExperimentPicker
- isOpen={experimentPickerTargetNodeId !== null}
- onClose={closeExperimentPicker}
+ isOpen={openEntityPicker === 'experiment'}
+ onClose={closeEntityPicker}
onSelect={handleExperimentPicked}
/>
)}
+ {isEditable && (
+ <MarkdownNotebookTaxonomicPicker
+ isOpen={openEntityPicker === 'feature-flag' || openEntityPicker === 'cohort'}
+ title={openEntityPicker === 'cohort' ? 'Add cohort to notebook' : 'Add feature flag to notebook'}
+ groupType={
+ openEntityPicker === 'cohort'
+ ? TaxonomicFilterGroupType.Cohorts
+ : TaxonomicFilterGroupType.FeatureFlags
+ }
+ onClose={closeEntityPicker}
+ onSelect={handleTaxonomicEntityPicked}
+ />
+ )}
+ {isEditable && (
+ <MarkdownNotebookEntityListPicker
+ isOpen={openEntityPicker === 'survey'}
+ title="Add survey to notebook"
+ searchPlaceholder="Search surveys"
+ entityIcon={<IconMessage />}
+ loadItems={loadSurveyPickerItems}
+ onClose={closeEntityPicker}
+ onSelect={(item) => insertPickedComponent('Survey', { id: String(item.id) })}
+ />
+ )}
+ {isEditable && (
+ <MarkdownNotebookEntityListPicker
+ isOpen={openEntityPicker === 'early-access-feature'}
+ title="Add early access feature to notebook"
+ searchPlaceholder="Search early access features"
+ entityIcon={<IconRocket />}
+ loadItems={loadEarlyAccessFeaturePickerItems}
+ onClose={closeEntityPicker}
+ onSelect={(item) => insertPickedComponent('EarlyAccessFeature', { id: String(item.id) })}
+ />
+ )}
</MarkdownNotebookRuntimeContext.Provider>
)
}
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
index a4a304afa77c..f47512ad8dfc 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
@@ -10,6 +10,8 @@
* - Authorial `<!-- … -->` comments become plain paragraphs: the note text stays visible, but its
* comment framing is lost.
* - Table column alignments are dropped — v1 tables do not store alignment.
+ * - Code block comment anchors (`ref=` tokens in the fence info string) are dropped — v1 code
+ * blocks carry no inline marks to anchor to.
*/
import {
COMMENT_COMPONENT_TAG,
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
index 94fba5279c46..4d59de59ec71 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
@@ -32,11 +32,12 @@ import '../Nodes/NotebookNodeUsageMetrics'
import '../Nodes/NotebookNodeZendeskTickets'
import clsx from 'clsx'
-import { BindLogic, useMountedLogic } from 'kea'
+import { BindLogic, useMountedLogic, useValues } from 'kea'
+import posthog from 'posthog-js'
import { type CSSProperties, type PointerEvent as ReactPointerEvent, useCallback, useMemo, useRef } from 'react'
-import { IconComment } from '@posthog/icons'
-import { LemonInput, LemonTextArea } from '@posthog/lemon-ui'
+import { IconComment, IconImage } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonTextArea, lemonToast } from '@posthog/lemon-ui'
import { createMarkdownNotebookRegistry } from 'lib/components/MarkdownNotebook'
import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'
@@ -51,7 +52,11 @@ import {
} from 'lib/components/MarkdownNotebook/types'
import { isNotebookPropValue, toSerializablePropValue } from 'lib/components/MarkdownNotebook/utils'
import { FEATURE_FLAGS } from 'lib/constants'
+import { useUploadFiles } from 'lib/hooks/useUploadFiles'
+import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'
+import { Spinner } from 'lib/lemon-ui/Spinner'
import { type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { NODE_ICONS } from '../nodeIcons'
import { NotebookNodeContext } from '../Nodes/NotebookNodeContext'
@@ -618,9 +623,41 @@ export function MountedRealNotebookNodeComponent({
export function ImageEdit({ node, updateProps }: NotebookComponentRenderProps): JSX.Element {
const src = typeof node.props.src === 'string' ? node.props.src : ''
const alt = typeof node.props.alt === 'string' ? node.props.alt : ''
+ const formRef = useRef<HTMLDivElement | null>(null)
+ const { objectStorageAvailable } = useValues(preflightLogic)
+ const { setFilesToUpload, filesToUpload, uploading } = useUploadFiles({
+ onUpload: (url, fileName) => {
+ updateProps({ src: url, ...(alt ? {} : { alt: fileName }) })
+ posthog.capture('notebook image uploaded', { name: fileName })
+ },
+ onError: (detail) => {
+ posthog.capture('notebook image upload failed', { error: detail })
+ lemonToast.error(`Error uploading image: ${detail}`)
+ },
+ })
return (
- <div className="MarkdownNotebook__component-form">
+ <div className="MarkdownNotebook__component-form" ref={formRef}>
+ <LemonFileInput
+ accept="image/*"
+ multiple={false}
+ value={filesToUpload}
+ onChange={setFilesToUpload}
+ loading={uploading}
+ showUploadedFiles={false}
+ alternativeDropTargetRef={formRef}
+ callToAction={
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={uploading ? <Spinner className="text-lg" textColored /> : <IconImage />}
+ disabledReason={objectStorageAvailable ? undefined : 'Enable object storage to upload images'}
+ tooltip={objectStorageAvailable ? 'Click here or drag and drop to upload an image' : null}
+ >
+ Upload image
+ </LemonButton>
+ }
+ />
<LemonInput
value={src}
onChange={(value) => updateProps({ src: value })}
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
index b49a54159bbb..6d71b90cfb80 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
@@ -12,6 +12,8 @@ import { NotebookNodeType } from '../types'
import {
appendMarkdownNotebookBlock,
buildMarkdownNotebookContent,
+ convertDroppedPostHogUrlToMarkdownNode,
+ convertDroppedRichContentNodeToMarkdownNode,
convertNotebookContentToMarkdown,
getMarkdownNotebookMarkdown,
getMarkdownNotebookTitle,
@@ -728,4 +730,89 @@ Users activated faster.
Body`)
})
+
+ describe('convertDroppedPostHogUrlToMarkdownNode', () => {
+ // Entity links drag with only their href; this mapping is what turns a dropped link
+ // into the resource's component node instead of a plain link.
+ it.each<[string, string, { tagName: string; props: Record<string, unknown> } | null]>([
+ ['feature flag', '/feature_flags/123', { tagName: 'FeatureFlag', props: { id: 123 } }],
+ [
+ 'feature flag with project prefix',
+ '/project/1/feature_flags/123',
+ { tagName: 'FeatureFlag', props: { id: 123 } },
+ ],
+ ['experiment', '/experiments/42', { tagName: 'Experiment', props: { id: 42 } }],
+ ['cohort', '/cohorts/7', { tagName: 'Cohort', props: { id: 7 } }],
+ [
+ 'saved insight',
+ '/insights/AbC123',
+ {
+ tagName: 'Query',
+ props: { query: { kind: 'SavedInsightNode', shortId: 'AbC123' }, hideFilters: true },
+ },
+ ],
+ [
+ 'survey',
+ '/surveys/018f6a2b-0000-0000-0000-000000000000',
+ { tagName: 'Survey', props: { id: '018f6a2b-0000-0000-0000-000000000000' } },
+ ],
+ [
+ 'recording',
+ '/replay/018f6a2b-1111-2222-3333-444444444444',
+ { tagName: 'Recording', props: { id: '018f6a2b-1111-2222-3333-444444444444' } },
+ ],
+ [
+ 'person by uuid',
+ '/persons/018f6a2b-1111-2222-3333-444444444444',
+ { tagName: 'Person', props: { id: '018f6a2b-1111-2222-3333-444444444444' } },
+ ],
+ [
+ 'person by distinct id',
+ '/person/user%40example.com',
+ { tagName: 'Person', props: { distinctId: '[email protected]' } },
+ ],
+ ['new flag form (no entity yet)', '/feature_flags/new', null],
+ ['new insight form (no entity yet)', '/insights/new', null],
+ ['unrecognized path', '/settings/project', null],
+ ])('%s', (_name, path, expected) => {
+ const node = convertDroppedPostHogUrlToMarkdownNode(`${window.location.origin}${path}`)
+
+ if (expected === null) {
+ expect(node).toBeNull()
+ } else {
+ expect(node).toMatchObject({ type: 'component', ...expected })
+ }
+ })
+
+ it('ignores URLs from other origins', () => {
+ expect(convertDroppedPostHogUrlToMarkdownNode('https://example.com/feature_flags/123')).toBeNull()
+ })
+ })
+
+ describe('convertDroppedRichContentNodeToMarkdownNode', () => {
+ it('maps a dragged recording payload to its markdown component', () => {
+ const node = convertDroppedRichContentNodeToMarkdownNode(NotebookNodeType.Recording, {
+ id: 'session-1',
+ noInspector: false,
+ })
+
+ expect(node).toMatchObject({
+ type: 'component',
+ tagName: 'Recording',
+ props: { id: 'session-1', noInspector: false },
+ })
+ })
+
+ it('defaults dropped queries to hidden filters', () => {
+ const node = convertDroppedRichContentNodeToMarkdownNode(NotebookNodeType.Query, {
+ query: { kind: NodeKind.EventsQuery, select: ['event'] },
+ })
+
+ expect(node).toMatchObject({ tagName: 'Query', props: { hideFilters: true } })
+ })
+
+ it('returns null for node types without a markdown counterpart', () => {
+ expect(convertDroppedRichContentNodeToMarkdownNode('ph-not-a-real-node', { id: 1 })).toBeNull()
+ })
+ })
})
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
index a541db202c92..d17ea190503b 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
@@ -2,14 +2,22 @@ import {
escapeCodeSpanText,
escapeInlineMarkdownText,
escapeMarkdownBlockLines,
+ makeEmptyParagraph,
parseMarkdownNotebook,
sanitizeNotebookLinkHref,
serializeMarkdownNotebook,
serializeNode,
} from 'lib/components/MarkdownNotebook/markdown'
-import { NotebookBlockNode, NotebookComponentProps, NotebookPropValue } from 'lib/components/MarkdownNotebook/types'
+import {
+ NotebookBlockNode,
+ NotebookComponentBlockNode,
+ NotebookComponentProps,
+ NotebookPropValue,
+} from 'lib/components/MarkdownNotebook/types'
import { getInlineText, isNotebookPropValue, toSerializablePropValue } from 'lib/components/MarkdownNotebook/utils'
import { JSONContent } from 'lib/components/RichContentEditor/types'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { urlToResource } from 'scenes/urls'
import { DocumentBlock, VisualizationBlock } from '~/queries/schema/schema-assistant-artifacts'
import {
@@ -118,6 +126,115 @@ export function appendMarkdownNotebookBlock(
)
}
+/** Converts a dragged legacy notebook resource (`node` + `properties` dataTransfer payload, as set
+ * by `useNotebookDrag`) into a markdown component block, or null when the node type has no
+ * markdown counterpart. */
+export function convertDroppedRichContentNodeToMarkdownNode(
+ nodeType: string,
+ attrs: Record<string, unknown>
+): NotebookBlockNode | null {
+ const tagName = NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[nodeType as NotebookNodeType]
+ if (!tagName) {
+ return null
+ }
+
+ const props = getSerializableAttrs(attrs)
+ return makeDroppedComponentNode(tagName, tagName === 'Query' ? withDefaultHiddenFilters(props) : props)
+}
+
+function makeDroppedComponentNode(tagName: string, props: NotebookComponentProps): NotebookComponentBlockNode {
+ return {
+ id: makeEmptyParagraph('dropped').id,
+ type: 'component',
+ tagName,
+ props,
+ }
+}
+
+function toNumericResourceId(ref: string): number | null {
+ const id = Number(ref)
+ return Number.isInteger(id) && id > 0 ? id : null
+}
+
+const REPLAY_SINGLE_PATH_REGEX = /^\/replay\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/
+const PERSON_BY_UUID_PATH_REGEX = /^\/persons\/([^/]+)$/
+const PERSON_BY_DISTINCT_ID_PATH_REGEX = /^\/person\/([^/]+)$/
+
+/** Maps a dropped PostHog resource URL to its markdown component block, or null when the URL isn't
+ * a recognized resource. Entity links (`Link`) drag with only their href, so this is what turns a
+ * dragged feature flag, experiment, insight, etc. into its special node rather than a plain link. */
+export function convertDroppedPostHogUrlToMarkdownNode(url: string): NotebookBlockNode | null {
+ let parsed: URL
+ try {
+ parsed = new URL(url, window.location.origin)
+ } catch {
+ return null
+ }
+ if (parsed.origin !== window.location.origin) {
+ return null
+ }
+
+ const path = removeProjectIdIfPresent(parsed.pathname)
+
+ const replayMatch = path.match(REPLAY_SINGLE_PATH_REGEX)
+ if (replayMatch) {
+ return makeDroppedComponentNode('Recording', { id: replayMatch[1] })
+ }
+ const personByUuidMatch = path.match(PERSON_BY_UUID_PATH_REGEX)
+ if (personByUuidMatch) {
+ return makeDroppedComponentNode('Person', { id: decodeURIComponent(personByUuidMatch[1]) })
+ }
+ const personByDistinctIdMatch = path.match(PERSON_BY_DISTINCT_ID_PATH_REGEX)
+ if (personByDistinctIdMatch) {
+ return makeDroppedComponentNode('Person', { distinctId: decodeURIComponent(personByDistinctIdMatch[1]) })
+ }
+
+ const resource = urlToResource(path)
+ if (!resource) {
+ return null
+ }
+
+ switch (resource.type) {
+ case 'feature_flag': {
+ const id = toNumericResourceId(resource.ref)
+ return id === null ? null : makeDroppedComponentNode('FeatureFlag', { id })
+ }
+ case 'experiment': {
+ const id = toNumericResourceId(resource.ref)
+ return id === null ? null : makeDroppedComponentNode('Experiment', { id })
+ }
+ case 'cohort': {
+ const id = toNumericResourceId(resource.ref)
+ return id === null ? null : makeDroppedComponentNode('Cohort', { id })
+ }
+ case 'insight':
+ // `/insights/new` matches the same `:id` slot as a real short id
+ return resource.ref === 'new'
+ ? null
+ : makeDroppedComponentNode('Query', {
+ query: { kind: NodeKind.SavedInsightNode, shortId: resource.ref },
+ hideFilters: true,
+ })
+ case 'survey':
+ return makeDroppedComponentNode('Survey', { id: resource.ref })
+ case 'early_access_feature':
+ return makeDroppedComponentNode('EarlyAccessFeature', { id: resource.ref })
+ default:
+ return null
+ }
+}
+
+/** A paragraph holding the dropped URL as a link — the fallback when a dragged URL isn't a
+ * recognized PostHog resource. */
+export function buildDroppedLinkParagraphNode(url: string): NotebookBlockNode {
+ const href = sanitizeNotebookLinkHref(url)
+ return {
+ id: makeEmptyParagraph('dropped-link').id,
+ type: 'paragraph',
+ children: [{ type: 'text', text: url, ...(href ? { marks: [{ type: 'link', href }] } : {}) }],
+ }
+}
+
export function serializeMarkdownNotebookComponent(tagName: string, props: NotebookComponentProps): string {
return serializeNode({
id: '',