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): improve sql editing performance (#65999)

Marius Andra108a5b375d1f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4b3f29474b12..20adcc53d1fb 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2141,9 +2141,9 @@ snapshots:
filters--event-select--light:
hash: v1.k794b7964.85fc96fa35f57098115faf049685cf4db9df3ae86b5d9682785bfedfa85c4308.pqqSwMfC0Ohk00cfTlzyCk_N4i1k0CX5K6c235rG6r4
filters-action-filter--autocapture-with-save-as-action--dark:
- hash: v1.k794b7964.c84cf5749f152d632fb17a4df8f333714a0dd15fd16454ee2cd2259c5e26b285.PvuBlhH3DnOzNi3twtxezmaYHQaoqs2MMV7DQL-jJHE
+ hash: v1.k794b7964.b357edf05c8eadf8c668a9238ce11f93b72889b89ab3bd6e25ec9077f05dfa58.Ja6HkXHEbL0CMrNUXKA2ZhmhMcUs0AEFK5jcc1bPo4s
filters-action-filter--autocapture-with-save-as-action--light:
- hash: v1.k794b7964.59bb3394f48082ee80a7e682b906e3ec2a5a6089e6f73d312c62703d1b48b597.PmEI5cE9dqxZqWSmrZHkjDH-gAJ8JrA0iPCZD-bFLBY
+ hash: v1.k794b7964.e769211b1001d34d4103379e7f6df0f8752603029be66b25545355e5ed171062.4opax1V7h3NyURT1jcZJq7ITphaaGh39pi9CcDB_jkY
filters-action-filter--bordered--dark:
hash: v1.k794b7964.3bd4de168e2581aa811049a1ab83536afe9558c127e80fefe70e2f16acabdc5c.2EagzyjmsMFtLemZXZkojlf8DO5WAP78jb0UA_ItvyM
filters-action-filter--bordered--light:
@@ -2153,13 +2153,13 @@ snapshots:
filters-action-filter--funnel-like--light:
hash: v1.k794b7964.444d56215dfd3e362de0eb5c4b1639850cf7405c9490d291525ad39d7e0d18b8.0XAB2nKR2oQc-8gLyXUn65N4U9orVn-cIwq3OCvUojU
filters-action-filter--funnels-group-custom-name--dark:
- hash: v1.k794b7964.59b447785850b220439082422f31120fbeb8953ac1f7771ea5dfccf7f5630882.jlO472sE6IpC-WaHPFyh4XuE5JqvcauGpWFFWCE8PLA
+ hash: v1.k794b7964.b0fa058dfef2a6c894f38a1ad35beffb4579702b9ffc85c34b596f8b0dc61c43.0tC9fNnVlzpBSmYPQREA3XeEG9ssTJlJ3FTh837RF_E
filters-action-filter--funnels-group-custom-name--light:
- hash: v1.k794b7964.f15759fac94360f9ba1f8e905635b6d5e724ab820063dc027f0012a731d41db1.7pMNlb55dOH54MAMSIhZQgkO3h-EhmIFbXgKLHknJQQ
+ hash: v1.k794b7964.5f696e8fb16f4790f16c85f3bf73397a77475b08cebd82984d61a4e3ecd4ff2a.5xRncUi4syL4Ck9LzCbBvVw-QtKu5Mbx07CEQ6b_nF8
filters-action-filter--funnels-group-default-name--dark:
- hash: v1.k794b7964.59e3a6452bdce7e5a6d88fd7f5b567c4438a8f7e136ef83837e22e75cb8fd785.qlf0VyTrbmCbG52V8-9YIfGvr_h7JlO0KzdFG12Nz6s
+ hash: v1.k794b7964.1fb2c089aea6667b57b3b397d83aa7b39c83a8b78a1562f09cd1a5158b395cc2.7lLFcx7Ewq4-j3NbAbO1lnEZ6eTNO-pqsasaAeF_ahc
filters-action-filter--funnels-group-default-name--light:
- hash: v1.k794b7964.7861f5ac8dd8c6923aeb34acc670c3686b5add6e3f6415cf96e9823507e08ba4.3UMqTiGD83n0lKZIdnqgCfYSJ0wkEb_wzooS5mV7_Kw
+ hash: v1.k794b7964.db50f5bfe4a5aea6da43a078db08343c7408f0114097e7f7fefc0c2e8eebf326.2-OioVyozZopSR-JSRc_BK8WHRXiW6Cbo4sN-0Uc2sk
filters-action-filter--property-filters-with-popover--dark:
hash: v1.k794b7964.84a2eff8cdda6913d63ef2a4cdd06108736d9686b97943e615e00fd535ff0d97.rgckFbpjk4YxNGWhGD5_6xrw9fiT9SJDBNGVRIeM7NQ
filters-action-filter--property-filters-with-popover--light:
@@ -2177,17 +2177,17 @@ snapshots:
filters-action-filter--standard--light:
hash: v1.k794b7964.858a3e18259edb4290038a70acffb8ba8eeff4bf8955c23414eb429ec6798f09.NOsoQALh5WGXujIqizs58u-ksyg1vrymcCZgGfBm-BQ
filters-action-filter--trends-group-custom-name--dark:
- hash: v1.k794b7964.d7bd0a62184316dee5872b5bd47e5bd7495f2b28b308d5c60be79a12cad62a51.PTauHQMBMjUSr568VuYHadpA4ZX-N6UYQglxx9H9DcI
+ hash: v1.k794b7964.e26938f89580b8d8e81634fa132996e641a6e2103000afc6974ba375c1eb9fec.s5ylCarArJTgBD8I_NaMIvDT-Pea2UvH8dOYHT1Qf0Y
filters-action-filter--trends-group-custom-name--light:
- hash: v1.k794b7964.d75de8e27c4186a9c958c87ab1fc9bd283db6a939347d36114406ee0273d5c32.ksBDJbiigRaMCsrcm2zYn3pwr2iB_8MbuFIqIRE-Ozc
+ hash: v1.k794b7964.09e935ae68f638b07c6327d8acd47c12b97302c862ab37f1a67f46dd906f98c7.IRLzAUoxKA17LrLb4q_RI9MpWkz8PPAqJesN_iJPuCk
filters-action-filter--trends-group-custom-name-hog-ql--dark:
- hash: v1.k794b7964.01542d41281f63b76ffab8a4906a1907f474305221fd0a1f8ff3b9f4ea924d2e.2bYsN2Whvjn4IyXTAtrRfL6AL6Doh8zjiTXm1e5ZQcs
+ hash: v1.k794b7964.9b329c539962881fb5bda8156506c5a7de748d9e03828accf1549318021c0f49.kafOnNLZTqbyoklrOT68jnFBNrYzaLWiWyV2NO4epY0
filters-action-filter--trends-group-custom-name-hog-ql--light:
- hash: v1.k794b7964.835530ff6d8fc0b9dda1020e902dd35d72c1f6e54f7558092c7b05302d152509.DjB70pPI81NG24AE1bJKH-A0wFjGKramigfb3e6cqBw
+ hash: v1.k794b7964.bfe820c21b0bfb08f294f67f385ef41e8fad0efdb3b3add933ef22ab2f75af6a.m28Kd7wRuI2kBl3u9UfDt6rse_ul81uQLHBkyT9WgRM
filters-action-filter--trends-group-default-name--dark:
- hash: v1.k794b7964.7451502088d8b62b19058cd57865796ad9d1bbdc4ba48ca12483da5c6e84e0ff.MkVbYhq3R-SurJprzGyUw49HuRehdOZ2fsrLQ3HMv_g
+ hash: v1.k794b7964.2b6dde742db89d0e7fbd5c8ffeb23f38ae316082c8bf2352c72e5100de50cc87.r3TQlNy7TQ1rdDKky6EJy_GdwibKw3BeFECsAE2x0aE
filters-action-filter--trends-group-default-name--light:
- hash: v1.k794b7964.d55d1c92f178d0f7df16460853804d70e93dfebfc29ad814da3abbdd03ee8298.IKpPCunPGq5fdMUPywrwOwO4YzHkWem6_CsNq5pNkqc
+ hash: v1.k794b7964.5e5d946ed22e89d22d1269dde072b8c3a48c1f97cfdedd25de26be794928d900.SHP9XLtRdca840_rtevrfzqL6EDSXySho2I7_f0TgUo
filters-breakdown-tag--breakdown-tag--dark:
hash: v1.k794b7964.41cf3b8b090e93c567b1b61054967987677a27a1c471ed4287ca39080c58205f.4Cd4O_Mgx2Jwe2xwc4s9hm8w6lsWPFSDR3fxYbDjOPk
filters-breakdown-tag--breakdown-tag--light:
diff --git a/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx b/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx
index 3abeea60a7c8..3f80e0aaf3be 100644
--- a/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx
@@ -2,7 +2,7 @@ import clsx from 'clsx'
import { KeyboardEvent, MutableRefObject, useCallback, useEffect, useRef, useState } from 'react'
import { IconSend, IconTrash } from '@posthog/icons'
-import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'
+import { LemonButton } from '@posthog/lemon-ui'
import { getNotebookStringProp, isPromptComponentNode } from './documentModel'
import { RestoreSelectionRequest } from './editorTypes'
@@ -118,6 +118,14 @@ export function EditablePromptComponent({
}
const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>): void => {
+ event.stopPropagation()
+
+ if (event.key === 'Enter' && !event.nativeEvent.isComposing && !event.shiftKey) {
+ event.preventDefault()
+ submitPrompt(event.currentTarget.value)
+ return
+ }
+
if (event.key === 'Backspace' || event.key === 'Delete') {
const selectionStart = event.currentTarget.selectionStart ?? 0
const selectionEnd = event.currentTarget.selectionEnd ?? selectionStart
@@ -181,21 +189,20 @@ export function EditablePromptComponent({
</div>
{isCollapsed ? null : (
<div className="MarkdownNotebook__ai-prompt-form">
- <LemonTextArea
+ <textarea
ref={setElementRef}
className="MarkdownNotebook__ai-prompt-input MarkdownNotebook__text-block--ai-prompt"
data-attr="markdown-notebook-ai-prompt"
value={question}
- onChange={updateQuestion}
- onPressEnter={submitPrompt}
+ onChange={(event) => {
+ event.stopPropagation()
+ updateQuestion(event.currentTarget.value)
+ }}
onKeyDown={handleKeyDown}
placeholder=""
- minRows={1}
- maxRows={6}
autoFocus={isActive}
- stopPropagation
- hideFocus
disabled={mode !== 'edit'}
+ rows={1}
/>
<LemonButton
type="primary"
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
index 69583aaf106d..77a52ab45375 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
@@ -798,8 +798,10 @@
.MarkdownNotebook__ai-prompt-form textarea.MarkdownNotebook__ai-prompt-input {
display: block;
height: auto;
- overflow: hidden;
+ overflow-y: auto;
text-overflow: clip;
+ /* stylelint-disable-next-line property-no-unknown -- Native textarea autosizing in supported browsers. */
+ field-sizing: content;
}
.MarkdownNotebook__ai-prompt-input:focus {
@@ -2018,6 +2020,14 @@ button.MarkdownNotebook__component-title:focus-visible {
gap: 0.375rem;
}
+.MarkdownNotebook__discussion-comment-input {
+ max-height: calc(1.4em * 6 + 1rem);
+ overflow-y: auto;
+ resize: none;
+ /* stylelint-disable-next-line property-no-unknown -- Native textarea autosizing in supported browsers. */
+ field-sizing: content;
+}
+
.MarkdownNotebook__discussion-comment-actions {
display: flex;
gap: 0.375rem;
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index 11fe5d932243..7a179c4822de 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -1946,6 +1946,46 @@ Tail paragraph`
expect(unmountComponent).not.toHaveBeenCalled()
})
+ it('does not re-render unchanged components when local edits receive a fresh empty AI writing index list', () => {
+ const renderComponent = jest.fn()
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Embed',
+ label: 'Embed',
+ category: 'Media',
+ ViewComponent: ({ node }) => {
+ renderComponent(node.props.src)
+ return createElement('div', { 'data-testid': 'stable-embed' })
+ },
+ },
+ ])
+ const initialMarkdown = `${TEST_NOTEBOOK_TITLE_MARKDOWN}
+
+Intro paragraph
+
+<Embed src="https://posthog.com" />
+
+<Embed src="https://example.com" />`
+
+ function NotebookWrapper(): JSX.Element {
+ const [value, setValue] = useState(initialMarkdown)
+ return createElement(MarkdownNotebook, {
+ value,
+ onChange: setValue,
+ registry,
+ aiWritingNodeIndexes: [],
+ })
+ }
+
+ const { container } = render(createElement(NotebookWrapper))
+ const renderCountBeforeEdit = renderComponent.mock.calls.length
+ expect(renderCountBeforeEdit).toBeGreaterThan(0)
+
+ updateContentEditableText(getBodyTextBlock(container), 'Updated paragraph')
+
+ expect(renderComponent).toHaveBeenCalledTimes(renderCountBeforeEdit)
+ })
+
it('keeps rendering other components when one component panel crashes', () => {
expect.hasAssertions()
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 0432892ebfb8..2bcbf108439b 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -211,7 +211,7 @@ import {
NotebookTextBlockNode,
NotebookTextSelectionRange,
} from './types'
-import { cloneNotebookNode, getInlineText, normalizeInlineNodes } from './utils'
+import { cloneNotebookNode, getInlineText, getNodeFingerprint, normalizeInlineNodes } from './utils'
export type MarkdownNotebookProps = {
value: string
@@ -262,6 +262,7 @@ export type MarkdownNotebookAskAIRequest = {
type CommitDocumentOptions = {
addToHistory?: boolean
+ historyOperations?: NotebookOperation[]
/** Set when the commit applies a remote merge: the notebook version being merged in.
* Remote caret pings already at this version reflect the change and must not be remapped. */
remoteMergeVersion?: number
@@ -297,6 +298,7 @@ const UNDO_TYPING_GROUP_MS = 1000
/** How many recent local serializations to remember for save-echo detection. Must comfortably
* cover the keystrokes that can land between a save being sent and its response echoing back. */
const MAX_TRACKED_LOCAL_SNAPSHOTS = 100
+const EMPTY_AI_WRITING_NODE_INDEX_SET = new Set<number>()
function createDefaultAIConversationId(): string {
if (typeof window !== 'undefined' && window.crypto?.randomUUID) {
@@ -339,6 +341,55 @@ function getLatestEmptyAIPromptNodeId(nodes: NotebookBlockNode[]): string | null
return null
}
+function getComponentNodeUpdateHistoryOperations(
+ nodes: NotebookBlockNode[],
+ index: number,
+ previousNode: NotebookBlockNode,
+ nextNode: NotebookBlockNode | null
+): NotebookOperation[] | undefined {
+ if (previousNode.type !== 'component' && nextNode?.type !== 'component') {
+ return undefined
+ }
+
+ const previousAfterId = index === 0 ? null : (nodes[index - 1]?.id ?? null)
+ if (!nextNode) {
+ return [{ type: 'insert_block', afterId: previousAfterId, node: cloneNotebookNode(previousNode) }]
+ }
+
+ if (
+ previousNode.type === 'component' &&
+ nextNode.type === 'component' &&
+ areComponentNodesEquivalent(previousNode, nextNode)
+ ) {
+ return []
+ }
+
+ if (previousNode.id === nextNode.id) {
+ return [{ type: 'replace_block', nodeId: previousNode.id, node: cloneNotebookNode(previousNode) }]
+ }
+
+ return [
+ { type: 'delete_block', nodeId: nextNode.id },
+ { type: 'insert_block', afterId: previousAfterId, node: cloneNotebookNode(previousNode) },
+ ]
+}
+
+function areComponentNodesEquivalent(
+ previousNode: NotebookComponentBlockNode,
+ nextNode: NotebookComponentBlockNode
+): boolean {
+ return (
+ previousNode.id === nextNode.id &&
+ previousNode.raw === nextNode.raw &&
+ getNodeFingerprint(previousNode) === getNodeFingerprint(nextNode) &&
+ componentNodeErrorsKey(previousNode) === componentNodeErrorsKey(nextNode)
+ )
+}
+
+function componentNodeErrorsKey(node: NotebookComponentBlockNode): string {
+ return node.errors?.join('\n') ?? ''
+}
+
/** A debug recording session: JSONL entries downloaded as a .log file on stop. */
type NotebookDebugLog = {
startedAt: number
@@ -500,7 +551,10 @@ export function MarkdownNotebook({
}, [])
const hasDiscussionComments = useMemo(() => document.nodes.some(isDiscussionCommentNode), [document])
- const aiWritingNodeIndexSet = useMemo(() => new Set(aiWritingNodeIndexes ?? []), [aiWritingNodeIndexes])
+ const aiWritingNodeIndexSet = useMemo(
+ () => (aiWritingNodeIndexes?.length ? new Set(aiWritingNodeIndexes) : EMPTY_AI_WRITING_NODE_INDEX_SET),
+ [aiWritingNodeIndexes]
+ )
useLayoutEffect(() => {
const element = mainRef.current
@@ -873,8 +927,12 @@ export function MarkdownNotebook({
}, [])
const pushHistoryEntry = useCallback(
- (previousDocument: NotebookDocument, nextDocument: NotebookDocument): void => {
- const inverseOps = diffNotebookDocuments(nextDocument, previousDocument)
+ (
+ previousDocument: NotebookDocument,
+ nextDocument: NotebookDocument,
+ historyOperations?: NotebookOperation[]
+ ): void => {
+ const inverseOps = historyOperations ?? diffNotebookDocuments(nextDocument, previousDocument)
if (!inverseOps.length) {
return
}
@@ -927,7 +985,7 @@ export function MarkdownNotebook({
const editableDocument = ensureEditableNotebookDocument(nextDocument)
const previousDocument = documentRef.current
if (options.addToHistory ?? true) {
- pushHistoryEntry(previousDocument, editableDocument)
+ pushHistoryEntry(previousDocument, editableDocument, options.historyOperations)
}
// Rendered remote carets ride along with the text they sit in.
mapRemoteCaretAnchors(previousDocument, editableDocument, options.remoteMergeVersion)
@@ -2210,19 +2268,30 @@ export function MarkdownNotebook({
const currentDocument = documentRef.current
const nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]
let didUpdate = false
- const nextNodes = nodes.flatMap((node) => {
+ let historyOperations: NotebookOperation[] | undefined
+ const nextNodes = nodes.flatMap((node, index) => {
if (didUpdate || node.id !== nodeId) {
return [node]
}
didUpdate = true
const updatedNode = updater(cloneNotebookNode(node))
+ historyOperations = getComponentNodeUpdateHistoryOperations(nodes, index, node, updatedNode)
return updatedNode ? [updatedNode] : []
})
- commitDocument({
- ...currentDocument,
- nodes: nextNodes,
- })
+ if (!didUpdate) {
+ return
+ }
+
+ commitDocument(
+ {
+ ...currentDocument,
+ nodes: nextNodes,
+ },
+ {
+ historyOperations,
+ }
+ )
},
[commitDocument]
)
@@ -4006,7 +4075,7 @@ export function MarkdownNotebook({
return false
},
- [insertMenu]
+ []
)
const moveFocusToAdjacentTableCell = useCallback(
@@ -5155,22 +5224,25 @@ export function MarkdownNotebook({
rememberedComponentPanels: componentPanelCacheEntry?.remembered,
persistComponentPanelVisibility,
isSelected: selectedComponentNodeIds.has(node.id),
- toggleComponentPanel: (panel) =>
+ toggleComponentPanel: (panel) => {
+ const nextPanels = {
+ ...nodeComponentPanels,
+ [panel]: !nodeComponentPanels[panel],
+ }
+
+ if (!persistComponentPanelVisibility) {
+ setLocalComponentPanels(node.id, nextPanels)
+ return
+ }
+
updateNode(node.id, (currentNode) => {
if (currentNode.type !== 'component') {
return currentNode
}
- const currentPanels = getComponentPanelVisibility(
- currentNode,
- DEFAULT_COMPONENT_PANEL_VISIBILITY
- )
- const nextPanels = {
- ...currentPanels,
- [panel]: !currentPanels[panel],
- }
return withPersistedComponentPanelProps(currentNode, componentDefinition, nextPanels)
- }),
+ })
+ },
setLocalComponentPanels,
rememberComponentPanels,
setBlockRef: (element) => {
diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx
new file mode 100644
index 000000000000..30c538fa4f26
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx
@@ -0,0 +1,103 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+
+import { useComponentPanelState } from './componentPanelContext'
+import { NotebookComponentShell } from './NotebookComponentShell'
+import { createMarkdownNotebookRegistry } from './registry'
+
+function PanelStateProbe(): JSX.Element {
+ const panelState = useComponentPanelState()
+
+ return (
+ <div data-attr="panel-state">
+ {panelState?.showEditPanel ? 'edit-open' : 'edit-closed'}{' '}
+ {panelState?.showViewPanel ? 'view-open' : 'view-closed'}
+ </div>
+ )
+}
+
+describe('NotebookComponentShell', () => {
+ it('provides markdown component panel state to rendered components', () => {
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Probe',
+ label: 'Probe',
+ category: 'Test',
+ ViewComponent: PanelStateProbe,
+ EditComponent: () => <div>Edit panel</div>,
+ },
+ ])
+
+ render(
+ <NotebookComponentShell
+ node={{
+ id: 'probe-node',
+ type: 'component',
+ tagName: 'Probe',
+ props: {},
+ }}
+ mode="edit"
+ componentPanels={{ filters: true, 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)}
+ />
+ )
+
+ expect(screen.getByTestId('panel-state').textContent).toBe('edit-open view-open')
+ })
+
+ it('prevents toolbar mouse down from changing notebook selection before toggling panels', () => {
+ const toggleComponentPanel = jest.fn()
+ const registry = createMarkdownNotebookRegistry([
+ {
+ tagName: 'Probe',
+ label: 'Probe',
+ category: 'Test',
+ ViewComponent: PanelStateProbe,
+ EditComponent: () => <div>Edit panel</div>,
+ },
+ ])
+
+ const { container } = render(
+ <NotebookComponentShell
+ node={{
+ id: 'probe-node',
+ type: 'component',
+ tagName: 'Probe',
+ props: {},
+ }}
+ mode="edit"
+ componentPanels={{ filters: true, results: true }}
+ persistComponentPanelVisibility={false}
+ 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 = container.querySelector('button[aria-label="Hide filters"]') as HTMLButtonElement
+
+ expect(fireEvent.mouseDown(filtersButton)).toBe(false)
+
+ fireEvent.click(filtersButton)
+
+ expect(toggleComponentPanel).toHaveBeenCalledWith('filters')
+ })
+})
diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
index 052fb16dc737..785bcc2e271a 100644
--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
@@ -1,10 +1,19 @@
import clsx from 'clsx'
-import { KeyboardEvent, ReactNode, memo, useState } from 'react'
+import {
+ KeyboardEvent,
+ MouseEvent as ReactMouseEvent,
+ PointerEvent as ReactPointerEvent,
+ ReactNode,
+ memo,
+ useMemo,
+ useState,
+} from 'react'
import { IconDatabase, IconEye, IconGraph, IconHide, IconList, IconPencil, IconPeople, IconTrash } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { PostHogErrorBoundary } from '@posthog/react'
+import { ComponentPanelContext } from './componentPanelContext'
import {
ComponentPanel,
ComponentPanelVisibility,
@@ -88,6 +97,14 @@ export function NotebookComponentShell({
'MarkdownNotebook__component-title',
`MarkdownNotebook__component-title--${titleDisplay.tone}`
)
+ const componentPanelState = useMemo(
+ () => ({
+ componentPanels,
+ showEditPanel,
+ showViewPanel,
+ }),
+ [componentPanels, showEditPanel, showViewPanel]
+ )
const titleContent = (
<>
{titleDisplay.icon ? (
@@ -188,6 +205,21 @@ export function NotebookComponentShell({
insertParagraphAfterNode()
}
}
+ const handleToolbarPointerDownCapture = (event: ReactPointerEvent<HTMLDivElement>): void => {
+ if (event.button !== 0) {
+ return
+ }
+
+ event.stopPropagation()
+ }
+ const handleToolbarMouseDownCapture = (event: ReactMouseEvent<HTMLDivElement>): void => {
+ if (event.button !== 0) {
+ return
+ }
+
+ event.preventDefault()
+ event.stopPropagation()
+ }
return (
<div
@@ -201,7 +233,11 @@ export function NotebookComponentShell({
tabIndex={mode === 'edit' ? 0 : undefined}
onKeyDown={handleKeyDown}
>
- <div className="MarkdownNotebook__component-toolbar">
+ <div
+ className="MarkdownNotebook__component-toolbar"
+ onPointerDownCapture={handleToolbarPointerDownCapture}
+ onMouseDownCapture={handleToolbarMouseDownCapture}
+ >
<div className="MarkdownNotebook__component-toolbar-left">
{canToggleComponentPanels ? (
<button
@@ -254,43 +290,45 @@ export function NotebookComponentShell({
</div>
) : null}
</div>
- {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}
- />
- </NotebookComponentPanelErrorBoundary>
- </div>
- ) : null}
- {showViewPanel ? (
- <div className="MarkdownNotebook__component-panel">
- {ViewComponent ? (
- <NotebookComponentPanelErrorBoundary node={node} panel="results">
- <ViewComponent
+ <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}
+ </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>
</div>
)
}
@@ -397,7 +435,8 @@ export function areNotebookComponentShellPropsEqual(
previousProps.componentPanels.results === nextProps.componentPanels.results &&
previousProps.rememberedComponentPanels?.filters === nextProps.rememberedComponentPanels?.filters &&
previousProps.rememberedComponentPanels?.results === nextProps.rememberedComponentPanels?.results &&
- getNodeFingerprint(previousProps.node) === getNodeFingerprint(nextProps.node)
+ (previousProps.node === nextProps.node ||
+ getNodeFingerprint(previousProps.node) === getNodeFingerprint(nextProps.node))
)
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/componentPanelContext.ts b/frontend/src/lib/components/MarkdownNotebook/componentPanelContext.ts
new file mode 100644
index 000000000000..126db4dacce5
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/componentPanelContext.ts
@@ -0,0 +1,15 @@
+import { createContext, useContext } from 'react'
+
+import { ComponentPanelVisibility } from './componentPanels'
+
+export type ComponentPanelState = {
+ componentPanels: ComponentPanelVisibility
+ showEditPanel: boolean
+ showViewPanel: boolean
+}
+
+export const ComponentPanelContext = createContext<ComponentPanelState | null>(null)
+
+export function useComponentPanelState(): ComponentPanelState | null {
+ return useContext(ComponentPanelContext)
+}
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
index 4d3ba0779c9c..840a04674c7e 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
@@ -96,6 +96,7 @@ const INLINE_TAG_NAMES = ['ref', 'mention'] as const
type InlineTagName = (typeof INLINE_TAG_NAMES)[number]
const INLINE_TAG_OPEN_REGEX = /^<(ref|mention)\s+id=(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')\s*>/
let generatedNodeIdCounter = 0
+const serializedNodeCache = new WeakMap<NotebookBlockNode, string>()
export function parseMarkdownNotebook(markdown: string | null | undefined): NotebookDocument {
const lines = (markdown ?? '').replace(/\r\n?/g, '\n').split('\n')
@@ -164,6 +165,17 @@ function isEmptyNotebookTitleNode(node: NotebookBlockNode | undefined): boolean
}
export function serializeNode(node: NotebookBlockNode): string {
+ const cachedValue = serializedNodeCache.get(node)
+ if (cachedValue !== undefined) {
+ return cachedValue
+ }
+
+ const serialized = serializeNodeUncached(node)
+ serializedNodeCache.set(node, serialized)
+ return serialized
+}
+
+function serializeNodeUncached(node: NotebookBlockNode): string {
if (node.type === 'heading') {
const [firstLine, ...followingLines] = serializeInlineNodes(node.children).split('\n')
return [`${'#'.repeat(node.level ?? 1)} ${firstLine}`, ...followingLines.map(escapeMarkdownLineStart)].join(
diff --git a/frontend/src/lib/components/MarkdownNotebook/remoteCarets.tsx b/frontend/src/lib/components/MarkdownNotebook/remoteCarets.tsx
index a6652231c347..6a1d9f018218 100644
--- a/frontend/src/lib/components/MarkdownNotebook/remoteCarets.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/remoteCarets.tsx
@@ -1,4 +1,4 @@
-import { MutableRefObject, RefObject, useLayoutEffect, useState } from 'react'
+import { MutableRefObject, RefObject, useEffect, useState } from 'react'
import {
findTextPosition,
@@ -229,7 +229,7 @@ export function RemoteCaretOverlay({
}): JSX.Element | null {
const [layouts, setLayouts] = useState<Record<string, RemoteCaretLayout>>({})
- useLayoutEffect(() => {
+ useEffect(() => {
const container = containerRef.current
if (!container) {
return
diff --git a/frontend/src/lib/components/MarkdownNotebook/utils.ts b/frontend/src/lib/components/MarkdownNotebook/utils.ts
index 657a8051b7c5..8e9247d3b640 100644
--- a/frontend/src/lib/components/MarkdownNotebook/utils.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/utils.ts
@@ -8,6 +8,8 @@ import {
NotebookPropValue,
} from './types'
+const nodeFingerprintCache = new WeakMap<NotebookBlockNode, string>()
+
export function hashString(value: string): string {
let hash = 5381
for (let index = 0; index < value.length; index++) {
@@ -106,6 +108,17 @@ export function getNodeSignature(node: NotebookBlockNode): string {
}
export function getNodeFingerprint(node: NotebookBlockNode): string {
+ const cachedFingerprint = nodeFingerprintCache.get(node)
+ if (cachedFingerprint !== undefined) {
+ return cachedFingerprint
+ }
+
+ const fingerprint = getUncachedNodeFingerprint(node)
+ nodeFingerprintCache.set(node, fingerprint)
+ return fingerprint
+}
+
+function getUncachedNodeFingerprint(node: NotebookBlockNode): string {
if (node.type === 'paragraph' || node.type === 'heading' || node.type === 'blockquote') {
return JSON.stringify({
type: node.type,
diff --git a/frontend/src/lib/lemon-ui/Tooltip/Tooltip.test.tsx b/frontend/src/lib/lemon-ui/Tooltip/Tooltip.test.tsx
new file mode 100644
index 000000000000..6cc8d23fb459
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/Tooltip/Tooltip.test.tsx
@@ -0,0 +1,63 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { Tooltip } from './Tooltip'
+
+describe('Tooltip', () => {
+ beforeEach(() => {
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ cleanup()
+ jest.useRealTimers()
+ })
+
+ it('does not mount Base UI trigger/root for idle uncontrolled tooltips', () => {
+ render(
+ <Tooltip title="Helpful context">
+ <button>Hover me</button>
+ </Tooltip>
+ )
+
+ const button = screen.getByRole('button', { name: 'Hover me' })
+
+ expect(button).not.toHaveAttribute('data-base-ui-tooltip-trigger')
+ expect(screen.queryByText('Helpful context')).not.toBeInTheDocument()
+
+ fireEvent.mouseEnter(button)
+ act(() => jest.advanceTimersByTime(399))
+
+ expect(button).not.toHaveAttribute('data-base-ui-tooltip-trigger')
+ expect(screen.queryByText('Helpful context')).not.toBeInTheDocument()
+
+ act(() => jest.advanceTimersByTime(1))
+
+ expect(screen.getByRole('button', { name: 'Hover me' })).toHaveAttribute('data-base-ui-tooltip-trigger')
+ expect(screen.getByText('Helpful context')).toBeInTheDocument()
+ })
+
+ it.each([
+ {
+ name: 'controlled',
+ props: { visible: false },
+ },
+ {
+ name: 'interactive',
+ props: { interactive: true },
+ },
+ {
+ name: 'doc link',
+ props: { docLink: 'https://posthog.com/docs' },
+ },
+ ])('mounts Base UI trigger/root immediately for $name tooltips', ({ props }) => {
+ render(
+ <Tooltip title="Helpful context" {...props}>
+ <button>Open me</button>
+ </Tooltip>
+ )
+
+ expect(screen.getByRole('button', { name: 'Open me' })).toHaveAttribute('data-base-ui-tooltip-trigger')
+ })
+})
diff --git a/frontend/src/lib/lemon-ui/Tooltip/Tooltip.tsx b/frontend/src/lib/lemon-ui/Tooltip/Tooltip.tsx
index 1cb13838bd97..09837795647f 100644
--- a/frontend/src/lib/lemon-ui/Tooltip/Tooltip.tsx
+++ b/frontend/src/lib/lemon-ui/Tooltip/Tooltip.tsx
@@ -2,7 +2,7 @@ import './Tooltip.scss'
import { Tooltip as BaseTooltip } from '@base-ui/react/tooltip'
import { Placement } from '@floating-ui/react'
-import React, { useEffect, useLayoutEffect, useState } from 'react'
+import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { IconInfo } from '@posthog/icons'
@@ -41,6 +41,11 @@ interface BaseTooltipProps {
* Run a function when showing the tooltip, for example to log an event.
*/
onOpen?: () => void
+ /**
+ * Closed, uncontrolled tooltips are common in large lists and toolbars. Lazy mounting keeps
+ * Base UI's root/trigger machinery out of idle render paths.
+ */
+ lazy?: boolean
}
export type RequiredTooltipProps = (
@@ -78,6 +83,16 @@ function placementToSideAlign(placement: Placement): { side: Side; align: Align
return { side, align }
}
+function composeEventHandlers<Event extends React.SyntheticEvent>(
+ currentHandler: ((event: Event) => void) | undefined,
+ nextHandler: (event: Event) => void
+): (event: Event) => void {
+ return (event: Event) => {
+ currentHandler?.(event)
+ nextHandler(event)
+ }
+}
+
export function Tooltip({
children,
title,
@@ -93,12 +108,119 @@ export function Tooltip({
docLink,
containerClassName,
onOpen,
+ lazy = true,
}: React.PropsWithChildren<RequiredTooltipProps>): JSX.Element {
const [uncontrolledOpen, setUncontrolledOpen] = useState(false)
- const [shouldRenderPortal, setShouldRenderPortal] = useState(false)
- const floatingContainer = useFloatingContainer()
+ const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
const open = controlledOpen ?? uncontrolledOpen
+ const child = React.isValidElement(children) ? children : <span>{children}</span>
+
+ const isInteractive = interactive || !!docLink
+ const useLazyMount = !!(title || docLink) && lazy && controlledOpen === undefined && !isInteractive
+
+ const clearOpenTimer = useCallback((): void => {
+ if (openTimer.current) {
+ clearTimeout(openTimer.current)
+ openTimer.current = null
+ }
+ }, [])
+
+ const queueOpen = useCallback((): void => {
+ clearOpenTimer()
+
+ if (delayMs <= 0) {
+ setUncontrolledOpen(true)
+ return
+ }
+
+ openTimer.current = setTimeout(() => {
+ openTimer.current = null
+ setUncontrolledOpen(true)
+ }, delayMs)
+ }, [clearOpenTimer, delayMs])
+
+ const cancelQueuedOpen = useCallback((): void => {
+ clearOpenTimer()
+ }, [clearOpenTimer])
+
+ useEffect(() => clearOpenTimer, [clearOpenTimer])
+
+ const handleOpenChange = useCallback(
+ (newOpen: boolean): void => {
+ if (controlledOpen === undefined) {
+ setUncontrolledOpen(newOpen)
+ }
+ },
+ [controlledOpen]
+ )
+
+ if (!title && !docLink) {
+ return <>{child}</>
+ }
+
+ if (useLazyMount && !open) {
+ const childProps = child.props as React.HTMLAttributes<HTMLElement>
+
+ return (
+ <>
+ {React.cloneElement(child, {
+ onMouseEnter: composeEventHandlers(childProps.onMouseEnter, queueOpen),
+ onMouseLeave: composeEventHandlers(childProps.onMouseLeave, cancelQueuedOpen),
+ onFocus: composeEventHandlers(childProps.onFocus, queueOpen),
+ onBlur: composeEventHandlers(childProps.onBlur, cancelQueuedOpen),
+ })}
+ </>
+ )
+ }
+
+ return (
+ <MountedTooltip
+ title={title}
+ className={className}
+ placement={placement}
+ fallbackPlacements={fallbackPlacements}
+ offset={offset}
+ arrowOffset={arrowOffset}
+ delayMs={delayMs}
+ closeDelayMs={closeDelayMs}
+ interactive={interactive}
+ docLink={docLink}
+ containerClassName={containerClassName}
+ onOpen={onOpen}
+ open={open}
+ onOpenChange={handleOpenChange}
+ child={child}
+ />
+ )
+}
+
+interface MountedTooltipProps extends Omit<BaseTooltipProps, 'visible' | 'lazy'> {
+ title?: TooltipTitle
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ child: React.ReactElement
+}
+
+function MountedTooltip({
+ child,
+ title,
+ className = '',
+ placement = 'top',
+ fallbackPlacements,
+ offset,
+ arrowOffset,
+ delayMs = 400,
+ closeDelayMs = 0,
+ interactive = false,
+ docLink,
+ containerClassName,
+ onOpen,
+ open,
+ onOpenChange,
+}: MountedTooltipProps): JSX.Element {
+ const [shouldRenderPortal, setShouldRenderPortal] = useState(false)
+ const floatingContainer = useFloatingContainer()
useLayoutEffect(() => {
if (open) {
@@ -119,14 +241,8 @@ export function Tooltip({
}
}, [open, onOpen])
- const child = React.isValidElement(children) ? children : <span>{children}</span>
-
- if (!title && !docLink) {
- return <>{child}</>
- }
-
const isInteractive = interactive || !!docLink
- const resolvedOffset = offset ?? (isInfoIconTrigger(children) ? INFO_ICON_OFFSET : DEFAULT_OFFSET)
+ const resolvedOffset = offset ?? (isInfoIconTrigger(child) ? INFO_ICON_OFFSET : DEFAULT_OFFSET)
const { side, align } = placementToSideAlign(placement)
const collisionAvoidance = fallbackPlacements
@@ -141,14 +257,8 @@ export function Tooltip({
fallbackAxisSide: 'start' as const,
}
- const handleOpenChange = (newOpen: boolean): void => {
- if (controlledOpen === undefined) {
- setUncontrolledOpen(newOpen)
- }
- }
-
return (
- <BaseTooltip.Root open={open} onOpenChange={handleOpenChange} disableHoverablePopup={!isInteractive}>
+ <BaseTooltip.Root open={open} onOpenChange={onOpenChange} disableHoverablePopup={!isInteractive}>
<BaseTooltip.Trigger delay={delayMs} closeDelay={closeDelayMs} render={child} />
{shouldRenderPortal && (
<BaseTooltip.Portal container={floatingContainer ?? undefined}>
diff --git a/frontend/src/lib/monaco/hogQLAutocompleteProvider.test.ts b/frontend/src/lib/monaco/hogQLAutocompleteProvider.test.ts
new file mode 100644
index 000000000000..8d8a2de00630
--- /dev/null
+++ b/frontend/src/lib/monaco/hogQLAutocompleteProvider.test.ts
@@ -0,0 +1,45 @@
+import { hogQLAutocompleteProvider } from 'lib/monaco/hogQLAutocompleteProvider'
+
+import { performQuery } from '~/queries/query'
+import { HogLanguage } from '~/queries/schema/schema-general'
+
+jest.mock('~/queries/query', () => ({
+ performQuery: jest.fn(),
+}))
+
+describe('hogQLAutocompleteProvider', () => {
+ beforeEach(() => {
+ jest.mocked(performQuery).mockReset()
+ })
+
+ it('returns an empty completion list when the autocomplete query fails', async () => {
+ jest.mocked(performQuery).mockRejectedValueOnce(new Error("trailing tokens after expression: 'is'"))
+ const provider = hogQLAutocompleteProvider(HogLanguage.hogQL)
+ const model = {
+ codeEditorLogic: {
+ isMounted: () => true,
+ props: {},
+ },
+ getOffsetAt: ({ column }: { column: number }) => column - 1,
+ getValue: () => 'select event is',
+ getWordUntilPosition: () => ({
+ word: 'is',
+ startColumn: 14,
+ endColumn: 16,
+ }),
+ }
+
+ const result = await provider.provideCompletionItems?.(
+ model as any,
+ { lineNumber: 1, column: 16 } as any,
+ {} as any,
+ {} as any
+ )
+
+ expect(result).toEqual({
+ suggestions: [],
+ incomplete: false,
+ })
+ expect(performQuery).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/lib/monaco/hogQLAutocompleteProvider.ts b/frontend/src/lib/monaco/hogQLAutocompleteProvider.ts
index 484a2fca0734..97ba525b6303 100644
--- a/frontend/src/lib/monaco/hogQLAutocompleteProvider.ts
+++ b/frontend/src/lib/monaco/hogQLAutocompleteProvider.ts
@@ -87,15 +87,17 @@ const kindToSortText = (kind: AutocompleteCompletionItemKind, label: string): st
return `3-${label}`
}
+const emptyCompletionList = (): languages.CompletionList => ({
+ suggestions: [],
+ incomplete: false,
+})
+
export const hogQLAutocompleteProvider = (type: HogLanguage): languages.CompletionItemProvider => ({
triggerCharacters: [' ', ',', '.', '{'],
provideCompletionItems: async (model, position) => {
const logic: BuiltLogic<codeEditorLogicType> | undefined = (model as any).codeEditorLogic
if (!logic || !logic.isMounted()) {
- return {
- suggestions: [],
- incomplete: false,
- }
+ return emptyCompletionList()
}
const word = model.getWordUntilPosition(position)
const startOffset = model.getOffsetAt({
@@ -128,7 +130,13 @@ export const hogQLAutocompleteProvider = (type: HogLanguage): languages.Completi
},
{ recursion: false }
)
- const response = await performQuery<HogQLAutocomplete>(query)
+ let response: NonNullable<HogQLAutocomplete['response']>
+ try {
+ response = await performQuery<HogQLAutocomplete>(query)
+ } catch {
+ return emptyCompletionList()
+ }
+
const completionItems = response.suggestions
const suggestions = completionItems.map<languages.CompletionItem>((item) => {
const kind = convertCompletionItemKind(item.kind)
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index 39e78b7965d9..8d6f9db96463 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -1119,7 +1119,7 @@ const Content = ({
}
return (
- <div className="flex-1 absolute inset-0 hide-scrollbar border-t overflow-auto">
+ <div className="absolute inset-0 flex flex-col hide-scrollbar border-t overflow-auto">
<SyncWarningsBanner warnings={response?.warnings} />
<InternalDataTableVisualization
uniqueKey={vizKey}
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
index 9b872aaaba30..cea3906ad044 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
@@ -1,7 +1,7 @@
import { Monaco } from '@monaco-editor/react'
import { useActions, useValues } from 'kea'
import type { editor as importedEditor } from 'monaco-editor'
-import { memo, useMemo } from 'react'
+import { memo, useCallback, useMemo, useRef } from 'react'
import { IconDatabase, IconGear, IconInfo, IconPlayFilled, IconSidebarClose } from '@posthog/icons'
import { LemonDivider } from '@posthog/lemon-ui'
@@ -9,6 +9,7 @@ import { LemonDivider } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { IconCancel } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -35,6 +36,8 @@ import { QueryPane } from './QueryPane'
import { QueryVariablesMenu } from './QueryVariablesMenu'
import { sqlEditorLogic, tabModelPath } from './sqlEditorLogic'
+const EMBEDDED_MAX_TOOL_CONTEXT_DEBOUNCE_MS = 150
+
interface QueryWindowProps {
onSetMonacoAndEditor: (monaco: Monaco, editor: importedEditor.IStandaloneCodeEditor) => void
tabId: string
@@ -100,6 +103,61 @@ export function QueryWindow({
const { setEditorVimModeEnabled } = useActions(userPreferencesLogic)
const { isDatabaseTreeCollapsed } = useValues(editorSizingLogic)
const canSendRawQuery = !!selectedConnectionId
+ const debouncedMaxToolQueryInput = useDebouncedValue(queryInput, EMBEDDED_MAX_TOOL_CONTEXT_DEBOUNCE_MS)
+ const debouncedMaxToolSourceQuery = useDebouncedValue(sourceQuery, EMBEDDED_MAX_TOOL_CONTEXT_DEBOUNCE_MS)
+ const executeSqlToolStateRef = useRef({ queryInput, sourceQuery })
+ executeSqlToolStateRef.current = { queryInput, sourceQuery }
+ const executeSqlToolContext = useMemo(
+ () => getExecuteSqlToolContext(debouncedMaxToolQueryInput, debouncedMaxToolSourceQuery),
+ [debouncedMaxToolQueryInput, debouncedMaxToolSourceQuery]
+ )
+ const executeSqlToolContextDescription = useMemo(
+ () => ({
+ text: 'Current query',
+ icon: iconForType('sql_editor'),
+ }),
+ []
+ )
+ const executeSqlToolIntroOverride = useMemo(
+ () => ({
+ headline: 'What data do you want to analyze?',
+ description: 'Let me help you quickly write SQL, and tweak it.',
+ }),
+ []
+ )
+ const executeSqlToolSuggestions = useMemo(() => [], [])
+ const handleExecuteSqlToolOutput = useCallback(
+ (toolOutput: unknown) => {
+ const { queryInput, sourceQuery } = executeSqlToolStateRef.current
+ applyExecuteSqlToolOutput({
+ toolOutput,
+ queryInput,
+ sourceQuery,
+ setSourceQuery,
+ setSuggestedQueryInput,
+ })
+ },
+ [setSourceQuery, setSuggestedQueryInput]
+ )
+ const executeSqlMaxToolProps = useMemo(
+ () => ({
+ identifier: 'execute_sql' as const,
+ context: executeSqlToolContext,
+ contextDescription: executeSqlToolContextDescription,
+ callback: handleExecuteSqlToolOutput,
+ suggestions: executeSqlToolSuggestions,
+ onMaxOpen: reportAIQueryPromptOpen,
+ introOverride: executeSqlToolIntroOverride,
+ }),
+ [
+ executeSqlToolContext,
+ executeSqlToolContextDescription,
+ executeSqlToolIntroOverride,
+ executeSqlToolSuggestions,
+ handleExecuteSqlToolOutput,
+ reportAIQueryPromptOpen,
+ ]
+ )
const sendRawQueryLabel = (
<span className="inline-flex items-center gap-1">
<span>Send raw query</span>
@@ -214,31 +272,7 @@ export function QueryWindow({
{mode === SQLEditorMode.Embedded && (
<SceneTitlePanelButton
buttonClassName="size-[26px]"
- maxToolProps={{
- identifier: 'execute_sql',
- context: getExecuteSqlToolContext(queryInput, sourceQuery),
- contextDescription: {
- text: 'Current query',
- icon: iconForType('sql_editor'),
- },
- callback: (toolOutput: unknown) => {
- applyExecuteSqlToolOutput({
- toolOutput,
- queryInput,
- sourceQuery,
- setSourceQuery,
- setSuggestedQueryInput,
- })
- },
- suggestions: [],
- onMaxOpen: () => {
- reportAIQueryPromptOpen()
- },
- introOverride: {
- headline: 'What data do you want to analyze?',
- description: 'Let me help you quickly write SQL, and tweak it.',
- },
- }}
+ maxToolProps={executeSqlMaxToolProps}
/>
)}
</div>
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index 8054d5641e47..53d5d5061370 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -52,6 +52,8 @@ export enum SQLEditorPanel {
Output = 'output',
}
+const VARIABLE_QUERY_SYNC_DEBOUNCE_MS = 150
+
interface SQLEditorProps {
tabId?: string
mode?: SQLEditorMode
@@ -96,6 +98,7 @@ export function SQLEditor({
const showOutputPanel = panel !== SQLEditorPanel.Query
const showSceneTitle = panel === SQLEditorPanel.Full && mode === SQLEditorMode.FullScene
const showDatabaseTreePanel = showQueryPanel && shouldShowDatabaseTree
+ const showFullSceneModals = mode === SQLEditorMode.FullScene
const editorSizingLogicProps = useMemo(
() => ({
@@ -210,7 +213,7 @@ export function SQLEditor({
<BindLogic logic={variableModalLogic} props={{ key: dataVisualizationLogicProps.key }}>
<BindLogic logic={outputPaneLogic} props={{ tabId }}>
<BindLogic logic={sqlEditorLogic} props={{ tabId, mode, monaco, editor }}>
- <VariablesQuerySync />
+ {showQueryPanel ? <VariablesQuerySync /> : null}
{panel === SQLEditorPanel.Output ? (
<div className="flex h-full min-h-0 flex-col overflow-hidden">
<OutputPane
@@ -257,9 +260,13 @@ export function SQLEditor({
</div>
</BindLogic>
)}
- <MaterializationModal tabId={tabId || ''} />
- <AccessControlModal />
- {!mode || mode === SQLEditorMode.FullScene ? <ViewLinkModal /> : null}
+ {showFullSceneModals ? (
+ <>
+ <MaterializationModal tabId={tabId || ''} />
+ <AccessControlModal />
+ <ViewLinkModal />
+ </>
+ ) : null}
</BindLogic>
</BindLogic>
</BindLogic>
@@ -676,7 +683,9 @@ function VariablesQuerySync(): null {
const { setEditorQuery } = useActions(variablesLogic)
useEffect(() => {
- setEditorQuery(queryInput ?? '')
+ const timeout = window.setTimeout(() => setEditorQuery(queryInput ?? ''), VARIABLE_QUERY_SYNC_DEBOUNCE_MS)
+
+ return () => window.clearTimeout(timeout)
}, [queryInput, setEditorQuery])
return null
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 0fbf5471cf66..182001d4acd9 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -165,6 +165,30 @@ function renderQueryOutline(editorInstance: editor.IStandaloneCodeEditor, node:
node.style.height = `${maxBottom - minTop + padY * 2}px`
}
+function clearQueryOutlineOverlay(
+ cache: sqlEditorLogicType['cache'],
+ fallbackEditor?: editor.IStandaloneCodeEditor | null
+): void {
+ cache.scrollDisposable?.dispose()
+ cache.scrollDisposable = null
+ cache.layoutDisposable?.dispose()
+ cache.layoutDisposable = null
+
+ if (cache.queryOutlineWidget) {
+ try {
+ ;(cache.queryOutlineEditor ?? fallbackEditor)?.removeOverlayWidget(cache.queryOutlineWidget)
+ } catch (e) {
+ console.warn('[sqlEditorLogic] failed to remove outline overlay widget', e)
+ }
+ }
+
+ cache.queryOutlineWidget = null
+ cache.queryOutlineEditor = null
+ cache.queryOutlineNode = null
+ cache.queryOutlineRange = null
+ cache.updateQueryOutline = null
+}
+
export const NEW_QUERY = 'Untitled'
export interface QueryTab {
@@ -601,7 +625,15 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
closeAccessControlModal: true,
})),
propsChanged(({ actions, props, cache }, oldProps) => {
- if (!oldProps.monaco && !oldProps.editor && props.monaco && props.editor) {
+ if (oldProps.editor && oldProps.editor !== props.editor) {
+ clearQueryOutlineOverlay(cache, oldProps.editor)
+ }
+
+ if (
+ (!oldProps.monaco || !oldProps.editor || oldProps.editor !== props.editor) &&
+ props.monaco &&
+ props.editor
+ ) {
actions.initialize()
// Listen for cursor position changes to update the active query highlight.
@@ -625,15 +657,18 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
outlineNode.className = 'active-query-outline'
outlineNode.style.position = 'absolute'
outlineNode.style.display = 'none'
+ clearQueryOutlineOverlay(cache, editorInstance)
const outlineWidget: editor.IOverlayWidget = {
- getId: () => 'sql-editor.active-query-outline',
+ getId: () => `sql-editor.active-query-outline.${props.tabId || 'default'}`,
getDomNode: () => outlineNode,
// Returning `null` keeps the widget unanchored — we drive its position
// manually via inline `top`/`left` styles set in `renderQueryOutline`.
getPosition: () => null,
}
+ editorInstance.removeOverlayWidget(outlineWidget)
editorInstance.addOverlayWidget(outlineWidget)
cache.queryOutlineWidget = outlineWidget
+ cache.queryOutlineEditor = editorInstance
cache.queryOutlineNode = outlineNode
cache.updateQueryOutline = (range: IRange | null): void => {
@@ -2647,21 +2682,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
beforeUnmount(({ cache, props }) => {
cache.cursorDisposable?.dispose()
cache.cursorDisposable = null
- cache.scrollDisposable?.dispose()
- cache.scrollDisposable = null
- cache.layoutDisposable?.dispose()
- cache.layoutDisposable = null
- if (cache.queryOutlineWidget && props.editor) {
- try {
- props.editor.removeOverlayWidget(cache.queryOutlineWidget)
- } catch (e) {
- console.warn('[sqlEditorLogic] failed to remove outline overlay widget', e)
- }
- }
- cache.queryOutlineWidget = null
- cache.queryOutlineNode = null
- cache.queryOutlineRange = null
- cache.updateQueryOutline = null
+ clearQueryOutlineOverlay(cache, props.editor)
cache.umountDataNode?.()
cache.umountDataNode = null
diff --git a/frontend/src/scenes/max/useMaxTool.test.tsx b/frontend/src/scenes/max/useMaxTool.test.tsx
new file mode 100644
index 000000000000..d1a3f9f6fc59
--- /dev/null
+++ b/frontend/src/scenes/max/useMaxTool.test.tsx
@@ -0,0 +1,48 @@
+import { cleanup, render } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import { maxGlobalLogic } from './maxGlobalLogic'
+import { useMaxTool } from './useMaxTool'
+
+function TestMaxTool({ context, active = true }: { context: Record<string, unknown>; active?: boolean }): null {
+ useMaxTool({
+ identifier: 'read_data',
+ context,
+ active,
+ })
+
+ return null
+}
+
+describe('useMaxTool', () => {
+ let logic: ReturnType<typeof maxGlobalLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = maxGlobalLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it('updates the registered tool context without deregistering between updates', () => {
+ const deregisterTool = jest.spyOn(logic.actions, 'deregisterTool')
+ const { rerender, unmount } = render(<TestMaxTool context={{ query: 'select 1' }} />)
+
+ expect(logic.values.registeredToolMap.read_data?.context).toEqual({ query: 'select 1' })
+
+ rerender(<TestMaxTool context={{ query: 'select 2' }} />)
+
+ expect(logic.values.registeredToolMap.read_data?.context).toEqual({ query: 'select 2' })
+ expect(deregisterTool).not.toHaveBeenCalled()
+
+ unmount()
+
+ expect(deregisterTool).toHaveBeenCalledWith('read_data')
+ })
+})
diff --git a/frontend/src/scenes/max/useMaxTool.ts b/frontend/src/scenes/max/useMaxTool.ts
index 271fb57d10f0..f45a2560c3e5 100644
--- a/frontend/src/scenes/max/useMaxTool.ts
+++ b/frontend/src/scenes/max/useMaxTool.ts
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import React, { useEffect } from 'react'
+import React, { useEffect, useMemo, useRef } from 'react'
import { IconWrench } from '@posthog/icons'
@@ -51,28 +51,39 @@ export function useMaxTool({
const definition = getToolDefinition(identifier)
const isMaxOpen = sidePanelOpen && selectedTab === SidePanelTab.Max
+ const activeIdentifierRef = useRef<string | null>(null)
+ const contextKey = useMemo(() => JSON.stringify(context), [context])
useEffect(() => {
- // Register/deregister tool
- if (active && definition) {
- registerTool({
- identifier,
- name: definition.name,
- description: definition.description,
- context,
- contextDescription,
- introOverride,
- suggestions,
- callback,
- clientExecution,
- })
- return (): void => deregisterTool(identifier)
+ if (!active || !definition) {
+ if (activeIdentifierRef.current) {
+ deregisterTool(activeIdentifierRef.current)
+ activeIdentifierRef.current = null
+ }
+ return
}
+
+ if (activeIdentifierRef.current && activeIdentifierRef.current !== identifier) {
+ deregisterTool(activeIdentifierRef.current)
+ }
+
+ activeIdentifierRef.current = identifier
+ registerTool({
+ identifier,
+ name: definition.name,
+ description: definition.description,
+ context,
+ contextDescription,
+ introOverride,
+ suggestions,
+ callback,
+ clientExecution,
+ })
}, [
active,
identifier,
definition,
- JSON.stringify(context), // oxlint-disable-line react-hooks/exhaustive-deps
+ contextKey,
contextDescription,
introOverride,
suggestions,
@@ -82,6 +93,15 @@ export function useMaxTool({
deregisterTool,
])
+ useEffect(() => {
+ return (): void => {
+ if (activeIdentifierRef.current) {
+ deregisterTool(activeIdentifierRef.current)
+ activeIdentifierRef.current = null
+ }
+ }
+ }, [deregisterTool])
+
return {
definition: active ? definition : null,
isMaxOpen,
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeContext.ts b/frontend/src/scenes/notebooks/Nodes/NotebookNodeContext.ts
index 80a85d8d5d36..ac1183bf5152 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeContext.ts
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeContext.ts
@@ -9,3 +9,12 @@ export const NotebookNodeContext = createContext<BuiltLogic<notebookNodeLogicTyp
export const useNotebookNode = (): BuiltLogic<notebookNodeLogicType> | undefined => {
return useContext(NotebookNodeContext)
}
+
+export const useRequiredNotebookNode = (): BuiltLogic<notebookNodeLogicType> => {
+ const nodeLogic = useNotebookNode()
+ if (!nodeLogic) {
+ throw new Error('Notebook node context is required')
+ }
+
+ return nodeLogic
+}
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.test.ts b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.test.ts
new file mode 100644
index 000000000000..52d7acfa57f3
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.test.ts
@@ -0,0 +1,73 @@
+import { getNotebookSqlOutputToolbarVisibility } from './NotebookNodeQuery'
+
+describe('NotebookNodeQuery', () => {
+ const markdownPanelState = ({
+ filters,
+ results,
+ }: {
+ filters: boolean
+ results: boolean
+ }): NonNullable<Parameters<typeof getNotebookSqlOutputToolbarVisibility>[0]['componentPanelState']> => ({
+ componentPanels: { filters, results },
+ showEditPanel: filters,
+ showViewPanel: results,
+ })
+
+ it('shows SQL output tabs only when markdown edit and view panels are both open', () => {
+ expect(
+ getNotebookSqlOutputToolbarVisibility({
+ componentPanelState: markdownPanelState({ filters: true, results: true }),
+ expanded: false,
+ isEditing: false,
+ })
+ ).toBe(true)
+
+ expect(
+ getNotebookSqlOutputToolbarVisibility({
+ componentPanelState: markdownPanelState({ filters: true, results: false }),
+ expanded: true,
+ isEditing: true,
+ })
+ ).toBe(false)
+
+ expect(
+ getNotebookSqlOutputToolbarVisibility({
+ componentPanelState: markdownPanelState({ filters: false, results: true }),
+ expanded: true,
+ isEditing: true,
+ })
+ ).toBe(false)
+
+ expect(
+ getNotebookSqlOutputToolbarVisibility({
+ componentPanelState: markdownPanelState({ filters: false, results: false }),
+ expanded: true,
+ isEditing: true,
+ })
+ ).toBe(false)
+ })
+
+ it('falls back to legacy expanded and editing state outside markdown notebooks', () => {
+ expect(
+ getNotebookSqlOutputToolbarVisibility({
+ componentPanelState: null,
+ expanded: true,
+ isEditing: true,
+ })
+ ).toBe(true)
+ expect(
+ getNotebookSqlOutputToolbarVisibility({
+ componentPanelState: null,
+ expanded: true,
+ isEditing: false,
+ })
+ ).toBe(false)
+ expect(
+ getNotebookSqlOutputToolbarVisibility({
+ componentPanelState: null,
+ expanded: false,
+ isEditing: true,
+ })
+ ).toBe(false)
+ })
+})
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx
index 5886028f3f88..dec05c8ba211 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx
@@ -1,9 +1,11 @@
-import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
+import { BindLogic, useActions, useValues } from 'kea'
import { useEffect, useMemo } from 'react'
import { LemonButton } from '@posthog/lemon-ui'
+import { useComponentPanelState } from 'lib/components/MarkdownNotebook/componentPanelContext'
import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
+import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { useSummarizeInsight } from 'scenes/insights/summarizeInsight'
@@ -32,10 +34,27 @@ import {
NotebookSQLEditorOutput,
NotebookSQLEditorSettings,
} from './components/NotebookSQLEditor'
-import { notebookNodeLogic } from './notebookNodeLogic'
+import { useRequiredNotebookNode } from './NotebookNodeContext'
import { UnsupportedNodePlaceholder } from './sharedNodeSupport'
import { SHORT_CODE_REGEX_MATCH_GROUPS } from './utils'
+type NotebookSqlOutputToolbarVisibilityProps = {
+ componentPanelState: ReturnType<typeof useComponentPanelState>
+ expanded: boolean
+ isEditing: boolean
+}
+
+export function getNotebookSqlOutputToolbarVisibility({
+ componentPanelState,
+ expanded,
+ isEditing,
+}: NotebookSqlOutputToolbarVisibilityProps): boolean {
+ const isOutputPaneOpen = componentPanelState?.showViewPanel ?? expanded
+ const isEditorPaneOpen = componentPanelState?.showEditPanel ?? isEditing
+
+ return isOutputPaneOpen && isEditorPaneOpen
+}
+
export const DEFAULT_QUERY: QuerySchema = {
kind: NodeKind.DataTableNode,
source: {
@@ -52,7 +71,7 @@ const Component = ({
updateAttributes,
}: NotebookNodeProps<NotebookNodeQueryAttributes>): JSX.Element | null => {
const { query, nodeId } = attributes
- const nodeLogic = useMountedLogic(notebookNodeLogic)
+ const nodeLogic = useRequiredNotebookNode()
const { expanded, nodeId: resolvedNodeId, notebookLogic } = useValues(nodeLogic)
const {
editingNodeIds,
@@ -62,6 +81,7 @@ const Component = ({
canvasFiltersOverride,
} = useValues(notebookLogic)
const { setTitlePlaceholder } = useActions(nodeLogic)
+ const componentPanelState = useComponentPanelState()
const summarizeInsight = useSummarizeInsight()
const sharedCachedInsight = query.kind === NodeKind.SavedInsightNode ? getSharedCachedInsight(query.shortId) : null
const sharedCachedInlineResults =
@@ -77,6 +97,12 @@ const Component = ({
dashboardItemId: query.kind === NodeKind.SavedInsightNode ? query.shortId : ('new' as const),
}
const { insightName } = useValues(insightLogic(insightLogicProps))
+ const isOutputPaneOpen = componentPanelState?.showViewPanel ?? expanded
+ const showSqlOutputToolbar = getNotebookSqlOutputToolbarVisibility({
+ componentPanelState,
+ expanded,
+ isEditing: !!editingNodeIds[resolvedNodeId],
+ })
useEffect(() => {
let title = 'Query'
@@ -138,7 +164,7 @@ const Component = ({
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [query])
- if (!expanded) {
+ if (!isOutputPaneOpen) {
return null
}
@@ -188,7 +214,7 @@ const Component = ({
<NotebookSQLEditorOutput
attributes={attributes}
updateAttributes={updateAttributes}
- showOutputToolbar={!!editingNodeIds[resolvedNodeId]}
+ showOutputToolbar={showSqlOutputToolbar}
/>
</div>
)
@@ -234,6 +260,7 @@ type NotebookNodeQueryAttributes = {
/* Whether canvasFiltersOverride is applied, as we should apply it only once */
isDefaultFilterApplied: boolean
showSettings?: boolean
+ outputTab?: OutputTab | null
}
export const Settings = ({
@@ -241,7 +268,7 @@ export const Settings = ({
updateAttributes,
}: NotebookNodeAttributeProperties<NotebookNodeQueryAttributes>): JSX.Element => {
const { query, isDefaultFilterApplied } = attributes
- const nodeLogic = useMountedLogic(notebookNodeLogic)
+ const nodeLogic = useRequiredNotebookNode()
const { notebookLogic } = useValues(nodeLogic)
const { canvasFiltersOverride } = useValues(notebookLogic)
@@ -375,6 +402,9 @@ export const NotebookNodeQuery = createPostHogWidgetNode<NotebookNodeQueryAttrib
showSettings: {
default: false,
},
+ outputTab: {
+ default: OutputTab.Results,
+ },
},
href: ({ query }) =>
isSavedInsightNode(query)
diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.test.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.test.tsx
index d3510bb15cb2..6528d9cc53b8 100644
--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.test.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.test.tsx
@@ -9,7 +9,12 @@ jest.mock('scenes/data-warehouse/editor/sqlEditorLogic', () => ({
sqlEditorLogic: jest.fn(),
}))
+import { act, render, waitFor } from '@testing-library/react'
+
+import { OutputTab, outputPaneLogic } from 'scenes/data-warehouse/editor/outputPaneLogic'
+
import { NodeKind, ProductKey } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
import { ChartDisplayType } from '~/types'
import {
@@ -18,10 +23,33 @@ import {
EMBEDDED_SQL_EDITOR_EDIT_MIN_HEIGHT,
EMBEDDED_SQL_EDITOR_MIN_HEIGHT,
getEmbeddedSqlEditorStyle,
+ getNotebookSqlEditorOutputTab,
getSqlEditorSourceQuery,
hasAlreadyRunSqlEditorSourceQuery,
+ useNotebookSQLOutputTabSync,
} from './NotebookSQLEditor'
+function OutputTabSyncHarness({
+ outputTab,
+ tabId,
+ updateAttributes,
+}: {
+ outputTab?: OutputTab | null
+ tabId: string
+ updateAttributes: jest.Mock
+}): JSX.Element | null {
+ useNotebookSQLOutputTabSync({
+ attributes: {
+ nodeId: 'node-1',
+ outputTab,
+ },
+ tabId,
+ updateAttributes,
+ })
+
+ return null
+}
+
describe('NotebookSQLEditor', () => {
it('adds notebook query tags to HogQL source queries', () => {
const sourceQuery = getSqlEditorSourceQuery({
@@ -133,6 +161,29 @@ describe('NotebookSQLEditor', () => {
expect(hasAlreadyRunSqlEditorSourceQuery(sourceQuery!, lastRunQuery)).toBe(true)
})
+ it('normalizes persisted embedded output tabs', () => {
+ expect(getNotebookSqlEditorOutputTab(OutputTab.Visualization)).toBe(OutputTab.Visualization)
+ expect(getNotebookSqlEditorOutputTab(OutputTab.Both)).toBe(OutputTab.Both)
+ expect(getNotebookSqlEditorOutputTab(undefined)).toBe(OutputTab.Results)
+ expect(getNotebookSqlEditorOutputTab('invalid')).toBe(OutputTab.Results)
+ })
+
+ it('persists embedded output tab changes to notebook node attributes', async () => {
+ initKeaTests()
+ const tabId = 'notebook-sql-output-tab-sync'
+ const updateAttributes = jest.fn()
+
+ render(<OutputTabSyncHarness outputTab={OutputTab.Results} tabId={tabId} updateAttributes={updateAttributes} />)
+
+ await waitFor(() => expect(outputPaneLogic({ tabId }).values.activeTab).toBe(OutputTab.Results))
+
+ act(() => {
+ outputPaneLogic({ tabId }).actions.setActiveTab(OutputTab.Visualization)
+ })
+
+ await waitFor(() => expect(updateAttributes).toHaveBeenCalledWith({ outputTab: OutputTab.Visualization }))
+ })
+
it('does not treat a changed SQL source as already run', () => {
const sourceQuery = getSqlEditorSourceQuery({
kind: NodeKind.HogQLQuery,
diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
index c4a88acf4ad6..dc21f197726e 100644
--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
@@ -3,6 +3,7 @@ import { useActions, useValues } from 'kea'
import { type CSSProperties, useEffect, useMemo, useRef, useState } from 'react'
import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'
+import { OutputTab, outputPaneLogic } from 'scenes/data-warehouse/editor/outputPaneLogic'
import { SQLEditor, SQLEditorPanel } from 'scenes/data-warehouse/editor/SQLEditor'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
@@ -64,6 +65,8 @@ const buildSourceQuery = (query: string): DataVisualizationNode => ({
display: ChartDisplayType.ActionsTable,
})
+const locallyPushedSqlEditorSourceQueryByTabId = new Map<string, DataVisualizationNode>()
+
export function getEmbeddedSqlEditorStyle(
height: string | number | undefined,
defaultHeight: string | number = EMBEDDED_SQL_EDITOR_DEFAULT_HEIGHT,
@@ -97,7 +100,8 @@ export function useNotebookQuerySQLEditorSync<T extends { query: QuerySchema }>(
attributes,
updateAttributes,
tabId,
-}: NotebookNodeAttributeProperties<T> & { tabId: string }): DataVisualizationNode | null {
+ autoRunOnFirstSeed = true,
+}: NotebookNodeAttributeProperties<T> & { tabId: string; autoRunOnFirstSeed?: boolean }): DataVisualizationNode | null {
const editorSourceQuery = useMemo(() => getSqlEditorSourceQuery(attributes.query), [attributes.query])
const logic = sqlEditorLogic({ tabId, mode: SQLEditorMode.Embedded })
const { queryInput, sourceQuery, lastRunQuery } = useValues(logic)
@@ -143,7 +147,11 @@ export function useNotebookQuerySQLEditorSync<T extends { query: QuerySchema }>(
lastLocalRef.current = editorSourceQuery
setQueryInput(editorSourceQuery.source.query)
setSourceQuery(editorSourceQuery)
- if (isFirstSeed && !hasAlreadyRunSqlEditorSourceQuery(editorSourceQuery, lastRunQuery)) {
+ if (
+ autoRunOnFirstSeed &&
+ isFirstSeed &&
+ !hasAlreadyRunSqlEditorSourceQuery(editorSourceQuery, lastRunQuery)
+ ) {
runQuery(editorSourceQuery.source.query)
}
return
@@ -152,6 +160,7 @@ export function useNotebookQuerySQLEditorSync<T extends { query: QuerySchema }>(
if (!equal(localQuery, lastLocalRef.current)) {
// Editor moved — push to Tiptap.
lastLocalRef.current = localQuery
+ locallyPushedSqlEditorSourceQueryByTabId.set(tabId, localQuery)
updateAttributes({ query: localQuery } as Partial<NotebookNodeAttributes<T>>)
return
}
@@ -159,18 +168,55 @@ export function useNotebookQuerySQLEditorSync<T extends { query: QuerySchema }>(
// Tiptap hasn't propagated a push we already made — wait for the next render.
}, [
editorSourceQuery,
+ autoRunOnFirstSeed,
lastRunQuery,
queryInput,
sourceQuery,
runQuery,
setQueryInput,
setSourceQuery,
+ tabId,
updateAttributes,
])
return editorSourceQuery
}
+function useNotebookQuerySQLEditorOutputSync<T extends { query: QuerySchema }>({
+ attributes,
+ tabId,
+}: Pick<NotebookNodeAttributeProperties<T>, 'attributes'> & { tabId: string }): DataVisualizationNode | null {
+ const editorSourceQuery = useMemo(() => getSqlEditorSourceQuery(attributes.query), [attributes.query])
+ const logic = sqlEditorLogic({ tabId, mode: SQLEditorMode.Embedded })
+ const { lastRunQuery } = useValues(logic)
+ const { initialize, runQuery, setQueryInput, setSourceQuery } = useActions(logic)
+ const lastAttrRef = useRef<DataVisualizationNode | null>(null)
+
+ useEffect(() => {
+ initialize()
+ }, [initialize])
+
+ useEffect(() => {
+ if (!editorSourceQuery || equal(editorSourceQuery, lastAttrRef.current)) {
+ return
+ }
+
+ const isFirstSeed = lastAttrRef.current === null
+ lastAttrRef.current = editorSourceQuery
+ if (!isFirstSeed && equal(editorSourceQuery, locallyPushedSqlEditorSourceQueryByTabId.get(tabId))) {
+ return
+ }
+
+ setQueryInput(editorSourceQuery.source.query)
+ setSourceQuery(editorSourceQuery)
+ if (isFirstSeed && !hasAlreadyRunSqlEditorSourceQuery(editorSourceQuery, lastRunQuery)) {
+ runQuery(editorSourceQuery.source.query)
+ }
+ }, [editorSourceQuery, lastRunQuery, runQuery, setQueryInput, setSourceQuery, tabId])
+
+ return editorSourceQuery
+}
+
export function useNotebookCodeSQLEditorSync<T extends { code: string }>({
attributes,
updateAttributes,
@@ -227,13 +273,56 @@ export function useNotebookCodeSQLEditorSync<T extends { code: string }>({
}, [code, queryInput, setQueryInput, setSourceQuery, updateAttributes])
}
-export function NotebookSQLEditorOutput<T extends { query: QuerySchema }>({
+export const getNotebookSqlEditorOutputTab = (outputTab: unknown): OutputTab => {
+ if (Object.values(OutputTab).includes(outputTab as OutputTab)) {
+ return outputTab as OutputTab
+ }
+
+ return OutputTab.Results
+}
+
+export function useNotebookSQLOutputTabSync<T extends { outputTab?: OutputTab | null }>({
+ attributes,
+ updateAttributes,
+ tabId,
+}: NotebookNodeAttributeProperties<T> & { tabId: string }): void {
+ const attributeOutputTab = getNotebookSqlEditorOutputTab(attributes.outputTab)
+ const logic = outputPaneLogic({ tabId })
+ const { activeTab } = useValues(logic)
+ const { setActiveTab } = useActions(logic)
+
+ const lastAttrRef = useRef<OutputTab | null>(null)
+ const lastLocalRef = useRef<OutputTab | null>(null)
+
+ useEffect(() => {
+ if (activeTab === attributeOutputTab) {
+ lastAttrRef.current = attributeOutputTab
+ lastLocalRef.current = activeTab
+ return
+ }
+
+ if (attributeOutputTab !== lastAttrRef.current) {
+ lastAttrRef.current = attributeOutputTab
+ lastLocalRef.current = attributeOutputTab
+ setActiveTab(attributeOutputTab)
+ return
+ }
+
+ if (activeTab !== lastLocalRef.current) {
+ lastLocalRef.current = activeTab
+ updateAttributes({ outputTab: activeTab } as Partial<NotebookNodeAttributes<T>>)
+ }
+ }, [activeTab, attributeOutputTab, setActiveTab, updateAttributes])
+}
+
+export function NotebookSQLEditorOutput<T extends { query: QuerySchema; outputTab?: OutputTab | null }>({
attributes,
updateAttributes,
showOutputToolbar,
}: NotebookNodeProps<T> & { showOutputToolbar: boolean }): JSX.Element | null {
const tabId = useMemo(() => getNotebookSqlEditorTabId(attributes.nodeId), [attributes.nodeId])
- const editorSourceQuery = useNotebookQuerySQLEditorSync({ attributes, updateAttributes, tabId })
+ const editorSourceQuery = useNotebookQuerySQLEditorOutputSync({ attributes, tabId })
+ useNotebookSQLOutputTabSync({ attributes, updateAttributes, tabId })
if (!editorSourceQuery) {
return null
@@ -263,7 +352,12 @@ export function NotebookSQLEditorSettings<T extends { query: QuerySchema }>({
updateAttributes,
}: NotebookNodeAttributeProperties<T>): JSX.Element {
const tabId = useMemo(() => getNotebookSqlEditorTabId(attributes.nodeId), [attributes.nodeId])
- const editorSourceQuery = useNotebookQuerySQLEditorSync({ attributes, updateAttributes, tabId })
+ const editorSourceQuery = useNotebookQuerySQLEditorSync({
+ attributes,
+ updateAttributes,
+ tabId,
+ autoRunOnFirstSeed: false,
+ })
// Focus the editor only when this user just inserted the node - a node mounting on
// notebook load or after a structural re-render must never steal the caret.
const [autoFocusQueryPane] = useState(() => wasNotebookNodeJustInserted(attributes.nodeId))
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
index 4a34ce1f9823..c166f0debfe2 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
@@ -102,6 +102,9 @@ const isSqlQueryNode = (nodeAttributes: NotebookNodeAttributes<any>): boolean =>
if (!query) {
return false
}
+ if (isHogQLQuery(query)) {
+ return true
+ }
if (isNodeWithSource(query)) {
return isHogQLQuery(query.source)
}
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx
index b81c42483d10..f5aa7e5d870c 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx
@@ -1,8 +1,8 @@
import { useValues } from 'kea'
-import { useEffect, useRef, useState } from 'react'
+import { KeyboardEvent, useEffect, useRef, useState } from 'react'
import { IconSend, IconTrash } from '@posthog/icons'
-import { LemonButton, LemonTextArea, ProfilePicture } from '@posthog/lemon-ui'
+import { LemonButton, ProfilePicture } from '@posthog/lemon-ui'
import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'
import {
@@ -117,6 +117,15 @@ export function NotebookDiscussionComment({
setDraft('')
}
+ const handleComposerKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>): void => {
+ event.stopPropagation()
+
+ if (event.key === 'Enter' && !event.nativeEvent.isComposing && !event.shiftKey) {
+ event.preventDefault()
+ submitReply()
+ }
+ }
+
return (
<div
className="MarkdownNotebook__discussion-comment"
@@ -149,17 +158,21 @@ export function NotebookDiscussionComment({
</div>
{isEditable ? (
<div className="MarkdownNotebook__discussion-comment-composer">
- <LemonTextArea
- value={draft}
- onChange={setDraft}
- onPressEnter={submitReply}
- placeholder={replies.length ? 'Reply...' : 'Comment...'}
- minRows={1}
- maxRows={6}
- autoFocus={wasNotebookNodeJustInserted(node.id)}
- stopPropagation
- data-attr="notebook-discussion-comment-input"
- />
+ <div className="flex flex-col rounded input-like">
+ <textarea
+ className="LemonTextArea MarkdownNotebook__discussion-comment-input w-full rounded"
+ value={draft}
+ onChange={(event) => {
+ event.stopPropagation()
+ setDraft(event.currentTarget.value)
+ }}
+ onKeyDown={handleComposerKeyDown}
+ placeholder={replies.length ? 'Reply...' : 'Comment...'}
+ rows={1}
+ autoFocus={wasNotebookNodeJustInserted(node.id)}
+ data-attr="notebook-discussion-comment-input"
+ />
+ </div>
<div className="MarkdownNotebook__discussion-comment-actions">
{isEditable ? (
<LemonButton
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx
index aad27ae8353a..297a9032e998 100644
--- a/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx
@@ -21,14 +21,24 @@ export type NotebookShareModalProps = {
}
export function NotebookShareModal({ shortId }: NotebookShareModalProps): JSX.Element {
+ const { isShareModalOpen } = useValues(notebookLogic({ shortId }))
+
+ if (!isShareModalOpen) {
+ return <></>
+ }
+
+ return <OpenNotebookShareModal shortId={shortId} />
+}
+
+function OpenNotebookShareModal({ shortId }: NotebookShareModalProps): JSX.Element {
const { content, isLocalOnly, isShareModalOpen } = useValues(notebookLogic({ shortId }))
const { closeShareModal } = useActions(notebookLogic({ shortId }))
const externalSharingEnabled = useFeatureFlag('NOTEBOOK_SHARING')
+ const [interestTracked, setInterestTracked] = useState(false)
const notebookUrl = urls.absolute(urls.currentProject(urls.notebook(shortId)))
const canvasUrl = urls.absolute(urls.canvas()) + `#🦔=${base64Encode(JSON.stringify(content))}`
- const [interestTracked, setInterestTracked] = useState(false)
const trackInterest = (): void => {
posthog.capture('pressed interested in notebook sharing', { url: notebookUrl })
}