Add Chart Builder: no-JSON Vega-Lite composer from a dataset (M4)

This commit is contained in:
2026-06-05 23:46:21 +03:00
parent 693f5d7073
commit c11afc273d
16 changed files with 1856 additions and 26 deletions
@@ -0,0 +1,254 @@
/* Chart Builder — two-pane modal body (spec §06). */
.builder {
display: grid;
grid-template-columns: minmax(320px, 360px) 1fr;
min-height: 480px;
min-width: 0;
}
.muted {
margin: 0;
padding: var(--space-5);
font-size: 14px;
color: var(--text-secondary);
}
/* ── Left: configuration ─────────────────────────────────────────────── */
.configPane {
display: flex;
flex-direction: column;
gap: var(--space-5);
padding: var(--space-5);
border-right: var(--border-width) solid var(--border);
overflow-y: auto;
min-width: 0;
}
.datasetName {
margin: 0;
font-size: 13px;
color: var(--text-secondary);
}
.datasetName strong {
color: var(--text);
}
.field {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.fieldLabel {
font-size: 12px;
font-weight: 500;
color: var(--text-secondary);
}
.channels {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.channelsHeader {
display: flex;
align-items: baseline;
justify-content: space-between;
}
.swap {
border: none;
background: transparent;
color: var(--accent);
font: inherit;
font-size: 12px;
cursor: pointer;
padding: var(--space-1) var(--space-2);
border-radius: var(--radius);
}
.swap:hover {
background: var(--layer-01);
}
.swap:focus-visible {
outline: 2px solid var(--focus);
outline-offset: 1px;
}
.channelRow {
display: grid;
grid-template-columns: 48px 1fr auto;
align-items: center;
gap: var(--space-2);
}
.channelLabel {
font-size: 12px;
font-weight: 600;
color: var(--text);
}
.select,
.typeSelect {
padding: var(--space-2) var(--space-3);
border: var(--border-width) solid var(--border-strong);
border-radius: var(--radius);
background: var(--bg);
color: var(--text);
font: inherit;
font-size: 13px;
}
.typeSelect {
font-size: 12px;
}
.select:focus-visible,
.typeSelect:focus-visible,
.dimInput:focus-visible {
outline: 2px solid var(--focus);
outline-offset: -1px;
}
.dimensions {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.dimInputs {
display: flex;
gap: var(--space-3);
}
.dimField {
display: flex;
flex-direction: column;
gap: var(--space-1);
font-size: 12px;
color: var(--text-secondary);
}
.dimInput {
width: 100px;
padding: var(--space-2) var(--space-3);
border: var(--border-width) solid var(--border-strong);
border-radius: var(--radius);
background: var(--bg);
color: var(--text);
font: inherit;
font-size: 13px;
}
.warnings {
display: flex;
flex-direction: column;
gap: var(--space-2);
margin: 0;
padding: var(--space-3);
list-style: none;
background: var(--layer-01);
border: var(--border-width) solid var(--border);
border-radius: var(--radius);
}
.warning {
font-size: 12px;
line-height: 1.4;
color: var(--text-secondary);
}
.warning::before {
content: '⚠ ';
color: var(--support-warning, var(--text-secondary));
}
.actions {
display: flex;
justify-content: flex-end;
gap: var(--space-3);
margin-top: auto;
}
.action {
height: 36px;
padding: 0 var(--space-5);
border: var(--border-width) solid var(--border-strong);
border-radius: var(--radius);
background: transparent;
color: var(--text);
font: inherit;
font-weight: 500;
cursor: pointer;
transition: background var(--dur-fast) var(--ease);
}
.action:hover {
background: var(--layer-01);
}
.action:focus-visible {
outline: 2px solid var(--focus);
outline-offset: 2px;
}
.primary {
background: var(--accent);
border-color: transparent;
color: var(--accent-contrast);
font-weight: 600;
}
.primary:hover {
background: var(--accent-hover);
}
.primary:disabled {
background: var(--layer-02, var(--layer-01));
color: var(--text-placeholder);
cursor: not-allowed;
}
/* ── Right: live preview ─────────────────────────────────────────────── */
.previewPane {
display: flex;
flex-direction: column;
padding: var(--space-5);
min-width: 0;
background: var(--bg);
}
.previewHint {
margin: auto;
font-size: 13px;
color: var(--text-secondary);
text-align: center;
}
.previewFrame {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
justify-content: center;
}
.previewHost {
width: 100%;
}
.previewError {
margin: auto 0;
padding: var(--space-3);
font-family: var(--font-mono);
font-size: 12px;
line-height: 1.5;
white-space: pre-wrap;
color: var(--support-error);
}
@@ -0,0 +1,77 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { createDataset } from '@core/dataset';
import { useChartBuilderStore } from '../stores/ChartBuilderStore';
import { useDatasetStore } from '../stores/DatasetStore';
import { useSnippetStore } from '../stores/SnippetStore';
import { ChartBuilderModal } from './ChartBuilderModal';
// The builder preview embeds a real Vega chart in an effect; stub the renderer so
// this render test stays a pure React/DOM check (the loop we guard against happens
// during commit, long before any chart is drawn).
vi.mock('../services/chart-renderer', () => ({
renderSpec: () => Promise.resolve({ destroy() {}, resize() {} }),
}));
// React 19 wants this flag set for act() to drive effects without warnings.
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const T = new Date('2026-06-01T00:00:00Z');
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
useChartBuilderStore.getState().reset();
useDatasetStore.getState().reset();
useSnippetStore.getState().reset();
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
describe('ChartBuilderModal', () => {
test('renders without an infinite update loop when the config has warnings (regression)', async () => {
// Two numeric columns → default mark Point (clean). Switching to Bar makes it
// "two measures on a non-scatter" → a NON-EMPTY warnings array — the exact
// condition that previously looped because the warnings selector returned a
// fresh array of objects on every render. The fix derives warnings via useMemo
// over the stable `config` reference instead.
const ds = createDataset({
name: 'Nums',
data: [
{ a: 1, b: 2 },
{ a: 3, b: 4 },
],
format: 'json',
source: 'inline',
now: T,
});
useDatasetStore.getState().add(ds);
useChartBuilderStore.getState().init(ds.id);
useChartBuilderStore.getState().setMark('bar');
expect(useChartBuilderStore.getState().config.mark).toBe('bar');
// If the component looped, this act() would throw "Maximum update depth exceeded".
await act(async () => {
root.render(<ChartBuilderModal />);
await Promise.resolve();
});
expect(container.textContent).toContain('Building from');
expect(container.textContent).toContain('scatter'); // the guidance hint rendered
});
test('shows the empty state when no dataset is loaded', async () => {
await act(async () => {
root.render(<ChartBuilderModal />);
await Promise.resolve();
});
expect(container.textContent).toContain('No dataset loaded');
});
});
+333
View File
@@ -0,0 +1,333 @@
/**
* Chart Builder — the modal body (spec §06).
*
* A two-pane composer: left is the configuration (dataset name, mark selector, one
* row per channel, optional dimensions, guidance, Create), right is a live preview
* of the spec the configuration produces. All spec logic and Tier-B defaults/guards
* come from `@core/chart-builder` via `ChartBuilderStore`; this component is the
* view. The preview is builder-local (its own debounced render over the shared
* `chart-renderer` service) rather than a reuse of `LivePreview`, which is bound to
* the snippet editor's stores.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
import { useShallow } from 'zustand/react/shallow';
import type { VisualizationSpec } from 'vega-embed';
import {
CHANNELS,
MARK_TYPES,
builderWarnings,
defaultFieldType,
isBuilderConfigValid,
isChannelTypeAllowed,
validFieldTypes,
type ChannelName,
type FieldType,
type MarkType,
} from '@core/chart-builder';
import type { ColumnType } from '@core/type-inference';
import { DatasetNotFoundError, prepareSpecForRender } from '@core/rendering';
import { chartConfigFor } from '@core/vega-themes';
import { renderSpec, type RenderHandle } from '../services/chart-renderer';
import { closeModal } from '../modals/ModalCoordinator';
import { useAppStore } from '../stores/AppStore';
import { useDatasetStore } from '../stores/DatasetStore';
import {
selectBuilderSpecText,
selectBuilderValid,
useChartBuilderStore,
} from '../stores/ChartBuilderStore';
import { SegmentedControl, type SegmentedOption } from './SegmentedControl';
import styles from './ChartBuilderModal.module.css';
const RENDER_DEBOUNCE_MS = 300;
/** Title-case a token for display (e.g. `bar` → `Bar`, `quantitative` → `Quantitative`). */
function titleCase(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1);
}
const MARK_OPTIONS: ReadonlyArray<SegmentedOption<MarkType>> = MARK_TYPES.map((m) => ({
value: m,
label: titleCase(m),
}));
const CHANNEL_LABELS: Record<ChannelName, string> = {
x: 'X',
y: 'Y',
color: 'Color',
size: 'Size',
};
/** A compact type indicator for a column option (text · # · date · ✓). */
function typeBadge(type: ColumnType): string {
switch (type) {
case 'number':
return '#';
case 'date':
return 'date';
case 'boolean':
return 'bool';
default:
return 'text';
}
}
/** Whether a column may be placed on a channel at all (Size discipline, §06). */
function columnAllowedOnChannel(channel: ChannelName, colType: ColumnType): boolean {
return isChannelTypeAllowed(channel, defaultFieldType(colType));
}
function ChannelRow({ channel }: { channel: ChannelName }) {
const columns = useChartBuilderStore((s) => s.columns);
const mapping = useChartBuilderStore((s) => s.config.encodings[channel] ?? null);
const setChannelColumn = useChartBuilderStore((s) => s.setChannelColumn);
const setChannelType = useChartBuilderStore((s) => s.setChannelType);
const colTypeOf = (name: string): ColumnType =>
columns.columnTypes.find((c) => c.name === name)?.type ?? 'string';
// Type options valid for this column AND allowed on this channel (e.g. Size hides
// Nominal). Shown only when >1 option and a column is selected (spec §06).
const typeOptions: FieldType[] = mapping
? validFieldTypes(colTypeOf(mapping.field)).filter((t) => isChannelTypeAllowed(channel, t))
: [];
return (
<div className={styles.channelRow}>
<label className={styles.channelLabel} htmlFor={`ch-${channel}`}>
{CHANNEL_LABELS[channel]}
</label>
<select
id={`ch-${channel}`}
className={styles.select}
value={mapping?.field ?? ''}
onChange={(e) => setChannelColumn(channel, e.target.value === '' ? null : e.target.value)}
>
<option value="">None</option>
{columns.columns.map((name) => {
const allowed = columnAllowedOnChannel(channel, colTypeOf(name));
return (
<option key={name} value={name} disabled={!allowed}>
{name} · {typeBadge(colTypeOf(name))}
{allowed ? '' : ' (needs a measure)'}
</option>
);
})}
</select>
{mapping && typeOptions.length > 1 && (
<select
className={styles.typeSelect}
aria-label={`${CHANNEL_LABELS[channel]} field type`}
value={mapping.type}
onChange={(e) => setChannelType(channel, e.target.value as FieldType)}
>
{typeOptions.map((t) => (
<option key={t} value={t}>
{titleCase(t)}
</option>
))}
</select>
)}
</div>
);
}
function BuilderPreview() {
const hostRef = useRef<HTMLDivElement>(null);
const handleRef = useRef<RenderHandle | null>(null);
const generationRef = useRef(0);
const [error, setError] = useState<string | null>(null);
const specText = useChartBuilderStore(selectBuilderSpecText);
const valid = useChartBuilderStore(selectBuilderValid);
const uiTheme = useAppStore((s) => s.uiTheme);
const datasets = useDatasetStore(useShallow((s) => s.datasets));
useEffect(() => {
const node = hostRef.current;
const timer = setTimeout(() => {
void (async () => {
const mine = ++generationRef.current;
// Below validation there is nothing to draw — clear the chart and show the
// configuration prompt, not an error (spec §06 → Live Preview placeholder).
if (!valid) {
handleRef.current?.destroy();
handleRef.current = null;
setError(null);
return;
}
if (!node) return;
try {
const parsed: unknown = JSON.parse(specText);
const prepared = prepareSpecForRender(parsed, { fitMode: 'width', datasets });
handleRef.current?.destroy();
handleRef.current = null;
const handle = await renderSpec(
node,
prepared as VisualizationSpec,
chartConfigFor(uiTheme),
);
if (mine !== generationRef.current) {
handle.destroy();
return;
}
handleRef.current = handle;
setError(null);
} catch (e) {
if (mine !== generationRef.current) return;
if (e instanceof DatasetNotFoundError) {
setError(`Dataset "${e.datasetName}" not found.`);
} else {
setError(`Couldn't render this chart: ${(e as Error).message}`);
}
}
})();
}, RENDER_DEBOUNCE_MS);
return () => clearTimeout(timer);
}, [specText, valid, uiTheme, datasets]);
// Finalize the view on unmount so the Vega view and its listeners don't leak.
useEffect(
() => () => {
handleRef.current?.destroy();
handleRef.current = null;
},
[],
);
return (
<div className={styles.previewPane}>
{!valid && (
<p className={styles.previewHint}>Map at least one channel to a column to see a chart.</p>
)}
<div className={styles.previewFrame} hidden={!valid || error !== null}>
<div className={styles.previewHost} ref={hostRef} />
</div>
{valid && error !== null && (
<pre className={styles.previewError} role="alert">
{error}
</pre>
)}
</div>
);
}
export function ChartBuilderModal() {
const datasetId = useChartBuilderStore((s) => s.datasetId);
const datasetName = useChartBuilderStore((s) => s.config.datasetName);
const mark = useChartBuilderStore((s) => s.config.mark);
const width = useChartBuilderStore((s) => s.config.width);
const height = useChartBuilderStore((s) => s.config.height);
const setMark = useChartBuilderStore((s) => s.setMark);
const swapXY = useChartBuilderStore((s) => s.swapXY);
const setWidth = useChartBuilderStore((s) => s.setWidth);
const setHeight = useChartBuilderStore((s) => s.setHeight);
const runCreate = useChartBuilderStore((s) => s.createSnippet);
// Derive validity + guidance from the stable `config` reference via useMemo, NOT
// from a store selector: `builderWarnings` builds a fresh array of objects each
// call, which no selector-equality (even useShallow, since the element objects
// differ every time) can stabilize — subscribing to it would re-render forever.
const config = useChartBuilderStore((s) => s.config);
const valid = useMemo(() => isBuilderConfigValid(config), [config]);
const warnings = useMemo(() => builderWarnings(config), [config]);
if (datasetId === null) {
return <p className={styles.muted}>No dataset loaded. Open this from a dataset in Datasets.</p>;
}
/** Parse a dimension input: blank → undefined, otherwise a non-negative integer. */
const parseDim = (raw: string): number | undefined => {
if (raw.trim() === '') return undefined;
const n = Number(raw);
return Number.isFinite(n) && n > 0 ? Math.round(n) : undefined;
};
return (
<div className={styles.builder}>
<div className={styles.configPane}>
<p className={styles.datasetName}>
Building from <strong>{datasetName}</strong>
</p>
<div className={styles.field}>
<span className={styles.fieldLabel}>Mark</span>
<SegmentedControl
label="Mark type"
options={MARK_OPTIONS}
value={mark}
onChange={setMark}
/>
</div>
<div className={styles.channels}>
<div className={styles.channelsHeader}>
<span className={styles.fieldLabel}>Encoding</span>
<button type="button" className={styles.swap} onClick={swapXY}>
Swap X/Y
</button>
</div>
{CHANNELS.map((channel) => (
<ChannelRow key={channel} channel={channel} />
))}
</div>
<div className={styles.dimensions}>
<span className={styles.fieldLabel}>Dimensions (optional)</span>
<div className={styles.dimInputs}>
<label className={styles.dimField}>
<span>Width</span>
<input
type="number"
min={1}
className={styles.dimInput}
value={width ?? ''}
placeholder="auto"
onChange={(e) => setWidth(parseDim(e.target.value))}
/>
</label>
<label className={styles.dimField}>
<span>Height</span>
<input
type="number"
min={1}
className={styles.dimInput}
value={height ?? ''}
placeholder="auto"
onChange={(e) => setHeight(parseDim(e.target.value))}
/>
</label>
</div>
</div>
{warnings.length > 0 && (
<ul className={styles.warnings}>
{warnings.map((w) => (
<li key={w.message} className={styles.warning}>
{w.message}
</li>
))}
</ul>
)}
<div className={styles.actions}>
<button type="button" className={styles.action} onClick={() => void closeModal()}>
Cancel
</button>
<button
type="button"
className={`${styles.action} ${styles.primary}`}
disabled={!valid}
onClick={() => runCreate()}
>
Create Snippet
</button>
</div>
</div>
<BuilderPreview />
</div>
);
}
+11 -4
View File
@@ -16,7 +16,7 @@ import { useState } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { datasetReference, type DataSource, type Dataset } from '@core/dataset';
import { detectFormat, detectFormatFromUrl, type DataFormat } from '@core/format-detection';
import { closeModal, resnapshot } from '../modals/ModalCoordinator';
import { closeModal, openModal, resnapshot } from '../modals/ModalCoordinator';
import { confirm } from '../stores/ConfirmStore';
import { notify } from '../stores/NotificationStore';
import { selectSelectedDataset, useDatasetStore, byModifiedDesc } from '../stores/DatasetStore';
@@ -221,9 +221,16 @@ function DatasetDetail({
<button type="button" className={styles.action} onClick={handleEdit}>
Edit
</button>
{/* "Build Chart from dataset" (spec §05) lands enabled with the Chart
Builder in M4. Per council (GOV.UK / NN/g), we don't ship a dead
disabled control in the meantime — the action appears when it works. */}
{/* Build Chart (spec §05 → §06) — opens the Chart Builder on this dataset.
Replaces the Datasets modal (one modal at a time, §01C); detail view has
no transient form state, so no discard prompt. */}
<button
type="button"
className={styles.action}
onClick={() => openModal('chartBuilder', String(dataset.id))}
>
Build Chart
</button>
<button
type="button"
className={`${styles.action} ${styles.danger}`}
+1 -1
View File
@@ -22,7 +22,7 @@ export function ModalShell() {
const name = useAppStore((s) => s.activeModal);
const config = getModalConfig(name);
const isLarge = name === 'datasets';
const isLarge = name === 'datasets' || name === 'chartBuilder';
// Move focus into the modal on open, return it to the trigger on close. For a
// large manager (list + detail), APG dialog-modal advises focusing a static
+13
View File
@@ -16,8 +16,10 @@
import type { ComponentType } from 'react';
import type { ActiveModal, ModalName } from './types';
import { ChartBuilderModal } from '../components/ChartBuilderModal';
import { DatasetsModal } from '../components/DatasetsModal';
import { ExtractModal } from '../components/ExtractModal';
import { useChartBuilderStore } from '../stores/ChartBuilderStore';
import { useDatasetStore } from '../stores/DatasetStore';
import { useExtractStore } from '../stores/ExtractStore';
@@ -62,6 +64,17 @@ export const MODAL_REGISTRY: Partial<Record<ModalName, ModalConfig>> = {
init: () => useExtractStore.getState().init(),
getState: () => ({ name: useExtractStore.getState().name }),
},
// Opened from a selected dataset's "Build Chart" action; `arg` is its id. Loads
// the dataset and pre-populates a smart default config (§06). Applies on Create
// (a new snippet), so there is nothing transient to lose on close — no getState.
chartBuilder: {
name: 'chartBuilder',
title: 'Chart Builder',
component: ChartBuilderModal,
isUrlNavigable: true,
init: (datasetId) => useChartBuilderStore.getState().init(datasetId ? Number(datasetId) : null),
},
};
export const getModalConfig = (name: ActiveModal): ModalConfig | undefined =>
+104
View File
@@ -0,0 +1,104 @@
import { beforeEach, describe, expect, test } from 'vitest';
import { createDataset } from '@core/dataset';
import { useChartBuilderStore } from './ChartBuilderStore';
import { useDatasetStore } from './DatasetStore';
import { useSnippetStore } from './SnippetStore';
const cb = () => useChartBuilderStore.getState();
const T = new Date('2026-06-01T00:00:00Z');
/** Seed a dataset directly into the store and return its id. */
function seedDataset(name: string, data: unknown): number {
const ds = createDataset({ name, data, format: 'json', source: 'inline', now: T });
useDatasetStore.getState().add(ds);
return ds.id;
}
beforeEach(() => {
cb().reset();
useDatasetStore.getState().reset();
useSnippetStore.getState().reset();
});
describe('init', () => {
test('pre-populates a smart default config from the dataset columns', () => {
const id = seedDataset('Traffic', [
{ day: '2026-01-01', visits: 10 },
{ day: '2026-01-02', visits: 20 },
]);
cb().init(id);
expect(cb().datasetId).toBe(id);
expect(cb().config.datasetName).toBe('Traffic');
// date × number → a Line time series, first col on X, second on Y.
expect(cb().config.mark).toBe('line');
expect(cb().config.encodings.x).toEqual({ field: 'day', type: 'temporal' });
expect(cb().config.encodings.y).toEqual({ field: 'visits', type: 'quantitative' });
});
test('lands empty when no dataset is found', () => {
cb().init(999);
expect(cb().datasetId).toBeNull();
expect(cb().config.encodings).toEqual({});
});
});
describe('channel editing', () => {
test('mapping a column seeds a channel-appropriate type (Size stays a measure)', () => {
const id = seedDataset('Mixed', [{ name: 'A', value: 5 }]);
cb().init(id);
// A numeric column on Size → Quantitative (allowed); a category cannot be chosen
// for Size in the UI, and the store keeps the type valid for the channel.
cb().setChannelColumn('size', 'value');
expect(cb().config.encodings.size).toEqual({ field: 'value', type: 'quantitative' });
});
test('swapXY flips the two axis mappings', () => {
const id = seedDataset('XY', [{ a: 'x', b: 1 }]);
cb().init(id);
const x0 = cb().config.encodings.x;
const y0 = cb().config.encodings.y;
cb().swapXY();
expect(cb().config.encodings.x).toEqual(y0);
expect(cb().config.encodings.y).toEqual(x0);
});
test('clearing a channel to None removes it from the config', () => {
const id = seedDataset('XY', [{ a: 'x', b: 1 }]);
cb().init(id);
cb().setChannelColumn('x', null);
expect(cb().config.encodings.x).toBeNull();
});
});
describe('createSnippet', () => {
test('builds a linked snippet, activates it, and resets the builder', () => {
const id = seedDataset('Sales', [
{ region: 'N', revenue: 100 },
{ region: 'S', revenue: 80 },
]);
cb().init(id);
expect(cb().createSnippet(T)).toBe(true);
const snippets = useSnippetStore.getState().snippets;
expect(snippets).toHaveLength(1);
const made = snippets[0];
// Linked to its dataset by name (§09F), and the spec references it.
expect(made.datasetRefs).toEqual(['Sales']);
expect(made.spec).toContain('"name": "Sales"');
expect(made.meta.createdWith).toBe('chart-builder');
expect(useSnippetStore.getState().activeSnippetId).toBe(made.id);
// Builder state is reset for a fresh next open.
expect(cb().datasetId).toBeNull();
});
test('refuses to create when no channel is mapped', () => {
const id = seedDataset('Empty', [{ a: 1 }]);
cb().init(id);
cb().setChannelColumn('x', null);
cb().setChannelColumn('y', null);
expect(cb().createSnippet(T)).toBe(false);
expect(useSnippetStore.getState().snippets).toHaveLength(0);
});
});
+180
View File
@@ -0,0 +1,180 @@
/**
* Chart Builder state (spec §06).
*
* Backs the Chart Builder modal: a no-JSON composer that turns a dataset + a mark
* + four channel mappings into a Vega-Lite spec saved as a new snippet. All the
* spec grammar and the Tier-B defaults/guards live in the portable core
* (`@core/chart-builder`); this store is the thin app-layer state + actions over
* that, plus the create-flow side effects (new snippet, toast, activate, close).
*
* `init(datasetId)` loads the dataset's columns and pre-populates a smart default
* config; with no dataset it lands empty so the modal can show "No dataset loaded".
* The mark is sticky after open (changing a column does not re-derive it) so the
* user's choice is never overridden mid-edit.
*/
import { create } from 'zustand';
import {
buildSnippetSpecText,
defaultBuilderConfig,
defaultFieldType,
generateChartName,
isBuilderConfigValid,
isChannelTypeAllowed,
validFieldTypes,
type BuilderColumns,
type BuilderConfig,
type ChannelName,
type FieldType,
type MarkType,
} from '@core/chart-builder';
import type { ColumnType } from '@core/type-inference';
import { closeModal } from '../modals/ModalCoordinator';
import { useDatasetStore } from './DatasetStore';
import { notify } from './NotificationStore';
import { useSnippetStore } from './SnippetStore';
/** An empty config — no dataset, nothing mapped (the "No dataset loaded" state). */
const EMPTY_CONFIG: BuilderConfig = { datasetName: '', mark: 'bar', encodings: {} };
const EMPTY_COLUMNS: BuilderColumns = { columns: [], columnTypes: [] };
export interface ChartBuilderState {
/** The dataset being built from, or null when none is loaded. */
datasetId: number | null;
/** The dataset's columns + inferred types (drives the dropdowns and defaults). */
columns: BuilderColumns;
/** The working configuration the preview and the produced spec read from. */
config: BuilderConfig;
/** Load a dataset and pre-populate a smart default config (spec §06 → Opening). */
init: (datasetId: number | null) => void;
setMark: (mark: MarkType) => void;
/** Map a column to a channel (null = "None"); seeds the channel's default type. */
setChannelColumn: (channel: ChannelName, columnName: string | null) => void;
setChannelType: (channel: ChannelName, type: FieldType) => void;
/** Swap the X and Y mappings (a one-click axis flip). */
swapXY: () => void;
setWidth: (width: number | undefined) => void;
setHeight: (height: number | undefined) => void;
/** Build the spec, create + activate a linked snippet, toast, and close. */
createSnippet: (now?: Date) => boolean;
reset: () => void;
}
/** The inferred type of a named column, defaulting to `string` if unknown. */
function columnType(columns: BuilderColumns, name: string): ColumnType {
return columns.columnTypes.find((c) => c.name === name)?.type ?? 'string';
}
export const useChartBuilderStore = create<ChartBuilderState>((set, get) => ({
datasetId: null,
columns: EMPTY_COLUMNS,
config: EMPTY_CONFIG,
init: (datasetId) => {
const dataset =
datasetId === null
? undefined
: useDatasetStore.getState().datasets.find((d) => d.id === datasetId);
if (!dataset) {
set({ datasetId: null, columns: EMPTY_COLUMNS, config: EMPTY_CONFIG });
return;
}
const columns: BuilderColumns = {
columns: dataset.columns,
columnTypes: dataset.columnTypes,
};
set({
datasetId: dataset.id,
columns,
config: defaultBuilderConfig(dataset.name, columns),
});
},
setMark: (mark) => set((s) => ({ config: { ...s.config, mark } })),
setChannelColumn: (channel, columnName) =>
set((s) => {
const encodings = { ...s.config.encodings };
if (columnName === null) {
encodings[channel] = null;
} else {
// Default to the column's natural type, but if that type isn't allowed on
// this channel (e.g. a category on Size), fall back to the first valid type
// that is — the UI also disables unsuitable columns, this is the guard.
const valid = validFieldTypes(columnType(s.columns, columnName));
const type =
valid.find((t) => isChannelTypeAllowed(channel, t)) ??
defaultFieldType(columnType(s.columns, columnName));
encodings[channel] = { field: columnName, type };
}
return { config: { ...s.config, encodings } };
}),
setChannelType: (channel, type) =>
set((s) => {
const current = s.config.encodings[channel];
if (!current) return s; // no field on this channel → nothing to retype
return {
config: {
...s.config,
encodings: { ...s.config.encodings, [channel]: { ...current, type } },
},
};
}),
swapXY: () =>
set((s) => ({
config: {
...s.config,
encodings: {
...s.config.encodings,
x: s.config.encodings.y ?? null,
y: s.config.encodings.x ?? null,
},
},
})),
setWidth: (width) => set((s) => ({ config: { ...s.config, width } })),
setHeight: (height) => set((s) => ({ config: { ...s.config, height } })),
createSnippet: (now) => {
const { config } = get();
if (!isBuilderConfigValid(config)) return false; // guarded by a disabled action too
const name = generateChartName(config);
const specText = buildSnippetSpecText(config);
// createSnippet mirrors datasetRefs from the spec, so the new snippet is linked
// to its dataset (§09F) without extra wiring. Provenance kept in meta (§06).
useSnippetStore.getState().createSnippet({
name,
spec: specText,
now,
meta: { createdWith: 'chart-builder', builtFromDataset: config.datasetName },
});
notify({
kind: 'success',
title: 'Snippet created',
message: `"${name}" was added to your library and opened in the editor.`,
});
void closeModal(true); // the create is the user's confirmation — no discard prompt
get().reset();
return true;
},
reset: () => set({ datasetId: null, columns: EMPTY_COLUMNS, config: EMPTY_CONFIG }),
}));
/**
* Selector: whether the config can be saved (≥1 channel mapped, spec §06 →
* Validation). Returns a boolean (stable under Object.is), so it is safe to
* subscribe to directly. Non-blocking *guidance* (`builderWarnings`) deliberately
* has NO selector here — it builds a fresh array of objects each call, which no
* subscription equality can stabilize; the component derives it via `useMemo` over
* the stable `config` reference instead (see ChartBuilderModal).
*/
export const selectBuilderValid = (s: ChartBuilderState) => isBuilderConfigValid(s.config);
/** Selector: the built spec as JSON text, for the live preview. */
export const selectBuilderSpecText = (s: ChartBuilderState) => buildSnippetSpecText(s.config);
+5 -1
View File
@@ -124,7 +124,11 @@ export const useSnippetStore = create<SnippetState>((set, get) => ({
createSnippet: (options) => {
get().commitDraft(); // flush the outgoing snippet's valid edits before switching away
const snippet = createSnippet(options);
const created = createSnippet(options);
// Mirror datasetRefs from the spec at creation, like publish does, so a snippet
// built with a named-data reference (Chart Builder, §06) is linked to its dataset
// immediately. Inline-data specs (the sample template) resolve to no refs.
const snippet = { ...created, datasetRefs: recomputeDatasetRefs(created.spec) };
set((s) => ({
snippets: [snippet, ...s.snippets],
activeSnippetId: snippet.id,