Files
supabase/apps/studio/components/interfaces/Explorer/QueryEditor/DisplaySettingsButton.tsx
T
CharisandJoshen Lim 8bdfe03fe7 refactor(studio): drop notebook type widening now that the API supports it (#49272)
## Summary

- Regenerates `packages/api-types` for the content endpoints now that
the Platform API's `notebook` content type has landed (list/get/upsert
`type` enums, plus `UpsertContentBody`'s notebook cell shape with
`_id`/`y_series`). Unrelated schema drift from the same regen
(Warehouse, SSO, notification exceptions, etc.) is excluded — only the
content-endpoint hunks are applied.
- Removes every local widening cast added while the API support was
pending (`content-query.ts`, `content-infinite-query.ts`,
`notebook-query.ts`, `notebook-upsert-mutation.ts`,
`sql-folders-query.ts`).
- What remains is scoped and renamed to match: draft ids
(`generateDraftId`/`isDraftId`), used only for cells created client-side
in the editor before their first save, dropped before they'd ever reach
the backend as a fake `_id`.

## Test plan

- [x] `pnpm typecheck` — clean
- [x] `pnpm --filter studio test` — full suite passes (518 files / 5471
tests)
- [x] `pnpm --filter studio run lint:ratchet` — no new warnings
- [x] `pnpm format` / prettier — clean

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

* **Bug Fixes**
* Improved notebook cell tracking during editing, reordering, insertion,
and deletion.
* Preserved existing cell identifiers while removing temporary draft
identifiers before saving.
* Improved chart configuration for selecting and displaying multiple
Y-axis series.
  * Strengthened notebook validation and content persistence behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-08-20 13:06:41 +08:00

289 lines
9.6 KiB
TypeScript

