Files
Saxon Fletcher 252f69e451 chore(studio): refine Explorer sidebar, onboarding, and notebooks (#50555)
## Summary

A round of small Explorer refinements.

**Sidebar**
- Adds a **Run SQL** row (with a `+` icon) above Notebooks in the
Explorer sidebar; opens a new query tab.

**Assistant**
- Assistant query cells now have the same **Save** dropdown as query
tabs (add to an existing notebook or create a new one). It shows only
when Explorer is enabled, and not while the query is still streaming.
- `SaveQueryDropdown` takes an optional `source`, so logs queries are
saved as log cells (keeping their time range) instead of database cells.
This also fixes saving logs queries from query tabs.
- The "Drafting notebook..." notice (and the notebook loading/status
rows) now span the full message width; `delete_notebook` parts use the
wide layout like create/update.

**Onboarding**
- Replaces the single page with a four-step walkthrough: Welcome to
Explorer (with a **Preview** badge), Run SQL, Notebooks, and Chat with
your project. Each step has an icon, heading, and short description,
with step dots and **Skip** / **Back** / **Next** buttons; the last step
ends with **Continue to Explorer**.
- Removes the "Choose how Explorer opens" choice (still available in
Account preferences) and the collapsible "Learn more" section. Skipping
or finishing still respects the saved startup preference.
- Deletes `ExplorerOnboardingLearnMore`, `ExplorerHomePreference`, and
`ExplorerHomePreview`, which were only used by onboarding.

**Notebooks**
- Query cells use the same max width as markdown cells (`48rem`, was
`72rem`).
- "Add query cell" / "Add markdown cell" are now **Add query** / **Add
markdown** everywhere; the buttons at the bottom of a notebook are
larger (34px, 18px icons).

## Test plan

- [ ] Explorer sidebar: **Run SQL** opens a new query tab
- [ ] Assistant: generate SQL, use **Save** to add it to a new and an
existing notebook; repeat with a logs query and confirm a log cell is
created
- [ ] Assistant: ask for a notebook and confirm the drafting notice is
full width
- [ ] Clear `hasCompletedOnboarding` in Explorer preferences and step
through onboarding (Next / Back / Skip); finishing or skipping respects
the startup preference set in Account preferences
- [ ] Notebook: query cells line up with markdown cell width; bottom add
buttons are larger


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
  - Added a **Run SQL** shortcut to Explorer navigation.
- Assistant query results can now be saved to notebooks, including log
queries.

- **Improvements**
- Updated Explorer onboarding with guided steps, progress navigation,
and visual previews.
  - Shortened Explorer action labels and refined control sizing.
- Reduced notebook query layout width and adjusted assistant notebook
displays.

- **Changes**
- Removed the Explorer startup preference selector and onboarding “Learn
more” section.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-18 14:38:29 +08:00

206 lines
7.1 KiB
TypeScript

import { type Hotkey } from '@tanstack/react-hotkeys'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import { AlignLeft, Check, Keyboard, Loader2, MoreVertical, SquareCode } from 'lucide-react'
import { useRouter } from 'next/router'
import { useCallback, useContext, useEffect, useRef, useState } from 'react'
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
KeyboardShortcut,
} from 'ui'
import { ExplorerToolbarAction } from './ExplorerToolbar'
import { QueryEditor, type ExplorerQueryModel, type QueryEditorHandle } from './QueryEditor'
import { SaveQueryDropdown } from './SaveQueryDropdown'
import { type QueryDisplay, type QueryResult } from './types'
import { toQuerySourceBinding } from '@/data/query-sources/query-source-registry'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { explorerQueryState, useExplorerQueryStateSnapshot } from '@/state/explorer-query'
import { useControlledRoleImpersonationState } from '@/state/role-impersonation-state'
import { hotkeyToKeys } from '@/state/shortcuts/formatShortcut'
import { SHORTCUT_DEFINITIONS, SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { createTabId, TabsStateContext } from '@/state/tabs'
/** Query-tab lifecycle adapter around the shared QueryEditor. */
export const ExplorerQueryTab = () => {
const router = useRouter()
const { id, ref } = useParams()
const tabs = useContext(TabsStateContext)
const querySnap = useExplorerQueryStateSnapshot()
const [isIntellisenseEnabled, setIsIntellisenseEnabled] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,
true
)
const queryEditorRef = useRef<QueryEditorHandle>(null)
const hotkeySequnece: Hotkey | undefined =
SHORTCUT_DEFINITIONS[SHORTCUT_IDS.SQL_EDITOR_FORMAT].sequence[0]
const formatKeys = hotkeySequnece ? hotkeyToKeys(hotkeySequnece) : undefined
const [restoredQueryKey, setRestoredQueryKey] = useState<string>()
const [showQuery, setShowQuery] = useState(true)
const stateDraft = id ? querySnap.drafts[id] : undefined
const draft = stateDraft?.projectRef === ref ? stateDraft : undefined
const result = draft && id ? querySnap.results[id] : undefined
const queryKey = id && ref ? `${ref}:${id}` : undefined
const isDraftReady = !!queryKey && restoredQueryKey === queryKey
const roleImpersonationState = useControlledRoleImpersonationState(
draft?._tag === 'database' ? draft.role : undefined,
useCallback(
(role) => {
if (id) explorerQueryState.setRole({ id, role })
},
[id]
)
)
useEffect(() => {
if (!id || !ref) return
setShowQuery(true)
explorerQueryState.restoreDraft({ id, projectRef: ref })
setRestoredQueryKey(`${ref}:${id}`)
}, [id, ref])
useEffect(() => {
if (!id || !isDraftReady || !draft?.pendingAutoRun) return
queryEditorRef.current?.run()
explorerQueryState.clearPendingAutoRun({ id })
}, [id, isDraftReady, draft?.pendingAutoRun])
if (!queryKey || restoredQueryKey !== queryKey) {
return (
<div
role="status"
aria-label="Loading query"
className="flex h-full items-center justify-center bg-surface-100"
>
<Loader2 className="animate-spin text-foreground-muted" size={18} />
</div>
)
}
if (!id || !draft) {
return (
<div className="flex h-full flex-col items-center justify-center gap-3 bg-surface-100">
<SquareCode className="text-foreground-muted" size={24} />
<div className="text-center">
<p className="text-sm font-medium">Query draft not found</p>
<p className="text-sm text-foreground-lighter">
This local draft may have been closed or cleared from this browser.
</p>
</div>
<Button variant="primary" onClick={() => router.push(`/project/${ref}/explorer`)}>
Back to Explorer
</Button>
</div>
)
}
const display: QueryDisplay = {
view: draft.view,
chart: draft.chart ? { ...draft.chart, y_series: [...draft.chart.y_series] } : undefined,
}
const query: ExplorerQueryModel =
draft._tag === 'logs'
? { ...toQuerySourceBinding(draft), uncheckedSql: draft.uncheckedSql }
: {
...toQuerySourceBinding(draft),
uncheckedSql: draft.uncheckedSql,
rowLimit: draft.rowLimit,
}
const persistTab = () => tabs.makeTabPermanent(createTabId('query', { id }))
const handleResultChange = (nextResult: QueryResult) => {
explorerQueryState.setResult({
id,
result: { ...nextResult, executedAt: Date.now() },
})
}
return (
<QueryEditor
ref={queryEditorRef}
id={id}
variant="viewport"
title={draft.name}
query={query}
result={result}
display={display}
showQuery={showQuery}
onShowQueryChange={setShowQuery}
roleImpersonationState={roleImpersonationState}
onTitleChange={(value) => {
persistTab()
const name = value.trim() || 'Run SQL'
explorerQueryState.updateDraft({ id, name })
tabs.updateTab(createTabId('query', { id }), { label: name })
}}
onSqlChange={(sql) => {
persistTab()
explorerQueryState.updateDraft({ id, sql })
}}
onSourceChange={(source) => {
persistTab()
explorerQueryState.updateDraft({ id, source })
}}
onRowLimitChange={(rowLimit) => {
persistTab()
explorerQueryState.updateDraft({ id, rowLimit })
}}
onResultChange={handleResultChange}
onDisplayChange={(display) => {
persistTab()
explorerQueryState.setDisplay({ id, display })
}}
toolbarActions={
<>
<SaveQueryDropdown
query={{ title: draft.name, sql: draft.uncheckedSql }}
source={toQuerySourceBinding(draft)}
/>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<ExplorerToolbarAction icon={<MoreVertical size={16} strokeWidth={2} />} />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-48" align="end">
<DropdownMenuItem
className="justify-between"
onClick={() => setIsIntellisenseEnabled(!isIntellisenseEnabled)}
>
<div className="flex items-center gap-x-2">
<Keyboard size={14} />
<span>Intellisense enabled</span>
</div>
{isIntellisenseEnabled && <Check className="text-brand" size={16} />}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="justify-between"
onClick={() => queryEditorRef.current?.prettify()}
>
<span className="flex items-center gap-x-2">
<AlignLeft size={14} />
Prettify SQL
</span>
{formatKeys && <KeyboardShortcut keys={formatKeys} />}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>
}
/>
)
}