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): add cell and block keyboard shortcuts (#96544)

Sinan Kucukkoselere6c2cc581a80
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index ccfb99658e28..a800ab34dd14 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -477,6 +477,69 @@ function createTouchList(touches: Touch[]): TouchList {
}
describe('MarkdownNotebook', () => {
+ it('moves a component block whose own control holds focus', () => {
+ // A cell's Run button takes focus on click, so the block element itself is not the active
+ // element. Resolving only exact matches moved whatever block still held the caret.
+ const onChange = jest.fn()
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Embed',
+ label: 'Embed',
+ category: 'Media',
+ ViewComponent: () => createElement('button', { type: 'button', 'data-attr': 'embed-run' }, 'Run'),
+ },
+ ])
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('First\n\n<Embed url="https://posthog.com" />'),
+ onChange,
+ registry,
+ })
+ )
+
+ const embedControl = container.querySelector('[data-attr="embed-run"]') as HTMLButtonElement
+ embedControl.focus()
+
+ fireEvent.keyDown(embedControl, { key: 'ArrowUp', altKey: true })
+
+ expect(onChange).toHaveBeenLastCalledWith(withNotebookTitle('<Embed url="https://posthog.com" />\n\nFirst'))
+ })
+
+ it('moves the focused block past its neighbour with Alt+Up and Alt+Down', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('First\n\nSecond\n\nThird'), onChange })
+ )
+
+ const secondBlock = getBodyTextBlock(container, 1)
+ secondBlock.focus()
+
+ fireEvent.keyDown(secondBlock, { key: 'ArrowDown', altKey: true })
+ expect(onChange).toHaveBeenLastCalledWith(withNotebookTitle('First\n\nThird\n\nSecond'))
+
+ fireEvent.keyDown(secondBlock, { key: 'ArrowUp', altKey: true })
+ expect(onChange).toHaveBeenLastCalledWith(withNotebookTitle('First\n\nSecond\n\nThird'))
+ })
+
+ it('claims Cmd+S inside a code editor, where the browser would offer to save the page', () => {
+ const onSaveRequested = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('Body'), onSaveRequested })
+ )
+
+ // Monaco renders a textarea inside `.monaco-editor`, which every other notebook shortcut
+ // steps around so the editor keeps its own keys. Saving is the exception.
+ const editor = document.createElement('div')
+ editor.className = 'monaco-editor'
+ const editorInput = document.createElement('textarea')
+ editor.appendChild(editorInput)
+ getBodyTextBlock(container, 0).appendChild(editor)
+
+ fireEvent.keyDown(editorInput, { key: 's', metaKey: true })
+
+ expect(onSaveRequested).toHaveBeenCalledTimes(1)
+ })
+
it('round-trips supported markdown blocks and inline formatting', () => {
const markdown = `# Heading
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 143a952ee546..5c9bf5fb52e2 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -286,6 +286,8 @@ export type MarkdownNotebookProps = {
canvasHeader?: ReactNode
className?: string
autoFocus?: boolean
+ /** Called on Cmd/Ctrl+S. Without it the key stays with the browser. */
+ onSaveRequested?: () => void
showDebug?: boolean
debugOpen?: boolean
onDebugOpenChange?: (isOpen: boolean) => void
@@ -621,6 +623,7 @@ function MarkdownNotebookEditor({
canvasHeader,
className,
autoFocus = false,
+ onSaveRequested,
showDebug = false,
debugOpen,
onDebugOpenChange,
@@ -4832,7 +4835,22 @@ function MarkdownNotebookEditor({
}
const handleNotebookKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
- if (mode !== 'edit' || event.altKey || !(event.metaKey || event.ctrlKey)) {
+ if (mode !== 'edit') {
+ return
+ }
+
+ // Claimed before the native-editable guard below, so Cmd+S inside a code editor does not
+ // fall through to the browser's "save page" dialog.
+ if (
+ onSaveRequested &&
+ (event.metaKey || event.ctrlKey) &&
+ !event.altKey &&
+ !event.shiftKey &&
+ event.key.toLowerCase() === 's'
+ ) {
+ event.preventDefault()
+ event.stopPropagation()
+ onSaveRequested()
return
}
@@ -4843,6 +4861,25 @@ function MarkdownNotebookEditor({
return
}
+ // Placed after the native-editable guard, so Monaco keeps Alt+Up/Down for moving a line.
+ if (
+ event.altKey &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ (event.key === 'ArrowUp' || event.key === 'ArrowDown')
+ ) {
+ if (moveActiveBlock(event.key === 'ArrowUp' ? 'previous' : 'next')) {
+ event.preventDefault()
+ event.stopPropagation()
+ }
+ return
+ }
+
+ if (event.altKey || !(event.metaKey || event.ctrlKey)) {
+ return
+ }
+
const key = event.key.toLowerCase()
const inlineMarkShortcuts: Partial<Record<string, NotebookInlineMark['type']>> = {
b: 'bold',
@@ -5024,17 +5061,17 @@ function MarkdownNotebookEditor({
return Math.max(1, Math.min(boundaryIndex, renderedNodes.length))
}
- const moveBlockToBoundary = (nodeId: string, boundaryIndex: number): void => {
+ const moveBlockToBoundary = (nodeId: string, boundaryIndex: number): boolean => {
const currentDocument = documentRef.current
const nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]
const fromIndex = nodes.findIndex((node) => node.id === nodeId)
if (fromIndex <= 0) {
- return
+ return false
}
const clampedBoundaryIndex = Math.max(1, Math.min(boundaryIndex, nodes.length))
if (clampedBoundaryIndex === fromIndex || clampedBoundaryIndex === fromIndex + 1) {
- return
+ return false
}
const nextNodes = [...nodes]
@@ -5045,6 +5082,57 @@ function MarkdownNotebookEditor({
movedNode
)
commitDocument({ ...currentDocument, nodes: nextNodes })
+ return true
+ }
+
+ // A text block never holds focus, because the canvas is the single editing host, so it has to
+ // be resolved from the caret instead.
+ const getKeyboardActiveNodeId = (): string | null => {
+ const nodes = documentRef.current.nodes
+ const activeElement = window.document.activeElement
+ if (activeElement instanceof HTMLElement) {
+ const nodeIdsByElement = new Map<HTMLElement, string>()
+ for (const node of nodes) {
+ const blockElement = blockRefs.current[node.id]
+ if (blockElement) {
+ nodeIdsByElement.set(blockElement, node.id)
+ }
+ }
+
+ // Focus often sits on a control inside the block rather than on the block itself, such as
+ // a cell's Run button, so the owning block is the nearest one above the focused element.
+ for (let element: HTMLElement | null = activeElement; element; element = element.parentElement) {
+ const focusedNodeId = nodeIdsByElement.get(element)
+ if (focusedNodeId) {
+ return focusedNodeId
+ }
+ }
+ }
+
+ const anchorNode = window.getSelection()?.anchorNode ?? null
+ const anchorElement = anchorNode instanceof HTMLElement ? anchorNode : (anchorNode?.parentElement ?? null)
+ const blockElement = anchorElement?.closest('[data-markdown-notebook-node-id]')
+ if (!(blockElement instanceof HTMLElement) || !canvasRef.current?.contains(blockElement)) {
+ return null
+ }
+
+ return blockElement.dataset.markdownNotebookNodeId ?? null
+ }
+
+ // `moveBlockToBoundary` takes an insert boundary rather than an index, which is why moving down
+ // is `+ 2` and not `+ 1`.
+ const moveActiveBlock = (direction: 'previous' | 'next'): boolean => {
+ const nodeId = getKeyboardActiveNodeId()
+ if (!nodeId) {
+ return false
+ }
+
+ const fromIndex = documentRef.current.nodes.findIndex((node) => node.id === nodeId)
+ if (fromIndex < 0) {
+ return false
+ }
+
+ return moveBlockToBoundary(nodeId, direction === 'previous' ? fromIndex - 1 : fromIndex + 2)
}
const handleBlockDragStart = (event: ReactDragEvent<HTMLDivElement>, nodeId: string): void => {
diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx
index b4da0d1284d0..1cd1a00ef30c 100644
--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx
@@ -1,8 +1,10 @@
import { fireEvent, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useContext, useEffect, useMemo } from 'react'
+import { createPortal } from 'react-dom'
import { useComponentPanelState } from './componentPanelContext'
+import { usePublishNotebookComponentRunHandler } from './componentRunHandlers'
import { NotebookComponentRunStatusContext } from './componentRunStatus'
import { NotebookComponentToolbarExtrasContext } from './componentToolbarExtras'
import { NotebookComponentShell } from './NotebookComponentShell'
@@ -20,6 +22,86 @@ function PanelStateProbe(): JSX.Element {
)
}
+type RunnableCellOptions = {
+ run?: jest.Mock
+ disabledReason?: string | null
+ moveFocusToAdjacentNode?: jest.Mock
+ insertParagraphAfterNode?: jest.Mock
+ /** 'native' mirrors an EditContext Monaco, which also renders an IME textarea the caret must
+ * not land in. 'textarea' mirrors an older build, where the textarea is the real input. */
+ withEditor?: false | 'native' | 'textarea'
+ runnable?: boolean
+ /** Renders the block's content through a portal, the way a modal or menu does. */
+ portalContent?: boolean
+}
+
+function renderCell({
+ run = jest.fn(),
+ disabledReason = null,
+ moveFocusToAdjacentNode = jest.fn(() => false),
+ insertParagraphAfterNode = jest.fn(),
+ withEditor = false,
+ runnable = true,
+ portalContent = false,
+}: RunnableCellOptions = {}): HTMLElement {
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Cell',
+ label: 'Cell',
+ category: 'Test',
+ ViewComponent: () =>
+ portalContent ? (
+ createPortal(<div data-attr="cell-portal">Portaled</div>, document.body)
+ ) : withEditor === 'native' ? (
+ <div className="monaco-editor">
+ <div className="native-edit-context" tabIndex={0} data-attr="cell-editor" />
+ <textarea className="ime-text-area" data-attr="cell-ime" />
+ </div>
+ ) : withEditor === 'textarea' ? (
+ <div className="monaco-editor">
+ <textarea className="inputarea" data-attr="cell-editor" />
+ </div>
+ ) : (
+ <div data-attr="cell-results">Results</div>
+ ),
+ ToolbarComponent: runnable
+ ? function CellToolbar(): JSX.Element {
+ usePublishNotebookComponentRunHandler({ run, disabledReason })
+ return <button type="button">Run</button>
+ }
+ : undefined,
+ },
+ ])
+
+ const { container } = render(
+ <NotebookComponentShell
+ node={{ id: 'cell-node', type: 'component', tagName: 'Cell', props: {} }}
+ mode="edit"
+ 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={insertParagraphAfterNode}
+ moveFocusToAdjacentNode={moveFocusToAdjacentNode}
+ />
+ )
+
+ return container.querySelector('.MarkdownNotebook__component-shell') as HTMLElement
+}
+
+const RUN_SHORTCUTS: [string, { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean }, boolean][] = [
+ ['Cmd+Enter', { metaKey: true }, false],
+ ['Ctrl+Enter', { ctrlKey: true }, false],
+ ['Shift+Enter', { shiftKey: true }, true],
+]
+
describe('NotebookComponentShell', () => {
it('provides markdown component panel state to rendered components', () => {
const registry = createMarkdownNotebookRegistry([
@@ -667,4 +749,63 @@ describe('NotebookComponentShell', () => {
expect(within(container).queryByText('Results')).toBeNull()
expect(within(container).getByLabelText('More actions')).toBeTruthy()
})
+
+ test.each(RUN_SHORTCUTS)('%s runs the cell from anywhere inside it', (_name, modifiers, movesOn) => {
+ const run = jest.fn()
+ const moveFocusToAdjacentNode = jest.fn(() => false)
+ const shell = renderCell({ run, moveFocusToAdjacentNode })
+
+ // Fired on the results, not the shell: a run has to start with focus anywhere in the cell.
+ fireEvent.keyDown(within(shell).getByTestId('cell-results'), { key: 'Enter', ...modifiers })
+
+ expect(run).toHaveBeenCalledTimes(1)
+ expect(moveFocusToAdjacentNode.mock.calls).toEqual(movesOn ? [['cell-node', 'next', 0]] : [])
+ })
+
+ test.each(RUN_SHORTCUTS)('%s does not run a cell that published a disabled reason', (_name, modifiers) => {
+ // A run already in flight disables the button; a second one races the poller and strands
+ // the spinner, so the shortcut has to refuse it too.
+ const run = jest.fn()
+ const shell = renderCell({ run, disabledReason: 'This cell is already running' })
+
+ fireEvent.keyDown(within(shell).getByTestId('cell-results'), { key: 'Enter', ...modifiers })
+
+ expect(run).not.toHaveBeenCalled()
+ })
+
+ test.each([
+ ['EditContext Monaco', 'native'],
+ ['textarea Monaco', 'textarea'],
+ ] as const)('moves focus out of a %s cell on Escape and back in on Enter', (_name, withEditor) => {
+ const shell = renderCell({ withEditor })
+ const editor = within(shell).getByTestId('cell-editor')
+ editor.focus()
+
+ fireEvent.keyDown(editor, { key: 'Escape' })
+ expect(document.activeElement).toBe(shell)
+
+ fireEvent.keyDown(shell, { key: 'Enter' })
+ expect(document.activeElement).toBe(editor)
+ })
+
+ it("ignores run shortcuts from a block's portaled modal or menu", () => {
+ // React bubbles a portal's events through the component tree, so they reach this shell even
+ // though the portal's DOM sits outside it. A source editor in a modal must keep its own keys.
+ const run = jest.fn()
+ renderCell({ run, portalContent: true })
+
+ fireEvent.keyDown(screen.getByTestId('cell-portal'), { key: 'Enter', shiftKey: true })
+ fireEvent.keyDown(screen.getByTestId('cell-portal'), { key: 'Enter', metaKey: true })
+
+ expect(run).not.toHaveBeenCalled()
+ })
+
+ it('keeps Enter adding a paragraph below a block that cannot run', () => {
+ const insertParagraphAfterNode = jest.fn()
+ const shell = renderCell({ runnable: false, insertParagraphAfterNode })
+
+ fireEvent.keyDown(shell, { key: 'Enter' })
+
+ expect(insertParagraphAfterNode).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
index 265bd258b5d4..a646874aaff6 100644
--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
@@ -38,6 +38,7 @@ import {
DEFAULT_COMPONENT_PANEL_VISIBILITY,
withPersistedComponentPanelProps,
} from './componentPanels'
+import { NotebookComponentRunHandler, NotebookComponentRunHandlerContext } from './componentRunHandlers'
import { useNotebookComponentRunStatus } from './componentRunStatus'
import {
NotebookComponentToolbarExtras,
@@ -132,6 +133,7 @@ export function NotebookComponentShell({
const canToggleComponentPanels = mode === 'edit'
const hasOpenComponentPanel = componentPanels.filters || componentPanels.results
const [toolbarExtras, setToolbarExtras] = useState<NotebookComponentToolbarExtras | null>(null)
+ const [runHandler, setRunHandler] = useState<NotebookComponentRunHandler | null>(null)
const titleDisplay = getComponentTitleDisplay(node, definition)
const toolbarTitle = getComponentToolbarTitle(node, definition, titleDisplay.label)
const isTitleEditable = definition?.editableTitle !== false
@@ -329,8 +331,77 @@ export function NotebookComponentShell({
event.currentTarget.blur()
}
}
+ const isRunnableCell = !!runHandler
+
+ const runFromKeyboard = (): boolean => {
+ if (!runHandler || runHandler.disabledReason) {
+ return false
+ }
+
+ runHandler.run()
+ return true
+ }
+
+ const focusCellEditor = (shell: HTMLElement): boolean => {
+ // Focusing the editor wrapper does nothing, because Monaco reads keystrokes from a hidden
+ // input of its own. Keep the bare `textarea` last: an EditContext Monaco also renders one
+ // for IME, and focusing that one leaves the caret outside the editor.
+ const editorInput = shell.querySelector<HTMLElement>(
+ '.monaco-editor .native-edit-context, .monaco-editor textarea.inputarea, .monaco-editor textarea'
+ )
+ if (!editorInput) {
+ return false
+ }
+
+ editorInput.focus()
+ return true
+ }
+
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
- if (mode !== 'edit' || event.target !== event.currentTarget) {
+ // A handler closer to the key already claimed it, such as Monaco's own Cmd+Enter.
+ if (mode !== 'edit' || event.defaultPrevented) {
+ return
+ }
+
+ // A modal or menu a block renders portals its DOM out of the shell, yet React still bubbles
+ // its events here through the component tree. Without this the source editor inside a
+ // widget's modal would run the cell on Shift+Enter instead of taking the newline.
+ if (event.target instanceof Node && !event.currentTarget.contains(event.target)) {
+ return
+ }
+
+ // Deliberately overrides Monaco's Shift+Enter, which inserts a plain newline that Enter
+ // already gives you.
+ if (event.key === 'Enter' && !event.altKey && (event.metaKey || event.ctrlKey || event.shiftKey)) {
+ const movesOn = event.shiftKey && !event.metaKey && !event.ctrlKey
+ if (runFromKeyboard()) {
+ event.preventDefault()
+ event.stopPropagation()
+ if (movesOn) {
+ moveFocusToAdjacentNode(node.id, 'next', 0)
+ }
+ }
+ return
+ }
+
+ // Monaco keeps Escape while it has something to dismiss (the suggestion list, the find
+ // box) and releases it once it has not, so this only fires when the editor is done with it.
+ if (
+ isRunnableCell &&
+ event.key === 'Escape' &&
+ event.target !== event.currentTarget &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.altKey &&
+ !event.shiftKey
+ ) {
+ event.preventDefault()
+ event.stopPropagation()
+ event.currentTarget.focus()
+ return
+ }
+
+ if (event.target !== event.currentTarget) {
return
}
@@ -355,6 +426,9 @@ export function NotebookComponentShell({
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault()
+ if (isRunnableCell && focusCellEditor(event.currentTarget)) {
+ return
+ }
insertParagraphAfterNode()
}
}
@@ -443,7 +517,12 @@ export function NotebookComponentShell({
{ToolbarComponent ? (
<div className="MarkdownNotebook__component-toolbar-controls">
<NotebookComponentToolbarErrorBoundary node={node}>
- <ToolbarComponent node={node} notebookMode={mode} updateProps={updateProps} />
+ {/* The run control publishes the cell's run action from here: the
+ toolbar is the one part of a cell that stays mounted while the
+ cell is collapsed, so the run shortcuts keep working when it is. */}
+ <NotebookComponentRunHandlerContext.Provider value={setRunHandler}>
+ <ToolbarComponent node={node} notebookMode={mode} updateProps={updateProps} />
+ </NotebookComponentRunHandlerContext.Provider>
</NotebookComponentToolbarErrorBoundary>
</div>
) : null}
diff --git a/frontend/src/lib/components/MarkdownNotebook/README.md b/frontend/src/lib/components/MarkdownNotebook/README.md
index 70455e7a40ed..e04eca4e9c7b 100644
--- a/frontend/src/lib/components/MarkdownNotebook/README.md
+++ b/frontend/src/lib/components/MarkdownNotebook/README.md
@@ -52,10 +52,33 @@ Because of this, all editing behavior must be dispatched from root-level handler
- `handleRootEditableKeyDown` (canvas `onKeyDown`) — Tab indentation, Enter splits, Backspace/Delete semantics, ArrowDown below a trailing code block
- the native `beforeinput` capture listener — `insertParagraph`/`insertLineBreak` (inside code blocks these insert a literal `\n` through the model, since the browser default inserts `<br>` elements that are invisible to `textContent`), `deleteContent*`, `historyUndo/Redo`, and a last-resort guard that cancels any unclaimed native range edit crossing inline-editable boundaries — the browser would otherwise restructure React-managed elements in place (e.g. merge two `<li>`s) and the next React commit would crash with `removeChild` DOM exceptions
- `handleRootEditableInput` (canvas `onInput`) — syncing typed text back into the document model
-- `handleNotebookKeyDown` (notebook root `onKeyDownCapture`) — Cmd/Ctrl shortcuts: bold/italic/underline (`B`/`I`/`U`), strikethrough (`Shift+X`), scoped select-all (`A`), copy of a focused component (`C`)
+- `handleNotebookKeyDown` (notebook root `onKeyDownCapture`) — Cmd/Ctrl shortcuts: bold/italic/underline (`B`/`I`/`U`), strikethrough (`Shift+X`), scoped select-all (`A`), copy of a focused component (`C`), save (`S`), and `Alt+Up`/`Alt+Down` to move the active block past its neighbour
These resolve the affected block with `getInlineEditableElementForSelection` and the `data-markdown-notebook-*` attributes. Do **not** add keyboard handlers to inner block components: they only fire in JSDOM tests (where events are dispatched directly on inner elements), so they create behavior that passes tests but never runs in the app.
+Two of the root shortcuts sit either side of the guard that skips native editable elements (`input`, `textarea`, `select`, `.monaco-editor`), and the order is the behavior. `Cmd/Ctrl+S` is claimed **before** it, so saving works inside a code editor too — left to the browser there, it opens the "save page" dialog over the notebook. `Alt+Up`/`Alt+Down` sits **after** it, so a code editor keeps the same keys for moving a line.
+
+`Cmd/Ctrl+S` calls the host's `onSaveRequested`; without that prop the key stays with the browser. The notebooks scene points it at `notebookLogic`'s `saveNotebookNow`, which skips the autosave debounce and applies the gates the autosave path already applies.
+
+## Cell keys
+
+A component block that publishes a run handler (`usePublishNotebookComponentRunHandler`, from `componentRunHandlers.ts`) is a **cell**, and `NotebookComponentShell` gives it notebook keys on top of the document keys every block has. The SQL, Python, and generated-widget blocks publish one; the legacy code blocks do not, so they keep the document keys alone. The generic editor never learns what SQL or Python is: the block's toolbar control publishes `run()` and the `disabledReason` guarding it, so a shortcut can never start a run the Run button would refuse — an in-flight run included, since a second one races the poller and strands the spinner.
+
+| Key | Where it works | What it does |
+| ---------------- | -------------------- | ----------------------------------------------- |
+| `Cmd/Ctrl+Enter` | anywhere in the cell | Runs the cell |
+| `Shift+Enter` | anywhere in the cell | Runs the cell and moves focus to the next block |
+| `Escape` | inside the editor | Moves focus out to the cell |
+| `Enter` | on the cell | Moves focus back into the editor |
+
+The run keys reach the whole cell so a run still starts with focus on the results or on a collapsed cell, where there is no editor on screen. Monaco binds its own `Cmd+Enter` and stops the event there, so a run from inside the editor never reaches the shell twice; `Shift+Enter` it treats as a plain newline, which `Enter` already gives you. `Escape` arrives only once Monaco has nothing left to dismiss (its suggestion list, its find box), which is what makes it safe to take.
+
+The shell only handles keys that happened inside its own DOM. A block that renders a modal or a menu portals that DOM out of the shell, and React still bubbles its events here through the component tree, so without the check a source editor in a modal would run the cell on `Shift+Enter` instead of taking the newline.
+
+`Escape`/`Enter` apply to cells alone. On every other block `Enter` keeps adding a paragraph below it, which is the document behavior. A cell therefore gives that up: add a block after one from the insert boundary instead.
+
+`Enter` focuses the element Monaco actually reads keystrokes from, and which one that is depends on the build. An EditContext-based Monaco uses `.native-edit-context` and renders a second textarea only for IME, so focusing that textarea puts the caret nowhere. The selector tries the EditContext element first and keeps the bare `textarea` last for older builds. `NotebookComponentShell.test.tsx` covers both shapes, because JSDOM alone cannot tell them apart.
+
## Sync model
The component receives two props: `value` (the local content owned by the caller, e.g. `notebookLogic.localContent`) and `remoteValue` (the latest known server content). Internally it tracks:
diff --git a/frontend/src/lib/components/MarkdownNotebook/componentRunHandlers.ts b/frontend/src/lib/components/MarkdownNotebook/componentRunHandlers.ts
new file mode 100644
index 000000000000..307ba0345b36
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/componentRunHandlers.ts
@@ -0,0 +1,29 @@
+import { createContext, useContext, useEffect } from 'react'
+
+/** `disabledReason` mirrors the run button's own gate, so a shortcut can never start a run the
+ * button would refuse. */
+export type NotebookComponentRunHandler = {
+ run: () => void
+ disabledReason?: string | null
+}
+
+// Lets the shell own the cell's key handling while knowing nothing about SQL or Python.
+export const NotebookComponentRunHandlerContext = createContext<
+ ((handler: NotebookComponentRunHandler | null) => void) | null
+>(null)
+
+export function usePublishNotebookComponentRunHandler(handler: NotebookComponentRunHandler | null): void {
+ const publishRunHandler = useContext(NotebookComponentRunHandlerContext)
+ const run = handler?.run
+ const disabledReason = handler?.disabledReason ?? null
+
+ useEffect(() => {
+ if (!publishRunHandler) {
+ return
+ }
+
+ publishRunHandler(run ? { run, disabledReason } : null)
+
+ return () => publishRunHandler(null)
+ }, [publishRunHandler, run, disabledReason])
+}
diff --git a/frontend/src/lib/components/MarkdownNotebook/index.ts b/frontend/src/lib/components/MarkdownNotebook/index.ts
index 740d0d4ab018..35347555b042 100644
--- a/frontend/src/lib/components/MarkdownNotebook/index.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/index.ts
@@ -15,6 +15,8 @@ export {
getMarkdownNotebookComponentDefaultProps,
mergeMarkdownNotebookRegistries,
} from './registry'
+export { NotebookComponentRunHandlerContext, usePublishNotebookComponentRunHandler } from './componentRunHandlers'
+export type { NotebookComponentRunHandler } from './componentRunHandlers'
export { NotebookComponentRunStatusContext } from './componentRunStatus'
export type { NotebookComponentRunStatus, NotebookComponentRunStatusResolver } from './componentRunStatus'
export { parseMarkdownNotebook, serializeMarkdownNotebook, htmlElementToInlineNodes } from './markdown'
diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsx
index 8a8446e3b136..8a28b875f0e5 100644
--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsx
@@ -3,6 +3,7 @@ import { useCallback } from 'react'
import { IconPlayFilled } from '@posthog/icons'
+import { usePublishNotebookComponentRunHandler } from 'lib/components/MarkdownNotebook/componentRunHandlers'
import type { NotebookComponentToolbarProps } from 'lib/components/MarkdownNotebook/types'
import { getSerializableProps } from 'lib/components/MarkdownNotebook/utils'
import { IconCancel } from 'lib/lemon-ui/icons'
@@ -51,11 +52,9 @@ export function NotebookCodeCellRunButton({ node, updateProps }: NotebookCompone
// will answer for. That excludes a public share, a viewer-level reader, and a history preview,
// all of which render this toolbar in view mode. Without the gate they get a control that
// returns 403, and a preview would run a version of the code the reader is not editing.
- if (isShared || !canEditNotebook) {
- return null
- }
+ const canRun = !isShared && canEditNotebook
- const run = (): void => {
+ const run = useCallback((): void => {
// A SQL cell's editor holds the code and the connection a keystroke or a just-picked
// connection before the document does, so prefer it while it is open. A Python cell has no
// such logic mounted and runs from the document.
@@ -73,6 +72,18 @@ export function NotebookCodeCellRunButton({ node, updateProps }: NotebookCompone
}
: {}
runNode(overrides)
+ }, [nodeId, runNode])
+
+ // A run in flight blocks the shortcuts, because the button turns into Cancel there and a run
+ // shortcut must never become a stop.
+ usePublishNotebookComponentRunHandler(
+ canRun
+ ? { run, disabledReason: isRunning ? 'This cell is already running' : (operationBlockReason ?? null) }
+ : null
+ )
+
+ if (!canRun) {
+ return null
}
return (
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
index df6fdaabf729..0a6ef65db56d 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
@@ -106,6 +106,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
reportMarkdownMergeConflicts,
publishMarkdownCaret,
setMarkdownAIPresenceActive,
+ saveNotebookNow,
} = useActions(notebookLogic)
const { setShowKernelInfo } = useActions(notebookSettingsLogic)
const remoteMarkdown = useMemo(() => getMarkdownNotebookMarkdown(notebook?.content), [notebook?.content])
@@ -701,6 +702,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
extraInsertCommands={isEditable ? buildExtraInsertCommands : undefined}
hiddenInsertCommandKeys={hiddenInsertCommandKeys}
onChange={isEditable ? handleMarkdownNotebookChange : undefined}
+ onSaveRequested={isEditable ? saveNotebookNow : undefined}
onConflict={reportMarkdownMergeConflicts}
remoteCarets={remoteCarets}
onCaretChange={isEditable ? publishMarkdownCaret : undefined}
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index 3d38fd57284c..299cb41765e0 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -545,6 +545,9 @@ export interface notebookLogicActions {
error: string
errorObject?: any
}
+ saveNotebookNow: () => {
+ value: true
+ }
saveNotebookSuccess: (
notebook: NotebookType | null,
payload?: {
@@ -804,6 +807,7 @@ export const notebookLogic = kea<notebookLogicType>([
showMarkdownMergeConflictDetails: (conflicts: NotebookCollaborationConflict[]) => ({ conflicts }),
dismissMarkdownMergeConflictDetails: true,
saveNotebook: (notebook: Pick<NotebookType, 'content' | 'title'>) => ({ notebook }),
+ saveNotebookNow: true,
renameNotebook: (title: string) => ({ title }),
setEditingNodeEditing: (nodeId: string, editing: boolean) => ({ nodeId, editing }),
exportJSON: true,
@@ -1964,6 +1968,20 @@ export const notebookLogic = kea<notebookLogicType>([
actions.setLocalContent(buildMarkdownNotebookContent(nextMarkdown, values.markdownEditorNodeId))
},
+ saveNotebookNow: () => {
+ // Autosave already saves every edit, so this only skips its debounce and repeats the
+ // gates that path applies. No local content means the notebook is already saved.
+ if (values.previewContent || values.autosavePaused || values.isLocalOnly) {
+ return
+ }
+
+ if (!values.localContent || !values.content || values.notebookLoading) {
+ return
+ }
+
+ actions.saveNotebook({ content: values.content, title: values.title })
+ },
+
setLocalContent: async ({ jsonContent, skipCapture }, breakpoint) => {
if (
values.mode !== 'canvas' &&
diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx
index 59dc95820762..650a8fdd4cf2 100644
--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx
+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx
@@ -2,6 +2,7 @@ import { useActions, useMountedLogic, useValues } from 'kea'
import { IconPlayFilled } from '@posthog/icons'
+import { usePublishNotebookComponentRunHandler } from 'lib/components/MarkdownNotebook/componentRunHandlers'
import type { NotebookComponentToolbarProps } from 'lib/components/MarkdownNotebook/types'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'
@@ -52,6 +53,14 @@ function EditableNotebookGeneratedWidgetRunButton({
const { dataRefreshInFlight, runDataDependenciesDisabledReason } = useValues(logic)
const { runDataDependencies } = useActions(logic)
+ // A refresh in flight blocks the shortcuts, matching the button, which is disabled while it loads.
+ usePublishNotebookComponentRunHandler({
+ run: runDataDependencies,
+ disabledReason: dataRefreshInFlight
+ ? 'This widget is already running'
+ : (runDataDependenciesDisabledReason ?? null),
+ })
+
return (
<LemonButton
data-attr="notebook-generated-widget-run-button"