mirror of
https://github.com/olehomelchenko/astrolabe.git
synced 2026-08-08 02:02:33 +00:00
Add Chart Builder: no-JSON Vega-Lite composer from a dataset (M4)
This commit is contained in:
@@ -0,0 +1,294 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
defaultFieldType,
|
||||
validFieldTypes,
|
||||
defaultMark,
|
||||
isChannelTypeAllowed,
|
||||
builderWarnings,
|
||||
defaultBuilderConfig,
|
||||
isBuilderConfigValid,
|
||||
buildChartSpec,
|
||||
buildSnippetSpecText,
|
||||
generateChartName,
|
||||
type BuilderColumns,
|
||||
type BuilderConfig,
|
||||
} from './chart-builder';
|
||||
import { VEGA_LITE_SCHEMA_URL } from './snippet';
|
||||
|
||||
const columns: BuilderColumns = {
|
||||
columns: ['category', 'value', 'when', 'flag'],
|
||||
columnTypes: [
|
||||
{ name: 'category', type: 'string' },
|
||||
{ name: 'value', type: 'number' },
|
||||
{ name: 'when', type: 'date' },
|
||||
{ name: 'flag', type: 'boolean' },
|
||||
],
|
||||
};
|
||||
|
||||
describe('defaultFieldType', () => {
|
||||
it('maps inferred column types to Vega-Lite field types (spec §06)', () => {
|
||||
expect(defaultFieldType('number')).toBe('quantitative');
|
||||
expect(defaultFieldType('date')).toBe('temporal');
|
||||
expect(defaultFieldType('string')).toBe('nominal');
|
||||
expect(defaultFieldType('boolean')).toBe('nominal');
|
||||
});
|
||||
|
||||
it('is always the head of validFieldTypes (no drift)', () => {
|
||||
for (const t of ['number', 'date', 'string', 'boolean'] as const) {
|
||||
expect(defaultFieldType(t)).toBe(validFieldTypes(t)[0]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('validFieldTypes (Tier B valid-type locking)', () => {
|
||||
it('never offers Quantitative for string/boolean, nor Temporal for non-date', () => {
|
||||
expect(validFieldTypes('string')).not.toContain('quantitative');
|
||||
expect(validFieldTypes('boolean')).not.toContain('quantitative');
|
||||
expect(validFieldTypes('number')).not.toContain('temporal');
|
||||
expect(validFieldTypes('string')).not.toContain('temporal');
|
||||
});
|
||||
|
||||
it('locks date to Temporal only and offers Ordinal where order is plausible', () => {
|
||||
expect(validFieldTypes('date')).toEqual(['temporal']);
|
||||
expect(validFieldTypes('number')).toContain('ordinal');
|
||||
expect(validFieldTypes('string')).toContain('ordinal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('defaultMark (Tier B smart default)', () => {
|
||||
it('picks Line for time × measure, Point for two measures, Bar for category × measure', () => {
|
||||
expect(defaultMark('temporal', 'quantitative')).toBe('line');
|
||||
expect(defaultMark('quantitative', 'temporal')).toBe('line');
|
||||
expect(defaultMark('quantitative', 'quantitative')).toBe('point');
|
||||
expect(defaultMark('nominal', 'quantitative')).toBe('bar');
|
||||
expect(defaultMark('quantitative', 'nominal')).toBe('bar');
|
||||
});
|
||||
|
||||
it('uses Point when both axes are discrete (Bar/Line/Area need a continuous axis)', () => {
|
||||
expect(defaultMark('nominal', 'nominal')).toBe('point');
|
||||
expect(defaultMark('nominal', 'ordinal')).toBe('point');
|
||||
});
|
||||
|
||||
it('falls back to Bar when an axis is unmapped', () => {
|
||||
expect(defaultMark('quantitative', null)).toBe('bar');
|
||||
expect(defaultMark(null, null)).toBe('bar');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isChannelTypeAllowed (Size discipline)', () => {
|
||||
it('forbids Size for Nominal and Temporal, allows it for Quantitative/Ordinal', () => {
|
||||
expect(isChannelTypeAllowed('size', 'nominal')).toBe(false);
|
||||
expect(isChannelTypeAllowed('size', 'temporal')).toBe(false);
|
||||
expect(isChannelTypeAllowed('size', 'quantitative')).toBe(true);
|
||||
expect(isChannelTypeAllowed('size', 'ordinal')).toBe(true);
|
||||
});
|
||||
|
||||
it('allows any type on X/Y/Color', () => {
|
||||
for (const ch of ['x', 'y', 'color'] as const) {
|
||||
expect(isChannelTypeAllowed(ch, 'nominal')).toBe(true);
|
||||
expect(isChannelTypeAllowed(ch, 'temporal')).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('builderWarnings (Tier B advisories)', () => {
|
||||
it('warns when a line/area mark is missing an axis', () => {
|
||||
const w = builderWarnings({
|
||||
datasetName: 'D',
|
||||
mark: 'line',
|
||||
encodings: { x: { field: 'a', type: 'temporal' } },
|
||||
});
|
||||
expect(w.some((m) => /need both an X and a Y/.test(m.message))).toBe(true);
|
||||
});
|
||||
|
||||
it('warns when two measures are drawn on a non-scatter mark', () => {
|
||||
const w = builderWarnings({
|
||||
datasetName: 'D',
|
||||
mark: 'bar',
|
||||
encodings: {
|
||||
x: { field: 'a', type: 'quantitative' },
|
||||
y: { field: 'b', type: 'quantitative' },
|
||||
},
|
||||
});
|
||||
expect(w.some((m) => /scatter/.test(m.message))).toBe(true);
|
||||
});
|
||||
|
||||
it('warns when a bar/line/area has no measure on either axis', () => {
|
||||
const w = builderWarnings({
|
||||
datasetName: 'D',
|
||||
mark: 'bar',
|
||||
encodings: { x: { field: 'a', type: 'nominal' }, y: { field: 'b', type: 'nominal' } },
|
||||
});
|
||||
expect(w.some((m) => /need a measure/.test(m.message))).toBe(true);
|
||||
});
|
||||
|
||||
it('warns when an area chart is split into colour series', () => {
|
||||
const w = builderWarnings({
|
||||
datasetName: 'D',
|
||||
mark: 'area',
|
||||
encodings: {
|
||||
x: { field: 't', type: 'temporal' },
|
||||
y: { field: 'v', type: 'quantitative' },
|
||||
color: { field: 'g', type: 'nominal' },
|
||||
},
|
||||
});
|
||||
expect(w.some((m) => m.channel === 'color')).toBe(true);
|
||||
});
|
||||
|
||||
it('is silent for a clean configuration', () => {
|
||||
const w = builderWarnings({
|
||||
datasetName: 'D',
|
||||
mark: 'line',
|
||||
encodings: { x: { field: 't', type: 'temporal' }, y: { field: 'v', type: 'quantitative' } },
|
||||
});
|
||||
expect(w).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('defaultBuilderConfig', () => {
|
||||
it('puts the first column on X and the second on Y, each with derived type', () => {
|
||||
const config = defaultBuilderConfig('Sales', columns);
|
||||
expect(config.mark).toBe('bar');
|
||||
expect(config.datasetName).toBe('Sales');
|
||||
expect(config.encodings.x).toEqual({ field: 'category', type: 'nominal' });
|
||||
expect(config.encodings.y).toEqual({ field: 'value', type: 'quantitative' });
|
||||
expect(config.encodings.color).toBeNull();
|
||||
expect(config.encodings.size).toBeNull();
|
||||
});
|
||||
|
||||
it('opens as a Line when the first two columns are date × number (smart mark)', () => {
|
||||
const timeSeries: BuilderColumns = {
|
||||
columns: ['day', 'visits'],
|
||||
columnTypes: [
|
||||
{ name: 'day', type: 'date' },
|
||||
{ name: 'visits', type: 'number' },
|
||||
],
|
||||
};
|
||||
const config = defaultBuilderConfig('Traffic', timeSeries);
|
||||
expect(config.mark).toBe('line');
|
||||
expect(config.encodings.x).toEqual({ field: 'day', type: 'temporal' });
|
||||
expect(config.encodings.y).toEqual({ field: 'visits', type: 'quantitative' });
|
||||
});
|
||||
|
||||
it('leaves Y unmapped when the dataset has a single column', () => {
|
||||
const single: BuilderColumns = {
|
||||
columns: ['only'],
|
||||
columnTypes: [{ name: 'only', type: 'number' }],
|
||||
};
|
||||
const config = defaultBuilderConfig('One', single);
|
||||
expect(config.encodings.x).toEqual({ field: 'only', type: 'quantitative' });
|
||||
expect(config.encodings.y).toBeNull();
|
||||
});
|
||||
|
||||
it('maps nothing when the dataset has no detected columns', () => {
|
||||
const config = defaultBuilderConfig('Empty', { columns: [], columnTypes: [] });
|
||||
expect(isBuilderConfigValid(config)).toBe(false);
|
||||
expect(config.encodings.x).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isBuilderConfigValid', () => {
|
||||
const base: BuilderConfig = { datasetName: 'D', mark: 'bar', encodings: {} };
|
||||
|
||||
it('requires at least one mapped channel', () => {
|
||||
expect(isBuilderConfigValid(base)).toBe(false);
|
||||
expect(isBuilderConfigValid({ ...base, encodings: { x: null, y: null } })).toBe(false);
|
||||
expect(
|
||||
isBuilderConfigValid({ ...base, encodings: { color: { field: 'c', type: 'nominal' } } }),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildChartSpec', () => {
|
||||
it('assembles schema, named data, tooltip mark, and mapped encodings', () => {
|
||||
const config = defaultBuilderConfig('Sales', columns);
|
||||
const spec = buildChartSpec(config);
|
||||
expect(spec).toEqual({
|
||||
$schema: VEGA_LITE_SCHEMA_URL,
|
||||
data: { name: 'Sales' },
|
||||
mark: { type: 'bar', tooltip: true },
|
||||
encoding: {
|
||||
x: { field: 'category', type: 'nominal' },
|
||||
y: { field: 'value', type: 'quantitative' },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('omits unmapped channels and preserves canonical channel order', () => {
|
||||
const config: BuilderConfig = {
|
||||
datasetName: 'D',
|
||||
mark: 'point',
|
||||
encodings: {
|
||||
size: { field: 's', type: 'quantitative' },
|
||||
x: { field: 'a', type: 'nominal' },
|
||||
color: null,
|
||||
},
|
||||
};
|
||||
const spec = buildChartSpec(config);
|
||||
expect(Object.keys(spec.encoding as object)).toEqual(['x', 'size']);
|
||||
});
|
||||
|
||||
it('omits the encoding block entirely when nothing is mapped', () => {
|
||||
const spec = buildChartSpec({ datasetName: 'D', mark: 'bar', encodings: {} });
|
||||
expect(spec.encoding).toBeUndefined();
|
||||
expect(spec.mark).toEqual({ type: 'bar', tooltip: true });
|
||||
});
|
||||
|
||||
it('writes explicit width/height only when provided', () => {
|
||||
const config: BuilderConfig = {
|
||||
datasetName: 'D',
|
||||
mark: 'area',
|
||||
encodings: { x: { field: 'a', type: 'temporal' } },
|
||||
width: 400,
|
||||
height: 300,
|
||||
};
|
||||
const spec = buildChartSpec(config);
|
||||
expect(spec.width).toBe(400);
|
||||
expect(spec.height).toBe(300);
|
||||
|
||||
const noDims = buildChartSpec({ ...config, width: undefined, height: undefined });
|
||||
expect(noDims.width).toBeUndefined();
|
||||
expect(noDims.height).toBeUndefined();
|
||||
});
|
||||
|
||||
it('carries every mark type through to the spec', () => {
|
||||
for (const mark of ['bar', 'line', 'point', 'area', 'circle'] as const) {
|
||||
const spec = buildChartSpec({
|
||||
datasetName: 'D',
|
||||
mark,
|
||||
encodings: { x: { field: 'a', type: 'nominal' } },
|
||||
});
|
||||
expect((spec.mark as { type: string }).type).toBe(mark);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildSnippetSpecText', () => {
|
||||
it('produces pretty-printed JSON that parses back to the spec', () => {
|
||||
const config = defaultBuilderConfig('Sales', columns);
|
||||
const text = buildSnippetSpecText(config);
|
||||
expect(text).toContain('\n ');
|
||||
expect(JSON.parse(text)).toEqual(buildChartSpec(config));
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateChartName', () => {
|
||||
it('reads "<Mark> chart of <y> by <x>" when both axes are mapped', () => {
|
||||
const config = defaultBuilderConfig('Sales', columns);
|
||||
expect(generateChartName(config)).toBe('Bar chart of value by category');
|
||||
});
|
||||
|
||||
it('names the single mapped field when only one channel is set', () => {
|
||||
const config: BuilderConfig = {
|
||||
datasetName: 'Sales',
|
||||
mark: 'line',
|
||||
encodings: { color: { field: 'region', type: 'nominal' } },
|
||||
};
|
||||
expect(generateChartName(config)).toBe('Line chart of region');
|
||||
});
|
||||
|
||||
it('falls back to the dataset name when nothing is mapped', () => {
|
||||
const config: BuilderConfig = { datasetName: 'Sales', mark: 'circle', encodings: {} };
|
||||
expect(generateChartName(config)).toBe('Circle chart of Sales');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* Chart Builder — pure Vega-Lite spec assembler (spec §06).
|
||||
*
|
||||
* Portable core: no browser APIs, no React, no store access. Turns a no-JSON
|
||||
* builder configuration (a mark, four optional encoding channels mapped to
|
||||
* dataset columns, optional pixel dimensions) into a complete Vega-Lite spec that
|
||||
* references the source dataset by name. The UI layer owns the controls; this
|
||||
* module owns the spec grammar — what a configuration *means* as Vega-Lite — and
|
||||
* the defaults the spec prescribes (pre-population, field-type derivation).
|
||||
*
|
||||
* The produced spec mirrors what the rest of Astrolabe authors by hand: a
|
||||
* `$schema` stamp (shared with the sample template), a named-data reference the
|
||||
* renderer resolves at preview time (rendering.ts), a mark with tooltips enabled,
|
||||
* the mapped encodings, and any explicit width/height. It is the same string-spec
|
||||
* shape the editor and preview consume — `buildSnippetSpecText` serializes it.
|
||||
*/
|
||||
|
||||
import type { ColumnType } from './type-inference';
|
||||
import { VEGA_LITE_SCHEMA_URL } from './snippet';
|
||||
|
||||
/** The five mark types the builder offers, in selector order (spec §06). */
|
||||
export const MARK_TYPES = ['bar', 'line', 'point', 'area', 'circle'] as const;
|
||||
export type MarkType = (typeof MARK_TYPES)[number];
|
||||
|
||||
/** The four Vega-Lite field types a channel may carry, in override-menu order. */
|
||||
export const FIELD_TYPES = ['quantitative', 'nominal', 'ordinal', 'temporal'] as const;
|
||||
export type FieldType = (typeof FIELD_TYPES)[number];
|
||||
|
||||
/** The four encoding channels the builder offers, in display order (spec §06). */
|
||||
export const CHANNELS = ['x', 'y', 'color', 'size'] as const;
|
||||
export type ChannelName = (typeof CHANNELS)[number];
|
||||
|
||||
/**
|
||||
* One channel's mapping: a dataset column `field` plus its `type`. A channel left
|
||||
* on "None" is represented by `null` in the config (omitted from the spec).
|
||||
*/
|
||||
export interface ChannelMapping {
|
||||
field: string;
|
||||
type: FieldType;
|
||||
}
|
||||
|
||||
/** The full builder configuration the assembler consumes. */
|
||||
export interface BuilderConfig {
|
||||
/** The dataset the spec references by name (`{ data: { name } }`). */
|
||||
datasetName: string;
|
||||
/** The active mark type. */
|
||||
mark: MarkType;
|
||||
/** Per-channel mapping; `null` (or absent) means the channel is unmapped. */
|
||||
encodings: Partial<Record<ChannelName, ChannelMapping | null>>;
|
||||
/** Optional explicit chart width in pixels. */
|
||||
width?: number;
|
||||
/** Optional explicit chart height in pixels. */
|
||||
height?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The field types a column may legitimately carry, given its inferred type — the
|
||||
* options the channel's type control offers (spec §06 → Tier B, valid-type
|
||||
* locking). A string/boolean is never Quantitative and a non-date is never
|
||||
* Temporal (Vega-Lite would mis-encode or error); a number defaults to
|
||||
* Quantitative but may be treated as a category. Ordinal is offered wherever the
|
||||
* user might reasonably assert an order (numbers, text), a deliberate superset of
|
||||
* Voyager's stricter menu. The list head is the default (see `defaultFieldType`).
|
||||
*
|
||||
* Convergent across the research: Voyager `getValidTypes`
|
||||
* (data-pane/field-list.tsx) + Draco `hard.lp` enc_type_valid (a string/boolean
|
||||
* can't be quantitative; temporal requires datetime). See
|
||||
* docs/chart-builder-research.md §4.
|
||||
*/
|
||||
export function validFieldTypes(columnType: ColumnType): FieldType[] {
|
||||
switch (columnType) {
|
||||
case 'number':
|
||||
return ['quantitative', 'ordinal', 'nominal'];
|
||||
case 'date':
|
||||
return ['temporal'];
|
||||
case 'boolean':
|
||||
return ['nominal'];
|
||||
default: // 'string'
|
||||
return ['nominal', 'ordinal'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Default Vega-Lite field type for a column from its inferred type (spec §06):
|
||||
* numeric → Quantitative, date → Temporal, everything else (text, boolean) →
|
||||
* Nominal. The default is the head of `validFieldTypes`, so the two never drift.
|
||||
* The user may override afterward, within `validFieldTypes`.
|
||||
*/
|
||||
export function defaultFieldType(columnType: ColumnType): FieldType {
|
||||
return validFieldTypes(columnType)[0];
|
||||
}
|
||||
|
||||
/** Continuous (measure-like) field types — quantitative and temporal. */
|
||||
function isContinuous(type: FieldType): boolean {
|
||||
return type === 'quantitative' || type === 'temporal';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a field type may be placed on a channel at all (spec §06 → Tier B, Size
|
||||
* discipline). X/Y/Color accept any type; **Size accepts only Quantitative or
|
||||
* Ordinal** — encoding a category or a date by symbol size is misleading (size
|
||||
* implies ordered magnitude). Draco makes this a hard constraint
|
||||
* (`hard.lp:53` size_nominal); we surface it as a UI gate that disables Size for
|
||||
* unsuitable columns rather than letting the user produce the bad encoding.
|
||||
* (Negative-value exclusion, `hard.lp:56`, needs row data and is left to the
|
||||
* data-aware layer; this type-level gate is what the builder enforces.)
|
||||
*/
|
||||
export function isChannelTypeAllowed(channel: ChannelName, type: FieldType): boolean {
|
||||
if (channel === 'size') return type === 'quantitative' || type === 'ordinal';
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The mark that best fits the X/Y field-type shape (spec §06 → Tier B, smart
|
||||
* default mark) — the research's strongest convergence (Draco mark-by-shape soft
|
||||
* constraints, Voyager effectiveness, FT, Datawrapper all agree;
|
||||
* docs/chart-builder-research.md §4):
|
||||
*
|
||||
* - temporal × quantitative → **Line** (a time series)
|
||||
* - quantitative × quantitative → **Point** (a scatter)
|
||||
* - one continuous + one discrete axis → **Bar** (category vs measure)
|
||||
* - both axes discrete → **Point** (Bar/Line/Area need a continuous axis)
|
||||
* - a single mapped axis, or nothing yet → **Bar** (the safe default)
|
||||
*
|
||||
* `null` means the channel is unmapped. This is the *default*; the user can switch
|
||||
* to any of the five marks afterward.
|
||||
*/
|
||||
export function defaultMark(xType: FieldType | null, yType: FieldType | null): MarkType {
|
||||
if (xType === null || yType === null) return 'bar';
|
||||
const timeVsMeasure =
|
||||
(xType === 'temporal' && yType === 'quantitative') ||
|
||||
(xType === 'quantitative' && yType === 'temporal');
|
||||
if (timeVsMeasure) return 'line';
|
||||
const xc = isContinuous(xType);
|
||||
const yc = isContinuous(yType);
|
||||
if (xc && yc) return 'point'; // two measures → scatter
|
||||
if (xc === yc) return 'point'; // both discrete → bar/line/area are invalid here
|
||||
return 'bar'; // one continuous axis, one categorical → category-vs-measure bar
|
||||
}
|
||||
|
||||
/** A dataset's columns paired with their inferred types — the builder's input. */
|
||||
export interface BuilderColumns {
|
||||
columns: readonly string[];
|
||||
columnTypes: ReadonlyArray<{ name: string; type: ColumnType }>;
|
||||
}
|
||||
|
||||
/** The derived field type for a named column, defaulting to Nominal if unknown. */
|
||||
function fieldTypeForColumn(name: string, columns: BuilderColumns): FieldType {
|
||||
const match = columns.columnTypes.find((c) => c.name === name);
|
||||
return defaultFieldType(match?.type ?? 'string');
|
||||
}
|
||||
|
||||
/**
|
||||
* The builder's opening configuration for a dataset (spec §06 → Default
|
||||
* pre-population, Tier B): the first column on X and the second (if any) on Y, each
|
||||
* with its derived field type; Color and Size start unmapped. The mark is the
|
||||
* **smart default** for the resulting X/Y shape (`defaultMark`) rather than always
|
||||
* Bar — a date-vs-number dataset opens as a Line, two measures as a Point — so the
|
||||
* first preview is already the conventional chart. A dataset with no detected
|
||||
* columns yields an all-unmapped config (the modal then prompts / disables Create).
|
||||
*/
|
||||
export function defaultBuilderConfig(datasetName: string, columns: BuilderColumns): BuilderConfig {
|
||||
const encodings: Partial<Record<ChannelName, ChannelMapping | null>> = {
|
||||
x: null,
|
||||
y: null,
|
||||
color: null,
|
||||
size: null,
|
||||
};
|
||||
const [first, second] = columns.columns;
|
||||
if (first !== undefined) {
|
||||
encodings.x = { field: first, type: fieldTypeForColumn(first, columns) };
|
||||
}
|
||||
if (second !== undefined) {
|
||||
encodings.y = { field: second, type: fieldTypeForColumn(second, columns) };
|
||||
}
|
||||
const mark = defaultMark(encodings.x?.type ?? null, encodings.y?.type ?? null);
|
||||
return { datasetName, mark, encodings };
|
||||
}
|
||||
|
||||
/** The channels actually mapped to a column, in canonical order. */
|
||||
function mappedChannels(config: BuilderConfig): Array<[ChannelName, ChannelMapping]> {
|
||||
return CHANNELS.flatMap((channel) => {
|
||||
const mapping = config.encodings[channel];
|
||||
return mapping ? [[channel, mapping] as [ChannelName, ChannelMapping]] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the configuration is renderable / saveable (spec §06 → Validation): at
|
||||
* least one channel must be mapped to a column. The modal gates the Create action
|
||||
* and the preview prompt on this.
|
||||
*/
|
||||
export function isBuilderConfigValid(config: BuilderConfig): boolean {
|
||||
return mappedChannels(config).length > 0;
|
||||
}
|
||||
|
||||
/** A non-blocking advisory about a configuration (spec §06 → Tier B warnings). */
|
||||
export interface BuilderWarning {
|
||||
/** The channel the hint is about, when it's channel-specific. */
|
||||
channel?: ChannelName;
|
||||
/** A short, plain-language hint the modal shows inline (not an error). */
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-blocking advisories for the current configuration (spec §06 → Tier B): the
|
||||
* encodings that render but read poorly, drawn from the research's soft rules
|
||||
* (docs/chart-builder-research.md §4, §7). These never block Create — `isBuilder
|
||||
* ConfigValid` is the only gate — they just steer the user toward a better chart.
|
||||
* Returned in a stable order so the UI list doesn't jitter as config changes.
|
||||
*/
|
||||
export function builderWarnings(config: BuilderConfig): BuilderWarning[] {
|
||||
const warnings: BuilderWarning[] = [];
|
||||
const x = config.encodings.x ?? null;
|
||||
const y = config.encodings.y ?? null;
|
||||
const { mark } = config;
|
||||
|
||||
// Line/area are two-axis marks: a single mapped axis can't draw a meaningful line
|
||||
// or band (Draco hard.lp:91 line_area requires both x and y).
|
||||
if ((mark === 'line' || mark === 'area') && (x === null || y === null)) {
|
||||
warnings.push({
|
||||
message: `${mark === 'line' ? 'Line' : 'Area'} charts need both an X and a Y axis.`,
|
||||
});
|
||||
}
|
||||
|
||||
// Bar/line/area need a measure on one axis; two categories give nothing to compare
|
||||
// (Draco soft.lp:47 only_discrete — the loudest nudge; hard.lp:97/:100 for bar).
|
||||
if (
|
||||
(mark === 'bar' || mark === 'line' || mark === 'area') &&
|
||||
x !== null &&
|
||||
y !== null &&
|
||||
!isContinuous(x.type) &&
|
||||
!isContinuous(y.type)
|
||||
) {
|
||||
warnings.push({
|
||||
message: `${markLabel(mark)} charts need a measure (quantitative or temporal) on the X or Y axis.`,
|
||||
});
|
||||
}
|
||||
|
||||
// Two measures on a non-scatter mark: a line/bar/area over two quantitative axes
|
||||
// misleads; a scatter is the conventional choice (Draco soft.lp c_c weights).
|
||||
if (
|
||||
x !== null &&
|
||||
y !== null &&
|
||||
x.type === 'quantitative' &&
|
||||
y.type === 'quantitative' &&
|
||||
mark !== 'point' &&
|
||||
mark !== 'circle'
|
||||
) {
|
||||
warnings.push({
|
||||
message: 'Two measures usually read best as a scatter — try Point or Circle.',
|
||||
});
|
||||
}
|
||||
|
||||
// Area split into many series hides per-component change (FT Visual Vocabulary:
|
||||
// "seeing change in components can be very difficult").
|
||||
if (mark === 'area' && config.encodings.color) {
|
||||
warnings.push({
|
||||
channel: 'color',
|
||||
message:
|
||||
'Area charts make per-series change hard to read; consider Line for multiple series.',
|
||||
});
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
|
||||
/** A built Vega-Lite spec, as a plain object (serialize with `buildSnippetSpecText`). */
|
||||
export type ChartSpec = Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* Assemble the complete Vega-Lite spec from a builder configuration (spec §06 →
|
||||
* Output). Includes the schema reference, a named data reference to the dataset,
|
||||
* the mark with tooltips enabled, every mapped encoding (field + field type), and
|
||||
* any explicit width/height. Unmapped channels are omitted; if nothing is mapped
|
||||
* the `encoding` block is omitted entirely (validation prevents saving that, but
|
||||
* the live preview may render a bare mark while the user is still configuring).
|
||||
*/
|
||||
export function buildChartSpec(config: BuilderConfig): ChartSpec {
|
||||
const spec: ChartSpec = {
|
||||
$schema: VEGA_LITE_SCHEMA_URL,
|
||||
data: { name: config.datasetName },
|
||||
mark: { type: config.mark, tooltip: true },
|
||||
};
|
||||
|
||||
const encoding: Record<string, { field: string; type: FieldType }> = {};
|
||||
for (const [channel, mapping] of mappedChannels(config)) {
|
||||
encoding[channel] = { field: mapping.field, type: mapping.type };
|
||||
}
|
||||
if (Object.keys(encoding).length > 0) spec.encoding = encoding;
|
||||
|
||||
if (config.width !== undefined) spec.width = config.width;
|
||||
if (config.height !== undefined) spec.height = config.height;
|
||||
|
||||
return spec;
|
||||
}
|
||||
|
||||
/** The built spec as pretty-printed JSON text, ready for a snippet's `spec`. */
|
||||
export function buildSnippetSpecText(config: BuilderConfig): string {
|
||||
return JSON.stringify(buildChartSpec(config), null, 2);
|
||||
}
|
||||
|
||||
/** Title-case a single mark type for display/naming (e.g. `bar` → `Bar`). */
|
||||
function markLabel(mark: MarkType): string {
|
||||
return mark.charAt(0).toUpperCase() + mark.slice(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* An auto-generated, descriptive name for the created snippet (spec §06 → Output:
|
||||
* "an auto-generated descriptive name"). When both X and Y are mapped it reads
|
||||
* "Bar chart of <y> by <x>"; otherwise it falls back to naming the dataset:
|
||||
* "Bar chart of <dataset>". Deterministic — no timestamp — so the name describes
|
||||
* the chart, not when it was made.
|
||||
*/
|
||||
export function generateChartName(config: BuilderConfig): string {
|
||||
const mark = markLabel(config.mark);
|
||||
const x = config.encodings.x;
|
||||
const y = config.encodings.y;
|
||||
if (x && y) return `${mark} chart of ${y.field} by ${x.field}`;
|
||||
const only = mappedChannels(config)[0];
|
||||
if (only) return `${mark} chart of ${only[1].field}`;
|
||||
return `${mark} chart of ${config.datasetName}`;
|
||||
}
|
||||
+11
-2
@@ -14,6 +14,13 @@
|
||||
/** Current schema version for a Snippet record (read-time migration target). */
|
||||
export const CURRENT_SNIPPET_VERSION = 1;
|
||||
|
||||
/**
|
||||
* The Vega-Lite schema URL stamped into generated specs (`$schema`). Shared so the
|
||||
* sample template and the Chart Builder agree on one version; the Monaco schema
|
||||
* service pins the same URI independently (infrastructure/monaco-schema.ts).
|
||||
*/
|
||||
export const VEGA_LITE_SCHEMA_URL = 'https://vega.github.io/schema/vega-lite/v6.json';
|
||||
|
||||
export interface Snippet {
|
||||
/** Unique, stable identifier. */
|
||||
id: string;
|
||||
@@ -45,7 +52,7 @@ export interface Snippet {
|
||||
* Inline data only — datasets arrive in M3.
|
||||
*/
|
||||
export const SAMPLE_SPEC = {
|
||||
$schema: 'https://vega.github.io/schema/vega-lite/v6.json',
|
||||
$schema: VEGA_LITE_SCHEMA_URL,
|
||||
description: 'A simple bar chart.',
|
||||
data: {
|
||||
values: [
|
||||
@@ -92,6 +99,8 @@ export interface CreateSnippetOptions {
|
||||
now?: Date;
|
||||
/** Id injection for deterministic tests; defaults to a random UUID. */
|
||||
id?: string;
|
||||
/** Seed the extensible metadata bag (e.g. Chart Builder provenance). */
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,7 +122,7 @@ export function createSnippet(options: CreateSnippetOptions = {}): Snippet {
|
||||
comment: '',
|
||||
tags: [],
|
||||
datasetRefs: [],
|
||||
meta: {},
|
||||
meta: options.meta ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user