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
+11 -4
View File
@@ -43,6 +43,7 @@ four; that wastes tokens and dilutes the answer. Map the decision to its seat(s)
| **Forms / validation / destructive-action** flow | **GOV.UK** → Carbon | | **Forms / validation / destructive-action** flow | **GOV.UK** → Carbon |
| General **usability** gut-check on a flow | **NN/g** 10 heuristics | | General **usability** gut-check on a flow | **NN/g** 10 heuristics |
| **Visual** styling (type, spacing, colour, component look) | **Carbon** + our `docs/architecture/09` | | **Visual** styling (type, spacing, colour, component look) | **Carbon** + our `docs/architecture/09` |
| **Which chart** for the data/intent (chart-type choice) | **FT Visual Vocabulary** + **Datawrapper** |
Then: read the cited file(s), extract the **specific** principle, and report it back with Then: read the cited file(s), extract the **specific** principle, and report it back with
a **citation (member + file path)** and a one-line "how it lands in Astrolabe." Don't a **citation (member + file path)** and a one-line "how it lands in Astrolabe." Don't
@@ -54,11 +55,13 @@ All paths are under `/Users/oleh/code/reference/`. Treat clones as **inspiration
law** — they drift; the published guidance is the truth, the clone is the fast index. law** — they drift; the published guidance is the truth, the clone is the fast index.
| Member | Path | Authoritative for | How to query | | Member | Path | Authoritative for | How to query |
| ------------------------------ | ---------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------------------ | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **IBM Carbon** | `carbon-website/src/pages/` | Notification taxonomy, status levels, empty/loading states, content basics, data-viz styling | grep `.mdx` under `components/notification`, `patterns/{empty-states,loading,status-indicator}-pattern`, `guidelines/content` | | **IBM Carbon** | `carbon-website/src/pages/` | Notification taxonomy, status levels, empty/loading states, content basics, data-viz styling | grep `.mdx` under `components/notification`, `patterns/{empty-states,loading,status-indicator}-pattern`, `guidelines/content` |
| **GOV.UK Design System** | `govuk-design-system/src/` | Error & validation messages, failure pages, forms, plain-language content, accessibility | `index.md` under `components/{error-message,error-summary,notification-banner}`, `patterns/{problem-with-the-service-pages,service-unavailable-pages,check-answers}`, `accessibility/` | | **GOV.UK Design System** | `govuk-design-system/src/` | Error & validation messages, failure pages, forms, plain-language content, accessibility | `index.md` under `components/{error-message,error-summary,notification-banner}`, `patterns/{problem-with-the-service-pages,service-unavailable-pages,check-answers}`, `accessibility/` |
| **WAI-ARIA APG** | `aria-practices/content/patterns/` | Keyboard interaction, focus management, ARIA roles/states for widgets | `<pattern>/<pattern>-pattern.html` — e.g. `dialog-modal`, `alertdialog`, `alert`, `listbox`, `menu-button`, `disclosure`, `switch`, `tabs`, `tooltip`, `windowsplitter` | | **WAI-ARIA APG** | `aria-practices/content/patterns/` | Keyboard interaction, focus management, ARIA roles/states for widgets | `<pattern>/<pattern>-pattern.html` — e.g. `dialog-modal`, `alertdialog`, `alert`, `listbox`, `menu-button`, `disclosure`, `switch`, `tabs`, `tooltip`, `windowsplitter` |
| **Nielsen Norman (distilled)** | `principles/nielsen-norman.md` | 10 usability heuristics; response-time / feedback budgets (0.1s / 1s / 10s) | read directly — it is short and curated | | **Nielsen Norman (distilled)** | `principles/nielsen-norman.md` | 10 usability heuristics; response-time / feedback budgets (0.1s / 1s / 10s) | read directly — it is short and curated |
| **FT Visual Vocabulary** | `chart-doctor/visual-vocabulary/` | Chart choice: data-relationship taxonomy (Magnitude, Correlation, Change-over-Time, Ranking, Distribution, Deviation, Part-to-whole, Spatial, Flow) → chart type | read `README.md` — the taxonomy is prose; each category gives a "use when…" definition + recommended chart types |
| **Datawrapper (distilled)** | `principles/datawrapper.md` | Chart choice in plain language; practical rules of thumb (bar-is-safe-default, line-vs-column, circles hard to compare, size = quantity) | read directly — short and curated; pairs with the FT clone |
## Close the loop ## Close the loop
@@ -82,6 +85,10 @@ contract, not the external source.
have never been applied before. This is the one event that reopens the one-off sweep have never been applied before. This is the one event that reopens the one-off sweep
(see _Scope_); after it, pointwise maintains the new seat like the rest. (see _Scope_); after it, pointwise maintains the new seat like the rest.
Candidate future seats (not yet seated): **FT Visual Vocabulary / Datawrapper** (chart Candidate future seats (not yet seated): **Shopify Polaris** (UX-writing depth),
choice — our domain), **Shopify Polaris** (UX-writing depth), **web.dev** (perceived **web.dev** (perceived performance / PWA / offline UX — seat at M6 per the plan).
performance / PWA / offline UX).
Seated at M4 (chart choice — our domain): **FT Visual Vocabulary** (clone) +
**Datawrapper** (distilled). Backfill is scoped to the Chart Builder itself (new
surface — no pre-existing chart-choice code to reconcile), so the seating debt is
discharged by building the builder against this canon rather than a separate sweep.
+9 -5
View File
@@ -48,7 +48,7 @@ doc before implementing.
| **M1** | **MVP core loop** | Author a Vega-Lite snippet, see it render live, it persists | §02, §03AC, §04, §09A | | **M1** | **MVP core loop** | Author a Vega-Lite snippet, see it render live, it persists | §02, §03AC, §04, §09A |
| **M1.5** | Visual design foundation ✅ | Apply the design language: tokens, IBM Plex, restyled M1 surfaces, chart theme | [arch 09](architecture/09-visual-design.md) | | **M1.5** | Visual design foundation ✅ | Apply the design language: tokens, IBM Plex, restyled M1 surfaces, chart theme | [arch 09](architecture/09-visual-design.md) |
| **M2** | Editor robustness | Draft/Published, validation, schema autocomplete, fit modes | §03DE, §04, §07(editor) | | **M2** | Editor robustness | Draft/Published, validation, schema autocomplete, fit modes | §03DE, §04, §07(editor) |
| **M3** | Datasets | Named reusable data + reference resolution in preview | §05, §03F, §09B | | **M3** | Datasets | Named reusable data + reference resolution in preview | §05, §03F, §09B |
| **M4** | Chart Builder | No-JSON chart composition from a dataset | §06 | | **M4** | Chart Builder | No-JSON chart composition from a dataset | §06 |
| **M5** | Settings + Import/Export | Preferences + workspace backup/transfer | §07, §08, §09C | | **M5** | Settings + Import/Export | Preferences + workspace backup/transfer | §07, §08, §09C |
| **M6** | Shell polish | Resize/toggle panes, routing, shortcuts, toasts, a11y, offline | §01, §10 | | **M6** | Shell polish | Resize/toggle panes, routing, shortcuts, toasts, a11y, offline | §01, §10 |
@@ -307,11 +307,15 @@ the reference.
- Build a bar chart from a dataset in a few clicks; preview live-updates; - Build a bar chart from a dataset in a few clicks; preview live-updates;
Create → new snippet opens and renders. Create → new snippet opens and renders.
**Council** seat **FT Visual Vocabulary** + **Datawrapper** (chart-choice canon) here: **Council****FT Visual Vocabulary** + **Datawrapper** are now **seated** (chart-choice
this is where Astrolabe stops being a pass-through JSON editor and starts making canon): this is where Astrolabe stops being a pass-through JSON editor and starts making
chart-shaped suggestions/defaults, so "_which chart, and why_" becomes a decision the app chart-shaped suggestions/defaults, so "_which chart, and why_" becomes a decision the app
owns — the one thing Carbon's data-viz styling doesn't cover. Seating triggers a one-off owns — the one thing Carbon's data-viz styling doesn't cover. Rather than a styling-only
backfill of the builder's defaults/affordances (see [`/council`](../.claude/skills/council/SKILL.md)). seating, we ran a full **research-first** pass (FT + Datawrapper + the formal engines
**Draco** and **Voyager**), recorded in [`docs/chart-builder-research.md`](chart-builder-research.md),
and chose the **Tier B "smart + guarded"** design: smart default mark for the data shape,
valid-type-locked field-type menus, Size-channel discipline, and non-blocking guidance.
The convergent rules and citations live in that doc; the spec (§06) was amended to match.
--- ---
+206
View File
@@ -0,0 +1,206 @@
# Chart Builder — Design Research (M4)
> **Status:** research complete; informs the M4 build (spec §06).
> **Decision:** build **Tier B — "smart + guarded"** (mark-first, still §06-shaped).
> **Why this doc exists:** the Chart Builder is the point where Astrolabe stops being
> a pass-through JSON editor and starts making chart-shaped suggestions/defaults.
> "Which chart, and why" becomes a decision the app owns, so we researched it
> deliberately before building. This is the record of what we studied and what we
> took from each source — the citations behind every default and guardrail in
> `src/core/chart-builder.ts`.
---
## 1. Scope of the builder (the constraint everything maps into)
Spec §06: compose a Vega-Lite chart from a dataset with **one mark**
{Bar, Line, Point, Area, Circle}, mapping columns to **four channels** (X, Y, Color,
Size), each carrying a **field type** ∈ {Quantitative, Nominal, Ordinal, Temporal},
plus optional pixel width/height → a complete spec saved as a snippet that
references the dataset by name. Column types are inferred upstream as
`number | string | date | boolean` (`src/core/type-inference.ts`).
No transforms (no binning, aggregation, stacking, regression), no second axis, no
geo. That narrow surface is the lens through which every source below was read:
"what does this canon tell us to do **within Bar/Line/Point/Area/Circle and
X/Y/Color/Size?**"
## 2. The sources
Two kinds: **formal CS** (how recommendation engines actually rank charts) and
**chart-choice canon** (how practitioners pick). They were chosen for being
**cloneable/grep-able offline** (the council's working model) and authoritative for
"which chart," which our other seats (Carbon/GOV.UK/APG/NN/g) don't cover.
| Source | What it is | Local path |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| **Draco** (uwdata) | Visualization design knowledge as ASP constraints — the formal "what makes a good chart," with hard (validity) + soft (preference) rules and weights, some learned from human perception experiments (Kim 2018, Saket 2018). | `reference/draco` |
| **Voyager** (vega) | UW IDL's recommendation/exploration tool on CompassQL — the _interaction_ model (field shelves, auto-add, type chips) and effectiveness-ranked encoding suggestions. | `reference/voyager` |
| **FT Visual Vocabulary** (Financial Times) | A poster/taxonomy mapping _what you want to show_ (9 data-relationship categories) → chart types. **Seated** in the council. | `reference/chart-doctor/visual-vocabulary/` |
| **Datawrapper** | Practitioner chart-choice in plain language; intent-first ("the chart's main statement becomes a compass"). **Seated** (distilled). | `reference/principles/datawrapper.md` |
**Theoretical basis, not seated (deliberately):** **Munzner**, _Visualization Analysis
and Design_ (marks & channels; the channel-effectiveness rankings — magnitude:
position → length → angle → area …; identity: spatial region → hue → shape;
expressiveness & effectiveness principles) and **Wilke**, _Fundamentals of Data
Visualization_ (`clauswilke/dataviz`; example directory by intent + "ugly/bad/wrong"
pedagogy). They are the _why_ beneath Draco and Voyager — Draco's soft weights are an
operationalization of exactly these Mackinlay/APT/Munzner effectiveness rankings — but
they restate the same rules the seated sources already give us, so seating them would
add overlap, not coverage. Cited here as grounding; revisit if we ever build the
intent-first "Tier C" front door, where Munzner's typology and Wilke's directory
would earn their place.
## 3. What we take from each source
### From Draco — validity guardrails + a preference ranking (the rigorous core)
Draco models a chart as ASP facts and rejects/ranks them with **hard** (∞ cost) and
**soft** (weighted) constraints (`asp/optimize.lp`). We can't ship an ASP solver in a
browser, but the rules are a lookup table. The portable subset:
- **Hard validity (block in the UI):** `reference/draco/asp/hard.lp`
- Quantitative on a string/boolean column — illegal (`:6`). Temporal only on a
datetime column (`:7`).
- **Size encoding a Nominal field — illegal** ("size implies order; nominal is
misleading", `:53`). Size cannot encode **negative** values (`:56`). Size only on
point/text marks (`:110`).
- Bar/Area must include a **zero baseline** on the measure axis (`:103-104`).
- Bar needs a categorical axis — both x and y continuous on a bar is malformed
(`:97`); Line/Area need **both** x and y, and not both discrete (`:91,:94`).
- Same field on x and y — illegal (`:122`). >20 categorical colors — illegal (`:172`).
- **Soft preference (the weights, `asp/weights.lp` + `asp/soft.lp`):**
- Channel-by-type appropriateness (lower = better): continuous data is free on x/y,
costs to put on color (10) or size (1); nominal cheapest on y then x then color;
ordered data expensive on size. → **fill X/Y before Color/Size.**
- Mark by data shape: continuous×continuous → **point** (line/area heavily
penalized); continuous×discrete aggregated → **bar**; discrete×discrete → point/rect.
- Prefer time on x (`temporal_y`, `:147`); never type a number as nominal
(`number_nominal`, weight 10); the loudest nudge is an all-discrete chart with no
measure (`only_discrete`, weight 30).
The hand-tuned `weights.lp` is the portable "common-sense" set; the learned
`weights_learned.lp` corroborates direction, not magnitude.
### From Voyager — the interaction model + the valid-type table
- **`getValidTypes` (`src/components/data-pane/field-list.tsx:140-155`) — adopted
almost verbatim:** number→{quantitative, nominal}, integer→{quantitative, nominal},
datetime→{temporal}, string→{nominal}, boolean→{nominal}. The type toggle shows only
when ≥2 valid types exist. (We extend slightly — see §4 — to also offer Ordinal,
which Voyager deliberately omits, `encoding.ts:131-134`.)
- **Auto-add / "auto" mark (`models/shelf/index.ts:72-81`):** Voyager lets a field be
added with `channel:'?'` and asks CompassQL to place it by `effectiveness`. The small
builder analogue is a **non-empty smart default** (`defaultBuilderConfig`) so the
preview is never blank.
- **Type chips + swap:** per-field type indicator with a click-to-change popover, and a
cheap x↔y swap (Voyager's `SPEC_FIELD_MOVE` is remove-both + re-add).
- **Out of scope (Voyager scope creep we reject):** wildcard shelves, the full Related
Views gallery, faceting (row/column), and embedding CompassQL/`compassql@0.20.2`
itself. We hand-roll a small decision table in `src/core/` instead of pulling the
engine.
### From FT Visual Vocabulary — the intent→chart taxonomy (and our coverage gaps)
`reference/chart-doctor/visual-vocabulary/README.md` (taxonomy is prose). Nine
categories; mapped to **our five marks**:
| FT category | What it shows | Our expression |
| -------------------- | --------------------------- | ----------------------------------------------------------------------------- |
| **Magnitude** | size comparisons | **Bar** (x=N, y=Q; horizontal x=Q, y=N for long labels) — primary |
| **Ranking** | position in an ordered list | **Bar, sorted** by value (the sort _is_ the feature) |
| **Change over Time** | trends | **Line** (x=T, y=Q; color=N for series); Bar/Area alternatives, single series |
| **Correlation** | relationship of 2+ measures | **Point** (x=Q, y=Q); **Circle/bubble** + size=Q for a third measure |
| **Deviation** | +/ from a reference | **Bar** with signed Q (diverging bar only) |
| **Distribution** | spread/frequency | weak: raw **Point** strip, or **Bar** of pre-binned counts (no bin transform) |
| **Part-to-whole** | component shares | **none well** — redirect to Magnitude/Bar; we can't show true proportions |
| **Spatial** | geography | **none** — exclude |
| **Flow** | movement between states | **none** — exclude |
**Coverage:** strong on Magnitude, Ranking, Change-over-Time, Correlation; partial on
Deviation/Distribution; none on Part-to-whole/Spatial/Flow. Honest gaps, not silent
degradation.
### From Datawrapper — plain-language rules + intent labels
`reference/principles/datawrapper.md`. Corroborates the same default-mark-by-intent
table (comparison→Bar, time→Line, correlation→Point/bubble) and supplies friendlier
intent words (Developments over time / Shares / Comparison / Correlation). Bindable
rules: bar is the safe default; bar over column on small screens; line for continuous
time, columns for a few points; circles are hard to compare precisely; size encodes a
quantity; area = single total (warn on multi-series).
## 4. The convergent rules — what all four agree on (high-confidence)
These are not a judgment call; the formal engines and the practitioner canon land on
the same place. They are the spec for `src/core/chart-builder.ts`:
1. **Column type → valid field types** (Voyager `getValidTypes`; Draco `hard.lp:6-7`):
`number`→{Quantitative (default), Ordinal, Nominal}; `date`→{Temporal only};
`string`→{Nominal (default), Ordinal}; `boolean`→{Nominal}. Never offer Q for
string/boolean, never Temporal for a non-date. (We add Ordinal where it's a defensible
user assertion of order; Voyager omits it for UX simplicity — our deliberate superset.)
2. **Default mark from the (X, Y) shape** (Draco mark-by-shape; Voyager effectiveness;
FT; Datawrapper): temporal × quantitative → **Line**; quantitative × quantitative →
**Point**; (nominal/ordinal) × quantitative → **Bar**; both-discrete → **Point**
(Bar/Line/Area are invalid with no continuous axis); single axis or unknown → Bar.
3. **Channel priority + Size discipline** (Draco `hard.lp:53,56,110` + non-positional
pref): fill X/Y before Color/Size; Color before Size. **Size is only valid for
Quantitative/Ordinal positive measures on Point/Circle marks** — disabled for Nominal,
Temporal, and negative data (not merely discouraged).
4. **Bar/Area zero-baseline; Line exempt** (Draco `hard.lp:103-104`; FT; ONS/Vox sources
FT links). We expose no axis-truncation control, so Vega-Lite's own defaults already
give zero-baseline bars and free-baseline lines — the rule is satisfied by _not adding_
an override, nothing to emit.
5. **Chart-choice polish** (FT; Datawrapper): sort bars when ranking; horizontal bar for
long category labels; Size encodes a quantity, Color a category; Area is for a single
series (warn against color-splitting into many).
## 5. The decision: Tier B — "smart + guarded"
Three tiers were on the table. **Tier B** was chosen (2026-06-05).
- **Tier A — spec-literal:** Bar default, four channel dropdowns, type override, smart
pre-population. Matches §06 verbatim but uses almost none of the research; stays a
"dumb" composer.
- **Tier B — smart + guarded (chosen):** Tier A **+** default _mark_ from the (X, Y) type
shape (not always Bar) **+** valid-type-only menus **+** inline non-blocking warnings
from the Draco rules **+** swap-X/Y **+** Size disabled for Nominal/Temporal/negative.
Still mark-first and §06-shaped, but genuinely intelligent. Requires a small §06
amendment (documented in the spec).
- **Tier C — intent-first aid:** Tier B **+** a "what do you want to show?" front door
(FT/Datawrapper intents → recommended mark + channel layout from intent × column
types). Highest "which chart & why" value; biggest UI; clearly extends §06. Deferred —
if revisited, this is where Munzner's typology and Wilke's directory would be seated.
## 6. How it maps to implementation
The convergent rules become pure functions in `src/core/chart-builder.ts`
(tested in `chart-builder.test.ts`), consumed by the builder store/modal:
- `validFieldTypes(columnType)` → the type menu (rule 1); `defaultFieldType` = its head.
- `defaultMark(xType, yType)` → smart default mark (rule 2); used by
`defaultBuilderConfig`.
- `isChannelTypeAllowed(channel, type)` → Size discipline gate (rule 3).
- `builderWarnings(config)` → inline non-blocking hints (rules 35: line/area need both
axes, area + many series, two measures better as a scatter, etc.).
- `buildChartSpec` / `buildSnippetSpecText` → assemble the final spec; zero-baseline is
Vega-Lite-default (rule 4), so nothing is emitted for it.
## 7. Anti-recommendations (what a naive builder would happily produce, and we don't)
The highest-value guardrails — encodings a naive UI emits that the canon rejects:
- A categorical column on **Size** (Draco hard `:53`) — blocked, not warned.
- A **truncated-axis bar** — prevented by never exposing an axis override (Draco `:103`).
- A high-cardinality category on **Color** → unreadable legend (soft w=10; >20 hard).
- A **Line between two raw measures** instead of a scatter (Draco soft w=20) — warned.
- An **all-categorical chart with no measure** (Draco soft w=30, the loudest) — warned.
- A **number typed Nominal** (Draco soft w=10) — discouraged via default = Quantitative.
---
_Citations are to files under `/Users/oleh/code/reference/`. The seated chart-choice
canon (FT clone + Datawrapper distill) lives in the council roster
(`.claude/skills/council/SKILL.md`); Draco/Voyager are reference clones, not council
seats — they're engineering sources, not user-facing design authorities._
+19 -4
View File
@@ -2,6 +2,8 @@
The Chart Builder is a visual, no-JSON way to compose a Vega-Lite chart from a selected dataset. The user picks a mark type and maps the dataset's columns to encoding channels; the builder produces a complete Vega-Lite spec and saves it as a new snippet that references the dataset. It is intended for users who want to start a chart quickly without hand-writing JSON in the _Spec Editor & Draft/Published Workflow_. The Chart Builder is a visual, no-JSON way to compose a Vega-Lite chart from a selected dataset. The user picks a mark type and maps the dataset's columns to encoding channels; the builder produces a complete Vega-Lite spec and saves it as a new snippet that references the dataset. It is intended for users who want to start a chart quickly without hand-writing JSON in the _Spec Editor & Draft/Published Workflow_.
> **Design level — "smart + guarded" (Tier B).** The builder is mark-first and stays within the inputs below, but it is not a dumb composer: it picks a sensible default mark for the data shape, offers only field types valid for each column, keeps unsuitable channel mappings out of reach, and surfaces non-blocking guidance for encodings that render poorly. These behaviors are derived from cross-source chart-choice research recorded in [`docs/chart-builder-research.md`](../chart-builder-research.md) (the convergence of Draco, Voyager, the FT Visual Vocabulary, and Datawrapper). The richer "intent-first" front door (ask _what do you want to show?_ and recommend a chart) is explicitly out of scope for now and noted there as a future tier.
## Opening ## Opening
- Launched from a selected dataset in the _Datasets_ manager via that dataset's "build chart" action. - Launched from a selected dataset in the _Datasets_ manager via that dataset's "build chart" action.
@@ -20,7 +22,7 @@ A two-pane modal:
### Mark type ### Mark type
- Single selection from an exact set of five mark types: **Bar, Line, Point, Area, Circle**. - Single selection from an exact set of five mark types: **Bar, Line, Point, Area, Circle**.
- Defaults to **Bar**. - On open, the mark **defaults to the type that best fits the pre-populated X/Y field-type shape** (Tier B smart default): a temporal axis against a measure → **Line**; two measures → **Point**; a category against a measure → **Bar**; two categories → **Point**; and **Bar** as the fallback when only one axis (or none) is mapped. The user can switch to any of the five afterward.
- Exactly one mark type is active at any time; selecting one updates the preview. - Exactly one mark type is active at any time; selecting one updates the preview.
### Encoding channels ### Encoding channels
@@ -28,13 +30,26 @@ A two-pane modal:
- Exactly four channels are offered, in this order: **X, Y, Color, Size**. - Exactly four channels are offered, in this order: **X, Y, Color, Size**.
- For each channel the user: - For each channel the user:
- Picks a dataset column from a dropdown of the dataset's detected columns (see _Datasets_ for column detection). A "None" option leaves the channel unmapped. Each column option shows a small type indicator alongside the column name. - Picks a dataset column from a dropdown of the dataset's detected columns (see _Datasets_ for column detection). A "None" option leaves the channel unmapped. Each column option shows a small type indicator alongside the column name.
- Optionally overrides the channel's **field type**, chosen from an exact set: **Quantitative, Nominal, Ordinal, Temporal**. The type override only appears once a column is selected for that channel. - Optionally overrides the channel's **field type**. The override appears only once a column is selected, and offers only the **types valid for that column** (Tier B valid-type locking) — a string/boolean column never offers Quantitative, and only a date column offers Temporal. Concretely: number → {Quantitative (default), Ordinal, Nominal}; date → {Temporal}; text → {Nominal (default), Ordinal}; boolean → {Nominal}. When a column admits only one valid type, no override control is shown.
- When a column is chosen, its field type defaults from the dataset's inferred column type (numeric → Quantitative, date → Temporal, otherwise Nominal); the user may change it afterward. - When a column is chosen, its field type defaults from the dataset's inferred column type (numeric → Quantitative, date → Temporal, otherwise Nominal); the user may change it within the valid set above.
- **Size discipline:** the **Size** channel accepts only Quantitative or Ordinal columns — size implies an ordered magnitude, so categorical (Nominal) and Temporal columns are not offered for Size (they remain available on X/Y/Color). A column that can't go on Size is shown disabled there with a brief reason.
- Clearing a channel back to "None" leaves it out of the produced spec. - Clearing a channel back to "None" leaves it out of the produced spec.
- A **Swap X/Y** control exchanges the X and Y mappings (field and type) in one click, for quickly flipping the axes of the pre-populated default without re-selecting both columns.
### Default pre-population ### Default pre-population
- On open, the first detected column is assigned to **X** and the second (if any) to **Y**, each with its derived field type. Remaining channels start unmapped. Mark type starts at Bar. - On open, the first detected column is assigned to **X** and the second (if any) to **Y**, each with its derived field type. Remaining channels start unmapped. The mark starts at the smart default for that X/Y shape (see _Mark type_), not unconditionally Bar.
### Guidance (non-blocking)
The builder surfaces short, plain-language hints for configurations that render but read poorly — advisory only, never blocking the **Create Snippet** action (validation below is the sole gate). These follow the chart-choice research ([`docs/chart-builder-research.md`](../chart-builder-research.md)) and include, for example:
- A **Line** or **Area** mark with only one axis mapped (both axes are needed to draw it).
- A **Bar/Line/Area** whose X and Y are both categories (nothing to measure).
- **Two measures** on a non-scatter mark (a scatter — Point/Circle — usually reads better).
- An **Area** chart split into multiple colour series (per-series change is hard to see).
A clean configuration shows no hints.
### Dimensions (optional) ### Dimensions (optional)
@@ -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 { useShallow } from 'zustand/react/shallow';
import { datasetReference, type DataSource, type Dataset } from '@core/dataset'; import { datasetReference, type DataSource, type Dataset } from '@core/dataset';
import { detectFormat, detectFormatFromUrl, type DataFormat } from '@core/format-detection'; 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 { confirm } from '../stores/ConfirmStore';
import { notify } from '../stores/NotificationStore'; import { notify } from '../stores/NotificationStore';
import { selectSelectedDataset, useDatasetStore, byModifiedDesc } from '../stores/DatasetStore'; import { selectSelectedDataset, useDatasetStore, byModifiedDesc } from '../stores/DatasetStore';
@@ -221,9 +221,16 @@ function DatasetDetail({
<button type="button" className={styles.action} onClick={handleEdit}> <button type="button" className={styles.action} onClick={handleEdit}>
Edit Edit
</button> </button>
{/* "Build Chart from dataset" (spec §05) lands enabled with the Chart {/* Build Chart (spec §05 §06) opens the Chart Builder on this dataset.
Builder in M4. Per council (GOV.UK / NN/g), we don't ship a dead Replaces the Datasets modal (one modal at a time, §01C); detail view has
disabled control in the meantime the action appears when it works. */} no transient form state, so no discard prompt. */}
<button
type="button"
className={styles.action}
onClick={() => openModal('chartBuilder', String(dataset.id))}
>
Build Chart
</button>
<button <button
type="button" type="button"
className={`${styles.action} ${styles.danger}`} className={`${styles.action} ${styles.danger}`}
+1 -1
View File
@@ -22,7 +22,7 @@ export function ModalShell() {
const name = useAppStore((s) => s.activeModal); const name = useAppStore((s) => s.activeModal);
const config = getModalConfig(name); 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 // 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 // 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 { ComponentType } from 'react';
import type { ActiveModal, ModalName } from './types'; import type { ActiveModal, ModalName } from './types';
import { ChartBuilderModal } from '../components/ChartBuilderModal';
import { DatasetsModal } from '../components/DatasetsModal'; import { DatasetsModal } from '../components/DatasetsModal';
import { ExtractModal } from '../components/ExtractModal'; import { ExtractModal } from '../components/ExtractModal';
import { useChartBuilderStore } from '../stores/ChartBuilderStore';
import { useDatasetStore } from '../stores/DatasetStore'; import { useDatasetStore } from '../stores/DatasetStore';
import { useExtractStore } from '../stores/ExtractStore'; import { useExtractStore } from '../stores/ExtractStore';
@@ -62,6 +64,17 @@ export const MODAL_REGISTRY: Partial<Record<ModalName, ModalConfig>> = {
init: () => useExtractStore.getState().init(), init: () => useExtractStore.getState().init(),
getState: () => ({ name: useExtractStore.getState().name }), 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 => 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) => { createSnippet: (options) => {
get().commitDraft(); // flush the outgoing snippet's valid edits before switching away 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) => ({ set((s) => ({
snippets: [snippet, ...s.snippets], snippets: [snippet, ...s.snippets],
activeSnippetId: snippet.id, activeSnippetId: snippet.id,
+294
View File
@@ -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');
});
});
+323
View File
@@ -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
View File
@@ -14,6 +14,13 @@
/** Current schema version for a Snippet record (read-time migration target). */ /** Current schema version for a Snippet record (read-time migration target). */
export const CURRENT_SNIPPET_VERSION = 1; 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 { export interface Snippet {
/** Unique, stable identifier. */ /** Unique, stable identifier. */
id: string; id: string;
@@ -45,7 +52,7 @@ export interface Snippet {
* Inline data only datasets arrive in M3. * Inline data only datasets arrive in M3.
*/ */
export const SAMPLE_SPEC = { export const SAMPLE_SPEC = {
$schema: 'https://vega.github.io/schema/vega-lite/v6.json', $schema: VEGA_LITE_SCHEMA_URL,
description: 'A simple bar chart.', description: 'A simple bar chart.',
data: { data: {
values: [ values: [
@@ -92,6 +99,8 @@ export interface CreateSnippetOptions {
now?: Date; now?: Date;
/** Id injection for deterministic tests; defaults to a random UUID. */ /** Id injection for deterministic tests; defaults to a random UUID. */
id?: string; 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: '', comment: '',
tags: [], tags: [],
datasetRefs: [], datasetRefs: [],
meta: {}, meta: options.meta ?? {},
}; };
} }