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(sql-editor): add save target chooser (#123032)

Jovan Sakovic04008b199435
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 28e59bcb6ef8..09c221add67f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10717,9 +10717,25 @@ snapshots:
scenes-app-data-warehouse-sql-editor--customer-images--light:
hash: v1.k794b7964.ce993f3850f54ddccef58a05eceb9e2c97aa9a55a10c79ccec026ab34b41ef2c.wKHSElvN1JjL3MGp2vC9ReSCbeinqDlJse66vWOjUDM
scenes-app-data-warehouse-sql-editor--edited-insight--dark:
- hash: v1.k794b7964.abdad45eda3e55d49184f287c8b9420cd51049214a4e373af2a2ce4a51a1f380.Am_pA69gDN8zJ0H5XBaRSA5ftzncD6v-fQf-StsCtcU
+ hash: v1.k794b7964.2fc7ade30339fb8c6206e4fe6fc97a3785581fb9902b460b33c926512ca98eed.JMgb4caOndC9O8YeM2-gQCr_EgLRdJWDfj5hlQD4IRg
scenes-app-data-warehouse-sql-editor--edited-insight--light:
- hash: v1.k794b7964.8b4b5e9d27e30dce860efa4ce720bb3b94b009ca4fbe2936e22bcffbd4e57d80.xkqB3l0Rj9En-0bg_bEmUZ4OPip0k9_0w76It2BKo_c
+ hash: v1.k794b7964.4d82d9cdfe87cff9433e16065df0ac1c7cfbf51388d337bd24b13a04865880f6.VGun-U0ZZYvjeWi568gNuYLIHD11weOqChXy4Kp0shU
+ scenes-app-data-warehouse-sql-editor--edited-insight-legacy-save-menu--dark:
+ hash: v1.k794b7964.e6974bfaaec7000e4993f9b00b3ec07c75518435f3a63abebd6eee147083ce0f.Ep9O78gdgJyVw4Uv8H0CVTfCkUpW2Px8qZRZfUXDSR0
+ scenes-app-data-warehouse-sql-editor--edited-insight-legacy-save-menu--light:
+ hash: v1.k794b7964.5f5955cf8adfb190dfd69dcb45539774ca034f10f2d9c842bbddd7ae47513a1a._AImCwGFDraUyz-iLlG53aXfViHCjR2OntqV9pkjj5U
+ scenes-app-data-warehouse-sql-editor--edited-insight-legacy-save-menu-quill--dark:
+ hash: v1.k794b7964.92cd356343020b382840007a73499c68ec5117d843f5ad2f0481dfcee0a8a914.aOMfXD77ciS9e-KvOoBgI2pE5tze1sgj6Wa5W5CfcL0
+ scenes-app-data-warehouse-sql-editor--edited-insight-legacy-save-menu-quill--light:
+ hash: v1.k794b7964.eab8a94bb1a2ac2b979c271af97e818d52ca4005777fb2ecdb985e02840ca062.Is5PNt7xU2JKVOKWYBIAJl1bAEYJ3hGGKUSsKx0djI4
+ scenes-app-data-warehouse-sql-editor--edited-insight-save-as-flow--dark:
+ hash: v1.k794b7964.ecf3ef6892eecb09a1a8d96e8662adf9cb21af9cc2b505918a8807ca9c3cb7a0.TptjO98cT9OL4B1t96GQyB7BceyBaC8ivMg6KTcykkc
+ scenes-app-data-warehouse-sql-editor--edited-insight-save-as-flow--light:
+ hash: v1.k794b7964.70913d3b128c5f2c1e2ba68fb22df44ed41d2e271ac025e2375e0b80f87b7107.cnAXfM2tAQ6GU6MpfwDeIi5rVrpzAUeTUCjHqMNqa94
+ scenes-app-data-warehouse-sql-editor--edited-insight-save-as-flow-quill--dark:
+ hash: v1.k794b7964.5e4b885ff8e3d06362c87620665f206e15ab38d1598b01b856dd24d0b60d5ecb.RfnAoKVmvRo-65Z_iBI63kbxS9JP_Xi4O6i9meOy5q0
+ scenes-app-data-warehouse-sql-editor--edited-insight-save-as-flow-quill--light:
+ hash: v1.k794b7964.08715ab7c3c716f438b9382b00339682cd41bbae555954929db235f38218b72d.pRsNuw-O3fR1dD4bwxfW_Rbhc6ean74Ye-7hLMBOP0I
scenes-app-data-warehouse-sql-editor--edited-view--dark:
hash: v1.k794b7964.938a62a81937113f22cf7e37329390813a11b16fb3e0f86076f353442d723a9f.98wO_IsLncv5LEivgTAi5xNjCgHijdNRi0BfiM2r9d0
scenes-app-data-warehouse-sql-editor--edited-view--light:
@@ -10748,6 +10764,10 @@ snapshots:
hash: v1.k794b7964.10ccff73d67e6f4d5aad149c0f730982cc4911e89fec03bf05de09b0f52f0c8d.mkYOiFsECj8Tq6ukVR9JjW41SKL0dy-Dqfbc5pDqaVY
scenes-app-data-warehouse-sql-editor--materialization-settings--light:
hash: v1.k794b7964.99aa3bde7ac4497a83b2008869c8efd14317eda8d8c08950e851089092df8df9.05p6Le0a2itun96QCw7Mk7VkwfAp50woApgM8ZyaHMs
+ scenes-app-data-warehouse-sql-editor--save-as-flow-quill--dark:
+ hash: v1.k794b7964.6831237843bcfc3e9e699cd545ccd2ffa5b45f8659bae9348559f7a519d1df2d.tDE9QcmqMr8Eizr8MkF8polVIC6J6WPd6X_4wItGJqY
+ scenes-app-data-warehouse-sql-editor--save-as-flow-quill--light:
+ hash: v1.k794b7964.73625a5a3d8f235b99692b3b486b26bce4e582bb52f336b1f542839ec6f8db90.urGwTjh3jNIKpJ-Lp09lenapN5fSdSXhBELaK0GWVOU
scenes-app-data-warehouse-sql-editor--sidebar-materialization-status--dark:
hash: v1.k794b7964.85acd8a7662a18e3cb74064b89ec1b5bf7f1dafc7040e3c03e89f8f216c3f4c7.hp3JoyDds6n5wOcIirv45esRuHBSQmVvjGgIqT_R934
scenes-app-data-warehouse-sql-editor--sidebar-materialization-status--light:
@@ -13133,9 +13153,9 @@ snapshots:
scenes-app-insights-side-panel-actions--unsaved-insight--light:
hash: v1.k794b7964.d1ae4193c6ddd6ec8ec70b8181cd1fa1e33cfa0728d586423355601166b2e8b2.GFGdmioAb_Lqr7qiZik9jLMbbO6yC4abdURWyrSNeOs
scenes-app-insights-sqlboxplot--edit-options--dark:
- hash: v1.k794b7964.308341cd522a4bd2fab85a8705cbcc008fab22bf951e4ebe054a14d33ab9c4af.3rsxL_RsaZvnIIYCFuaz3Zr3M3kpJYecNWcWDyJpbTU
+ hash: v1.k794b7964.7569df154271b6f96bc44f07aa58ffc8812e67018b4e6b28cb0860dd588d0bf5.tpCrEP3Jq5SU8p8h2fxG24kbb0MQXtAT7eQVOhol23g
scenes-app-insights-sqlboxplot--edit-options--light:
- hash: v1.k794b7964.355f2119731714f7c84a2443841ca489f7d3275e26f697bb31fc7ecce6fc84d4.0pKjvw68pUVvD78l6SSrXN7Wm9X1rMMCPZImjqsikO0
+ hash: v1.k794b7964.d61ac1c3fecc32e091c6d12abd142dd299cbf85a5e542ba5dc642e2e5e966107.JHN2CPZjBVWRPwvwT1htC-4Qbf2ASiAiwF8K7a8DcHU
scenes-app-insights-sqlboxplot--grouped-series--dark:
hash: v1.k794b7964.e8e02705d2c2c04c95c28531323ac3afda9177a46f6d3207f1566faa0bdb357d.3VyKBqkXAnxXNZufZ_HlYp7q3M3J3E2go7zXqIPKQzE
scenes-app-insights-sqlboxplot--grouped-series--light:
@@ -16108,6 +16128,14 @@ snapshots:
hash: v1.k794b7964.cf89a12669d5221b2441fbfb4439b8b1b38191943438a2c1a220444148329954.B4ew6uW3gZCbPU_3vTOggsOyHojRlyvuXxh5FZnlO-0
scenes-dashboards-customize-breakdown-colors--customize-breakdown-colors--light:
hash: v1.k794b7964.441dbd7e00749f71e50c7b8c7b123485c1bc2da25498c43381bd12b2581f3034.ddH2Si9PeHnZaq2SataU1dDaQdDTMxWiJkhDaPlJypM
+ scenes-data-warehouse-sql-editor-save-as-menu--lemon--dark:
+ hash: v1.k794b7964.c8381daea51188b60917d813e9abd669cdc3c023e875271355beb61e983d36c0.0BJysFKR95itIhseWAQM6CQls20WHUzaazGI8dIqQU0
+ scenes-data-warehouse-sql-editor-save-as-menu--lemon--light:
+ hash: v1.k794b7964.ce49834d2dd9a3e8d8f7f2ded91b0977b7c4f6fa9ae4094a26f75958097ce647.giNr9vzojfM_H0KtB2m449ZMzA2qtjt_Taw5_XsjwvQ
+ scenes-data-warehouse-sql-editor-save-as-menu--quill--dark:
+ hash: v1.k794b7964.71d22f1784db63d4d163056fc4ca69f28ec4769dc924324114f81a1e73d6dd5d.zDoDPkZY04gocUtFOs0koHllRDvOQ9EtmB4RMM_F7qA
+ scenes-data-warehouse-sql-editor-save-as-menu--quill--light:
+ hash: v1.k794b7964.6515668099ff3a4bd1bbb4dac22586daeb8a1419fbd49d8bec87336b00cb3a50.bRgz6NTo6yEZtn_77eHLnzNprgOyoTnF7g6bWrSxMEY
scenes-inbox-scout-tags--editor-and-filter--dark:
hash: v1.k794b7964.79b0730ad23bc4daace066e8418a8f851d9a3e018bce50cd906f6f9276017d39.oiSmz7Fd649f4FBQK82nQ2-HLpGPZPaM9stDumq8qPo
scenes-inbox-scout-tags--editor-and-filter--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 0c4d87209310..fb7bc8a22efa 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -524,6 +524,7 @@ export const FEATURE_FLAGS = {
SIGNUP_AA_TEST_4_WAY: 'signup-aa-test-4-way', // owner: @andehen #team-experiments multivariate=control,test-1,test-2,test-3
SLACK_DWH: 'slack-dwh', // owner: @MarconLP #team-warehouse-sources
SQL_EDITOR_BI_MODE: 'sql-editor-bi-mode', // owner: @mariusandra #team-data-tools
+ SQL_EDITOR_SAVE_AS_CHOOSER: 'sql-editor-save-as-chooser', // owner: #team-data-tools
SQL_EDITOR_VIM_MODE: 'sql-editor-vim-mode', // owner: @arthurdedeus
SSE_DASHBOARDS: 'sse-dashboards', // owner: @aspicer #team-analytics-platform
SSO_SETTINGS_REDESIGN: 'sso-settings-redesign', // owner: @reecejones #team-platform-features
diff --git a/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.tsx b/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.tsx
index d8cbc1f6c9db..b4501f4c3da7 100644
--- a/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.tsx
+++ b/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.tsx
@@ -17,8 +17,10 @@ export interface LemonMenuItemBase extends Pick<
| 'icon'
| 'sideIcon'
| 'sideAction'
+ | 'disabled'
| 'disabledReason'
| 'tooltip'
+ | 'tooltipDocLink'
| 'tooltipPlacement'
| 'active'
| 'status'
diff --git a/frontend/src/scenes/data-warehouse/editor/QuillSQLEditorSceneActions.tsx b/frontend/src/scenes/data-warehouse/editor/QuillSQLEditorSceneActions.tsx
index 1f928cea80be..dd55a5f4c8a7 100644
--- a/frontend/src/scenes/data-warehouse/editor/QuillSQLEditorSceneActions.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QuillSQLEditorSceneActions.tsx
@@ -8,7 +8,6 @@ import {
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
- DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@posthog/quill'
@@ -16,43 +15,56 @@ import { AccessControlAction } from 'lib/components/AccessControlAction'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { QuillSaveAsMenuItems } from 'products/data_warehouse/frontend/sql_editor/QuillSaveAsMenu'
+import type { SaveAsTarget, SaveAsTargetId } from 'products/data_warehouse/frontend/sql_editor/saveAsTargets'
+
import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'
import { SaveAsMenuItem, editorSceneLogic } from './editorSceneLogic'
import { sqlEditorLogic } from './sqlEditorLogic'
export interface QuillSQLEditorSecondarySaveMenuItem extends SaveAsMenuItem {
onClick: () => void
- accessDisabledReason: string | null | undefined
+ disabledReason: string | null | undefined
}
export interface QuillSQLEditorSceneActionsProps {
isMaterializedView: boolean
+ closeObjectLabel: string
closeObjectTooltip: string
editingViewDisabledReason: string | undefined
editingViewLoading: boolean
onUpdateView: () => void
saveAsInsightDisabledReason: string | undefined
saveAsDisabledReason: string | undefined
- saveAsViewAccessDisabledReason: string | null
- saveAsEndpointDisabledReason: string | null
continueInNotebookAccessDisabledReason: string | null
secondarySaveMenuItems: QuillSQLEditorSecondarySaveMenuItem[]
+ legacySaveMenuItems: QuillSQLEditorSecondarySaveMenuItem[]
+ saveAsTargets: SaveAsTarget[]
+ onSaveAsTargetSelect: (target: SaveAsTargetId) => void
+ onSaveAsMenuOpen: () => void
onPrimarySaveClick: () => void
+ primarySaveDisabledReason: string | null | undefined
+ saveAsChooserEnabled: boolean
}
export function QuillSQLEditorSceneActions({
isMaterializedView,
+ closeObjectLabel,
closeObjectTooltip,
editingViewDisabledReason,
editingViewLoading,
onUpdateView,
saveAsInsightDisabledReason,
saveAsDisabledReason,
- saveAsViewAccessDisabledReason,
- saveAsEndpointDisabledReason,
continueInNotebookAccessDisabledReason,
secondarySaveMenuItems,
+ legacySaveMenuItems,
+ saveAsTargets,
+ onSaveAsTargetSelect,
+ onSaveAsMenuOpen,
onPrimarySaveClick,
+ primarySaveDisabledReason,
+ saveAsChooserEnabled,
}: QuillSQLEditorSceneActionsProps): JSX.Element {
const { updateInsightButtonEnabled, saveAsMenuItems, notebooksLoading } = useValues(editorSceneLogic)
const {
@@ -66,21 +78,19 @@ export function QuillSQLEditorSceneActions({
} = useValues(sqlEditorLogic)
const { updatingDataWarehouseSavedQuery } = useValues(dataWarehouseViewsLogic)
const { convertToNotebook, openHistoryModal } = useActions(editorSceneLogic)
- const {
- updateInsight,
- closeEditingObject,
- saveAsInsight,
- saveAsView,
- saveAsEndpoint,
- updateEditingMetric,
- setEditingMetricName,
- discardChanges,
- } = useActions(sqlEditorLogic)
+ const { updateInsight, closeEditingObject, updateEditingMetric, setEditingMetricName, discardChanges } =
+ useActions(sqlEditorLogic)
const continueInNotebookDisabledReason = queryInput?.trim()
? continueInNotebookAccessDisabledReason
: 'Write a SQL query before continuing'
+ const onSaveMenuOpenChange = (open: boolean): void => {
+ if (open && saveAsChooserEnabled) {
+ onSaveAsMenuOpen()
+ }
+ }
+
const historyButton = (dataAttr?: string): JSX.Element => (
<Button variant="outline" onClick={() => openHistoryModal()} data-attr={dataAttr}>
<IconBook />
@@ -116,44 +126,32 @@ export function QuillSQLEditorSceneActions({
</DropdownMenuItem>
)
- const saveAsMenuItemsGroup = (
- <DropdownMenuGroup>
- {continueInNotebookMenuItem}
- <DropdownMenuItem disabledReason={saveAsInsightDisabledReason} onClick={() => saveAsInsight()}>
- Save as new insight...
- </DropdownMenuItem>
- <DropdownMenuItem
- disabledReason={saveAsDisabledReason ?? saveAsViewAccessDisabledReason}
- onClick={() => saveAsView()}
- >
- Save as new view...
- </DropdownMenuItem>
- <DropdownMenuItem
- disabledReason={saveAsDisabledReason ?? saveAsEndpointDisabledReason}
- onClick={() => saveAsEndpoint()}
- >
- Save as endpoint...
- </DropdownMenuItem>
- </DropdownMenuGroup>
+ const continueInNotebookButton = (
+ <Button
+ variant="outline"
+ onClick={() => convertToNotebook()}
+ loading={notebooksLoading}
+ disabledReason={continueInNotebookDisabledReason}
+ data-attr="sql-editor-continue-in-notebook-button"
+ >
+ <IconNotebook />
+ Continue in a notebook
+ </Button>
)
- const secondarySaveMenuContent = (
- <DropdownMenuContent align="end">
- {secondarySaveMenuItems.map((item) => (
- <DropdownMenuItem
- key={item.action}
- disabledReason={
- (item.action === 'insight' ? saveAsInsightDisabledReason : saveAsDisabledReason) ??
- item.accessDisabledReason
- }
- onClick={item.onClick}
- >
+ const legacySaveAsMenuItemsGroup = (
+ <DropdownMenuGroup>
+ {continueInNotebookMenuItem}
+ {legacySaveMenuItems.map((item) => (
+ <DropdownMenuItem key={item.action} disabledReason={item.disabledReason} onClick={item.onClick}>
{item.label}
</DropdownMenuItem>
))}
- </DropdownMenuContent>
+ </DropdownMenuGroup>
)
+ const saveAsTargetMenuItems = <QuillSaveAsMenuItems targets={saveAsTargets} onSelect={onSaveAsTargetSelect} />
+
const saveOptionsTrigger = (dataAttr?: string): JSX.Element => (
<DropdownMenuTrigger
render={
@@ -176,7 +174,8 @@ export function QuillSQLEditorSceneActions({
<>
{historyButton()}
{discardChangesButton}
- <DropdownMenu>
+ {saveAsChooserEnabled && continueInNotebookButton}
+ <DropdownMenu onOpenChange={onSaveMenuOpenChange}>
<ButtonGroup>
<AccessControlAction
resourceType={AccessControlResourceType.WarehouseObjects}
@@ -195,13 +194,19 @@ export function QuillSQLEditorSceneActions({
</AccessControlAction>
{saveOptionsTrigger()}
</ButtonGroup>
- <DropdownMenuContent align="end">{saveAsMenuItemsGroup}</DropdownMenuContent>
+ <DropdownMenuContent
+ align="end"
+ className={saveAsChooserEnabled ? 'w-80' : undefined}
+ data-attr={saveAsChooserEnabled ? 'sql-editor-save-as-dialog' : undefined}
+ >
+ {saveAsChooserEnabled ? saveAsTargetMenuItems : legacySaveAsMenuItemsGroup}
+ </DropdownMenuContent>
</DropdownMenu>
<Button
variant="default"
size="icon"
onClick={() => closeEditingObject()}
- aria-label="close"
+ aria-label={closeObjectLabel}
tooltip={closeObjectTooltip}
>
<IconX />
@@ -211,7 +216,8 @@ export function QuillSQLEditorSceneActions({
<>
{historyButton('sql-editor-insight-history-button')}
{discardChangesButton}
- <DropdownMenu>
+ {saveAsChooserEnabled && continueInNotebookButton}
+ <DropdownMenu onOpenChange={onSaveMenuOpenChange}>
<ButtonGroup>
<Button
variant="primary"
@@ -226,22 +232,29 @@ export function QuillSQLEditorSceneActions({
</Button>
{saveOptionsTrigger('sql-editor-save-options-button')}
</ButtonGroup>
- <DropdownMenuContent align="end">
- {saveAsMenuItemsGroup}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() => closeEditingObject()}
- data-attr="sql-editor-reset-view"
- title={closeObjectTooltip}
- >
- Reset view
- </DropdownMenuItem>
+ <DropdownMenuContent
+ align="end"
+ className={saveAsChooserEnabled ? 'w-80' : undefined}
+ data-attr={saveAsChooserEnabled ? 'sql-editor-save-as-dialog' : undefined}
+ >
+ {saveAsChooserEnabled ? saveAsTargetMenuItems : legacySaveAsMenuItemsGroup}
</DropdownMenuContent>
</DropdownMenu>
+ <Button
+ variant="default"
+ size="icon"
+ onClick={() => closeEditingObject()}
+ aria-label={closeObjectLabel}
+ tooltip={closeObjectTooltip}
+ data-attr="sql-editor-reset-view"
+ >
+ <IconX />
+ </Button>
</>
) : editingMetricName ? (
<>
- <DropdownMenu>
+ {saveAsChooserEnabled && continueInNotebookButton}
+ <DropdownMenu onOpenChange={onSaveMenuOpenChange}>
<ButtonGroup>
<Button
variant="primary"
@@ -254,7 +267,23 @@ export function QuillSQLEditorSceneActions({
</Button>
{saveOptionsTrigger()}
</ButtonGroup>
- {secondarySaveMenuContent}
+ <DropdownMenuContent
+ align="end"
+ className={saveAsChooserEnabled ? 'w-80' : undefined}
+ data-attr={saveAsChooserEnabled ? 'sql-editor-save-as-dialog' : undefined}
+ >
+ {saveAsChooserEnabled
+ ? saveAsTargetMenuItems
+ : secondarySaveMenuItems.map((item) => (
+ <DropdownMenuItem
+ key={item.action}
+ disabledReason={item.disabledReason}
+ onClick={item.onClick}
+ >
+ {item.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
</DropdownMenu>
<Button
variant="default"
@@ -268,40 +297,44 @@ export function QuillSQLEditorSceneActions({
</>
) : (
<>
- {saveAsMenuItems.primary.action === 'insight' && (
- <Button
- variant="outline"
- onClick={() => convertToNotebook()}
- loading={notebooksLoading}
- disabledReason={continueInNotebookDisabledReason}
- data-attr="sql-editor-continue-in-notebook-button"
- >
- <IconNotebook />
- Continue in a notebook
- </Button>
- )}
- <DropdownMenu>
- <ButtonGroup>
- <Button
- variant="primary"
- onClick={onPrimarySaveClick}
- disabledReason={
- (saveAsMenuItems.primary.action === 'insight'
- ? saveAsInsightDisabledReason
- : saveAsDisabledReason) ??
- (saveAsMenuItems.primary.action === 'endpoint'
- ? saveAsEndpointDisabledReason
- : saveAsMenuItems.primary.action === 'view'
- ? saveAsViewAccessDisabledReason
- : undefined)
- }
+ {(saveAsChooserEnabled || saveAsMenuItems.primary.action === 'insight') && continueInNotebookButton}
+ {saveAsChooserEnabled ? (
+ <DropdownMenu onOpenChange={onSaveMenuOpenChange}>
+ <DropdownMenuTrigger
+ render={<Button variant="primary" data-attr="sql-editor-save-options-button" />}
>
- {saveAsMenuItems.primary.label}
- </Button>
- {saveOptionsTrigger('sql-editor-save-options-button')}
- </ButtonGroup>
- {secondarySaveMenuContent}
- </DropdownMenu>
+ Save as
+ <IconChevronDown />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-80" data-attr="sql-editor-save-as-dialog">
+ {saveAsTargetMenuItems}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <DropdownMenu>
+ <ButtonGroup>
+ <Button
+ variant="primary"
+ onClick={onPrimarySaveClick}
+ disabledReason={primarySaveDisabledReason}
+ >
+ {saveAsMenuItems.primary.label}
+ </Button>
+ {saveOptionsTrigger('sql-editor-save-options-button')}
+ </ButtonGroup>
+ <DropdownMenuContent align="end">
+ {secondarySaveMenuItems.map((item) => (
+ <DropdownMenuItem
+ key={item.action}
+ disabledReason={item.disabledReason}
+ onClick={item.onClick}
+ >
+ {item.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
</>
)}
</div>
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index 9dcde2395364..6fe70aef322e 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -11,7 +11,7 @@ import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
+import { LemonMenu, LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
@@ -43,6 +43,12 @@ import { MaterializationRunActions } from 'products/data_warehouse/frontend/shar
import { ViewLinkModal } from 'products/data_warehouse/frontend/shared/components/ViewLinkModal'
import { connectionSelectorLogic } from 'products/data_warehouse/frontend/shared/logics/connectionSelectorLogic'
import { aiChartRecommendationLogic } from 'products/data_warehouse/frontend/sql_editor/aiChartRecommendationLogic'
+import {
+ LemonSaveAsMenuContent,
+ getLemonSaveAsTargetMenuItems,
+} from 'products/data_warehouse/frontend/sql_editor/LemonSaveAsMenu'
+import { SAVE_AS_TARGETS } from 'products/data_warehouse/frontend/sql_editor/saveAsTargets'
+import type { SaveAsTarget, SaveAsTargetId } from 'products/data_warehouse/frontend/sql_editor/saveAsTargets'
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'
@@ -506,8 +512,14 @@ function AccessControlModal(): JSX.Element | null {
}
function SQLEditorSceneTitle(): JSX.Element | null {
- const { titleSectionProps, updateInsightButtonEnabled, saveAsMenuItems, notebooksLoading } =
- useValues(editorSceneLogic)
+ const {
+ titleSectionProps,
+ updateInsightButtonEnabled,
+ saveAsMenuItems,
+ notebooksLoading,
+ editorSource,
+ dashboardId,
+ } = useValues(editorSceneLogic)
const {
queryInput,
editingView,
@@ -518,7 +530,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
selectedConnectionId,
hasEditorChanges,
} = useValues(sqlEditorLogic)
- const { convertToNotebook, openHistoryModal } = useActions(editorSceneLogic)
+ const { convertToNotebook, openHistoryModal, openSaveAsMenu, selectSaveAsTarget } = useActions(editorSceneLogic)
const {
updateInsight,
closeEditingObject,
@@ -539,6 +551,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
const { response, responseError, responseLoading } = useValues(dataNodeLogic)
const { updatingDataWarehouseSavedQuery } = useValues(dataWarehouseViewsLogic)
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
+ const saveAsChooserEnabled = useFeatureFlag('SQL_EDITOR_SAVE_AS_CHOOSER')
const debouncedQueryInput = useDebouncedValue(queryInput, MAX_TOOL_CONTEXT_DEBOUNCE_MS)
const debouncedSourceQuery = useDebouncedValue(sourceQuery, MAX_TOOL_CONTEXT_DEBOUNCE_MS)
@@ -578,65 +591,6 @@ function SQLEditorSceneTitle(): JSX.Element | null {
AccessControlLevel.Editor
)
- const secondarySaveMenuItems = useMemo(
- () =>
- saveAsMenuItems.secondary.map((item) => ({
- ...item,
- onClick: () => {
- if (item.action === 'insight') {
- saveAsInsight()
- return
- }
-
- if (item.action === 'endpoint') {
- saveAsEndpoint()
- return
- }
-
- if (item.action === 'metric') {
- saveAsMetric()
- return
- }
-
- saveAsView()
- },
- accessDisabledReason:
- item.action === 'view'
- ? saveAsViewAccessDisabledReason
- : item.action === 'endpoint'
- ? saveAsEndpointDisabledReason
- : undefined,
- })),
- [
- saveAsEndpoint,
- saveAsInsight,
- saveAsMetric,
- saveAsMenuItems.secondary,
- saveAsView,
- saveAsViewAccessDisabledReason,
- saveAsEndpointDisabledReason,
- ]
- )
-
- const onPrimarySaveClick = (): void => {
- if (saveAsMenuItems.primary.action === 'endpoint') {
- saveAsEndpoint()
- return
- }
-
- if (saveAsMenuItems.primary.action === 'metric') {
- saveAsMetric()
- return
- }
-
- if (saveAsMenuItems.primary.action === 'view') {
- saveAsView()
- return
- }
-
- saveAsInsight()
- }
-
const saveAsInsightDisabledReason = insightLoading
? 'Loading insight...'
: !queryInput?.trim()
@@ -663,6 +617,90 @@ function SQLEditorSceneTitle(): JSX.Element | null {
return undefined
}, [insightLoading, isSourceQueryLastRun, responseLoading, responseError, response])
+ const saveAsEndpointQueryDisabledReason = useMemo(() => {
+ if (insightLoading) {
+ return 'Wait for the insight to load before creating an endpoint'
+ }
+
+ if (!queryInput?.trim()) {
+ return 'Write a SQL query before creating an endpoint'
+ }
+
+ if (responseLoading) {
+ return 'Wait for the current query to finish before creating an endpoint'
+ }
+
+ if (!isSourceQueryLastRun || responseError || !response) {
+ return 'Run the current query successfully to check which columns the endpoint will return'
+ }
+
+ return undefined
+ }, [insightLoading, queryInput, responseLoading, isSourceQueryLastRun, responseError, response])
+
+ const disabledReasonForSaveAsTarget = (target: SaveAsTargetId): string | null | undefined => {
+ if (target === 'insight') {
+ return saveAsInsightDisabledReason
+ }
+ if (target === 'view') {
+ return saveAsDisabledReason ?? saveAsViewAccessDisabledReason
+ }
+ if (target === 'endpoint') {
+ return saveAsEndpointQueryDisabledReason ?? saveAsEndpointDisabledReason
+ }
+ return saveAsDisabledReason
+ }
+
+ const hasContextualRecommendation = editorSource !== 'insight' || dashboardId !== null
+ const saveAsTargets: SaveAsTarget[] = [saveAsMenuItems.primary, ...saveAsMenuItems.secondary].map((item) => ({
+ id: item.action,
+ ...SAVE_AS_TARGETS[item.action],
+ recommended: hasContextualRecommendation && item.action === saveAsMenuItems.primary.action,
+ disabledReason: disabledReasonForSaveAsTarget(item.action),
+ dataAttr: item.dataAttr ?? `sql-editor-save-as-${item.action}`,
+ }))
+
+ const saveAsTarget = (target: SaveAsTargetId): void => {
+ if (target === 'insight') {
+ saveAsInsight()
+ } else if (target === 'view') {
+ saveAsView()
+ } else if (target === 'endpoint') {
+ saveAsEndpoint()
+ } else {
+ saveAsMetric()
+ }
+ }
+
+ const onSaveAsTargetSelect = (target: SaveAsTargetId): void => {
+ selectSaveAsTarget(target)
+ saveAsTarget(target)
+ }
+
+ const onSaveAsMenuVisibilityChange = (visible: boolean): void => {
+ if (visible) {
+ openSaveAsMenu()
+ }
+ }
+
+ const secondarySaveMenuItems = saveAsMenuItems.secondary.map((item) => ({
+ ...item,
+ onClick: () => saveAsTarget(item.action),
+ disabledReason: disabledReasonForSaveAsTarget(item.action),
+ }))
+
+ const legacySaveMenuItems = [
+ { action: 'insight' as const, label: 'Save as new insight...' },
+ { action: 'view' as const, label: 'Save as new view...' },
+ { action: 'endpoint' as const, label: 'Save as endpoint...' },
+ ].map((item) => ({
+ ...item,
+ onClick: () => saveAsTarget(item.action),
+ disabledReason: disabledReasonForSaveAsTarget(item.action),
+ }))
+
+ const onPrimarySaveClick = (): void => saveAsTarget(saveAsMenuItems.primary.action)
+ const primarySaveDisabledReason = disabledReasonForSaveAsTarget(saveAsMenuItems.primary.action)
+
const {
disabledReason: editingViewDisabledReason,
loading: editingViewLoading,
@@ -672,10 +710,15 @@ function SQLEditorSceneTitle(): JSX.Element | null {
const EditingViewButtonIcon = editingViewLoading ? Spinner : IconDownload
const closeObjectTooltip = editingInsight
- ? 'Close this insight and reset the SQL editor to an unsaved query without clearing your SQL or visualization settings.'
+ ? 'Stop editing this insight. Keep the current SQL and visualization settings in a new unsaved query.'
: editingView
- ? 'Close this view and reset the SQL editor to an unsaved query without clearing your SQL or visualization settings.'
- : 'Reset the SQL editor to an unsaved query without clearing your SQL or visualization settings.'
+ ? 'Stop editing this view. Keep the current SQL and visualization settings in a new unsaved query.'
+ : 'Start a new unsaved query. Keep the current SQL and visualization settings.'
+ const closeObjectLabel = editingInsight
+ ? 'Stop editing insight'
+ : editingView
+ ? 'Stop editing view'
+ : 'Start a new query'
const continueInNotebookButton = (
<LemonButton
type="secondary"
@@ -702,6 +745,10 @@ function SQLEditorSceneTitle(): JSX.Element | null {
: 'Write a SQL query before continuing',
'data-attr': 'sql-editor-continue-in-notebook-button',
}
+ const lemonSaveAsTargetMenuItems = getLemonSaveAsTargetMenuItems({
+ targets: saveAsTargets,
+ onSelect: onSaveAsTargetSelect,
+ })
const discardChangesButton = (
<LemonButton
type="secondary"
@@ -764,17 +811,22 @@ function SQLEditorSceneTitle(): JSX.Element | null {
todayRailNav ? (
<QuillSQLEditorSceneActions
isMaterializedView={isMaterializedView}
+ closeObjectLabel={closeObjectLabel}
closeObjectTooltip={closeObjectTooltip}
editingViewDisabledReason={editingViewDisabledReason}
editingViewLoading={editingViewLoading}
onUpdateView={updateEditingView}
saveAsInsightDisabledReason={saveAsInsightDisabledReason}
saveAsDisabledReason={saveAsDisabledReason}
- saveAsViewAccessDisabledReason={saveAsViewAccessDisabledReason}
- saveAsEndpointDisabledReason={saveAsEndpointDisabledReason}
continueInNotebookAccessDisabledReason={continueInNotebookAccessDisabledReason}
secondarySaveMenuItems={secondarySaveMenuItems}
+ legacySaveMenuItems={legacySaveMenuItems}
+ saveAsTargets={saveAsTargets}
+ onSaveAsTargetSelect={onSaveAsTargetSelect}
+ onSaveAsMenuOpen={openSaveAsMenu}
onPrimarySaveClick={onPrimarySaveClick}
+ primarySaveDisabledReason={primarySaveDisabledReason}
+ saveAsChooserEnabled={saveAsChooserEnabled}
/>
) : (
<div className="flex flex-wrap items-center gap-2">
@@ -789,6 +841,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
History
</LemonButton>
{discardChangesButton}
+ {saveAsChooserEnabled && continueInNotebookButton}
<AccessControlAction
resourceType={AccessControlResourceType.WarehouseObjects}
minAccessLevel={AccessControlLevel.Editor}
@@ -804,30 +857,18 @@ function SQLEditorSceneTitle(): JSX.Element | null {
icon: <IconChevronDown />,
dropdown: {
placement: 'bottom-end',
- overlay: (
+ className: saveAsChooserEnabled ? 'w-80' : undefined,
+ onVisibilityChange: saveAsChooserEnabled
+ ? onSaveAsMenuVisibilityChange
+ : undefined,
+ overlay: saveAsChooserEnabled ? (
+ <LemonSaveAsMenuContent
+ targets={saveAsTargets}
+ onSelect={onSaveAsTargetSelect}
+ />
+ ) : (
<LemonMenuOverlay
- items={[
- continueInNotebookMenuItem,
- {
- label: 'Save as new insight...',
- disabledReason: saveAsInsightDisabledReason,
- onClick: () => saveAsInsight(),
- },
- {
- label: 'Save as new view...',
- disabledReason:
- saveAsDisabledReason ??
- saveAsViewAccessDisabledReason,
- onClick: () => saveAsView(),
- },
- {
- label: 'Save as endpoint...',
- disabledReason:
- saveAsDisabledReason ??
- saveAsEndpointDisabledReason,
- onClick: () => saveAsEndpoint(),
- },
- ]}
+ items={[continueInNotebookMenuItem, ...legacySaveMenuItems]}
/>
),
},
@@ -841,7 +882,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
icon={<IconX />}
type="tertiary"
size="small"
- aria-label="close"
+ aria-label={closeObjectLabel}
tooltip={closeObjectTooltip}
/>
</>
@@ -857,6 +898,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
History
</LemonButton>
{discardChangesButton}
+ {saveAsChooserEnabled && continueInNotebookButton}
<LemonButton
disabledReason={
saveAsInsightDisabledReason ??
@@ -871,44 +913,18 @@ function SQLEditorSceneTitle(): JSX.Element | null {
'data-attr': 'sql-editor-save-options-button',
dropdown: {
placement: 'bottom-end',
- overlay: (
+ className: saveAsChooserEnabled ? 'w-80' : undefined,
+ onVisibilityChange: saveAsChooserEnabled
+ ? onSaveAsMenuVisibilityChange
+ : undefined,
+ overlay: saveAsChooserEnabled ? (
+ <LemonSaveAsMenuContent
+ targets={saveAsTargets}
+ onSelect={onSaveAsTargetSelect}
+ />
+ ) : (
<LemonMenuOverlay
- items={[
- {
- items: [
- continueInNotebookMenuItem,
- {
- label: 'Save as new insight...',
- disabledReason: saveAsInsightDisabledReason,
- onClick: () => saveAsInsight(),
- },
- {
- label: 'Save as new view...',
- disabledReason:
- saveAsDisabledReason ??
- saveAsViewAccessDisabledReason,
- onClick: () => saveAsView(),
- },
- {
- label: 'Save as endpoint...',
- disabledReason:
- saveAsDisabledReason ??
- saveAsEndpointDisabledReason,
- onClick: () => saveAsEndpoint(),
- },
- ],
- },
- {
- items: [
- {
- label: 'Reset view',
- 'data-attr': 'sql-editor-reset-view',
- tooltip: closeObjectTooltip,
- onClick: () => closeEditingObject(),
- },
- ],
- },
- ]}
+ items={[continueInNotebookMenuItem, ...legacySaveMenuItems]}
/>
),
},
@@ -916,9 +932,19 @@ function SQLEditorSceneTitle(): JSX.Element | null {
>
Update insight
</LemonButton>
+ <LemonButton
+ onClick={() => closeEditingObject()}
+ icon={<IconX />}
+ type="tertiary"
+ size="small"
+ aria-label={closeObjectLabel}
+ tooltip={closeObjectTooltip}
+ data-attr="sql-editor-reset-view"
+ />
</>
) : editingMetricName ? (
<>
+ {saveAsChooserEnabled && continueInNotebookButton}
<LemonButton
type="primary"
size="small"
@@ -930,17 +956,17 @@ function SQLEditorSceneTitle(): JSX.Element | null {
icon: <IconChevronDown />,
dropdown: {
placement: 'bottom-end',
- overlay: (
- <LemonMenuOverlay
- items={secondarySaveMenuItems.map((item) => ({
- ...item,
- disabledReason:
- (item.action === 'insight'
- ? saveAsInsightDisabledReason
- : saveAsDisabledReason) ??
- item.accessDisabledReason,
- }))}
+ className: saveAsChooserEnabled ? 'w-80' : undefined,
+ onVisibilityChange: saveAsChooserEnabled
+ ? onSaveAsMenuVisibilityChange
+ : undefined,
+ overlay: saveAsChooserEnabled ? (
+ <LemonSaveAsMenuContent
+ targets={saveAsTargets}
+ onSelect={onSaveAsTargetSelect}
/>
+ ) : (
+ <LemonMenuOverlay items={secondarySaveMenuItems} />
),
},
}}
@@ -958,43 +984,46 @@ function SQLEditorSceneTitle(): JSX.Element | null {
</>
) : (
<>
- {saveAsMenuItems.primary.action === 'insight' && continueInNotebookButton}
- <LemonButton
- type="primary"
- size="small"
- onClick={onPrimarySaveClick}
- disabledReason={
- (saveAsMenuItems.primary.action === 'insight'
- ? saveAsInsightDisabledReason
- : saveAsDisabledReason) ??
- (saveAsMenuItems.primary.action === 'endpoint'
- ? saveAsEndpointDisabledReason
- : saveAsMenuItems.primary.action === 'view'
- ? saveAsViewAccessDisabledReason
- : undefined)
- }
- sideAction={{
- icon: <IconChevronDown />,
- 'data-attr': 'sql-editor-save-options-button',
- dropdown: {
- placement: 'bottom-end',
- overlay: (
- <LemonMenuOverlay
- items={secondarySaveMenuItems.map((item) => ({
- ...item,
- disabledReason:
- (item.action === 'insight'
- ? saveAsInsightDisabledReason
- : saveAsDisabledReason) ??
- item.accessDisabledReason,
- }))}
- />
- ),
- },
- }}
- >
- {saveAsMenuItems.primary.label}
- </LemonButton>
+ {(saveAsChooserEnabled || saveAsMenuItems.primary.action === 'insight') &&
+ continueInNotebookButton}
+ {saveAsChooserEnabled ? (
+ <LemonMenu
+ items={[
+ {
+ title: 'Save query as',
+ items: lemonSaveAsTargetMenuItems,
+ },
+ ]}
+ placement="bottom-end"
+ className="w-80"
+ onVisibilityChange={onSaveAsMenuVisibilityChange}
+ >
+ <LemonButton
+ type="primary"
+ size="small"
+ data-attr="sql-editor-save-options-button"
+ >
+ Save as
+ </LemonButton>
+ </LemonMenu>
+ ) : (
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={onPrimarySaveClick}
+ disabledReason={primarySaveDisabledReason}
+ sideAction={{
+ icon: <IconChevronDown />,
+ 'data-attr': 'sql-editor-save-options-button',
+ dropdown: {
+ placement: 'bottom-end',
+ overlay: <LemonMenuOverlay items={secondarySaveMenuItems} />,
+ },
+ }}
+ >
+ {saveAsMenuItems.primary.label}
+ </LemonButton>
+ )}
</>
)}
</div>
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index f71797ab3f20..2f80543f0512 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -37,8 +37,7 @@ import { expect, userEvent } from 'storybook/test'
import { QueryInfo } from './output-pane-tabs/QueryInfo'
import { sqlEditorLogic } from './sqlEditorLogic'
-// The SQL editor scene gates on warehouse-objects access; grant it on the storybook app context
-// before the story mounts and restore the original on unmount so story order can't leak.
+// Grant saved-object access before the story mounts and restore it on unmount so story order can't leak.
const grantWarehouseAccess: Decorator = function GrantWarehouseAccess(Story): JSX.Element {
const appContext = (window as any).POSTHOG_APP_CONTEXT
const original = useRef<{ value: unknown }>()
@@ -47,6 +46,7 @@ const grantWarehouseAccess: Decorator = function GrantWarehouseAccess(Story): JS
appContext.resource_access_control = {
...appContext.resource_access_control,
[AccessControlResourceType.WarehouseObjects]: AccessControlLevel.Editor,
+ [AccessControlResourceType.Endpoint]: AccessControlLevel.Editor,
}
}
useEffect(
@@ -215,6 +215,7 @@ const meta: Meta = {
'/api/projects/:team_id/query_tab_state/user': [200, { tabs: [] }],
},
post: {
+ '/api/projects/:team_id/file_system/home_folder/': { id: 'example-home', path: 'Users/Example' },
'/api/environments/:team_id/query/:kind': async ({ request }) => {
const body = (await request.json()) as Record<string, any>
const kind = body?.query?.kind
@@ -254,6 +255,48 @@ export default meta
type Story = StoryObj<{}>
export const TopToolsPerServer: Story = {}
+// Leaves the save menu open so the snapshot shows the chooser.
+// The scene re-renders the toolbar while it loads, which can drop an early click, so this retries until the menu stays open.
+const openSaveMenu: Story['play'] = async ({ canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body)
+ await waitFor(
+ async () => {
+ if (!body.queryByText('Save query as')) {
+ const trigger = canvasElement.querySelector<HTMLElement>('[data-attr="sql-editor-save-options-button"]')
+ expect(trigger).toBeTruthy()
+ await userEvent.click(trigger!)
+ }
+ expect(body.getByText('Save query as')).toBeVisible()
+ },
+ { timeout: 30000, interval: 1000 }
+ )
+}
+
+// Waits for the insight to load and show its unsaved edit before it opens the save menu.
+const openEditedInsightSaveMenu: Story['play'] = async (context) => {
+ const canvas = within(context.canvasElement)
+ await waitFor(
+ () => expect(canvas.getByRole('button', { name: 'Discard changes' })).toHaveAttribute('aria-disabled', 'false'),
+ { timeout: 30000 }
+ )
+ await openSaveMenu(context)
+}
+
+export const SaveAsFlowQuill: Story = {
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.SQL_EDITOR_SAVE_AS_CHOOSER, FEATURE_FLAGS.TODAY_RAIL_NAV],
+ msw: {
+ mocks: {
+ get: {
+ '/api/projects/:team_id/warehouse_expressions/': { results: [] },
+ '/api/environments/:team_id/warehouse_expressions/': { results: [] },
+ },
+ },
+ },
+ },
+ play: openSaveMenu,
+}
+
export const CustomerImages: Story = {
tags: ['hogqlx-images'],
parameters: {
@@ -445,6 +488,7 @@ export const EditedView: Story = {
export const EditedInsight: Story = {
parameters: {
+ featureFlags: [FEATURE_FLAGS.SQL_EDITOR_SAVE_AS_CHOOSER],
pageUrl: `${urls.sqlEditor({ insightShortId: DISCARD_INSIGHT.short_id })}#q=SELECT%202`,
msw: { mocks: discardMocks },
},
@@ -456,6 +500,62 @@ export const EditedInsight: Story = {
)
await waitFor(() => expect(canvas.getByText('Edited')).toBeVisible())
await expect(canvas.getByRole('button', { name: 'Update insight' })).toHaveAttribute('aria-disabled', 'false')
+ await expect(canvas.getByRole('button', { name: 'Continue in a notebook' })).toBeVisible()
+ await userEvent.click(canvasElement.querySelector('[data-attr="sql-editor-save-options-button"]')!)
+ const menu = within(canvasElement.ownerDocument.body)
+ await menu.findByText('Save query as')
+ await expect(menu.queryByRole('menuitem', { name: 'Continue in a notebook' })).not.toBeInTheDocument()
+ await expect(
+ canvasElement.ownerDocument.querySelector('[data-attr="sql-editor-save-as-insight"]')
+ ).toHaveAttribute('aria-disabled', 'false')
+ await expect(
+ canvasElement.ownerDocument.querySelector('[data-attr="sql-editor-save-view-button"]')
+ ).toHaveAttribute('aria-disabled', 'true')
+ await expect(
+ canvasElement.ownerDocument.querySelector('[data-attr="sql-editor-save-as-endpoint"]')
+ ).toHaveAttribute('aria-disabled', 'true')
+ // The popover fades in, so wait for it instead of asserting visibility on the first frame.
+ await waitFor(() =>
+ expect(
+ menu.getByText('Run the current query successfully to check which columns the endpoint will return')
+ ).toBeVisible()
+ )
+ await userEvent.keyboard('{Escape}')
+ await waitFor(() => expect(menu.queryByText('Save query as')).not.toBeInTheDocument())
+ await userEvent.click(canvas.getByRole('button', { name: 'Stop editing insight' }))
+ await waitFor(() => expect(canvas.queryByRole('button', { name: 'Update insight' })).not.toBeInTheDocument())
+ await expect(canvas.getByRole('button', { name: 'Save as' })).toBeVisible()
+ await expect(sqlEditorLogic({ tabId: 'default' }).values.queryInput).toEqual('SELECT 2')
+ },
+}
+
+export const EditedInsightSaveAsFlow: Story = {
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.SQL_EDITOR_SAVE_AS_CHOOSER],
+ pageUrl: `${urls.sqlEditor({ insightShortId: DISCARD_INSIGHT.short_id })}#q=SELECT%202`,
+ msw: { mocks: discardMocks },
+ },
+ play: openEditedInsightSaveMenu,
+}
+
+export const EditedInsightSaveAsFlowQuill: Story = {
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.SQL_EDITOR_SAVE_AS_CHOOSER, FEATURE_FLAGS.TODAY_RAIL_NAV],
+ pageUrl: `${urls.sqlEditor({ insightShortId: DISCARD_INSIGHT.short_id })}#q=SELECT%202`,
+ msw: { mocks: discardMocks },
+ },
+ play: openEditedInsightSaveMenu,
+}
+
+export const EditedInsightLegacySaveMenu: Story = {
+ parameters: {
+ featureFlags: { [FEATURE_FLAGS.SQL_EDITOR_SAVE_AS_CHOOSER]: false },
+ pageUrl: `${urls.sqlEditor({ insightShortId: DISCARD_INSIGHT.short_id })}#q=SELECT%202`,
+ msw: { mocks: discardMocks },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await canvas.findByRole('button', { name: 'Discard changes' }, { timeout: 15000 })
await userEvent.click(canvasElement.querySelector('[data-attr="sql-editor-save-options-button"]')!)
const menu = within(canvasElement.ownerDocument.body)
await expect(await menu.findByRole('menuitem', { name: 'Save as new insight...' })).toHaveAttribute(
@@ -466,11 +566,22 @@ export const EditedInsight: Story = {
'aria-disabled',
'true'
)
- await expect(canvas.queryByRole('button', { name: /^close$/ })).not.toBeInTheDocument()
- await userEvent.click(menu.getByText('Reset view'))
- await waitFor(() => expect(canvas.queryByRole('button', { name: 'Update insight' })).not.toBeInTheDocument())
- await expect(canvas.getByRole('button', { name: 'Save as insight' })).toBeVisible()
- await expect(sqlEditorLogic({ tabId: 'default' }).values.queryInput).toEqual('SELECT 2')
+ await expect(menu.getByRole('menuitem', { name: 'Save as endpoint...' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true'
+ )
+ await expect(menu.queryByText('Save query as')).not.toBeInTheDocument()
+ },
+}
+
+export const EditedInsightLegacySaveMenuQuill: Story = {
+ ...EditedInsightLegacySaveMenu,
+ parameters: {
+ ...EditedInsightLegacySaveMenu.parameters,
+ featureFlags: {
+ [FEATURE_FLAGS.SQL_EDITOR_SAVE_AS_CHOOSER]: false,
+ [FEATURE_FLAGS.TODAY_RAIL_NAV]: true,
+ },
},
}
diff --git a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
index 6ffe40385724..c5f071dc927c 100644
--- a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
@@ -31,6 +31,8 @@ import { notebooksModel } from '~/models/notebooksModel'
import { DataVisualizationNode, FileSystemIconType, HogQLFilters, NodeKind } from '~/queries/schema/schema-general'
import { Breadcrumb, ProjectTreeRef } from '~/types'
+import type { SaveAsTargetId } from 'products/data_warehouse/frontend/sql_editor/saveAsTargets'
+
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { DataWarehouseSavedQuery, LinkBreadcrumb, InsightModel } from '../../../types'
import { NEW_QUERY, normalizeFiltersForUrl, sqlEditorLogic, toDataVisualizationNode } from './sqlEditorLogic'
@@ -38,7 +40,7 @@ import type { QueryTab, SqlEditorSource } from './sqlEditorLogic'
import { SQLEditorMode } from './sqlEditorModes'
export interface SaveAsMenuItem {
- action: 'insight' | 'endpoint' | 'view' | 'metric'
+ action: SaveAsTargetId
label: string
dataAttr?: string
}
@@ -208,6 +210,12 @@ export interface editorSceneLogicActions {
openHistoryModal: () => {
value: true
}
+ openSaveAsMenu: () => {
+ value: true
+ }
+ selectSaveAsTarget: (target: SaveAsTargetId) => {
+ target: SaveAsTargetId
+ }
shareTab: () => {
value: true
}
@@ -318,6 +326,8 @@ export const editorSceneLogic = kea<editorSceneLogicType>([
shareTab: true,
openHistoryModal: true,
closeHistoryModal: true,
+ openSaveAsMenu: true,
+ selectSaveAsTarget: (target: SaveAsTargetId) => ({ target }),
}),
reducers({
isHistoryModalOpen: [
@@ -612,6 +622,19 @@ export const editorSceneLogic = kea<editorSceneLogicType>([
],
}),
listeners(({ actions, values }) => ({
+ openSaveAsMenu: () => {
+ // pinned: analytics event name - renaming breaks dashboards
+ posthog.capture('sql-editor-save-as-modal-opened', {
+ editor_source: values.editorSource,
+ })
+ },
+ selectSaveAsTarget: ({ target }) => {
+ // pinned: analytics event name and property - renaming breaks dashboards
+ posthog.capture('sql-editor-save-as-target-selected', {
+ target,
+ editor_source: values.editorSource,
+ })
+ },
convertToNotebook: () => {
const { title, content } = buildSqlNotebook(
values.queryInput ?? '',
diff --git a/products/data_warehouse/frontend/sql_editor/LemonSaveAsMenu.tsx b/products/data_warehouse/frontend/sql_editor/LemonSaveAsMenu.tsx
new file mode 100644
index 000000000000..528f452ac8da
--- /dev/null
+++ b/products/data_warehouse/frontend/sql_editor/LemonSaveAsMenu.tsx
@@ -0,0 +1,59 @@
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
+import type { LemonMenuItem, LemonMenuItems } from 'lib/lemon-ui/LemonMenu/LemonMenu'
+
+import type { SaveAsMenuProps } from './saveAsTargets'
+
+export interface LemonSaveAsMenuContentProps extends SaveAsMenuProps {
+ beforeItems?: LemonMenuItem[]
+ afterItemSections?: LemonMenuItem[][]
+}
+
+export function getLemonSaveAsTargetMenuItems({ targets, onSelect }: SaveAsMenuProps): LemonMenuItem[] {
+ return targets.map((target) => {
+ const Icon = target.icon
+
+ return {
+ key: target.id,
+ icon: <Icon className="text-lg" />,
+ label: (
+ <span className="flex min-w-0 flex-1 flex-col items-start gap-0.5 py-1 text-left">
+ <span className="flex flex-wrap items-center gap-2">
+ <span className="font-semibold text-default">{target.label}</span>
+ {target.recommended ? <LemonTag size="small">Recommended</LemonTag> : null}
+ </span>
+ <span className="text-xs font-normal text-secondary">{target.description}</span>
+ {target.disabledReason ? (
+ <span className="text-xs font-normal text-warning">{target.disabledReason}</span>
+ ) : null}
+ </span>
+ ),
+ onClick: () => onSelect(target.id),
+ // The label already shows the disabled reason, so the tooltip keeps only the help text.
+ disabled: !!target.disabledReason,
+ tooltip: target.helpText,
+ tooltipDocLink: target.docsUrl,
+ 'data-attr': target.dataAttr,
+ }
+ })
+}
+
+export function LemonSaveAsMenuContent({
+ targets,
+ onSelect,
+ beforeItems = [],
+ afterItemSections = [],
+}: LemonSaveAsMenuContentProps): JSX.Element {
+ const items: LemonMenuItems = [
+ ...(beforeItems.length ? [{ items: beforeItems }] : []),
+ { title: 'Save query as', items: getLemonSaveAsTargetMenuItems({ targets, onSelect }) },
+ ...afterItemSections.map((items) => ({ items })),
+ ]
+
+ return (
+ <div className="min-w-0" data-attr="sql-editor-save-as-modal">
+ <LemonMenuOverlay items={items} tooltipPlacement="left" />
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/sql_editor/QuillSaveAsMenu.tsx b/products/data_warehouse/frontend/sql_editor/QuillSaveAsMenu.tsx
new file mode 100644
index 000000000000..b3a877205f72
--- /dev/null
+++ b/products/data_warehouse/frontend/sql_editor/QuillSaveAsMenu.tsx
@@ -0,0 +1,77 @@
+import type { FocusEvent } from 'react'
+
+import {
+ Badge,
+ Button,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@posthog/quill'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+import type { SaveAsMenuProps, SaveAsTarget, SaveAsTargetId } from './saveAsTargets'
+
+export function QuillSaveAsMenuItems({ targets, onSelect }: SaveAsMenuProps): JSX.Element {
+ return (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Save query as</DropdownMenuLabel>
+ {targets.map((target) => (
+ <QuillSaveAsMenuItem key={target.id} target={target} onSelect={onSelect} />
+ ))}
+ </DropdownMenuGroup>
+ )
+}
+
+function QuillSaveAsMenuItem({
+ target,
+ onSelect,
+}: {
+ target: SaveAsTarget
+ onSelect: (id: SaveAsTargetId) => void
+}): JSX.Element {
+ const Icon = target.icon
+ return (
+ <Tooltip disableHoverablePopup={false}>
+ {/* Disabled items ignore the pointer, so a wrapper catches the hover. The item's own
+ `disabledReason` would replace the help text, and the label already shows the reason. */}
+ <TooltipTrigger render={<div className="w-full min-w-0" />}>
+ {/* The menu takes focus back from the item as the pointer leaves it. Keep that blur away
+ from the trigger, or the tooltip closes before the pointer reaches its docs link. */}
+ <div className="contents" onFocus={stopPropagation} onBlur={stopPropagation}>
+ <DropdownMenuItem
+ className="w-full min-w-0"
+ onClick={() => onSelect(target.id)}
+ disabled={!!target.disabledReason}
+ data-attr={target.dataAttr}
+ description={
+ <span className="flex flex-col gap-0.5">
+ <span>{target.description}</span>
+ {target.disabledReason ? (
+ <span className="text-warning-foreground">{target.disabledReason}</span>
+ ) : null}
+ </span>
+ }
+ >
+ <Icon />
+ {target.label}
+ {target.recommended ? <Badge>Recommended</Badge> : null}
+ </DropdownMenuItem>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="left" align="center" className="max-w-xs flex-col items-start">
+ <span className="text-xs">{target.helpText}</span>
+ <Button variant="link" size="inline" render={<LinkPrimitive to={target.docsUrl} target="_blank" />}>
+ Read the docs
+ </Button>
+ </TooltipContent>
+ </Tooltip>
+ )
+}
+
+function stopPropagation(event: FocusEvent): void {
+ event.stopPropagation()
+}
diff --git a/products/data_warehouse/frontend/sql_editor/SaveAsMenu.stories.tsx b/products/data_warehouse/frontend/sql_editor/SaveAsMenu.stories.tsx
new file mode 100644
index 000000000000..0a81181403fe
--- /dev/null
+++ b/products/data_warehouse/frontend/sql_editor/SaveAsMenu.stories.tsx
@@ -0,0 +1,69 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@posthog/quill'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'
+
+import { LemonSaveAsMenuContent } from './LemonSaveAsMenu'
+import { QuillSaveAsMenuItems } from './QuillSaveAsMenu'
+import { SAVE_AS_TARGETS } from './saveAsTargets'
+import type { SaveAsTarget, SaveAsTargetMetadata } from './saveAsTargets'
+
+const targets: SaveAsTarget[] = (Object.entries(SAVE_AS_TARGETS) as [SaveAsTarget['id'], SaveAsTargetMetadata][]).map(
+ ([id, target], index) => ({
+ ...target,
+ id,
+ recommended: index === 0,
+ disabledReason:
+ id === 'endpoint'
+ ? 'Run the current query successfully to check which columns the endpoint will return'
+ : undefined,
+ dataAttr: `save-as-${id}`,
+ })
+)
+
+const meta: Meta<typeof LemonSaveAsMenuContent> = {
+ title: 'Scenes/Data warehouse/SQL editor/Save as menu',
+ component: LemonSaveAsMenuContent,
+ args: {
+ targets,
+ onSelect: () => {},
+ },
+ // The menu opens leftwards from a right-aligned trigger, so the box keeps the whole menu inside the snapshot.
+ decorators: [
+ (Story) => (
+ <div className="flex h-[30rem] w-[22rem] items-start justify-end">
+ <Story />
+ </div>
+ ),
+ ],
+}
+
+export default meta
+type Story = StoryObj<typeof LemonSaveAsMenuContent>
+
+export const Lemon: Story = {
+ render: (args) => (
+ <LemonDropdown
+ startVisible
+ placement="bottom-end"
+ className="w-80"
+ overlay={<LemonSaveAsMenuContent {...args} />}
+ closeOnClickInside
+ >
+ <LemonButton type="primary">Save as</LemonButton>
+ </LemonDropdown>
+ ),
+}
+
+export const Quill: Story = {
+ render: (args) => (
+ <DropdownMenu defaultOpen>
+ <DropdownMenuTrigger render={<Button variant="primary" />}>Save as</DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-80" data-attr="sql-editor-save-as-dialog">
+ <QuillSaveAsMenuItems {...args} />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ),
+}
diff --git a/products/data_warehouse/frontend/sql_editor/saveAsTargets.ts b/products/data_warehouse/frontend/sql_editor/saveAsTargets.ts
new file mode 100644
index 000000000000..7889b9971321
--- /dev/null
+++ b/products/data_warehouse/frontend/sql_editor/saveAsTargets.ts
@@ -0,0 +1,56 @@
+import type { ComponentType } from 'react'
+
+import { IconCalculator, IconDatabase, IconEndpoints, IconGraph } from '@posthog/icons'
+
+export type SaveAsTargetId = 'insight' | 'view' | 'endpoint' | 'metric'
+
+export interface SaveAsTargetMetadata {
+ label: string
+ description: string
+ helpText: string
+ docsUrl: string
+ icon: ComponentType<{ className?: string }>
+}
+
+export interface SaveAsTarget extends SaveAsTargetMetadata {
+ id: SaveAsTargetId
+ recommended: boolean
+ disabledReason?: string | null
+ dataAttr?: string
+}
+
+export interface SaveAsMenuProps {
+ targets: SaveAsTarget[]
+ onSelect: (target: SaveAsTargetId) => void
+}
+
+export const SAVE_AS_TARGETS: Record<SaveAsTargetId, SaveAsTargetMetadata> = {
+ insight: {
+ label: 'Insight',
+ description: 'Visualize and share the query results.',
+ helpText: 'Create a chart or table that you can share or add to a dashboard.',
+ docsUrl: 'https://posthog.com/docs/data-warehouse/query#sql-visualizations',
+ icon: IconGraph,
+ },
+ view: {
+ label: 'View',
+ description: 'Reuse the query results in other SQL queries.',
+ helpText: 'Create a table that other SQL queries can use. You can materialize the view after you save it.',
+ docsUrl: 'https://posthog.com/docs/data-warehouse/views',
+ icon: IconDatabase,
+ },
+ endpoint: {
+ label: 'Endpoint',
+ description: 'Make the query available through an API.',
+ helpText: 'Create a versioned API that runs this query and returns its results.',
+ docsUrl: 'https://posthog.com/docs/endpoints',
+ icon: IconEndpoints,
+ },
+ metric: {
+ label: 'Metric',
+ description: 'Define a reusable business measure.',
+ helpText: 'Create a governed measure that people and tools can use from one shared definition.',
+ docsUrl: 'https://posthog.com/docs/semantic-layer/metrics',
+ icon: IconCalculator,
+ },
+}