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,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}`;
|
||||
}
|
||||
Reference in New Issue
Block a user