Repository navigation
feat(editor): add a chart view for query results - #1193
Conversation
f48c542 to
9acf4d6
Compare
| maxPoints = MAX_CHART_POINTS, | ||
| ): ChartDataPoint[] { | ||
| const rows = result.rows.length > maxPoints ? result.rows.slice(0, maxPoints) : result.rows; | ||
| return transformResultToChartData({...result, rows}, config); |
There was a problem hiding this comment.
WARNING: NULL values in a numeric Y column are plotted as 0
classifyResultColumns skips NULLs when deciding a column is numeric, but transformResultToChartData then does typeof val === 'number' ? val : Number(val) || 0, so every NULL (and Number(null)) becomes a real 0 data point. In a line chart this draws a false dip to zero; in a bar chart it draws a zero-height bar indistinguishable from a real 0. For query results (LEFT JOINs, sparse metrics) NULL is common. Map null/undefined to null here (Recharts renders a gap with connectNulls={false}) instead of coercing to 0, rather than reusing the notebook transform unchanged.
|
|
||
| // Module-level so the choice survives the result panel remounting (switching | ||
| // editor tabs unmounts it). Keyed by tab id or result entry id; not persisted. | ||
| const states = new Map<string, ResultChartState>(); |
There was a problem hiding this comment.
SUGGESTION: Module-level states map is never pruned
Entries keyed by tab id / result entry id are never removed when a tab closes or a multi-result run is replaced (entry ids are regenerated per run), so the map grows for the lifetime of the app. Also, update() notifies every subscriber on any change, re-rendering all mounted result panels. Consider exposing a clearResultChartState(key) and calling it on tab close / result replacement, or keying the notification per key.
Code Review SummaryStatus: No Issues Found | Recommendation: Merge The changes since the last reviewed commit ( Files Reviewed (2 files)
Previous Review Summaries (2 snapshots, latest commit 6fc02d5)Current summary above is authoritative. Previous snapshots are kept for context only. Previous review (commit 6fc02d5)Status: No Issues Found | Recommendation: Merge Both findings from the previous review are fixed at the current head (
Files Reviewed (chart-related files in the rebased PR)
Previous review (commit 9acf4d6)Status: 2 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)WARNING
SUGGESTION
Files Reviewed (36 files)
Reviewed by claude-sonnet-5.5 · Input: 250 · Output: 1.1K · Cached: 162.1K Review guidance: REVIEW.md from base branch |
debba
left a comment
There was a problem hiding this comment.
Thanks for this, it's a big one and it shows how much care went into it! Unmounting the grid while the chart is shown, instead of just hiding it, is a great call: DataGrid's document-level Delete/Backspace can't act on rows nobody can see, and selection, pending edits and scroll come back when you switch back. EditorResultChart.test.tsx covers exactly that. No effects, useSyncExternalStore for the state, theme tokens only, aria-pressed toggles, a labelled select, a figure with a caption, all 11 locales. Really nice.
One thing I'd like fixed before merge: NULL Y values are plotted as 0. shapeResultChartData reuses transformResultToChartData, which does Number(val) || 0. With sparse data (LEFT JOIN aggregates, missing months) lines show false dips to 0 and the tooltip says 0, and the fallback in formatChartValue for missing values can never run. In the result chart path a null should stay null, and then you can decide on connectNulls for lines.
Then the rebase after #676:
- New files land under
packages/web-ui/.... When I tried it,Editor.tsx, the locales,setup.tsandCellChart.tsxmerged on their own. ResultsWindowPage.tsxis a modify/delete conflict. Main rewrote that page, and itsMultiResultPanelalready getsallowChart. You need to re-addallowChartto the single-resultResultEntryContent.- After the rebase,
EditorResultChart.test.tsxfails 3 tests because the Editor now callsuseTabularisClient(). The test needs a client provider, like the one intests/pages/EditorHistoryReplay.test.tsx.
Nits, fine as follow-ups:
classifyResultColumnsscans all loaded rows, not just the plotted 1,000, and it's called fromgetChartUnavailableReason,getChartValueColumns,reconcileResultChartConfig,buildDefaultResultChartConfigandgetSeriesSlots. That's several full passes per config click: fine for normal pages, noticeable with big ones. Classifying once per result would avoid it.- The module-level
statesMap inuseResultChartState.tsnever drops entries when a tab closes. NUMERIC_STRINGalso matches zero-padded codes like ZIP or phone strings ("01234").TEMPORAL_STRINGisn't anchored at the end, so"2024-01-01abc"counts as a date.buildTemporalFormattersstops at HH:MM, so timestamps that differ only in seconds get identical ticks.countinResultChart.tsxisn't locale-formatted, whilescopeCappedis.
Let a loaded SQL result switch between the grid and a bar or line chart with explicit X and Y column selection (TabularisDB#1168, first milestone). - Grid | Chart toggle in the result status bar of query tabs, the multi-result Tabs view and the detached results window. Table tabs and the stacked view are unchanged. - Defaults from column types: a date-like X starts a line chart, a text X a bar chart; Y skips id columns when it can. Stored config is kept per result and reconciled when columns change. - Charts only the loaded rows (capped at 1,000 points) and says so, including when more rows are not loaded. - Reuses Recharts, the notebook chart transform and the theme palette (now a shared hook). Series colours use a colour-blind-checked token order, follow the column, and lines get dash patterns. - Native buttons with aria-pressed, a labelled X select, a figure with a screen-reader caption, keyboard point navigation, reduced-motion support and empty states with a way back to the grid. Closes TabularisDB#1168
In Chart view the data toolbar still offered New Row, Delete Row and the copy format, delimiter and header controls. New Row added a pending row the chart can't show, so the user added an invisible row. Chart view now leaves those actions out. The toolbar row only appears while edits are pending, and then shows just the pending-changes bar, so Submit and Rollback stay reachable. Grid view is unchanged.
shapeResultChartData reused the notebook transform, which turns every NULL into 0. With sparse results (LEFT JOIN aggregates, missing months) lines dipped to 0, bars drew a zero, and the tooltip said 0. The result chart now shapes its own points and keeps NULL as null: - Lines break at a NULL (connectNulls stays off, so the chart never draws values the query didn't return). A value with NULLs on both sides gets a marker even above 40 points, so it doesn't vanish. - Bars leave the slot empty. - The tooltip keeps NULL entries and shows them as a muted dash via formatChartValue's missing-value fallback. Notebook charts are unchanged.
classifyResultColumns scanned every loaded row and ran from five helpers, so one config click made several full passes over large pages. It now looks only at the rows a chart can plot (the first 1,000) and caches the result per QueryResult in a WeakMap, since results are replaced rather than mutated.
- NUMERIC_STRING no longer accepts zero-padded codes ("01234", "007"),
so ZIP or phone columns stay text. "0" and "0.5" still count.
- TEMPORAL_STRING is anchored at the end, so "2024-01-01abc" is text.
A trailing UTC offset ("+00", "+05:30", "Z", " UTC") is still a date.
- Temporal ticks and tooltips include seconds when any timestamp has
them, so points a few seconds apart no longer share a tick label.
"Rows plotted: N" and the screen-reader caption passed the raw number, while the capped note grouped its digits. All three now use formatChartCount, which also falls back to English for an invalid locale instead of throwing like toLocaleString.
The module-level map in useResultChartState kept the view and config of
every tab ever opened. EditorProvider already has one place where every
closed tab ends up (it releases the tab's query session there), so it
now also calls forgetResultChartStates for those tabs, which removes the
tab's own state and that of its result entries.
Entry ids are `${tabId}-result-${index}` and are reused on every run, so
re-running a multi-statement query doesn't add entries to the map. The
prefix now comes from resultEntryIdPrefix in multiResult.ts, so the two
sides can't drift apart.
9acf4d6 to
6fc02d5
Compare
|
Thanks for the careful review, @debba. Everything is addressed, and the branch is rebased onto main after #676. Each item is its own commit, so it's easy to review one at a time. Rebase after #676
NULL Y values plotted as 0 (
Chart view toolbar (
Nits
I also updated the plan doc to match: NULL gaps, the chart-view toolbar, and question 3 now only asks about notebook charts. |
debba
left a comment
There was a problem hiding this comment.
Thanks for turning this around so carefully. Splitting every review point into its own commit made the re-review really easy, and the NULL fix went further than I asked: gaps on lines, empty bar slots, a marker for isolated points and the missing value shown in the tooltip, all with real Recharts renders in the tests. Hiding New Row and the copy controls in chart view, which you found yourself while trying it in the app, is a good catch too.
I checked every point from my last review against the code and they are all fixed, and the rebase is clean as well. There are just two small things left before I can merge, and both are quick:
-
CI is red at "Check web API inventory". Your
Editor.tsxchanges move theset_window_titleinvoke from line 726 to 734, soweb-ui-project/docs/web-ui-parity.jsonis stale. Runningpnpm web:inventory:writeand committing the file fixes it. Until then the later CI steps, including the full test run, don't run at all. -
The new test "forgets a closed tab's result chart view" in
tests/contexts/EditorProvider.test.tsxis flaky: it failed about half the time on my machine. It adds the two tabs before the asyncload_editor_preferenceshas resolved, and when that lands it replaces the connection's tabs with an initial tab, so the "kept" tab is treated as closed too. Waiting for the initial tab first and taking the last two tabs makes it pass reliably for me:await waitFor(() => expect(result.current.tabs).toHaveLength(1)); // ... const [closed, kept] = result.current.tabs.slice(-2).map((tab) => tab.id);
The app behaviour is correct, it's only the test.
A few things that can wait for a follow-up, none of them block this PR:
- A result with a single numeric column (
SELECT COUNT(*) AS n FROM t) shows "No numeric columns to plot", which reads oddly since there is one. Maybe a different message for "needs a second column for X". - With duplicate column names (
SELECT a.id, b.id ...) the X select gets two options with the same key and value, and both point to the first column. - Recharts now sits in the shared
resultsWindowSyncchunk, so the detached results window loads it even if nobody opens a chart. Lazy loadingResultChartwould avoid that. The Editor route itself only grows by about 6 kB gzipped, so not a big deal.
Push those two fixes and I'll do a last manual pass before merging.
…t state test The test added its two tabs before the async load_editor_preferences resolved. When it did, it replaced the connection's tabs with an initial tab, so the "kept" tab was closed too and the test failed about half the time. It now waits for the initial tab, then uses the last two tabs.
|
Thanks for the careful re-review, and for tracking down why that test was flaky. Both fixes are pushed:
I put the commits on top of your merge of I'll handle the follow-ups in a separate PR: a clearer message when the result has only one numeric column, duplicate column names in the X select, and lazy-loading |
There was a problem hiding this comment.
Thanks again for the two fixes. The API inventory is current, and the closed-tab test waits for the preferences load before taking the last two tabs. The ten relevant test files pass (144 tests), and that previously flaky case passed ten consecutive runs.
I have now tried this in the real macOS app, built from this PR with the WebDriver feature and a separate SQLite fixture. Bar and line views work, NULL values leave gaps, and loading all 1,200 rows shows the first-1,000 cap. The detached window can switch to a chart and render it; reattaching keeps the main window's chart choice. Closing the chart tab and opening a new console starts in Grid view again.
Approved. The existing follow-ups remain, and I reproduced the first two in the app:
- A single numeric column (
SELECT COUNT(*) AS n ...) says "No numeric columns to plot", though the value is numeric. - Duplicate column names produce indistinguishable X options with the same value.
- Lazy-load ResultChart so a detached results window does not load Recharts before it is needed.
The native checks are complete. These can stay as follow-ups.
* fix(result-chart): reference columns by index so repeated names work A result can repeat a column name (`SELECT a.id, b.id ...`). The chart config stored column names, so the X select got two options with the same key and value, both pointing at the first column, and Y series of the same name collided in the chart data. The result chart now has its own config that references columns by index. X options and Y toggles are keyed by index, chart points use index keys (`c0`, `c1`, ...), and a repeated name is shown as `id (2)` from its second copy on. The config also keeps the column names it was made for, so a re-run that moves columns still plots the same ones. * feat(result-chart): plot a single numeric column by row number A result with one numeric column (`SELECT amount FROM orders ORDER BY created_at`) said "No numeric columns to plot", which read oddly since there is one. It had nothing to put on X. The X select now offers "Row number" first, and a single numeric column is plotted by it by default. Ticks show grouped row numbers and the tooltip reads "Row 12". The only numeric column is disabled as an X option, and a stored config that has it on X falls back to the defaults, so the chart can no longer get stuck on an empty state. A single value (`SELECT COUNT(*) AS n FROM t`) is still not charted: a one-bar chart says less than the grid. It gets its own message that asks for a second column for X or more rows. New strings in all 11 locales. * perf(result-chart): load the chart and Recharts only when Chart view opens ResultChart was imported statically by ResultEntryContent, so Recharts landed in the shared resultsWindowSync chunk and the detached results window downloaded it even when nobody opened a chart. The panels now render LazyResultChart, a React.lazy wrapper. Its fallback keeps the chart's place in the layout and fades a muted spinner in only after 200ms, so the usual fast load shows no flash. Hovering or focusing the Chart toggle starts the download early, and a failed load can be retried. Production build: resultsWindowSync goes from 553.5 kB (162.5 kB gzip) to 177.6 kB (51.2 kB gzip). ResultChart is its own 14.1 kB (5.5 kB gzip) chunk; Recharts sits in a chunk shared with the notebook chart, which the Editor already loaded before. * fix(result-chart): show a failed chart load in place, with a retry React.lazy keeps a rejected chunk load, so the chart couldn't be retried and the error reached the editor's boundary. Catch it next to the chart, offer Try again (with a fresh lazy component) and Show grid. --------- Co-authored-by: Andrea Debernardi <andrea@debbaweb.it>
Closes #1168.
Plan first, as suggested in #1168: the plan is in
.github/planning/result-charts.md(the first commit). It covers chart types, how columns are picked, where the chart lives, data limits, design and accessibility, and three open questions. A first implementation of that plan is in the second commit so it can be tried, but I'm happy to change any of it once we agree on the plan. Opened as a draft until then.What
This is the first milestone of #1168. A loaded SQL result can now switch between the grid and a bar or line chart, with explicit X and Y column selection.
Grid | Charttoggle sits in the result status bar of query tabs, the multi-result Tabs view and the detached results window. Table-browse tabs and the stacked multi-result view work exactly as before.How
packages/web-ui/src/utils/resultChart.ts). A column whose loaded values are all numbers or numeric strings counts as numeric, so DECIMALs sent as strings work too. If a date-like column exists, it goes on X and the chart starts as a line. Otherwise the first text column goes on X and the chart starts as a bar. Y defaults to the first numeric column that isn't X, and skipsid/*_idcolumns when there's another option.useSyncExternalStorestore (packages/web-ui/src/hooks/useResultChartState.ts) keeps the view and config per tab (single result) or per entry (multi-result), so they survive switching editor tabs. A stored config is reconciled against the current columns, so a re-run that drops or changes columns falls back sensibly. It isn't persisted yet; that's planned for milestone two.packages/web-ui/tests/pages/EditorResultChart.test.tsx.NotebookView, so there's no new dependency and no bundle growth. The chart reuses theCellChartConfigshape; its data shaping (shapeResultChartData) keeps NULL values as gaps rather than going through the notebook'stransformResultToChartData. The theme palette moved fromCellChart.tsxtopackages/web-ui/src/hooks/useChartPalette.tsso both charts share it; notebook output is unchanged.packages/web-ui/src/utils/chartPalette.ts) was checked for protan/deutan separation across all built-in themes. Colour follows the column, lines after the first are dashed, and the Y chips carry a key that matches the mark.prefers-reduced-motion. The chart dims during a refresh, and empty states offer "Show grid".aria-pressedand visible focus. The X select is labelled. The chart is a<figure>with a screen-reader caption, and Recharts' keyboard layer moves between points with the arrow keys (the tooltip follows). The Grid view is the data-table fallback.editor.resultChart.*keys in all 11 locales.Screenshots
Real desktop app (debug build), SQLite.
Line chart, dark theme
Bar chart, light theme
No numeric columns: empty state
NULL values leave a gap instead of a dip to 0
Pending edits: Submit / Rollback stay reachable in Chart view
Tests
packages/web-ui/tests/utils/resultChart.test.ts: column classification, default chart selection from column types, reconciling changed columns, toggling X/Y and the series limit, row scope and cap, data shaping, number/date formatting, colour slots, dashes and bar spacing.packages/web-ui/tests/utils/chartPalette.test.ts: token order, de-duplication and theme radius.packages/web-ui/tests/hooks/useResultChartState.test.ts,packages/web-ui/tests/hooks/usePrefersReducedMotion.test.ts.packages/web-ui/tests/components/ui/ResultViewToggle.test.tsx,ResultChart.test.tsx,ResultChartPlot.test.tsx(real Recharts render),ResultEntryContent.test.tsx(toggle, opt-in, compact mode, per-entry state).packages/web-ui/tests/pages/EditorResultChart.test.tsx: the Editor toggle keeps selection and pending edits, keeps the choice per tab, and doesn't appear on table tabs.packages/web-ui/tests/pages/EditorResultChart.test.tsx: in Chart view the row and copy actions aren't rendered, the pending bar stays while edits are pending and can roll them back, and Grid view is unchanged.packages/web-ui/tests/utils/resultChart.test.tsandpackages/web-ui/tests/components/ui/ResultChartPlot.test.tsx: NULLs as gaps (split line path, empty bar slot, isolated-point marker, "—" in the tooltip), zero-padded codes, anchored dates, seconds in ticks, locale-formatted counts, and classification caching.packages/web-ui/tests/hooks/useResultChartState.test.tsandpackages/web-ui/tests/contexts/EditorProvider.test.tsx: closing a tab forgets its chart state and its entries' state.Checks run:
npx tsc -b(inpackages/web-ui): clean.pnpm lint(ESLint with jsx-a11y, Prettier, theme token check): clean.npx vitest --config packages/web-ui/vitest.config.ts run --testTimeout=30000(from the repo root): 464 files, 7,283 tests. 7,278 pass. The 5 failures are all inweb-ui-project/tests/runWebUiTasks.test.mjs. They fail the same way on a cleanmaincheckout here (5 of 6), and this PR doesn't touchweb-ui-project/.