flint-chart: Flint in an application
The chart input is the same ChartAssemblyInput the flint-chart-author
skill writes, and the interaction_spec and update ops are the
flint-interaction-author skill's. This skill is the code around them:
install, compile, mount, read the chart, link charts, and bespoke gestures.
Write code only when the user asks for it.
In code, data is a runtime value: load it with normal code (a real CSV
parser, never line.split(',')) and pass data: { values: rows }. Keep the
values as the data has them; semantic_types reads them.
Install and compile
For MCP clients, the server can run with npx:
npx -y flint-chart-mcp
For JavaScript or TypeScript projects:
npm install flint-chart
npm install flint-chart is the whole install: it comes with every backend
(Vega-Lite, ECharts, Chart.js, Plotly). React is an optional peer, needed only
for flint-chart/react.
- Draw with
<FlintChart backend="…"> from flint-chart/react, or mountChart
from flint-chart/interactive; presets, update helpers and types come from
flint-chart/interactive too.
- Compile with
assembleVegaLite, assembleECharts, assembleChartjs or
assemblePlotly from flint-chart; renderSvg from flint-chart/render
draws a static SVG (Vega-Lite or ECharts).
- Only for an app bundled into one file (no code splitting): import
flint-chart/react/<backend> or flint-chart/interactive/<backend>
(vegalite, echarts, chartjs, plotly), which reaches no other backend,
so the file carries one library.
Then compile with the requested backend:
import { assembleChartjs, assembleECharts, assembleVegaLite } from 'flint-chart';
const vegaLiteSpec = assembleVegaLite(input);
const echartsOption = assembleECharts(input);
const chartjsConfig = assembleChartjs(input);
Python support is planned for a later release. Until the PyPI package is
published, use the npm package or MCP server for released workflows.
Mount
import { mountChart, navigate, legendToggle } from 'flint-chart/interactive';
const surface = mountChart(container, input, {
backend: 'vegalite',
renderer: 'svg',
interactions: [navigate({ axes: 'x' }), legendToggle()],
chartId: 'sales',
});
await surface.ready;
const warnings = await surface.warnings; // interactions the chart could not honour
// …
surface.destroy();
| Member |
What it does |
ready, warnings |
Promises: the first render; the dropped or yielded interactions. Every call below waits for ready itself. |
applyUpdate(update, options?) |
Retains one update by id; replaces the layer with the same id. options.transition.duration animates a viewport. |
setUpdates(updates) |
Replaces every retained update. |
clearUpdate(id) |
Removes one layer. |
dispatch(id, payload) |
Runs an externalInteraction handler and applies what it returns. |
getState() |
What the chart shows now; undefined before ready. |
onChange(callback) |
Every change to that state, after the render; returns the unsubscribe. |
layout |
Once ready: plot, the plot box { width, height } on a chart that draws one plot; views, each drawn view as { role, box: { x, y, width, height } } (role plot, text, tile or rule; facet panels row by row); block, the box the views take with their axes and headers, without title and keys. Boxes are in pixels from the drawn chart's top left, read from what it drew, so they follow filters and resizes. undefined on charts with a category rail and on non-Vega-Lite backends. |
refresh() |
Re-projects overlays after the host rescales the chart. |
element, chartId |
The mount's root and the stable chart id. |
destroy() |
Removes listeners, the renderer, and the DOM. |
input is a ChartAssemblyInput. Presets go in input.interaction_spec as
JSON or in options.interactions as factory calls. Both may appear; spec
entries mount first, and a code definition with a spec entry's id
replaces it with an interaction_overridden info warning.
- A malformed
interaction_spec, a repeated code id, or a code definition
the chart cannot honour fails the mount with an error that names it. A spec
entry the chart cannot honour is dropped with a warning instead.
options.availableSize: { width?, height? } is the room the host gives the
chart. It becomes the canvasSize ceiling on the sides given, so the chart
lays out for that room rather than being scaled into it.
options.updates holds retained updates present at the first render, for a
chart that starts with a part hidden or framed.
renderer: 'svg' for charts whose marks a host reads from the DOM, or under
a few thousand marks; 'canvas' for maps and dense charts.
- A
Year or Date field makes a temporal axis whose rows hold Dates or
ISO strings; a bare number such as 2013 reads as milliseconds after 1970.
A semantic_types entry may be an object,
{ semanticType, intrinsicDomain: [lo, hi] }; the intrinsic domain holds an
axis still while the rows change.
options: { addTooltips: false } on the input is the switch for the
tooltip, for a chart whose hidden values it would give away.
- Build with a bundler. The interactive entry reaches every backend through
lazy imports with no file extension; when
echarts, chart.js, and
plotly.js-dist-min are not installed, mark them external (esbuild
--splitting --external:echarts --external:chart.js --external:plotly.js-dist-min;
Vite build.rollupOptions.external).
- In React, use
<FlintChart> from flint-chart/react rather than mounting
in an effect; see "In React" below.
In React
import { FlintChart, type FlintChartHandle } from 'flint-chart/react';
import { clickHighlight } from 'flint-chart/interactive';
const chartRef = useRef<FlintChartHandle>(null);
<FlintChart
ref={chartRef}
spec={input}
interactions={[clickHighlight({ targets: ['mark'] })]}
width="100%"
fit="relayout"
=> setSelected(change.state.selected)}
=> report(error)}
/>;
| Prop |
What it does |
spec |
The ChartAssemblyInput, interaction_spec included. A change of content remounts; rows compare by reference. |
interactions |
Factory calls added to the spec's entries, or (fromSpec) => definitions for the full list. A factory rebuilt with the same id and options keeps the chart; a changed option remounts it. |
updates |
Host updates, diffed by id. Passing even [] mounts the runtime on a chart with no interactions. |
width, height, fit |
The box. fit is scale-down (default; never scales up), crop (natural size, clipped), or relayout (the box becomes the layout room; a resize remounts once it settles, so a selection does not survive it). |
onChange, onInteraction |
The state after a change, and the raw gesture record. |
onRender, onWarnings, onError |
Each mount's render and warnings; a failed mount, shown in the box as a muted error. |
fallback |
Shown until the chart mounts. |
ariaLabel, chartId |
ariaLabel applies in place; a new chartId remounts. |
The ref's FlintChartHandle holds surface (the mounted surface or null),
applyUpdate, clearUpdate, dispatch, getState, and refresh. A remount
keeps the old chart on screen until the new one is ready.
Read the chart
getState() field |
Holds |
selected |
The marks the chart emphasizes now, previews included. |
entries |
The same marks per update id, with layer: 'retained' | 'preview'. |
hidden |
Legend values a legend-toggle hides, as { channel, value }. |
viewport |
The domain on view after a pan or zoom; absent on a chart that does not navigate. |
categoryOrder |
The order of the reorderable axis now. |
windows |
Category rail windows, { start, count, total } per channel. |
Each element's value is the mark in field terms: a bar's category and
measure, a legend item's { channel, field, domain }, a histogram bar's
{ field, range }. The host owns the rows and queries them from the value and
the geometry.
onChange fires after every render with a ChartChange: phase (preview
while a gesture runs, commit for a committed change or a host call, cancel
when a gesture ends with nothing), interactionId and action (absent for a
host call and for a reset), the gesture's own target and geometry, and the
state after. An overlay or a data swap leaves no trace in the state, so the
host keeps that model itself.
const valuesOf = (elements: readonly SemanticElement[]) => elements.map((element) => element.value);
// A panel follows the gesture live, else shows what the chart shows.
surface.onChange(({ phase, target, state }) => {
const hit = valuesOf(target?.elements ?? []);
panel.show(phase === 'preview' && hit.length > 0 ? hit : valuesOf(state.selected));
});
// An agent context reads committed state only: values and ranges, never rows.
surface.onChange(({ phase, state, geometry }) => {
if (phase !== 'commit') return;
sendContext({ selected: valuesOf(state.selected), range: geometry?.domain, hidden: state.hidden, viewport: state.viewport });
});
The container also emits a bubbling DOM event, flint-interaction, for every
canvas interaction, before the chart reacts: detail.chartId,
detail.interactionId, and detail.event, the same CanvasInteractionEvent
a handler gets. It fires for a definition whose handle returns null, so it
is the path for a host that draws its own response to a gesture.
Things the surface holds fixed: no preset changes the layout, so a zoom never
recomputes the bar step, the ticks, or the domain (filter the rows and mount
again for that); the mute level is set at mount; Escape reaches a chart after
a press on it, and only that chart; a preset's toggle (select,
click-highlight) needs Shift, Ctrl, or Meta, and a plain second click
replaces; a press on an overlay path resolves to no mark, so a click-none
reset on the definition that drew the overlay clears it at that press.
Apply updates and read the result
applyUpdate, setUpdates and dispatch take the same { id, ops } layers
as the interaction skill's "Update the chart", and return what applied.
The result. applyUpdate, setUpdates, and dispatch return a
ChartUpdateResult: { status: 'applied' | 'partially-applied' | 'unsupported', resolvedTargets, unresolvedTargets, unsupportedOps }. An
unresolved target has a wrong field or value; an unsupported op needs a
preset the chart does not mount. What the chart shows is what the result says
it shows: fix an unresolved key or drop an unsupported op before describing
the chart.
Link charts
linkCharts links mounted charts on the fields they share. A selection on one
chart (a click, a brush, a group focus, a hover) becomes one condition, a part
per field; every chart emphasizes the marks that meet it, the source included,
through one linked-selection layer; a reset on any chart clears it everywhere.
import { linkCharts, mountChart, clickHighlight, brushX } from 'flint-chart/interactive';
const link = linkCharts({
bars: { input: barsInput, surface: mountChart(barsEl, barsInput, { backend: 'vegalite', interactions: [clickHighlight()] }) },
trend: { input: trendInput, surface: mountChart(trendEl, trendInput, { backend: 'vegalite', interactions: [brushX()] }) },
}, { fields: ['region', 'month'] });
for (const [id, chart] of Object.entries(await link.links)) console.log(id, chart.notes); // what each chart left out
link.onCondition(({ condition }) => table.filter(condition)); // { region: { in: ['Asia'] }, month: { range: [start, end] } }
// link.clear(); link.destroy();
A table, a filter or any control beside linked charts joins the same
condition: link.select(parts) sets parts as if a chart had selected them, and
onCondition gives the table what to show. One condition, so a row click, a
region picker and a brush combine (AND) and a reset on any chart clears them all.
row.addEventListener('click', () => link.select({ country: { in: [row.dataset.country] } }));
regionPicker.addEventListener('change', (e) => link.select({ region: e.target.value ? { in: [e.target.value] } : null })); // null lets go
link.onCondition(({ condition }) => renderTable(rows.filter((r) => meets(r, condition))));
select only takes fields in fields; a chart shows a part when its marks
carry the field (encode it, or put it on detail).
- The link emphasizes the matching marks; to drop rows instead (a filter), give
the charts filtered data as below.
import { FlintChart, useLinkedCharts } from 'flint-chart/react';
const link = useLinkedCharts({ bars: barsInput, trend: trendInput }, { fields: ['region', 'month'] });
<FlintChart spec={barsInput} {...link.chart('bars')} />;
// link.select({ region: { in: ["Asia"] } }) from a table or control; link.clear()
<FlintChart spec={trendInput} {...link.chart('trend', { onChange: setPageState, updates: myUpdates })} />;
// the chart's own onChange, onRender and updates go through chart(id, own); a prop after the spread replaces the link's
// link.condition.condition is the same condition; filtered rows in `spec` keep it
- A chart receives a field when its marks carry it (encode it, on
detail if
nothing else shows it), and sends through each selecting interaction whose
subject includes a connected field. { charts: { trend: { receive: false } } }
keeps a chart as drawn; send: false keeps its selections to itself.
- The link emphasizes; it never filters or re-aggregates. To filter, read the
condition (
onCondition, link.condition) and give each chart its rows:
beside linkCharts, a set-data update (a new spec remounts the chart, and
the link holds the old surface); beside useLinkedCharts, a spec with the
filtered rows.
setUpdates replaces every layer, the link's included, until the condition
next changes; use applyUpdate and clearUpdate beside a link.
linkCharts checks the charts with the validator, loaded on first use; pass
{ links } from validateLinks (flint-chart/validate) to skip that load.
For a link linkCharts does not express (a payload each chart reads its own
way), wire onChange to an externalInteraction on the other charts:
const linked = externalInteraction<{ countries: string[] }>({
id: 'linked',
handle: ({ countries }) => ({
id: 'linked',
ops: [{ op: 'set-style', targets: [{ select: { where: { Country: { in: countries } } } }], value: { state: 'emphasized' } }],
}),
});
source.onChange(({ phase, interactionId, state }) => {
if (phase !== 'commit' || !interactionId) return; // host writes carry no id: no loop
void other.dispatch('linked', { countries: state.selected.map((element) => String(element.value.Country)) });
});
Linked charts share one theme_spec so a value has one colour everywhere.
The same dispatch drives a chart over time: a playback loop dispatches one
frame per animation frame, and the handler returns the whole layer for that
frame.
When no preset fits
A host that runs code mounts a CanvasInteractionDef in options.interactions
beside presets: a trigger, what it affords, and a handler that returns the
layer for its id.
import { rectangleTrigger, type CanvasInteractionDef } from 'flint-chart/interactive';
const timebox: CanvasInteractionDef = {
id: 'timebox',
eventSource: rectangleTrigger('contain'),
affordances: { plot: { cursor: 'region' } },
reset: ['click-none', 'escape'],
handle(event) {
if (event.action !== 'select-region' || event.phase !== 'commit') return null;
const x = event.geometry.domain?.x;
const y = event.geometry.domain?.y;
if (x?.kind !== 'interval' || y?.kind !== 'interval') return null;
const keep = seriesInsideBox(x.start, x.end, Number(y.start), Number(y.end)); // host logic over host rows
return {
id: 'timebox',
ops: [{ op: 'set-style',
targets: keep.map((series) => ({ select: { key: { Series: series } } })),
value: { state: 'emphasized' } }],
};
},
};
| Field |
Role |
id |
Names the interaction in events and the layer it retains. |
eventSource |
The trigger: what to capture and how to read it. |
affordances |
The kinds of hit the handler receives, each with its cursor and hover; a hit of a kind not listed never reaches it. Keys: mark, legend-item, axis-label, plot. Cursors: activate, drag, region, navigate, inspect, draw. Hovers: target (the mark), cohort (its group). |
handle(event, context) |
Returns the whole layer for this id, or null for no change. |
reset |
Gestures that clear the layer: click-none, double-click, escape. A reset reports as a commit with no interactionId. It suits a layer of styles the state shows; an overlay or a data layer is cleared by the host. |
Triggers.
| Trigger |
The reader does |
action |
geometry.plot |
geometry.domain |
Affordance key |
clickTrigger |
Clicks a mark, legend item, or axis label. |
click-element, click-legend, click-axis |
point |
— |
mark, legend-item, axis-label |
hoverTrigger |
Moves over a mark. |
hover-element, hover-legend, hover-axis |
point |
— |
same |
dragTrigger(tolerance?) |
Presses a mark, or a projectable overlay path, within tolerance px (12) and drags. |
drag |
drag { start, current, delta } |
the pointer's values; geometry.projection while over a projectable overlay |
mark |
rectangleTrigger(match?, guide?) |
Drags a rectangle. |
select-region |
rect |
x, y intervals |
plot |
xBrushTrigger(match?, mode?, guide?), yBrushTrigger(…) |
Drags an interval along one axis. |
brush-x, brush-y |
rect |
that axis's interval |
plot |
lassoTrigger(match?, guide?) |
Draws a freehand region; previews begin at the third point. |
select-lasso |
polygon |
points: the stroke so far, in data values |
plot |
angularBrushTrigger(match?, mode?, guide?) |
Drags a sector on a polar chart. |
brush-angle |
angular-sector |
— |
plot |
inspectTrigger(mode?) |
Moves over the plot. |
inspect-x, inspect-y, inspect-xy |
point |
x, y values |
plot |
inspectIndexTrigger(axis?, show?, seriesBy?) |
Moves along the index axis. |
inspect-x, inspect-y |
point |
the index value |
plot |
navigationTrigger({ axes?, pan?, zoom?, reset? }) |
Drags, wheels, pinches. |
pan-viewport, zoom-viewport, reset-viewport |
viewport { delta, factor, anchor } |
the viewport after the move |
plot |
contextTrigger, longPressTrigger(ms?), doubleActivateTrigger |
Right-clicks, holds (500 ms), double-clicks a mark. |
context-element, long-press-element, double-activate-element |
point |
— |
mark |
match is 'intersect' (default) or 'contain' and decides which marks the
region's target lists. guide styles the drawn shape; false hides it. A
region is ephemeral: its guide and its preview end at the commit. A brush or
select with mode: 'stateful' keeps its region on screen and editable, and
event.operation reads create, move, resize-leading, resize-trailing,
or clear. Spread a trigger to tune it:
{ ...hoverTrigger, defaultAssistDistance: 28 } acquires the nearest mark
within 28 px. A chart admits a trigger when it offers what the trigger needs,
per what list_interaction_presets says each preset requires; a code definition the chart cannot honour throws at
mount with a message that names what it needed.
The event.
interface CanvasInteractionEvent {
action: string; // from the table
phase: 'start' | 'preview' | 'commit' | 'cancel'; // clicks and hovers skip start
operation?: string; // a stateful brush's edit, or pan | zoom | reset
geometry: { plot?, domain?, projection? };
target: { visual: { kind, role }, elements: [{ value, records? }] } | null;
modifiers?: { shift, ctrl, meta };
description?: { kind, type, content, text }; // on focus-element from accessible-navigation
}
target.elements[i].value holds the mark's encoded values, derived fields
included; records holds the source rows when the runtime can prove them. A
region target lists every mark inside. A legend hit's value is a
LegendTargetValue: { channel, field, domain: { kind: 'value', value } },
or { kind: 'interval', start, end } on a continuous legend. An axis-label
hit's value is an AxisTargetValue: { axis, field, value }.
geometry.domain is inverted through the plot's scales: a brush on a time
axis gives domain.x = { kind: 'interval', start: Date, end: Date }, a linear
axis gives numbers, a discrete axis gives the category.
description arrives on focus-element while accessible-navigation walks
the chart: what the focused element is (type, such as "Bar") and what it
represents (content), with the spoken text. The walk's emphasis reports
through onChange as a preview.
geometry.projection.kind === 'path' during a drag over an overlay with
projectable: true: segment.start.value and segment.end.value are the
overlay rows on each side of the pointer and segment.t the fraction between
them.
The types. flint-chart/interactive exports these, and flint-chart/react
re-exports them. onChange receives a ChartChange: the gesture's own
target and geometry, and the chart's state after it. Generated from the
source by npm run gen:reference:
interface ChartChange {
// `preview` while a gesture runs, `commit` for a committed change, `cancel` when a gesture ends with none.
phase: ChartChangePhase;
// `host` for `updates`, `applyUpdate`, `clearUpdate` and `dispatch`; always `commit`.
source: ChartChangeSource;
changed: ChartStateFacet[];
// The interaction behind the change: a reader's gesture, or an external interaction run by `dispatch`.
interactionId?: string;
action?: CanvasInteractionAction;
// The gesture's own hit: the hovered point, or the marks at an inspected index.
target?: SemanticTarget | null;
// The gesture's geometry: a brushed range, an index value, or the viewport after a move.
geometry?: CanvasInteractionEvent['geometry'];
// The reset gesture a reader made: a click on nothing, Escape, or a double-click. Reported even when the chart held nothing to reset, so a host that shows a selection of its own can let it go.
reset?: InteractionResetGesture;
state: ChartState;
previous: ChartState;
}
interface ChartState {
chartType: string;
// The marks the chart emphasizes or focuses now, previews included.
selected: SemanticElement[];
// The emphasized marks of each update, by update id; `selected` is their union.
entries?: ReadonlyMap<string, ChartStateEntry>;
// The legend values a toggle hides now.
hidden?: ChartHiddenValue[];
// The domain the plot shows now, when the chart navigates.
viewport?: DomainGeometry;
// The category window of each rail.
windows?: Partial<Record<'x' | 'y', ChartCategoryWindow>>;
categoryOrder?: unknown[];
// The notes the chart holds now, previews included; `inView` tells which ones it draws.
annotations?: ChartAnnotation[];
// The active filter of each field, set by filter controls; absent fields show every value.
filters?: Readonly<Record<string, FilterValue>>;
}
interface SemanticTarget {
visual: {
kind: 'mark' | 'path' | 'region' | 'widget' | 'handle' | 'legend' | 'axis' | 'chart' | 'title' | 'header';
role: string;
};
elements: SemanticElement[];
}
interface SemanticElement {
// Values represented by the mark's channels, or by a semantic control such as a legend item.
value: Record<string, unknown>;
// Contributing input records when provenance is available; zero or many may support one value.
records?: Record<string, unknown>[];
}
interface LegendTargetValue {
channel?: string;
field?: string;
// The entry's value on a reader's hit; read `domain`, which every legend target carries.
value?: unknown;
domain: LegendDomain;
}
type LegendDomain =
| { kind: 'value'; value: unknown }
| { kind: 'interval'; start?: number; end?: number };
interface AxisTargetValue {
axis: 'x' | 'y';
field: string;
value: unknown;
}
interface DomainGeometry {
x?: DomainCoordinate;
y?: DomainCoordinate;
points?: DomainPoint[];
// The detail level a multi-level projected chart draws for this viewport.
level?: string;
// On a multi-level projected chart, the coarsest-level region under the plot centre: its feature id and properties plus the joined row fields.
focus?: Record<string, unknown>;
}
type DomainCoordinate =
| { kind: 'value'; value: DomainValue }
| { kind: 'interval'; start: DomainValue; end: DomainValue };
type DomainValue = number | Date | string;
interface DomainPoint {
x?: DomainValue;
y?: DomainValue;
}
interface ChartHiddenValue {
channel: string;
value: unknown;
}
type FilterValue =
| { in: unknown[] }
| { range: [unknown, unknown] };
context is the chart state plus available, every drawn mark, for
building refs, and selected, the current emphasis, for a toggle rule.
The handler.
- It returns the complete layer for the id on every
preview and commit;
the runtime drops the preview on cancel. A null on a preview shows
nothing until the commit, which is how a rule applies to the committed box
only. A region gesture keeps a preview layer under the interaction's id
while the drag runs, so a commit after previews restates the layer; a
null there lets the last preview stand.
- It maps geometry to the host's model and the model to ops. Host side
effects (state, panels, overlays the host draws) come from
flint-interaction or onChange, which carry the same event; the handler
itself returns ops and leaves the DOM to the runtime.
- Triggers have one owner for code definitions as for presets; two code
definitions on one trigger throw at mount.
navigate({ pan: false }) goes
beside a region trigger.
- An element drag owns the press on the marks it affords. A press there is a
drag with phase start; target is the pressed mark through every phase.
The layer returned at start is kept as the gesture's preview, and a release
without movement commits that preview with no further call. No click
definition fires on those marks, so the definition that drags a mark also
answers its press.
- A click definition that affords
hover on marks receives preview events
for the hover cue. Return null or an emphasis for them, and the layer on
commit.
Patterns.
| Pattern |
Flow |
Pieces |
| Gesture rule |
Flint in, Flint out |
A region trigger reads geometry.domain; the host rule picks rows; set-style by key (the timebox above). |
| Host-drawn detail |
Flint in, custom out |
hoverTrigger or inspectTrigger with a null handle; the host listens to flint-interaction for the resolved element and draws a lens, a cursor, or a badge over the mount. |
| Application drives the chart |
external in, Flint out |
externalInteraction plus dispatch per frame: a playback year, a reveal progress. |
| Drag along a path |
press, then drag |
One dragTrigger() definition and one layer. At start on a mark it returns the mark's path as a set-overlay line with interactive: true, projectable: true and order, plus set-data for the current position. On preview and commit with geometry.projection it returns the same two ops for the pointer's position. intrinsicDomain on the x and y fields holds the axes still across the swaps. |
| Freehand stroke |
draw |
The rows to guess form their own series, and a mount update sets opacity: 0 on that series, which keeps the axis. lassoTrigger('contain', false) with plot: { cursor: 'draw' } is the pen: geometry.domain.points become the rows of a set-overlay line. An externalInteraction reveals the truth as an overlay, then the host clears the hide. |
| Chart-level zoom |
wheel |
When the layout itself must change (bar step, ticks, domain), filter the rows and mountChart again in a hidden layer; swap on ready. No preset re-lays out. |
| Semantic zoom on a map |
navigate |
A Choropleth with level: 'auto' (US states, then counties) or with your own levels: [{ value, url, feature?, enter?, exit? }] (one GeoJSON or TopoJSON object per level, rows joined on the feature id or featureKey, baseMapUrl drawn beneath as land without data), or a Map with levelField and levels; navigate(), and set-viewport { region: { key } } with a transition to fly into a region. Navigation events carry geometry.domain.level and focus (the coarsest region under the centre). A hover reaches the host through a hover affordance (hover: 'target'); a handler that returns null leaves the map as drawn. |
Host-drawn detail, the shape of it:
const probe: CanvasInteractionDef = {
id: 'probe',
eventSource: { ...hoverTrigger, defaultAssistDistance: 28 },
affordances: { mark: { hover: 'target' } },
handle() { return null; },
};
container.addEventListener('flint-interaction', (e) => {
const { interactionId, event } = (e as CustomEvent<FlintInteractionEventDetail>).detail;
if (interactionId !== 'probe' || event.phase !== 'preview') return;
const row = event.target?.elements[0]?.records?.[0];
if (row) lens.show(row); // the host draws; the chart is unchanged
});
Worked examples
A chart that drives the app
User: "In my dashboard, a click selects the country and a double-click opens
its page. Zooming the y axis would help too." A scatter of gdp by life
with color: continent and detail: country.
navigate holds the double-click by default for its reset, and
double-activate needs it; reset: ["escape"] frees it. click-highlight
takes targets: ["mark"] so the app's selection comes from marks only.
{
"interactions": [
{ "type": "click-highlight", "options": { "targets": ["mark"] } },
{ "type": "double-activate" },
{ "type": "navigate", "options": { "axes": "y", "reset": ["escape"] } }
]
}
The app reads the selection from onChange on a commit whose action is
click-element, and the activation from one whose action is
double-activate-element.
Code: two linked charts
Two bar charts share a Country field: GDP per country, and population per
country. A click on one emphasizes the same country on both.
import { mountChart, clickHighlight, linkCharts } from 'flint-chart/interactive';
const mount = (el: HTMLElement, input: ChartAssemblyInput) =>
({ input, surface: mountChart(el, input, { backend: 'vegalite', interactions: [clickHighlight({ targets: ['mark'] })] }) });
const link = linkCharts({ gdp: mount(gdpEl, gdpInput), population: mount(popEl, popInput) }, { fields: ['Country'] });
The clicked chart drops its own emphasis once the link shows the condition, so
both charts show one selection. A click-none, Escape, or double-click on
either chart clears it on both; the link's own writes are host changes, so no
chart echoes them back.
Bespoke: a rule over the brushed box
A line chart of Series by Month. The reader drags a box; the series whose
every point in that month range lies inside the y range stay emphasized. No
preset applies a rule over series, so the definition is the timebox above:
rectangleTrigger('contain'), a plot affordance with the region cursor,
a handler that acts on select-region at commit, and reset: ['click-none', 'escape'] so a click on empty plot clears it. It mounts beside
navigate({ pan: false }) when the chart also zooms, since both ask for the
plot drag otherwise.
Validation checklist
- Every trigger, cursor, and field name is one from this skill or the
installed
flint-chart/interactive types.
- Every definition declares
affordances for the hits its trigger yields.
- No two definitions, and no definition and spec entry, share a trigger or
an
id.
- The surface is destroyed on unmount, and every
applyUpdate or dispatch
result is read.
1---2name: flint-app-author3description: "Use when: the user asks for code that uses flint-chart: add Flint to a JS/TS app, a React component, a notebook or a script; mount a chart with interactions; read selections with onChange; apply updates from code; link charts in an app; or build a gesture no preset gives. Not for chart specs shown through the MCP tools."4metadata:5 source: https://skillmd.com/skills/microsoft/flint-app-author6---78# flint-chart: Flint in an application910The chart input is the same `ChartAssemblyInput` the `flint-chart-author`11skill writes, and the `interaction_spec` and update ops are the12`flint-interaction-author` skill's. This skill is the code around them:13install, compile, mount, read the chart, link charts, and bespoke gestures.14Write code only when the user asks for it.1516In code, data is a runtime value: load it with normal code (a real CSV17parser, never `line.split(',')`) and pass `data: { values: rows }`. Keep the18values as the data has them; `semantic_types` reads them.1920## Install and compile2122For MCP clients, the server can run with `npx`:2324```bash25npx -y flint-chart-mcp26```2728For JavaScript or TypeScript projects:2930```bash31npm install flint-chart32```3334- `npm install flint-chart` is the whole install: it comes with every backend35 (Vega-Lite, ECharts, Chart.js, Plotly). React is an optional peer, needed only36 for `flint-chart/react`.37- Draw with `<FlintChart backend="…">` from `flint-chart/react`, or `mountChart`38 from `flint-chart/interactive`; presets, update helpers and types come from39 `flint-chart/interactive` too.40- Compile with `assembleVegaLite`, `assembleECharts`, `assembleChartjs` or41 `assemblePlotly` from `flint-chart`; `renderSvg` from `flint-chart/render`42 draws a static SVG (Vega-Lite or ECharts).43- Only for an app bundled into one file (no code splitting): import44 `flint-chart/react/<backend>` or `flint-chart/interactive/<backend>`45 (`vegalite`, `echarts`, `chartjs`, `plotly`), which reaches no other backend,46 so the file carries one library.4748Then compile with the requested backend:4950```ts51import { assembleChartjs, assembleECharts, assembleVegaLite } from 'flint-chart';5253const vegaLiteSpec = assembleVegaLite(input);54const echartsOption = assembleECharts(input);55const chartjsConfig = assembleChartjs(input);56```5758Python support is planned for a later release. Until the PyPI package is59published, use the npm package or MCP server for released workflows.6061## Mount6263```ts64import { mountChart, navigate, legendToggle } from 'flint-chart/interactive';6566const surface = mountChart(container, input, {67 backend: 'vegalite',68 renderer: 'svg',69 interactions: [navigate({ axes: 'x' }), legendToggle()],70 chartId: 'sales',71});72await surface.ready;73const warnings = await surface.warnings; // interactions the chart could not honour74// …75surface.destroy();76```7778| Member | What it does |79| --- | --- |80| `ready`, `warnings` | Promises: the first render; the dropped or yielded interactions. Every call below waits for `ready` itself. |81| `applyUpdate(update, options?)` | Retains one update by id; replaces the layer with the same id. `options.transition.duration` animates a viewport. |82| `setUpdates(updates)` | Replaces every retained update. |83| `clearUpdate(id)` | Removes one layer. |84| `dispatch(id, payload)` | Runs an `externalInteraction` handler and applies what it returns. |85| `getState()` | What the chart shows now; `undefined` before `ready`. |86| `onChange(callback)` | Every change to that state, after the render; returns the unsubscribe. |87| `layout` | Once ready: `plot`, the plot box `{ width, height }` on a chart that draws one plot; `views`, each drawn view as `{ role, box: { x, y, width, height } }` (role `plot`, `text`, `tile` or `rule`; facet panels row by row); `block`, the box the views take with their axes and headers, without title and keys. Boxes are in pixels from the drawn chart's top left, read from what it drew, so they follow filters and resizes. `undefined` on charts with a category rail and on non-Vega-Lite backends. |88| `refresh()` | Re-projects overlays after the host rescales the chart. |89| `element`, `chartId` | The mount's root and the stable chart id. |90| `destroy()` | Removes listeners, the renderer, and the DOM. |9192- `input` is a `ChartAssemblyInput`. Presets go in `input.interaction_spec` as93 JSON or in `options.interactions` as factory calls. Both may appear; spec94 entries mount first, and a code definition with a spec entry's `id`95 replaces it with an `interaction_overridden` info warning.96- A malformed `interaction_spec`, a repeated code `id`, or a code definition97 the chart cannot honour fails the mount with an error that names it. A spec98 entry the chart cannot honour is dropped with a warning instead.99- `options.availableSize: { width?, height? }` is the room the host gives the100 chart. It becomes the `canvasSize` ceiling on the sides given, so the chart101 lays out for that room rather than being scaled into it.102- `options.updates` holds retained updates present at the first render, for a103 chart that starts with a part hidden or framed.104- `renderer: 'svg'` for charts whose marks a host reads from the DOM, or under105 a few thousand marks; `'canvas'` for maps and dense charts.106- A `Year` or `Date` field makes a temporal axis whose rows hold `Date`s or107 ISO strings; a bare number such as `2013` reads as milliseconds after 1970.108 A `semantic_types` entry may be an object,109 `{ semanticType, intrinsicDomain: [lo, hi] }`; the intrinsic domain holds an110 axis still while the rows change.111- `options: { addTooltips: false }` on the input is the switch for the112 tooltip, for a chart whose hidden values it would give away.113- Build with a bundler. The interactive entry reaches every backend through114 lazy imports with no file extension; when `echarts`, `chart.js`, and115 `plotly.js-dist-min` are not installed, mark them external (esbuild116 `--splitting --external:echarts --external:chart.js --external:plotly.js-dist-min`;117 Vite `build.rollupOptions.external`).118- In React, use `<FlintChart>` from `flint-chart/react` rather than mounting119 in an effect; see "In React" below.120121## In React122123```tsx124import { FlintChart, type FlintChartHandle } from 'flint-chart/react';125import { clickHighlight } from 'flint-chart/interactive';126127const chartRef = useRef<FlintChartHandle>(null);128129<FlintChart130 ref={chartRef}131 spec={input}132 interactions={[clickHighlight({ targets: ['mark'] })]}133 width="100%"134 fit="relayout"135 onChange={(change) => setSelected(change.state.selected)}136 onError={(error) => report(error)}137/>;138```139140| Prop | What it does |141| --- | --- |142| `spec` | The `ChartAssemblyInput`, `interaction_spec` included. A change of content remounts; rows compare by reference. |143| `interactions` | Factory calls added to the spec's entries, or `(fromSpec) => definitions` for the full list. A factory rebuilt with the same id and options keeps the chart; a changed option remounts it. |144| `updates` | Host updates, diffed by id. Passing even `[]` mounts the runtime on a chart with no interactions. |145| `width`, `height`, `fit` | The box. `fit` is `scale-down` (default; never scales up), `crop` (natural size, clipped), or `relayout` (the box becomes the layout room; a resize remounts once it settles, so a selection does not survive it). |146| `onChange`, `onInteraction` | The state after a change, and the raw gesture record. |147| `onRender`, `onWarnings`, `onError` | Each mount's render and warnings; a failed mount, shown in the box as a muted error. |148| `fallback` | Shown until the chart mounts. |149| `ariaLabel`, `chartId` | `ariaLabel` applies in place; a new `chartId` remounts. |150151The ref's `FlintChartHandle` holds `surface` (the mounted surface or `null`),152`applyUpdate`, `clearUpdate`, `dispatch`, `getState`, and `refresh`. A remount153keeps the old chart on screen until the new one is ready.154155## Read the chart156157| `getState()` field | Holds |158| --- | --- |159| `selected` | The marks the chart emphasizes now, previews included. |160| `entries` | The same marks per update id, with `layer: 'retained' \| 'preview'`. |161| `hidden` | Legend values a `legend-toggle` hides, as `{ channel, value }`. |162| `viewport` | The domain on view after a pan or zoom; absent on a chart that does not navigate. |163| `categoryOrder` | The order of the reorderable axis now. |164| `windows` | Category rail windows, `{ start, count, total }` per channel. |165166Each element's `value` is the mark in field terms: a bar's category and167measure, a legend item's `{ channel, field, domain }`, a histogram bar's168`{ field, range }`. The host owns the rows and queries them from the value and169the geometry.170171`onChange` fires after every render with a `ChartChange`: `phase` (`preview`172while a gesture runs, `commit` for a committed change or a host call, `cancel`173when a gesture ends with nothing), `interactionId` and `action` (absent for a174host call and for a reset), the gesture's own `target` and `geometry`, and the175`state` after. An overlay or a data swap leaves no trace in the state, so the176host keeps that model itself.177178```ts179const valuesOf = (elements: readonly SemanticElement[]) => elements.map((element) => element.value);180181// A panel follows the gesture live, else shows what the chart shows.182surface.onChange(({ phase, target, state }) => {183 const hit = valuesOf(target?.elements ?? []);184 panel.show(phase === 'preview' && hit.length > 0 ? hit : valuesOf(state.selected));185});186187// An agent context reads committed state only: values and ranges, never rows.188surface.onChange(({ phase, state, geometry }) => {189 if (phase !== 'commit') return;190 sendContext({ selected: valuesOf(state.selected), range: geometry?.domain, hidden: state.hidden, viewport: state.viewport });191});192```193194The container also emits a bubbling DOM event, `flint-interaction`, for every195canvas interaction, before the chart reacts: `detail.chartId`,196`detail.interactionId`, and `detail.event`, the same `CanvasInteractionEvent`197a handler gets. It fires for a definition whose `handle` returns `null`, so it198is the path for a host that draws its own response to a gesture.199200Things the surface holds fixed: no preset changes the layout, so a zoom never201recomputes the bar step, the ticks, or the domain (filter the rows and mount202again for that); the mute level is set at mount; Escape reaches a chart after203a press on it, and only that chart; a preset's toggle (`select`,204`click-highlight`) needs Shift, Ctrl, or Meta, and a plain second click205replaces; a press on an overlay path resolves to no mark, so a `click-none`206reset on the definition that drew the overlay clears it at that press.207208## Apply updates and read the result209210`applyUpdate`, `setUpdates` and `dispatch` take the same `{ id, ops }` layers211as the interaction skill's "Update the chart", and return what applied.212**The result.** `applyUpdate`, `setUpdates`, and `dispatch` return a213`ChartUpdateResult`: `{ status: 'applied' | 'partially-applied' |214'unsupported', resolvedTargets, unresolvedTargets, unsupportedOps }`. An215unresolved target has a wrong field or value; an unsupported op needs a216preset the chart does not mount. What the chart shows is what the result says217it shows: fix an unresolved key or drop an unsupported op before describing218the chart.219220## Link charts221222`linkCharts` links mounted charts on the fields they share. A selection on one223chart (a click, a brush, a group focus, a hover) becomes one condition, a part224per field; every chart emphasizes the marks that meet it, the source included,225through one `linked-selection` layer; a reset on any chart clears it everywhere.226227```ts228import { linkCharts, mountChart, clickHighlight, brushX } from 'flint-chart/interactive';229230const link = linkCharts({231 bars: { input: barsInput, surface: mountChart(barsEl, barsInput, { backend: 'vegalite', interactions: [clickHighlight()] }) },232 trend: { input: trendInput, surface: mountChart(trendEl, trendInput, { backend: 'vegalite', interactions: [brushX()] }) },233}, { fields: ['region', 'month'] });234for (const [id, chart] of Object.entries(await link.links)) console.log(id, chart.notes); // what each chart left out235link.onCondition(({ condition }) => table.filter(condition)); // { region: { in: ['Asia'] }, month: { range: [start, end] } }236// link.clear(); link.destroy();237```238239**A table, a filter or any control beside linked charts** joins the same240condition: `link.select(parts)` sets parts as if a chart had selected them, and241`onCondition` gives the table what to show. One condition, so a row click, a242region picker and a brush combine (AND) and a reset on any chart clears them all.243244```ts245row.addEventListener('click', () => link.select({ country: { in: [row.dataset.country] } }));246regionPicker.addEventListener('change', (e) => link.select({ region: e.target.value ? { in: [e.target.value] } : null })); // null lets go247link.onCondition(({ condition }) => renderTable(rows.filter((r) => meets(r, condition))));248```249250- `select` only takes fields in `fields`; a chart shows a part when its marks251 carry the field (encode it, or put it on `detail`).252- The link emphasizes the matching marks; to drop rows instead (a filter), give253 the charts filtered data as below.254255```tsx256import { FlintChart, useLinkedCharts } from 'flint-chart/react';257258const link = useLinkedCharts({ bars: barsInput, trend: trendInput }, { fields: ['region', 'month'] });259<FlintChart spec={barsInput} {...link.chart('bars')} />;260// link.select({ region: { in: ["Asia"] } }) from a table or control; link.clear()261<FlintChart spec={trendInput} {...link.chart('trend', { onChange: setPageState, updates: myUpdates })} />;262// the chart's own onChange, onRender and updates go through chart(id, own); a prop after the spread replaces the link's263// link.condition.condition is the same condition; filtered rows in `spec` keep it264```265266- A chart receives a field when its marks carry it (encode it, on `detail` if267 nothing else shows it), and sends through each selecting interaction whose268 subject includes a connected field. `{ charts: { trend: { receive: false } } }`269 keeps a chart as drawn; `send: false` keeps its selections to itself.270- The link emphasizes; it never filters or re-aggregates. To filter, read the271 condition (`onCondition`, `link.condition`) and give each chart its rows:272 beside `linkCharts`, a `set-data` update (a new spec remounts the chart, and273 the link holds the old surface); beside `useLinkedCharts`, a `spec` with the274 filtered rows.275- `setUpdates` replaces every layer, the link's included, until the condition276 next changes; use `applyUpdate` and `clearUpdate` beside a link.277- `linkCharts` checks the charts with the validator, loaded on first use; pass278 `{ links }` from `validateLinks` (`flint-chart/validate`) to skip that load.279280For a link `linkCharts` does not express (a payload each chart reads its own281way), wire `onChange` to an `externalInteraction` on the other charts:282283```ts284const linked = externalInteraction<{ countries: string[] }>({285 id: 'linked',286 handle: ({ countries }) => ({287 id: 'linked',288 ops: [{ op: 'set-style', targets: [{ select: { where: { Country: { in: countries } } } }], value: { state: 'emphasized' } }],289 }),290});291source.onChange(({ phase, interactionId, state }) => {292 if (phase !== 'commit' || !interactionId) return; // host writes carry no id: no loop293 void other.dispatch('linked', { countries: state.selected.map((element) => String(element.value.Country)) });294});295```296297Linked charts share one `theme_spec` so a value has one colour everywhere.298299The same `dispatch` drives a chart over time: a playback loop dispatches one300frame per animation frame, and the handler returns the whole layer for that301frame.302303## When no preset fits304305A host that runs code mounts a `CanvasInteractionDef` in `options.interactions`306beside presets: a trigger, what it affords, and a handler that returns the307layer for its id.308309```ts310import { rectangleTrigger, type CanvasInteractionDef } from 'flint-chart/interactive';311312const timebox: CanvasInteractionDef = {313 id: 'timebox',314 eventSource: rectangleTrigger('contain'),315 affordances: { plot: { cursor: 'region' } },316 reset: ['click-none', 'escape'],317 handle(event) {318 if (event.action !== 'select-region' || event.phase !== 'commit') return null;319 const x = event.geometry.domain?.x;320 const y = event.geometry.domain?.y;321 if (x?.kind !== 'interval' || y?.kind !== 'interval') return null;322 const keep = seriesInsideBox(x.start, x.end, Number(y.start), Number(y.end)); // host logic over host rows323 return {324 id: 'timebox',325 ops: [{ op: 'set-style',326 targets: keep.map((series) => ({ select: { key: { Series: series } } })),327 value: { state: 'emphasized' } }],328 };329 },330};331```332333| Field | Role |334| --- | --- |335| `id` | Names the interaction in events and the layer it retains. |336| `eventSource` | The trigger: what to capture and how to read it. |337| `affordances` | The kinds of hit the handler receives, each with its cursor and hover; a hit of a kind not listed never reaches it. Keys: `mark`, `legend-item`, `axis-label`, `plot`. Cursors: `activate`, `drag`, `region`, `navigate`, `inspect`, `draw`. Hovers: `target` (the mark), `cohort` (its group). |338| `handle(event, context)` | Returns the whole layer for this id, or `null` for no change. |339| `reset` | Gestures that clear the layer: `click-none`, `double-click`, `escape`. A reset reports as a commit with no `interactionId`. It suits a layer of styles the state shows; an overlay or a data layer is cleared by the host. |340341**Triggers.**342343| Trigger | The reader does | `action` | `geometry.plot` | `geometry.domain` | Affordance key |344| --- | --- | --- | --- | --- | --- |345| `clickTrigger` | Clicks a mark, legend item, or axis label. | `click-element`, `click-legend`, `click-axis` | `point` | — | `mark`, `legend-item`, `axis-label` |346| `hoverTrigger` | Moves over a mark. | `hover-element`, `hover-legend`, `hover-axis` | `point` | — | same |347| `dragTrigger(tolerance?)` | Presses a mark, or a projectable overlay path, within `tolerance` px (12) and drags. | `drag` | `drag { start, current, delta }` | the pointer's values; `geometry.projection` while over a projectable overlay | `mark` |348| `rectangleTrigger(match?, guide?)` | Drags a rectangle. | `select-region` | `rect` | `x`, `y` intervals | `plot` |349| `xBrushTrigger(match?, mode?, guide?)`, `yBrushTrigger(…)` | Drags an interval along one axis. | `brush-x`, `brush-y` | `rect` | that axis's interval | `plot` |350| `lassoTrigger(match?, guide?)` | Draws a freehand region; previews begin at the third point. | `select-lasso` | `polygon` | `points`: the stroke so far, in data values | `plot` |351| `angularBrushTrigger(match?, mode?, guide?)` | Drags a sector on a polar chart. | `brush-angle` | `angular-sector` | — | `plot` |352| `inspectTrigger(mode?)` | Moves over the plot. | `inspect-x`, `inspect-y`, `inspect-xy` | `point` | `x`, `y` values | `plot` |353| `inspectIndexTrigger(axis?, show?, seriesBy?)` | Moves along the index axis. | `inspect-x`, `inspect-y` | `point` | the index value | `plot` |354| `navigationTrigger({ axes?, pan?, zoom?, reset? })` | Drags, wheels, pinches. | `pan-viewport`, `zoom-viewport`, `reset-viewport` | `viewport { delta, factor, anchor }` | the viewport after the move | `plot` |355| `contextTrigger`, `longPressTrigger(ms?)`, `doubleActivateTrigger` | Right-clicks, holds (500 ms), double-clicks a mark. | `context-element`, `long-press-element`, `double-activate-element` | `point` | — | `mark` |356357`match` is `'intersect'` (default) or `'contain'` and decides which marks the358region's `target` lists. `guide` styles the drawn shape; `false` hides it. A359region is ephemeral: its guide and its preview end at the commit. A brush or360`select` with `mode: 'stateful'` keeps its region on screen and editable, and361`event.operation` reads `create`, `move`, `resize-leading`, `resize-trailing`,362or `clear`. Spread a trigger to tune it:363`{ ...hoverTrigger, defaultAssistDistance: 28 }` acquires the nearest mark364within 28 px. A chart admits a trigger when it offers what the trigger needs,365per what `list_interaction_presets` says each preset requires; a code definition the chart cannot honour throws at366mount with a message that names what it needed.367368**The event.**369370```ts371interface CanvasInteractionEvent {372 action: string; // from the table373 phase: 'start' | 'preview' | 'commit' | 'cancel'; // clicks and hovers skip start374 operation?: string; // a stateful brush's edit, or pan | zoom | reset375 geometry: { plot?, domain?, projection? };376 target: { visual: { kind, role }, elements: [{ value, records? }] } | null;377 modifiers?: { shift, ctrl, meta };378 description?: { kind, type, content, text }; // on focus-element from accessible-navigation379}380```381382- `target.elements[i].value` holds the mark's encoded values, derived fields383 included; `records` holds the source rows when the runtime can prove them. A384 region target lists every mark inside. A legend hit's `value` is a385 `LegendTargetValue`: `{ channel, field, domain: { kind: 'value', value } }`,386 or `{ kind: 'interval', start, end }` on a continuous legend. An axis-label387 hit's `value` is an `AxisTargetValue`: `{ axis, field, value }`.388- `geometry.domain` is inverted through the plot's scales: a brush on a time389 axis gives `domain.x = { kind: 'interval', start: Date, end: Date }`, a linear390 axis gives numbers, a discrete axis gives the category.391- `description` arrives on `focus-element` while `accessible-navigation` walks392 the chart: what the focused element is (`type`, such as "Bar") and what it393 represents (`content`), with the spoken `text`. The walk's emphasis reports394 through `onChange` as a `preview`.395- `geometry.projection.kind === 'path'` during a drag over an overlay with396 `projectable: true`: `segment.start.value` and `segment.end.value` are the397 overlay rows on each side of the pointer and `segment.t` the fraction between398 them.399400**The types.** `flint-chart/interactive` exports these, and `flint-chart/react`401re-exports them. `onChange` receives a `ChartChange`: the gesture's own402`target` and `geometry`, and the chart's `state` after it. Generated from the403source by `npm run gen:reference`:404405<!-- event-types:start -->406```ts407interface ChartChange {408 // `preview` while a gesture runs, `commit` for a committed change, `cancel` when a gesture ends with none.409 phase: ChartChangePhase;410 // `host` for `updates`, `applyUpdate`, `clearUpdate` and `dispatch`; always `commit`.411 source: ChartChangeSource;412 changed: ChartStateFacet[];413 // The interaction behind the change: a reader's gesture, or an external interaction run by `dispatch`.414 interactionId?: string;415 action?: CanvasInteractionAction;416 // The gesture's own hit: the hovered point, or the marks at an inspected index.417 target?: SemanticTarget | null;418 // The gesture's geometry: a brushed range, an index value, or the viewport after a move.419 geometry?: CanvasInteractionEvent['geometry'];420 // The reset gesture a reader made: a click on nothing, Escape, or a double-click. Reported even when the chart held nothing to reset, so a host that shows a selection of its own can let it go.421 reset?: InteractionResetGesture;422 state: ChartState;423 previous: ChartState;424}425426interface ChartState {427 chartType: string;428 // The marks the chart emphasizes or focuses now, previews included.429 selected: SemanticElement[];430 // The emphasized marks of each update, by update id; `selected` is their union.431 entries?: ReadonlyMap<string, ChartStateEntry>;432 // The legend values a toggle hides now.433 hidden?: ChartHiddenValue[];434 // The domain the plot shows now, when the chart navigates.435 viewport?: DomainGeometry;436 // The category window of each rail.437 windows?: Partial<Record<'x' | 'y', ChartCategoryWindow>>;438 categoryOrder?: unknown[];439 // The notes the chart holds now, previews included; `inView` tells which ones it draws.440 annotations?: ChartAnnotation[];441 // The active filter of each field, set by filter controls; absent fields show every value.442 filters?: Readonly<Record<string, FilterValue>>;443}444445interface SemanticTarget {446 visual: {447 kind: 'mark' | 'path' | 'region' | 'widget' | 'handle' | 'legend' | 'axis' | 'chart' | 'title' | 'header';448 role: string;449 };450 elements: SemanticElement[];451}452453interface SemanticElement {454 // Values represented by the mark's channels, or by a semantic control such as a legend item.455 value: Record<string, unknown>;456 // Contributing input records when provenance is available; zero or many may support one value.457 records?: Record<string, unknown>[];458}459460interface LegendTargetValue {461 channel?: string;462 field?: string;463 // The entry's value on a reader's hit; read `domain`, which every legend target carries.464 value?: unknown;465 domain: LegendDomain;466}467468type LegendDomain =469 | { kind: 'value'; value: unknown }470 | { kind: 'interval'; start?: number; end?: number };471472interface AxisTargetValue {473 axis: 'x' | 'y';474 field: string;475 value: unknown;476}477478interface DomainGeometry {479 x?: DomainCoordinate;480 y?: DomainCoordinate;481 points?: DomainPoint[];482 // The detail level a multi-level projected chart draws for this viewport.483 level?: string;484 // On a multi-level projected chart, the coarsest-level region under the plot centre: its feature id and properties plus the joined row fields.485 focus?: Record<string, unknown>;486}487488type DomainCoordinate =489 | { kind: 'value'; value: DomainValue }490 | { kind: 'interval'; start: DomainValue; end: DomainValue };491492type DomainValue = number | Date | string;493494interface DomainPoint {495 x?: DomainValue;496 y?: DomainValue;497}498499interface ChartHiddenValue {500 channel: string;501 value: unknown;502}503504type FilterValue =505 | { in: unknown[] }506 | { range: [unknown, unknown] };507```508<!-- event-types:end -->509- `context` is the chart state plus `available`, every drawn mark, for510 building refs, and `selected`, the current emphasis, for a toggle rule.511512**The handler.**513514- It returns the complete layer for the id on every `preview` and `commit`;515 the runtime drops the preview on `cancel`. A `null` on a `preview` shows516 nothing until the commit, which is how a rule applies to the committed box517 only. A region gesture keeps a preview layer under the interaction's id518 while the drag runs, so a commit after previews restates the layer; a519 `null` there lets the last preview stand.520- It maps geometry to the host's model and the model to ops. Host side521 effects (state, panels, overlays the host draws) come from522 `flint-interaction` or `onChange`, which carry the same event; the handler523 itself returns ops and leaves the DOM to the runtime.524- Triggers have one owner for code definitions as for presets; two code525 definitions on one trigger throw at mount. `navigate({ pan: false })` goes526 beside a region trigger.527- An element drag owns the press on the marks it affords. A press there is a528 `drag` with phase `start`; `target` is the pressed mark through every phase.529 The layer returned at `start` is kept as the gesture's preview, and a release530 without movement commits that preview with no further call. No click531 definition fires on those marks, so the definition that drags a mark also532 answers its press.533- A click definition that affords `hover` on marks receives `preview` events534 for the hover cue. Return `null` or an emphasis for them, and the layer on535 `commit`.536537**Patterns.**538539| Pattern | Flow | Pieces |540| --- | --- | --- |541| Gesture rule | Flint in, Flint out | A region trigger reads `geometry.domain`; the host rule picks rows; `set-style` by key (the timebox above). |542| Host-drawn detail | Flint in, custom out | `hoverTrigger` or `inspectTrigger` with a `null` handle; the host listens to `flint-interaction` for the resolved element and draws a lens, a cursor, or a badge over the mount. |543| Application drives the chart | external in, Flint out | `externalInteraction` plus `dispatch` per frame: a playback year, a reveal progress. |544| Drag along a path | press, then drag | One `dragTrigger()` definition and one layer. At `start` on a mark it returns the mark's path as a `set-overlay` `line` with `interactive: true, projectable: true` and `order`, plus `set-data` for the current position. On `preview` and `commit` with `geometry.projection` it returns the same two ops for the pointer's position. `intrinsicDomain` on the x and y fields holds the axes still across the swaps. |545| Freehand stroke | draw | The rows to guess form their own series, and a mount update sets `opacity: 0` on that series, which keeps the axis. `lassoTrigger('contain', false)` with `plot: { cursor: 'draw' }` is the pen: `geometry.domain.points` become the rows of a `set-overlay` line. An `externalInteraction` reveals the truth as an overlay, then the host clears the hide. |546| Chart-level zoom | wheel | When the layout itself must change (bar step, ticks, domain), filter the rows and `mountChart` again in a hidden layer; swap on `ready`. No preset re-lays out. |547| Semantic zoom on a map | navigate | A Choropleth with `level: 'auto'` (US states, then counties) or with your own `levels: [{ value, url, feature?, enter?, exit? }]` (one GeoJSON or TopoJSON object per level, rows joined on the feature `id` or `featureKey`, `baseMapUrl` drawn beneath as land without data), or a Map with `levelField` and `levels`; `navigate()`, and `set-viewport { region: { key } }` with a `transition` to fly into a region. Navigation events carry `geometry.domain.level` and `focus` (the coarsest region under the centre). A hover reaches the host through a hover affordance (`hover: 'target'`); a handler that returns `null` leaves the map as drawn. |548549Host-drawn detail, the shape of it:550551```ts552const probe: CanvasInteractionDef = {553 id: 'probe',554 eventSource: { ...hoverTrigger, defaultAssistDistance: 28 },555 affordances: { mark: { hover: 'target' } },556 handle() { return null; },557};558container.addEventListener('flint-interaction', (e) => {559 const { interactionId, event } = (e as CustomEvent<FlintInteractionEventDetail>).detail;560 if (interactionId !== 'probe' || event.phase !== 'preview') return;561 const row = event.target?.elements[0]?.records?.[0];562 if (row) lens.show(row); // the host draws; the chart is unchanged563});564```565566## Worked examples567568### A chart that drives the app569570User: "In my dashboard, a click selects the country and a double-click opens571its page. Zooming the y axis would help too." A scatter of `gdp` by `life`572with `color: continent` and `detail: country`.573574`navigate` holds the double-click by default for its reset, and575`double-activate` needs it; `reset: ["escape"]` frees it. `click-highlight`576takes `targets: ["mark"]` so the app's selection comes from marks only.577578```json579{580 "interactions": [581 { "type": "click-highlight", "options": { "targets": ["mark"] } },582 { "type": "double-activate" },583 { "type": "navigate", "options": { "axes": "y", "reset": ["escape"] } }584 ]585}586```587588The app reads the selection from `onChange` on a `commit` whose `action` is589`click-element`, and the activation from one whose `action` is590`double-activate-element`.591592### Code: two linked charts593594Two bar charts share a `Country` field: GDP per country, and population per595country. A click on one emphasizes the same country on both.596597```ts598import { mountChart, clickHighlight, linkCharts } from 'flint-chart/interactive';599600const mount = (el: HTMLElement, input: ChartAssemblyInput) =>601 ({ input, surface: mountChart(el, input, { backend: 'vegalite', interactions: [clickHighlight({ targets: ['mark'] })] }) });602const link = linkCharts({ gdp: mount(gdpEl, gdpInput), population: mount(popEl, popInput) }, { fields: ['Country'] });603```604605The clicked chart drops its own emphasis once the link shows the condition, so606both charts show one selection. A `click-none`, Escape, or double-click on607either chart clears it on both; the link's own writes are host changes, so no608chart echoes them back.609610### Bespoke: a rule over the brushed box611612A line chart of `Series` by `Month`. The reader drags a box; the series whose613every point in that month range lies inside the y range stay emphasized. No614preset applies a rule over series, so the definition is the `timebox` above:615`rectangleTrigger('contain')`, a `plot` affordance with the `region` cursor,616a handler that acts on `select-region` at `commit`, and `reset:617['click-none', 'escape']` so a click on empty plot clears it. It mounts beside618`navigate({ pan: false })` when the chart also zooms, since both ask for the619plot drag otherwise.620621## Validation checklist6226231. Every trigger, cursor, and field name is one from this skill or the624 installed `flint-chart/interactive` types.6252. Every definition declares `affordances` for the hits its trigger yields.6263. No two definitions, and no definition and spec entry, share a trigger or627 an `id`.6284. The surface is destroyed on unmount, and every `applyUpdate` or `dispatch`629 result is read.630