import { BarChart2, Settings2, Table } from 'lucide-react'
import { useEffect, useEffectEvent, useMemo } from 'react'
import {
Checkbox,
Popover,
PopoverContent,
PopoverSeparator,
PopoverTrigger,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
ToggleGroup,
ToggleGroupItem,
Tooltip,
TooltipContent,
TooltipTrigger,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import {
MultiSelector,
MultiSelectorContent,
MultiSelectorItem,
MultiSelectorList,
MultiSelectorTrigger,
} from 'ui-patterns/multi-select'
import { ExplorerToolbarAction } from '../ExplorerToolbar'
import { type QueryDisplay, type QueryResult } from '../types'
import { checkHasNonPositiveValues } from '@/components/ui/QueryBlock/QueryBlock.utils'
import { MAX_CHART_Y_SERIES, type ChartConfig } from '@/data/content/notebooks/notebook-schema'
interface DisplaySettingsButtonProps {
display: QueryDisplay
result?: QueryResult
columns: string[]
disabled: boolean
onChange: (display: QueryDisplay) => void
}
const getLogScaleDisabledReason = (y_series: string[]) => {
if (y_series.length === 0) return 'Select a column for the Y axis first'
if (y_series.length > 1) return 'Only available with a single Y axis column'
return 'Data contains zero or negative values'
}
export const DisplaySettingsButton = ({
display,
result,
columns,
disabled,
onChange,
}: DisplaySettingsButtonProps) => {
const { view, chart } = display
const {
type = 'bar',
x_column,
y_series = [],
cumulative = false,
show_labels = false,
scale = 'linear',
} = chart ?? {}
const hasNonPositiveValues = useMemo(
() => checkHasNonPositiveValues(result?.rows ?? [], y_series[0]),
[result, y_series]
)
// Logarithmic scale only applies to a single series.
const canToggleLogScale = useMemo(() => {
if (y_series.length !== 1 || !result || (result.rows ?? []).length === 0) return false
return !hasNonPositiveValues
}, [hasNonPositiveValues, result, y_series.length])
const onChangeView = (view: 'table' | 'chart') => {
onChange({ ...display, view })
}
const onUpdateChartConfig = (payload: Partial<ChartConfig>) => {
onChange({
...display,
chart: {
type: chart?.type ?? 'bar',
x_column: chart?.x_column ?? '',
y_series: chart?.y_series ?? [],
cumulative: chart?.cumulative ?? false,
scale: chart?.scale ?? 'linear',
show_labels: chart?.show_labels ?? false,
...payload,
},
})
}
const resetToLinearScale = useEffectEvent(() => {
onUpdateChartConfig({ scale: 'linear' })
})
useEffect(() => {
if (scale === 'log' && (hasNonPositiveValues || y_series.length > 1)) {
resetToLinearScale()
}
}, [hasNonPositiveValues, scale, y_series.length])
return (
<Popover>
<PopoverTrigger asChild>
<ExplorerToolbarAction disabled={disabled} icon={<Settings2 />} tooltip="Result settings" />
</PopoverTrigger>
<PopoverContent side="bottom" className="flex flex-col gap-y-3 p-0 py-3 mr-8 w-80">
<div className="flex flex-col gap-y-3 px-3">
<p className="text-xs tracking-tighter uppercase font-mono text-foreground-lighter">
Result display settings
</p>
<FormItemLayout isReactForm={false} label="View data as">
<ToggleGroup
value={view}
onValueChange={(value) => {
if (value === 'table' || value === 'chart') onChangeView(value)
}}
variant="outline"
type="single"
>
<ToggleGroupItem value="table" className="w-full gap-x-2 data-[state=on]:bg-accent">
<Table size={14} />
<p>Table</p>
</ToggleGroupItem>
<ToggleGroupItem value="chart" className="w-full gap-x-2 data-[state=on]:bg-accent">
<BarChart2 size={14} />
<p>Chart</p>
</ToggleGroupItem>
</ToggleGroup>
</FormItemLayout>
</div>
{view === 'chart' && (
<>
<PopoverSeparator />
<FormItemLayout isReactForm={false} label="Render chart as" className="px-3 mb-1">
<ToggleGroup
value={type}
onValueChange={(value) => {
if (value === 'bar' || value === 'line') onUpdateChartConfig({ type: value })
}}
variant="outline"
type="single"
>
<ToggleGroupItem value="bar" className="w-full data-[state=on]:bg-accent">
Bar
</ToggleGroupItem>
<ToggleGroupItem value="line" className="w-full data-[state=on]:bg-accent">
Line
</ToggleGroupItem>
</ToggleGroup>
</FormItemLayout>
<div className="px-3 flex flex-col gap-y-2">
<FormItemLayout
isReactForm={false}
layout="flex-row-reverse"
label="X axis"
className="[&>div:first-child]:xl:w-3/5"
>
<Select
value={x_column}
onValueChange={(x_column) => onUpdateChartConfig({ x_column })}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select a column" />
</SelectTrigger>
<SelectContent>
{columns.map((x) => (
<SelectItem key={x} value={x}>
{x}
</SelectItem>
))}
</SelectContent>
</Select>
</FormItemLayout>
<FormItemLayout
isReactForm={false}
layout="flex-row-reverse"
label="Y Axis"
className="[&>div:first-child]:xl:w-3/5"
>
<MultiSelector
values={y_series}
onValuesChange={(values) => {
if (values.length > MAX_CHART_Y_SERIES) return
onUpdateChartConfig({ y_series: values })
}}
className="w-full"
>
<MultiSelectorTrigger
mode="inline-combobox"
label={`Select up to ${MAX_CHART_Y_SERIES} columns`}
deletableBadge
badgeLimit="wrap"
showIcon={false}
className="min-w-32!"
/>
<MultiSelectorContent>
<MultiSelectorList>
{columns.map((x) => (
<MultiSelectorItem
key={x}
value={x}
disabled={y_series.length >= MAX_CHART_Y_SERIES && !y_series.includes(x)}
>
{x}
</MultiSelectorItem>
))}
</MultiSelectorList>
</MultiSelectorContent>
</MultiSelector>
</FormItemLayout>
<FormItemLayout
isReactForm={false}
layout="flex-row-reverse"
label="Scale"
className="[&>div:first-child]:xl:w-3/5"
>
<Select
value={scale}
onValueChange={(scale) =>
onUpdateChartConfig({ scale: scale as 'log' | 'linear' })
}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select a column" />
</SelectTrigger>
<SelectContent>
<SelectItem value="linear">Linear</SelectItem>
<Tooltip>
<TooltipTrigger asChild>
<SelectItem
disabled={!canToggleLogScale}
value="log"
className={!canToggleLogScale ? '!pointer-events-auto' : undefined}
>
Logarithmic
</SelectItem>
</TooltipTrigger>
{!canToggleLogScale && (
<TooltipContent side="left">
{getLogScaleDisabledReason(y_series)}
</TooltipContent>
)}
</Tooltip>
</SelectContent>
</Select>
</FormItemLayout>
<FormItemLayout id="cumulative" isReactForm={false} layout="flex" label="Cumulative">
<Checkbox
id="cumulative"
checked={cumulative}
onCheckedChange={(cumulative) =>
onUpdateChartConfig({ cumulative: Boolean(cumulative) })
}
/>
</FormItemLayout>
<FormItemLayout
id="show_labels"
isReactForm={false}
layout="flex"
label="Show labels"
>
<Checkbox
id="show_labels"
checked={show_labels}
onCheckedChange={(show_labels) =>
onUpdateChartConfig({ show_labels: Boolean(show_labels) })
}
/>
</FormItemLayout>
</div>
</>
)}
</PopoverContent>
</Popover>
)
}