mirror of
https://github.com/olehomelchenko/astrolabe.git
synced 2026-08-08 10:12:34 +00:00
Add Chart Builder: no-JSON Vega-Lite composer from a dataset (M4)
This commit is contained in:
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user