Skip to content

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

fix(notebooks): restore per-node actions, menu, and canvas controls in markdown notebooks (#75573)

Arthur Moreira de Deusabeb205d8142
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
index 690616b25165..4316223a3223 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
@@ -1751,6 +1751,13 @@ h3.MarkdownNotebook__text-block--heading {
border-top: 0;
}
+.MarkdownNotebook__component-custom-actions {
+ display: flex;
+ gap: 0.5rem;
+ align-items: center;
+ padding: 0.25rem 0.5rem 0.5rem;
+}
+
.MarkdownNotebook__component-mode-actions,
.MarkdownNotebook__component-actions,
.MarkdownNotebook__component-edit-footer {
@@ -1947,6 +1954,14 @@ button.MarkdownNotebook__component-title:focus-visible {
background: var(--markdown-notebook-component-background);
}
+.MarkdownNotebook__real-node--settings-only {
+ min-height: 0;
+
+ .MarkdownNotebook__real-node-settings {
+ border-bottom: 0;
+ }
+}
+
.MarkdownNotebook__real-node-settings {
border-bottom: 1px solid var(--color-border-primary);
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index 0d544d595d8e..b7a051885bc4 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -8944,6 +8944,7 @@ After component`,
const onChange = jest.fn()
const { container } = render(createElement(MarkdownNotebook, { value: markdown, onChange }))
const shell = container.querySelector('.MarkdownNotebook__component-shell')
+ const actionsContainer = container.querySelector('.MarkdownNotebook__component-actions') as HTMLElement
const modeButtons = Array.from(
container.querySelectorAll('.MarkdownNotebook__component-mode-actions button')
) as HTMLButtonElement[]
@@ -8958,6 +8959,9 @@ After component`,
expect(modeButtons[1].getAttribute('aria-label')).toEqual('Hide results')
expect(toolbarLeftChildren[0].classList.contains('MarkdownNotebook__component-title')).toBe(true)
expect(toolbarLeftChildren[1].classList.contains('MarkdownNotebook__component-mode-actions')).toBe(true)
+ // Edit mode folds via the eye/title; the collapse button is canvas-only
+ expect(container.querySelector('button[aria-label="Collapse"]')).toBeNull()
+ expect(actionsContainer.contains(deleteButton)).toBe(true)
expect(deleteButton).toBeInstanceOf(HTMLButtonElement)
const stackedPanels = Array.from(shell?.querySelectorAll('.MarkdownNotebook__component-panel') ?? [])
expect(stackedPanels).toHaveLength(2)
@@ -9063,6 +9067,48 @@ After component`,
)
})
+ it('toggles canvas filters locally without persisting hide props to the document', () => {
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Probe',
+ label: 'Probe',
+ category: 'Test',
+ viewModeFilters: true,
+ ViewComponent: () => createElement('div', { 'data-testid': 'probe-results' }, 'Results'),
+ EditComponent: () => createElement('div', { 'data-testid': 'probe-filters' }, 'Filters'),
+ },
+ ])
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: '<Probe />',
+ mode: 'view',
+ allowViewModeFilters: true,
+ registry,
+ onChange,
+ })
+ )
+
+ // Canvas default: results visible, filters closed behind the gear.
+ expect(container.querySelector('[data-testid="probe-results"]')).toBeInstanceOf(HTMLElement)
+ expect(container.querySelector('[data-testid="probe-filters"]')).toBeNull()
+
+ const filtersButton = container.querySelector('button[aria-label="Show filters"]') as HTMLButtonElement
+ expect(filtersButton).toBeInstanceOf(HTMLButtonElement)
+
+ fireEvent.click(filtersButton)
+
+ expect(container.querySelector('[data-testid="probe-filters"]')).toBeInstanceOf(HTMLElement)
+ // Opening is encoded as the absence of hide* props: persisting from a canvas would
+ // round-trip the panel straight back to the closed fallback. It must stay local.
+ expect(onChange).not.toHaveBeenCalled()
+
+ fireEvent.click(container.querySelector('button[aria-label="Hide filters"]') as HTMLButtonElement)
+
+ expect(container.querySelector('[data-testid="probe-filters"]')).toBeNull()
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
it('hides component mode actions when requested by the component definition', () => {
const registry = createMarkdownNotebookRegistry([
{
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index e7747c597841..59d97597434d 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -37,6 +37,7 @@ import { mergeNotebookMarkdownChanges } from './collaboration'
import {
ComponentPanelCacheEntry,
ComponentPanelVisibility,
+ CANVAS_COMPONENT_PANEL_VISIBILITY,
DEFAULT_COMPONENT_PANEL_VISIBILITY,
getComponentPanelVisibility,
getInsertedComponentPanelVisibility,
@@ -271,6 +272,9 @@ export type MarkdownNotebookProps = {
) => NotebookBlockNode[] | Promise<NotebookBlockNode[] | null> | null
focusAIPromptRequest?: number
aiWritingNodeIndexes?: number[]
+ /** In view mode, keep the filters toggle for definitions with `viewModeFilters` — for
+ * read-only canvases where the filters panel is the only way to configure a node. */
+ allowViewModeFilters?: boolean
placeholder?: string
className?: string
autoFocus?: boolean
@@ -579,6 +583,7 @@ function MarkdownNotebookEditor({
convertExternalDataTransferToNodes,
focusAIPromptRequest,
aiWritingNodeIndexes,
+ allowViewModeFilters = false,
placeholder = 'Start writing...',
className,
autoFocus = false,
@@ -5736,14 +5741,23 @@ function MarkdownNotebookEditor({
const componentDefinition =
node.type === 'component' ? getMarkdownNotebookComponentDefinition(mergedRegistry, node.tagName) : undefined
const componentPanelCacheEntry = node.type === 'component' ? componentPanelCache[node.id] : undefined
+ // Only edit mode persists panel visibility to the document. Persisting encodes "open" as
+ // the ABSENCE of hide* props, which a canvas fallback of filters-closed would immediately
+ // override — opening filters would round-trip to closed. View-mode toggles stay local.
const persistComponentPanelVisibility =
- node.type === 'component' ? shouldPersistComponentPanelProps(node, componentDefinition) : false
+ mode === 'edit' && node.type === 'component'
+ ? shouldPersistComponentPanelProps(node, componentDefinition)
+ : false
+ const fallbackComponentPanels =
+ mode === 'view' && allowViewModeFilters
+ ? CANVAS_COMPONENT_PANEL_VISIBILITY
+ : DEFAULT_COMPONENT_PANEL_VISIBILITY
const nodeComponentPanels =
node.type === 'component'
? !persistComponentPanelVisibility && componentPanelCacheEntry?.current
? componentPanelCacheEntry.current
- : getComponentPanelVisibility(node, DEFAULT_COMPONENT_PANEL_VISIBILITY)
- : DEFAULT_COMPONENT_PANEL_VISIBILITY
+ : getComponentPanelVisibility(node, fallbackComponentPanels)
+ : fallbackComponentPanels
const shouldShowInlineInsertMenuButton =
!isTitleRow && (isBlankInsertMenuButtonRow(node) || (isToolInsertMenuOpen && isTextBlockNode(node)))
const hasInvalidInsertMenuQuery =
@@ -5831,6 +5845,7 @@ function MarkdownNotebookEditor({
componentPanels: nodeComponentPanels,
rememberedComponentPanels: componentPanelCacheEntry?.remembered,
persistComponentPanelVisibility,
+ allowViewModeFilters,
isSelected: selectedComponentNodeIds.has(node.id),
toggleComponentPanel: (panel) => {
const nextPanels = {
diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx
index 431c881fb4d4..9f7a978130ef 100644
--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx
@@ -1,7 +1,10 @@
-import { fireEvent, render, screen } from '@testing-library/react'
+import { fireEvent, render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useContext, useEffect } from 'react'
import { useComponentPanelState } from './componentPanelContext'
import { NotebookComponentRunStatusContext } from './componentRunStatus'
+import { NotebookComponentToolbarExtrasContext } from './componentToolbarExtras'
import { NotebookComponentShell } from './NotebookComponentShell'
import { createMarkdownNotebookRegistry } from './registry'
@@ -143,4 +146,295 @@ describe('NotebookComponentShell', () => {
expect(shell.classList.contains('MarkdownNotebook__component-shell--status-stale')).toBe(true)
})
+
+ it('renders toolbar extras published by the component', async () => {
+ const onAction = jest.fn()
+ const onMenuItem = jest.fn()
+
+ function ExtrasProbe(): JSX.Element {
+ const setToolbarExtras = useContext(NotebookComponentToolbarExtrasContext)
+ useEffect(() => {
+ setToolbarExtras?.({
+ actions: [{ text: 'Add metric', onClick: onAction }],
+ menuItems: [{ label: 'Refresh', onClick: onMenuItem }],
+ })
+ }, [setToolbarExtras])
+ return <div>Results</div>
+ }
+
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Probe',
+ label: 'Probe',
+ category: 'Test',
+ ViewComponent: ExtrasProbe,
+ },
+ ])
+
+ const renderShell = (mode: 'edit' | 'view'): ReturnType<typeof render> =>
+ render(
+ <NotebookComponentShell
+ node={{
+ id: 'probe-node',
+ type: 'component',
+ tagName: 'Probe',
+ props: {},
+ }}
+ mode={mode}
+ componentPanels={{ filters: false, results: true }}
+ persistComponentPanelVisibility={false}
+ isSelected={false}
+ registry={registry}
+ toggleComponentPanel={jest.fn()}
+ setLocalComponentPanels={jest.fn()}
+ rememberComponentPanels={jest.fn()}
+ setBlockRef={jest.fn()}
+ updateNode={jest.fn()}
+ deleteNode={jest.fn()}
+ deleteSelectedNotebookBlocks={jest.fn(() => false)}
+ insertParagraphAfterNode={jest.fn()}
+ moveFocusToAdjacentNode={jest.fn(() => false)}
+ />
+ )
+
+ const editRender = renderShell('edit')
+
+ const actionButton = screen.getByText('Add metric')
+ fireEvent.click(actionButton)
+ expect(onAction).toHaveBeenCalled()
+
+ await userEvent.click(screen.getByLabelText('More actions'))
+ await userEvent.click(await screen.findByText('Refresh'))
+ expect(onMenuItem).toHaveBeenCalled()
+
+ editRender.unmount()
+
+ // The menu still renders in view mode (e.g. profile canvases), the actions row does not.
+ renderShell('view')
+ expect(screen.queryByText('Add metric')).toBeNull()
+ expect(screen.getByLabelText('More actions')).toBeTruthy()
+ })
+
+ it('shows the filters toggle in view mode only when the host and definition opt in', () => {
+ const toggleComponentPanel = jest.fn()
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Probe',
+ label: 'Probe',
+ category: 'Test',
+ ViewComponent: () => <div>Results</div>,
+ EditComponent: () => <div>Filters panel</div>,
+ viewModeFilters: true,
+ },
+ ])
+
+ const renderShell = (allowViewModeFilters: boolean, filtersOpen: boolean): ReturnType<typeof render> =>
+ render(
+ <NotebookComponentShell
+ node={{
+ id: 'probe-node',
+ type: 'component',
+ tagName: 'Probe',
+ props: {},
+ }}
+ mode="view"
+ componentPanels={{ filters: filtersOpen, results: true }}
+ persistComponentPanelVisibility={false}
+ allowViewModeFilters={allowViewModeFilters}
+ isSelected={false}
+ registry={registry}
+ toggleComponentPanel={toggleComponentPanel}
+ setLocalComponentPanels={jest.fn()}
+ rememberComponentPanels={jest.fn()}
+ setBlockRef={jest.fn()}
+ updateNode={jest.fn()}
+ deleteNode={jest.fn()}
+ deleteSelectedNotebookBlocks={jest.fn(() => false)}
+ insertParagraphAfterNode={jest.fn()}
+ moveFocusToAdjacentNode={jest.fn(() => false)}
+ />
+ )
+
+ // Without the host opt-in (regular read-only notebooks) the toggle stays hidden.
+ const withoutOptIn = renderShell(false, false)
+ expect(within(withoutOptIn.container).queryByLabelText('Show filters')).toBeNull()
+ withoutOptIn.unmount()
+
+ const closedFilters = renderShell(true, false)
+ fireEvent.click(within(closedFilters.container).getByLabelText('Show filters'))
+ expect(toggleComponentPanel).toHaveBeenCalledWith('filters')
+ expect(within(closedFilters.container).queryByText('Filters panel')).toBeNull()
+ // The results visibility toggle stays edit-only: results always render in view mode.
+ expect(within(closedFilters.container).queryByLabelText('Hide results')).toBeNull()
+ closedFilters.unmount()
+
+ const openFilters = renderShell(true, true)
+ expect(within(openFilters.container).getByText('Filters panel')).toBeTruthy()
+ expect(within(openFilters.container).getByText('Results')).toBeTruthy()
+ })
+
+ it('disables the filters toggle when the component publishes a disabled reason', () => {
+ const toggleComponentPanel = jest.fn()
+
+ function ExtrasProbe(): JSX.Element {
+ const setToolbarExtras = useContext(NotebookComponentToolbarExtrasContext)
+ useEffect(() => {
+ setToolbarExtras?.({
+ actions: [],
+ menuItems: null,
+ filtersDisabledReason: 'Create a journey to configure this panel',
+ })
+ }, [setToolbarExtras])
+ return <div>Results</div>
+ }
+
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Probe',
+ label: 'Probe',
+ category: 'Test',
+ ViewComponent: ExtrasProbe,
+ EditComponent: () => <div>Filters panel</div>,
+ viewModeFilters: true,
+ },
+ ])
+
+ const { container } = render(
+ <NotebookComponentShell
+ node={{
+ id: 'probe-node',
+ type: 'component',
+ tagName: 'Probe',
+ props: {},
+ }}
+ mode="view"
+ componentPanels={{ filters: false, results: true }}
+ persistComponentPanelVisibility={false}
+ allowViewModeFilters={true}
+ isSelected={false}
+ registry={registry}
+ toggleComponentPanel={toggleComponentPanel}
+ setLocalComponentPanels={jest.fn()}
+ rememberComponentPanels={jest.fn()}
+ setBlockRef={jest.fn()}
+ updateNode={jest.fn()}
+ deleteNode={jest.fn()}
+ deleteSelectedNotebookBlocks={jest.fn(() => false)}
+ insertParagraphAfterNode={jest.fn()}
+ moveFocusToAdjacentNode={jest.fn(() => false)}
+ />
+ )
+
+ const filtersButton = within(container).getByLabelText('Show filters')
+ expect(filtersButton.getAttribute('aria-disabled')).toBe('true')
+ fireEvent.click(filtersButton)
+ expect(toggleComponentPanel).not.toHaveBeenCalled()
+ })
+
+ it('collapses output on read-only canvases', () => {
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Probe',
+ label: 'Probe',
+ category: 'Test',
+ ViewComponent: () => <div>Results</div>,
+ },
+ ])
+
+ const renderShell = (
+ allowViewModeFilters: boolean,
+ componentPanels: { filters: boolean; results: boolean }
+ ): ReturnType<typeof render> =>
+ render(
+ <NotebookComponentShell
+ node={{
+ id: 'probe-node',
+ type: 'component',
+ tagName: 'Probe',
+ props: {},
+ }}
+ mode="view"
+ componentPanels={componentPanels}
+ persistComponentPanelVisibility={false}
+ allowViewModeFilters={allowViewModeFilters}
+ isSelected={false}
+ registry={registry}
+ toggleComponentPanel={jest.fn()}
+ setLocalComponentPanels={jest.fn()}
+ rememberComponentPanels={jest.fn()}
+ setBlockRef={jest.fn()}
+ updateNode={jest.fn()}
+ deleteNode={jest.fn()}
+ deleteSelectedNotebookBlocks={jest.fn(() => false)}
+ insertParagraphAfterNode={jest.fn()}
+ moveFocusToAdjacentNode={jest.fn(() => false)}
+ />
+ )
+
+ // Plain view mode ignores a collapsed results panel and offers no collapse toggle.
+ const plainView = renderShell(false, { filters: false, results: false })
+ expect(within(plainView.container).getByText('Results')).toBeTruthy()
+ expect(within(plainView.container).queryByLabelText('Collapse')).toBeNull()
+ plainView.unmount()
+
+ const expandedCanvas = renderShell(true, { filters: false, results: true })
+ expect(within(expandedCanvas.container).getByText('Results')).toBeTruthy()
+ expect(within(expandedCanvas.container).getByLabelText('Collapse')).toBeTruthy()
+ expandedCanvas.unmount()
+
+ const collapsedCanvas = renderShell(true, { filters: false, results: false })
+ expect(within(collapsedCanvas.container).queryByText('Results')).toBeNull()
+ expect(within(collapsedCanvas.container).getByLabelText('Expand')).toBeTruthy()
+ })
+
+ it('keeps the toolbar menu when collapsing unmounts the component', () => {
+ function ExtrasProbe(): JSX.Element {
+ const setToolbarExtras = useContext(NotebookComponentToolbarExtrasContext)
+ useEffect(() => {
+ setToolbarExtras?.({ actions: [], menuItems: [{ label: 'Refresh', onClick: jest.fn() }] })
+ }, [setToolbarExtras])
+ return <div>Results</div>
+ }
+
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Probe',
+ label: 'Probe',
+ category: 'Test',
+ ViewComponent: ExtrasProbe,
+ },
+ ])
+
+ const buildShell = (componentPanels: { filters: boolean; results: boolean }): JSX.Element => (
+ <NotebookComponentShell
+ node={{
+ id: 'probe-node',
+ type: 'component',
+ tagName: 'Probe',
+ props: {},
+ }}
+ mode="edit"
+ componentPanels={componentPanels}
+ persistComponentPanelVisibility={false}
+ isSelected={false}
+ registry={registry}
+ toggleComponentPanel={jest.fn()}
+ setLocalComponentPanels={jest.fn()}
+ rememberComponentPanels={jest.fn()}
+ setBlockRef={jest.fn()}
+ updateNode={jest.fn()}
+ deleteNode={jest.fn()}
+ deleteSelectedNotebookBlocks={jest.fn(() => false)}
+ insertParagraphAfterNode={jest.fn()}
+ moveFocusToAdjacentNode={jest.fn(() => false)}
+ />
+ )
+
+ const { container, rerender } = render(buildShell({ filters: false, results: true }))
+ expect(within(container).getByLabelText('More actions')).toBeTruthy()
+
+ rerender(buildShell({ filters: false, results: false }))
+ expect(within(container).queryByText('Results')).toBeNull()
+ expect(within(container).getByLabelText('More actions')).toBeTruthy()
+ })
})
diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
index 3d6f2a86c6db..3f440c1dc72c 100644
--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
@@ -11,18 +11,32 @@ import {
useState,
} from 'react'
-import { IconDatabase, IconEye, IconGraph, IconHide, IconList, IconPencil, IconPeople, IconTrash } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
+import {
+ IconCollapse,
+ IconDatabase,
+ IconEllipsis,
+ IconExpand,
+ IconEye,
+ IconPencil,
+ IconGraph,
+ IconHide,
+ IconList,
+ IconPeople,
+ IconTrash,
+} from '@posthog/icons'
+import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
import { PostHogErrorBoundary } from '@posthog/react'
import { ComponentPanelContext } from './componentPanelContext'
import {
+ CANVAS_COMPONENT_PANEL_VISIBILITY,
ComponentPanel,
ComponentPanelVisibility,
DEFAULT_COMPONENT_PANEL_VISIBILITY,
withPersistedComponentPanelProps,
} from './componentPanels'
import { useNotebookComponentRunStatus } from './componentRunStatus'
+import { NotebookComponentToolbarExtras, NotebookComponentToolbarExtrasContext } from './componentToolbarExtras'
import { getNotebookObjectProp, getNotebookStringProp } from './documentModel'
import { InsertMenuSelectionDirection } from './editorTypes'
import { getMarkdownNotebookComponentDefinition } from './registry'
@@ -50,6 +64,8 @@ export type NotebookComponentShellProps = {
componentPanels: ComponentPanelVisibility
rememberedComponentPanels?: ComponentPanelVisibility
persistComponentPanelVisibility: boolean
+ /** Surface-level opt-in for definitions with `viewModeFilters` (read-only canvases). */
+ allowViewModeFilters?: boolean
isSelected: boolean
registry: NotebookComponentRegistry
toggleComponentPanel: (panel: ComponentPanel) => void
@@ -69,6 +85,7 @@ export function NotebookComponentShell({
componentPanels,
rememberedComponentPanels,
persistComponentPanelVisibility,
+ allowViewModeFilters,
isSelected,
registry,
toggleComponentPanel,
@@ -86,10 +103,19 @@ export function NotebookComponentShell({
const errors = [...(node.errors ?? []), ...(definition?.validateProps?.(node.props) ?? [])]
const ViewComponent = definition?.ViewComponent
const EditComponent = definition?.EditComponent ?? definition?.ViewComponent
- const showEditPanel = mode === 'edit' && componentPanels.filters
+ // Read-only canvases (e.g. customer profiles) keep the filters toggle: it's the only way to
+ // configure nodes there, matching the legacy notebook's canvas behavior.
+ const isViewModeCanvas = mode === 'view' && !!allowViewModeFilters
+ const showViewModeFilters = isViewModeCanvas && !!definition?.viewModeFilters && !definition.hideModeActions
+ const showEditPanel = (mode === 'edit' || showViewModeFilters) && componentPanels.filters
+ // Plain view mode (shared/read-only notebooks) always shows results; canvases can collapse them.
const showViewPanel =
- (mode === 'view' || componentPanels.results) && !(showEditPanel && definition?.exclusiveEditPanel)
+ ((mode === 'view' && !isViewModeCanvas) || componentPanels.results) &&
+ !(showEditPanel && definition?.exclusiveEditPanel)
const showModeActions = mode === 'edit' && !!definition && !definition.hideModeActions
+ // Edit mode already covers folding via the eye/title, so collapse only shows where those
+ // controls don't render: read-only canvases.
+ const showCollapseToggle = isViewModeCanvas && !!definition && !definition.hideModeActions
const canToggleComponentPanels = mode === 'edit'
const hasOpenComponentPanel = componentPanels.filters || componentPanels.results
const titleDisplay = getComponentTitleDisplay(node, definition)
@@ -115,6 +141,9 @@ export function NotebookComponentShell({
}),
[componentPanels, showEditPanel, showViewPanel]
)
+ const [toolbarExtras, setToolbarExtras] = useState<NotebookComponentToolbarExtras | null>(null)
+ const toolbarMenuItems = toolbarExtras?.menuItems?.some(Boolean) ? toolbarExtras.menuItems : null
+ const toolbarActions = mode === 'edit' && toolbarExtras?.actions.length ? toolbarExtras.actions : null
const [titleDraft, setTitleDraft] = useState<string | null>(null)
const [isEditingTitle, setIsEditingTitle] = useState(false)
// A browser fires two `click`s before `dblclick`. Defer the title's collapse so a rename
@@ -160,7 +189,9 @@ export function NotebookComponentShell({
const restoredPanelVisibility =
rememberedComponentPanels && (rememberedComponentPanels.filters || rememberedComponentPanels.results)
? rememberedComponentPanels
- : DEFAULT_COMPONENT_PANEL_VISIBILITY
+ : isViewModeCanvas
+ ? CANVAS_COMPONENT_PANEL_VISIBILITY
+ : DEFAULT_COMPONENT_PANEL_VISIBILITY
const nextPanelVisibility = hasOpenComponentPanel ? { filters: false, results: false } : restoredPanelVisibility
if (hasOpenComponentPanel) {
@@ -305,7 +336,7 @@ export function NotebookComponentShell({
) : (
<div className={titleClassName}>{titleContent}</div>
)}
- {showModeActions ? (
+ {showModeActions || showViewModeFilters ? (
<div className="MarkdownNotebook__component-mode-actions">
<LemonButton
aria-label={filtersLabel}
@@ -313,16 +344,19 @@ export function NotebookComponentShell({
icon={<IconPencil />}
active={componentPanels.filters}
tooltip={filtersLabel}
+ disabledReason={toolbarExtras?.filtersDisabledReason ?? undefined}
onClick={() => toggleComponentPanel('filters')}
/>
- <LemonButton
- aria-label={resultsLabel}
- size="xsmall"
- icon={componentPanels.results ? <IconEye /> : <IconHide />}
- active={componentPanels.results}
- tooltip={resultsLabel}
- onClick={() => toggleComponentPanel('results')}
- />
+ {showModeActions ? (
+ <LemonButton
+ aria-label={resultsLabel}
+ size="xsmall"
+ icon={componentPanels.results ? <IconEye /> : <IconHide />}
+ active={componentPanels.results}
+ tooltip={resultsLabel}
+ onClick={() => toggleComponentPanel('results')}
+ />
+ ) : null}
</div>
) : null}
</div>
@@ -382,58 +416,96 @@ export function NotebookComponentShell({
{resolvedTitle}
</div>
) : null}
- {mode === 'edit' ? (
+ {mode === 'edit' || toolbarMenuItems || showCollapseToggle ? (
<div className="MarkdownNotebook__component-actions">
- <LemonButton
- aria-label="Delete component"
- size="xsmall"
- icon={<IconTrash />}
- tooltip="Delete"
- status="danger"
- onClick={deleteNode}
- />
- </div>
- ) : null}
- </div>
- <ComponentPanelContext.Provider value={componentPanelState}>
- {errors.length ? (
- <div className="MarkdownNotebook__component-errors">
- {errors.map((error) => (
- <div key={error}>{error}</div>
- ))}
- </div>
- ) : null}
- {showEditPanel && EditComponent ? (
- <div className="MarkdownNotebook__component-panel">
- <NotebookComponentPanelErrorBoundary node={node} panel="filters">
- <EditComponent
- node={node}
- mode="edit"
- notebookMode={mode}
- updateProps={updateProps}
- deleteNode={deleteNode}
+ {showCollapseToggle ? (
+ <LemonButton
+ aria-label={hasOpenComponentPanel ? 'Collapse' : 'Expand'}
+ size="xsmall"
+ icon={hasOpenComponentPanel ? <IconCollapse /> : <IconExpand />}
+ tooltip={hasOpenComponentPanel ? 'Collapse' : 'Expand'}
+ onClick={toggleAllComponentPanels}
/>
- </NotebookComponentPanelErrorBoundary>
+ ) : null}
+ {toolbarMenuItems ? (
+ <LemonMenu items={toolbarMenuItems} placement="bottom-end">
+ <LemonButton
+ aria-label="More actions"
+ size="xsmall"
+ icon={<IconEllipsis />}
+ tooltip="More actions"
+ />
+ </LemonMenu>
+ ) : null}
+ {mode === 'edit' ? (
+ <LemonButton
+ aria-label="Delete component"
+ size="xsmall"
+ icon={<IconTrash />}
+ tooltip="Delete"
+ status="danger"
+ onClick={deleteNode}
+ />
+ ) : null}
</div>
) : null}
- {showViewPanel ? (
- <div className="MarkdownNotebook__component-panel">
- {ViewComponent ? (
- <NotebookComponentPanelErrorBoundary node={node} panel="results">
- <ViewComponent
+ </div>
+ <NotebookComponentToolbarExtrasContext.Provider value={setToolbarExtras}>
+ <ComponentPanelContext.Provider value={componentPanelState}>
+ {errors.length ? (
+ <div className="MarkdownNotebook__component-errors">
+ {errors.map((error) => (
+ <div key={error}>{error}</div>
+ ))}
+ </div>
+ ) : null}
+ {showEditPanel && EditComponent ? (
+ <div className="MarkdownNotebook__component-panel">
+ <NotebookComponentPanelErrorBoundary node={node} panel="filters">
+ <EditComponent
node={node}
- mode="view"
+ mode="edit"
notebookMode={mode}
updateProps={updateProps}
deleteNode={deleteNode}
/>
</NotebookComponentPanelErrorBoundary>
- ) : (
- <UnknownComponentView node={node} />
- )}
+ </div>
+ ) : null}
+ {showViewPanel ? (
+ <div className="MarkdownNotebook__component-panel">
+ {ViewComponent ? (
+ <NotebookComponentPanelErrorBoundary node={node} panel="results">
+ <ViewComponent
+ node={node}
+ mode="view"
+ notebookMode={mode}
+ updateProps={updateProps}
+ deleteNode={deleteNode}
+ />
+ </NotebookComponentPanelErrorBoundary>
+ ) : (
+ <UnknownComponentView node={node} />
+ )}
+ </div>
+ ) : null}
+ </ComponentPanelContext.Provider>
+ {toolbarActions ? (
+ <div className="MarkdownNotebook__component-custom-actions">
+ {toolbarActions.map((action, index) => (
+ <LemonButton
+ key={index}
+ size="xsmall"
+ type="secondary"
+ icon={action.icon}
+ onClick={action.onClick}
+ >
+ {action.text}
+ </LemonButton>
+ ))}
</div>
) : null}
- </ComponentPanelContext.Provider>
+ </NotebookComponentToolbarExtrasContext.Provider>
</div>
)
}
@@ -533,6 +605,7 @@ export function areNotebookComponentShellPropsEqual(
return (
previousProps.mode === nextProps.mode &&
+ previousProps.allowViewModeFilters === nextProps.allowViewModeFilters &&
previousProps.updateNode === nextProps.updateNode &&
previousProps.deleteSelectedNotebookBlocks === nextProps.deleteSelectedNotebookBlocks &&
previousProps.moveFocusToAdjacentNode === nextProps.moveFocusToAdjacentNode &&
diff --git a/frontend/src/lib/components/MarkdownNotebook/componentPanels.ts b/frontend/src/lib/components/MarkdownNotebook/componentPanels.ts
index 28f559327dc9..96eabc612a60 100644
--- a/frontend/src/lib/components/MarkdownNotebook/componentPanels.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/componentPanels.ts
@@ -14,6 +14,13 @@ export const DEFAULT_COMPONENT_PANEL_VISIBILITY: ComponentPanelVisibility = {
results: true,
}
+// Read-only canvases (customer profiles) show results with filters tucked away behind the
+// pencil, matching the legacy profile layout.
+export const CANVAS_COMPONENT_PANEL_VISIBILITY: ComponentPanelVisibility = {
+ filters: false,
+ results: true,
+}
+
export const INSERTED_COMPONENT_PANEL_VISIBILITY: ComponentPanelVisibility = {
filters: true,
results: true,
diff --git a/frontend/src/lib/components/MarkdownNotebook/componentToolbarExtras.ts b/frontend/src/lib/components/MarkdownNotebook/componentToolbarExtras.ts
new file mode 100644
index 000000000000..7364f982775b
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/componentToolbarExtras.ts
@@ -0,0 +1,21 @@
+import { createContext } from 'react'
+
+import type { LemonButtonProps, LemonMenuItems } from '@posthog/lemon-ui'
+
+export type NotebookComponentToolbarAction = Pick<LemonButtonProps, 'icon'> & {
+ text: string
+ onClick: () => void
+}
+
+export type NotebookComponentToolbarExtras = {
+ actions: NotebookComponentToolbarAction[]
+ menuItems: LemonMenuItems | null
+ /** Disables the shell's filters toggle with this tooltip (e.g. nothing to configure yet). */
+ filtersDisabledReason?: string | null
+}
+
+// Bridge for node implementations (mounted inside a panel) to surface their custom
+// actions and menu items on the component shell's toolbar, which renders above them.
+export const NotebookComponentToolbarExtrasContext = createContext<
+ ((extras: NotebookComponentToolbarExtras | null) => void) | null
+>(null)
diff --git a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx
index 41ddb7d4aa06..fd559330cc6a 100644
--- a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx
@@ -34,6 +34,7 @@ export function renderNode({
componentPanels,
rememberedComponentPanels,
persistComponentPanelVisibility,
+ allowViewModeFilters,
isSelected,
toggleComponentPanel,
setLocalComponentPanels,
@@ -81,6 +82,7 @@ export function renderNode({
componentPanels: ComponentPanelVisibility
rememberedComponentPanels?: ComponentPanelVisibility
persistComponentPanelVisibility: boolean
+ allowViewModeFilters?: boolean
isSelected: boolean
toggleComponentPanel: (panel: ComponentPanel) => void
setLocalComponentPanels: (nodeId: string, panels: ComponentPanelVisibility) => void
@@ -182,6 +184,7 @@ export function renderNode({
toggleComponentPanel={toggleComponentPanel}
rememberedComponentPanels={rememberedComponentPanels}
persistComponentPanelVisibility={persistComponentPanelVisibility}
+ allowViewModeFilters={allowViewModeFilters}
setLocalComponentPanels={setLocalComponentPanels}
rememberComponentPanels={rememberComponentPanels}
setBlockRef={setBlockRef}
diff --git a/frontend/src/lib/components/MarkdownNotebook/types.ts b/frontend/src/lib/components/MarkdownNotebook/types.ts
index d01ab46bd736..14df5bf3f0d0 100644
--- a/frontend/src/lib/components/MarkdownNotebook/types.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/types.ts
@@ -167,6 +167,9 @@ export type NotebookComponentDefinition = {
EditComponent?: (props: NotebookComponentRenderProps) => JSX.Element
exclusiveEditPanel?: boolean
hideModeActions?: boolean
+ /** Show the filters toggle in view mode too, when the host opts in via `allowViewModeFilters`
+ * (read-only canvases like customer profiles, where filters are the only way to configure a node). */
+ viewModeFilters?: boolean
insertCommand?: NotebookComponentInsertCommand
}
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeCustomerJourney/NotebookNodeCustomerJourney.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeCustomerJourney/NotebookNodeCustomerJourney.tsx
index d760b0710fbf..308ac063a37d 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeCustomerJourney/NotebookNodeCustomerJourney.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeCustomerJourney/NotebookNodeCustomerJourney.tsx
@@ -32,7 +32,7 @@ type NotebookNodeCustomerJourneyAttributes = {
const Component = ({ attributes }: NotebookNodeProps<NotebookNodeCustomerJourneyAttributes>): JSX.Element | null => {
const isJourneysEnabled = useFeatureFlag('CUSTOMER_ANALYTICS_JOURNEYS')
const { expanded, notebookLogic } = useValues(notebookNodeLogic)
- const { setMenuItems, setTitlePlaceholder } = useActions(notebookNodeLogic)
+ const { setMenuItems, setTitlePlaceholder, setSettingsDisabledReason } = useActions(notebookNodeLogic)
const { personId, groupKey, groupTypeIndex, tabId } = attributes
const logicKey = getLogicKey({ personId, groupKey, tabId })
@@ -46,6 +46,13 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeCustomerJourney
}
}, [setTitlePlaceholder, activeJourney])
+ // The settings panel only selects between journeys, so it has nothing to offer until one exists
+ useEffect(() => {
+ setSettingsDisabledReason(
+ !journeysLoading && journeyOptions.length === 0 ? 'Create a journey to configure this panel' : null
+ )
+ }, [setSettingsDisabledReason, journeysLoading, journeyOptions.length])
+
useOnMountEffect(() => {
const removeMenuItem = getCustomerProfileRemoveMenuItem(NotebookNodeType.CustomerJourney)
const editJourneysMenuItem = {
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeUsageMetrics.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeUsageMetrics.tsx
index 64eebb8d388e..83b1c37d53b5 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeUsageMetrics.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeUsageMetrics.tsx
@@ -1,12 +1,11 @@
import { BindLogic, useActions, useValues } from 'kea'
+import { useEffect } from 'react'
import { IconPlusSmall, IconRefresh } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TeamMembershipLevel } from 'lib/constants'
-import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { UsageMetricsConfig, UsageMetricsModal } from 'scenes/settings/environment/UsageMetricsConfig'
@@ -56,13 +55,23 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeUsageMetricsAtt
const { loadData } = useActions(logic)
const usageMetricsConfigLogicProps = { logicKey: attributes.nodeId, onMetricsChanged: loadData }
const { openModal } = useActions(usageMetricsConfigLogic(usageMetricsConfigLogicProps))
+ const { reportUsageMetricsCreateButtonClicked } = useActions(eventUsageLogic)
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
- useOnMountEffect(() => {
+ useEffect(() => {
const removeMenuItem = getCustomerProfileRemoveMenuItem(NotebookNodeType.UsageMetrics)
const addMetricMenuItem = {
label: 'Add metric',
sideIcon: <IconPlusSmall />,
- onClick: openModal,
+ disabledReason: restrictedReason ?? undefined,
+ 'data-attr': 'usage-metrics-node-add-metric',
+ onClick: () => {
+ reportUsageMetricsCreateButtonClicked()
+ openModal()
+ },
}
const refreshMenuItem = {
label: 'Refresh',
@@ -74,7 +83,8 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeUsageMetricsAtt
return
}
setMenuItems([addMetricMenuItem, refreshMenuItem])
- })
+ // oxlint-disable-next-line exhaustive-deps
+ }, [restrictedReason])
if (!expanded) {
return null
@@ -104,10 +114,7 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeUsageMetricsAtt
return (
<BindLogic logic={usageMetricsConfigLogic} props={usageMetricsConfigLogicProps}>
<div className="@container">
- <div className="flex justify-end px-4 pt-4">
- <AddUsageMetricButton />
- </div>
- <div className="grid grid-cols-1 @md:grid-cols-2 @xl:grid-cols-4 gap-4 px-4 pb-4 pt-2">
+ <div className="grid grid-cols-1 @md:grid-cols-2 @xl:grid-cols-4 gap-4 p-4">
{results.map((metric) => (
<UsageMetricCard key={metric.id} metric={metric} />
))}
@@ -118,31 +125,6 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeUsageMetricsAtt
)
}
-function AddUsageMetricButton(): JSX.Element {
- const { openModal } = useActions(usageMetricsConfigLogic)
- const { reportUsageMetricsCreateButtonClicked } = useActions(eventUsageLogic)
- const restrictedReason = useRestrictedArea({
- scope: RestrictionScope.Project,
- minimumAccessLevel: TeamMembershipLevel.Admin,
- })
-
- return (
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconPlusSmall />}
- disabledReason={restrictedReason}
- data-attr="usage-metrics-node-add-metric"
- onClick={() => {
- reportUsageMetricsCreateButtonClicked()
- openModal()
- }}
- >
- Add metric
- </LemonButton>
- )
-}
-
function UsageMetricsEmptyState(): JSX.Element {
const { openModal } = useActions(usageMetricsConfigLogic)
const restrictedReason = useRestrictedArea({
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
index 1e70f55a783d..e423b4bbf3a4 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
@@ -26,6 +26,11 @@ import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
import { isHogQLQuery, isNodeWithSource } from '~/queries/utils'
import type { CommentType } from '../../../types'
+import {
+ convertNotebookContentToMarkdown,
+ insertMarkdownNotebookBlockAfterNode,
+ isMarkdownNotebookContent,
+} from '../Notebook/markdownNotebookV2'
import type { NotebookKernelInfo } from '../Notebook/notebookKernelInfoLogic'
import type { notebookLogicType } from '../Notebook/notebookLogic'
import {
@@ -928,6 +933,7 @@ export interface notebookNodeLogicValues {
ref: HTMLElement | null
resizeable: boolean
sendMessage: <T extends keyof NotebookNodeMessages>(message: T, payload: NotebookNodeMessages[T]) => boolean
+ settingsDisabledReason: string | null
settingsPlacement: NotebookNodeSettingsPlacement
sourceComment: CommentType | null | undefined
sqlV2ReturnVariable: string
@@ -1046,6 +1052,9 @@ export interface notebookNodeLogicActions {
setResizeable: (resizeable: boolean) => {
resizeable: boolean
}
+ setSettingsDisabledReason: (settingsDisabledReason: string | null) => {
+ settingsDisabledReason: string | null
+ }
setTitlePlaceholder: (titlePlaceholder: string) => {
titlePlaceholder: string
}
@@ -1154,6 +1163,7 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([
setResizeable: (resizeable: boolean) => ({ resizeable }),
setActions: (actions: (NotebookNodeAction | undefined)[]) => ({ actions }),
setMenuItems: (menuItems: LemonMenuItems | null) => ({ menuItems }),
+ setSettingsDisabledReason: (settingsDisabledReason: string | null) => ({ settingsDisabledReason }),
insertAfter: (content: JSONContent) => ({ content }),
updateAttributes: (attributes: Partial<NotebookNodeAttributes<any>>) => ({ attributes }),
setPreviousNode: (node: RichContentNode | null) => ({ node }),
@@ -1253,6 +1263,12 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([
setMenuItems: (_, { menuItems }) => menuItems,
},
],
+ settingsDisabledReason: [
+ null as string | null,
+ {
+ setSettingsDisabledReason: (_, { settingsDisabledReason }) => settingsDisabledReason,
+ },
+ ],
messageListeners: [
props.messageListeners as NotebookNodeMessagesListeners,
{
@@ -1540,6 +1556,22 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([
targetLogic?.actions.selectNode()
},
+ insertAfter: ({ content }) => {
+ const notebookLogic = values.notebookLogic
+ if (!isMarkdownNotebookContent(notebookLogic.values.content)) {
+ return
+ }
+ // The converter serializes the children of a doc, so a single leaf node must be
+ // wrapped in an array to be serialized itself.
+ const insertedMarkdown = convertNotebookContentToMarkdown(content.type === 'doc' ? content : [content])
+ if (!insertedMarkdown.trim()) {
+ return
+ }
+ notebookLogic.actions.setLocalContent(
+ insertMarkdownNotebookBlockAfterNode(notebookLogic.values.content, values.nodeId, insertedMarkdown)
+ )
+ },
+
setExpanded: ({ expanded }) => {
if (expanded) {
posthog.capture('notebook node expanded', {
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
index 997677a913bf..30f866e70388 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
@@ -762,6 +762,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
createAIConversationId={uuid}
deferRemoteValue={markdownEditorInteractionActive}
onInteractionStateChange={setMarkdownEditorInteractionActive}
+ allowViewModeFilters={mountedNotebookLogic.props.mode === 'canvas'}
className="Notebook__markdown-v2"
data-attr="notebook-markdown-v2"
autoFocus={isEditable}
diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.scss b/frontend/src/scenes/notebooks/Notebook/Notebook.scss
index 2ecdca1d1982..2445e59c9589 100644
--- a/frontend/src/scenes/notebooks/Notebook/Notebook.scss
+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.scss
@@ -525,6 +525,11 @@
.NotebookColumn__content {
width: var(--notebook-column-right-width);
transform: translateX(100%);
+
+ // Sidebar nodes lost the legacy NotebookNode__gap spacer between them
+ > * + * {
+ margin-top: 0.75rem;
+ }
}
}
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
index ba4e279d73d7..29cc3250cb5a 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
@@ -33,7 +33,15 @@ import '../Nodes/NotebookNodeZendeskTickets'
import clsx from 'clsx'
import { BindLogic, useMountedLogic, useValues } from 'kea'
import posthog from 'posthog-js'
-import { type CSSProperties, type PointerEvent as ReactPointerEvent, useCallback, useMemo, useRef } from 'react'
+import {
+ type CSSProperties,
+ type PointerEvent as ReactPointerEvent,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+} from 'react'
import { IconComment, IconImage } from '@posthog/icons'
import { LemonButton, LemonInput, LemonTextArea, lemonToast } from '@posthog/lemon-ui'
@@ -43,6 +51,7 @@ import {
QUERY_SQL_INSERT_COMMAND_KEY,
createMarkdownNotebookRegistry,
} from 'lib/components/MarkdownNotebook'
+import { NotebookComponentToolbarExtrasContext } from 'lib/components/MarkdownNotebook/componentToolbarExtras'
import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'
import { isDiscussionCommentProps } from 'lib/components/MarkdownNotebook/markdown'
import {
@@ -240,6 +249,9 @@ export const NOTEBOOK_MARKDOWN_REGISTRY: NotebookComponentRegistry = createMarkd
ViewComponent: RealNotebookNodeView,
EditComponent: definition.EditComponent ?? RealNotebookNodeEdit,
exclusiveEditPanel: definition.exclusiveEditPanel,
+ // Nodes with a Settings panel keep their filters toggle on read-only canvases
+ // (customer profiles), where the panel is the only way to configure them.
+ viewModeFilters: !!options?.Settings,
insertCommand: definition.insertCommand,
getTitle: (node: NotebookComponentBlockNode) =>
getMarkdownNotebookNodeTitle(node, nodeType, options, label),
@@ -557,6 +569,27 @@ export function MountedRealNotebookNodeComponent({
)
const nodeLogic = useMountedLogic(notebookNodeLogic(logicProps))
+ const {
+ actions: nodeActions,
+ customMenuItems: nodeMenuItems,
+ settingsDisabledReason: nodeSettingsDisabledReason,
+ } = useValues(nodeLogic)
+ const setToolbarExtras = useContext(NotebookComponentToolbarExtrasContext)
+
+ // The settings-panel instance (editOnly) shares the shell with the content instance;
+ // only the latter publishes, so a hidden panel doesn't clear the other's extras.
+ // No unmount cleanup on purpose: collapsing the node unmounts the component, and the
+ // toolbar menu must survive the collapse. The shell drops the state when IT unmounts.
+ useEffect(() => {
+ if (editOnly || !setToolbarExtras) {
+ return
+ }
+ setToolbarExtras({
+ actions: nodeActions,
+ menuItems: nodeMenuItems,
+ filtersDisabledReason: nodeSettingsDisabledReason,
+ })
+ }, [editOnly, nodeActions, nodeMenuItems, nodeSettingsDisabledReason, setToolbarExtras])
const Component = options.Component
const Settings = options.Settings
@@ -633,7 +666,15 @@ export function MountedRealNotebookNodeComponent({
return (
<NotebookNodeContext.Provider value={nodeLogic}>
<BindLogic logic={notebookNodeLogic} props={logicProps}>
- <div className="MarkdownNotebook__real-node" style={nodeStyle}>
+ <div
+ className={clsx(
+ 'MarkdownNotebook__real-node',
+ // The settings-only (filters panel) instance sizes to its content — the
+ // 8rem min-height is for node output, not a one-row filter bar.
+ editOnly && 'MarkdownNotebook__real-node--settings-only'
+ )}
+ style={nodeStyle}
+ >
{showSettings ? (
<div className="MarkdownNotebook__real-node-settings">
<Settings attributes={attributes} updateAttributes={updateAttributes} />
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
index 285dd8bade49..97861eb33d19 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
@@ -17,6 +17,7 @@ import {
convertNotebookContentToMarkdown,
getMarkdownNotebookMarkdown,
getMarkdownNotebookTitle,
+ insertMarkdownNotebookBlockAfterNode,
isMarkdownNotebookContent,
notebookArtifactContentToMarkdown,
notebookContentHasCommentMarks,
@@ -64,6 +65,38 @@ describe('markdownNotebookV2', () => {
)
})
+ it('inserts markdown blocks after the block with a matching nodeId prop', () => {
+ const content = buildMarkdownNotebookContent(
+ '# Activation\n\n<UsageMetrics nodeId="target-node" />\n\nClosing paragraph'
+ )
+ const nextContent = insertMarkdownNotebookBlockAfterNode(content, 'target-node', '<Survey id="s1" />')
+
+ expect(getMarkdownNotebookMarkdown(nextContent)).toEqual(
+ '# Activation\n\n<UsageMetrics nodeId="target-node" />\n\n<Survey id="s1" />\n\nClosing paragraph'
+ )
+ })
+
+ it('inserts markdown blocks after the block with a matching parsed block id', () => {
+ const markdown = '# Activation\n\nMiddle paragraph\n\nClosing paragraph'
+ const middleBlockId = parseMarkdownNotebook(markdown).nodes[1].id
+ const nextContent = insertMarkdownNotebookBlockAfterNode(
+ buildMarkdownNotebookContent(markdown),
+ middleBlockId,
+ 'Inserted paragraph'
+ )
+
+ expect(getMarkdownNotebookMarkdown(nextContent)).toEqual(
+ '# Activation\n\nMiddle paragraph\n\nInserted paragraph\n\nClosing paragraph'
+ )
+ })
+
+ it('appends at the end when no block matches the target node id', () => {
+ const content = buildMarkdownNotebookContent('# Activation')
+ const nextContent = insertMarkdownNotebookBlockAfterNode(content, 'missing-node', '<Survey id="s1" />')
+
+ expect(getMarkdownNotebookMarkdown(nextContent)).toEqual('# Activation\n\n\n<Survey id="s1" />')
+ })
+
it('converts common legacy notebook nodes to markdown', () => {
const content: JSONContent = {
type: 'doc',
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
index 7ff1cf54d098..3966f2f51654 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
@@ -130,6 +130,33 @@ export function appendMarkdownNotebookBlock(
)
}
+/** Inserts a markdown block right after the block identified by `targetNodeId` (a component's
+ * persisted `nodeId` prop, or the parsed block id). Appends at the end when no block matches. */
+export function insertMarkdownNotebookBlockAfterNode(
+ content: JSONContent | null | undefined,
+ targetNodeId: string,
+ blockMarkdown: string
+): JSONContent {
+ if (!blockMarkdown.trim()) {
+ return buildMarkdownNotebookContent(getMarkdownNotebookMarkdown(content), getMarkdownNotebookNodeId(content))
+ }
+
+ const document = parseMarkdownNotebook(getMarkdownNotebookMarkdown(content))
+ const targetIndex = document.nodes.findIndex(
+ (node) => node.id === targetNodeId || (node.type === 'component' && node.props.nodeId === targetNodeId)
+ )
+ if (targetIndex === -1) {
+ return appendMarkdownNotebookBlock(content, blockMarkdown)
+ }
+
+ const nodes = [...document.nodes]
+ nodes.splice(targetIndex + 1, 0, ...parseMarkdownNotebook(blockMarkdown).nodes)
+ return buildMarkdownNotebookContent(
+ serializeMarkdownNotebook({ ...document, nodes }),
+ getMarkdownNotebookNodeId(content)
+ )
+}
+
/** 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. */