Elicit.js

JSON specs

A JSON spec describes a chart as data, with the same keywords and options as the JavaScript API. compile(json) returns the spec Elicit() takes, so a chart can be stored, sent or generated. The examples on this site show both forms: switch between JavaScript and JSON above the code.

API reference

compile(json, options?)

Turns a JSON spec into the spec Elicit(), Elicit.dataset() or ds.chart() takes. It throws, with the path into the JSON, for an unknown keyword, an unregistered function or an expression it cannot read.

compile(json, { functions? }) → ElicitSpec
Options
OptionType · defaultDescription
functions
Record<string, Function>default{}
The functions the spec names with { "fn": "<name>" }. A name here wins over one set with registerFunction.
Returns / emits

A spec. It builds one chart, so compile again for another.

registerFunction(name, fn)

Registers a function for every later compile(). Registering a name again replaces it.

registerFunction(name, fn) → void

recorder(options?)

Writes a spec built in JavaScript as JSON. It returns the namespaces plot, elements, edit, constraints, layout, guides, looks, widgets and format. Build the spec from them, then call toJSON(spec). While recording, a factory returns its JSON descriptor. live(fn) runs fn with the factories building for real, for a function the spec keeps that calls one. stop() ends the recording, and the factories build for real from then on.

recorder({ functions? }) → Recorder
recorder.toJSON(spec) → { json, functions }
recorder.live(fn) → the value fn returns
recorder.stop() → void
Options
OptionType · defaultDescription
functions
Record<string, Function>default{}
Names for the functions the spec uses. A function left out is named after its option.

A factory call is an object with a type

Write each factory call as an object whose type is the factory's name. barY({ fill: "teal" }) becomes { "type": "barY", "fill": "teal" }. Options keep their names. A scoped edit takes its dotted path: edit.line.draw() is { "type": "line.draw" }.

Where a descriptor sits decides how its type is read:

KeyHolds
marks, and a composite's partsmarks and chart elements
elementschart elements
guidesguides
constraints, and an edit's constrainconstraints
layoutlayouts
a mark's edits, and edit on a channel, an axis or a legendedits

compile works on all three spec shapes:

Elicit(compile(json));
const ds = Elicit.dataset(compile(datasetJson));
ds.chart(compile(chartJson));

A chart from JSON

One mark, one edit and one constraint. Each is an object with a type.

// The whole chart is data. Each factory call is an object with a "type".
const json = {
"width": 420, "height": 250,
"margins": { "top": 16, "right": 16, "bottom": 32, "left": 40 },
"data": [
{ "party": "Red", "share": 38 },
],
"schema": {
"party": { "type": "categorical" },
"share": { "type": "quantitative", "domain": [0, 100] }
},
"constraints": [{ "type": "clamp", "min": 0, "max": 60 }],
"marks": [
{
"type": "barY",
"fill": "#50AEB7",
"channels": {
"x": { "field": "party" },
"y": { "field": "share", "edit": { "type": "move" } }
}
}
]
};
const chart = Elicit(compile(json));
mount(chart.dom());
Try: Drag a bar. The clamp stops it at 60.

Expressions

An option that takes a function in JavaScript takes { "expr": "…" } in JSON. An expression is one JavaScript expression over the option's variables:

OptionVariables
a channel's expr, a mark's style options (fill, opacity, dy, …), width, height, path, wrap, contains, constraints.contain (parent, child), and layout.* (where, in)datum, index, data
lock, contextdatum, index, table
format, tickFormatvalue
an axis's tickSize, stroke, fill, fontWeight; a grid's stroke, strokeWidth, strokeDashvalue, index
a guide's options, an axis's transform, an edit's whenthe keys of the context: data, scales, width, height, …
tip, and a tip's textdatum, ctx

A channel carries its expression directly: "fill": { "expr": "…" } is the JSON form of fill: { fn: (d) => … }, and it is read-only in the same way.

An expression reads properties with . and [], and takes numbers, strings, true, false, null, arrays and objects. Its operators are + - * / %, < <= > >=, == !=, && || ??, ! and ? :. == compares without converting, as === does in JavaScript. It calls these functions and no others:

FunctionsResult
abs, min, max, round, floor, ceil, sqrt, pow, clamp(v, lo, hi)a number
format(v, specifier), timeFormat(date, specifier)text, through a d3 specifier
year(date), month(date), day(date)part of a date; January is month 0
length(v), slice(v, start, end), includes(v, item), lower(v), upper(v), string(v), number(v)text and list helpers
sum, mean, median, minOf, maxOf, extent — each (rows, field)a column's summary
count(rows), distinct(rows, field)the number of rows; a column's distinct values

Expressions for a fill, a lock, a guide and a tick label

The fill re-derives from each row. The lock fixes the rows whose kind is actual.

// An "expr" is a function written as text. Its variables depend on the option.
const json = {
"width": 420, "height": 260,
"margins": { "top": 16, "right": 16, "bottom": 32, "left": 48 },
"data": [
{ "year": 2021, "rate": 3.4, "kind": "actual" },
],
"schema": {
"year": { "type": "ordinal" },
"rate": { "type": "quantitative", "domain": [0, 10] },
"kind": { "type": "categorical" }
},
// The rows that are given stay fixed.
"lock": { "expr": "datum.kind == 'actual'" },
"marks": [
{
"type": "barY",
"channels": {
"x": { "field": "year" },
"y": { "field": "rate", "edit": { "type": "move" } },
// A derived channel: recomputed from the row after every edit.
"fill": { "expr": "datum.kind == 'actual' ? '#94A5B3' : datum.rate > 5 ? '#EE7B5E' : '#50AEB7'" }
}
}
],
// A guide option reads the chart: here, the mean of a column.
"guides": [{ "type": "rule", "y": { "expr": "mean(data, 'rate')" }, "label": "mean" }],
"axes": { "y": { "tickFormat": { "expr": "value + ' %'" } } }
};
const chart = Elicit(compile(json));
mount(chart.dom());
Try: Drag a forecast bar above 5. Its fill changes and the mean line follows.

Named functions

Code that is more than one expression stays in JavaScript. Name it in the spec with { "fn": "<name>" }, and supply it in one of two places:

  • compile(json, { functions: { name: fn } }) supplies it for that spec.
  • registerFunction(name, fn) supplies it for every later compile().

A name in functions wins over a registered one. The function receives the same arguments as in the JavaScript API.

custom takes its function as the descriptor's fn: edit.custom(fn, { gesture: "click" }) is { "type": "custom", "fn": "<name>", "gesture": "click" }. The same holds for constraints.custom, layout.custom and guides.custom. A channel takes it the same way: "fill": { "fn": "<name>" }.

onChange takes a named function, and so does a d3 scale passed as a channel's scale.

A custom edit by name

The spec names snapToTens. compile() receives it in functions.

// Code a spec cannot hold is named in it, and supplied where it is compiled.
const snapToTens = (ctx) => ({
...ctx.datum,
y: Math.round(ctx.scales.y.invertValue(ctx.pointer.y) / 10) * 10,
});
const json = {
"width": 380, "height": 260,
"margins": { "top": 14, "right": 14, "bottom": 26, "left": 34 },
"data": [{ "x": 30, "y": 30 }, { "x": 70, "y": 70 }],
"schema": {
"x": { "type": "quantitative", "domain": [0, 100] },
"y": { "type": "quantitative", "domain": [0, 100] }
},
"marks": [
{
"type": "point",
"fill": "#50AEB7",
"size": 8,
"channels": { "x": { "field": "x" }, "y": { "field": "y" } },
// `edit.custom(fn)`: the function is the descriptor's "fn".
"edits": [{ "type": "custom", "fn": "snapToTens" }]
}
]
};
const chart = Elicit(compile(json, { functions: { snapToTens } }));
mount(chart.dom());
Try: Drag a point. Its y lands on a multiple of 10.

Predicates, formats, renderers and dates

The values the library provides are written by name:

  • when takes a predicate's name: "when": "shift". The predicates are shift, noShift, alt, noAlt, near and far. Those with an argument are descriptors: { "type": "modifier", "key": "metaKey" }, { "type": "noModifier", "key": "metaKey" } and { "type": "nearWithin", "threshold": 12 }.
  • format and tickFormat take a d3-format string, as in JavaScript. A format.* helper is a descriptor: { "type": "time", "specifier": "%b %Y" }, { "type": "percent", "specifier": ".0%" }, { "type": "prefix", "prefix": "$", "inner": ",.0f" }.
  • renderer takes "svg" or "canvas", the same names a JavaScript spec takes.
  • theme, projection, curve and a scale's scheme take the names they take in JavaScript.

Write a date as an ISO string. compile turns the strings in a temporal field's rows into dates.

Names for predicates, formats and the renderer

A canvas chart over a temporal column, with a time format and a currency prefix.

// Predicates, formats and the renderer are written by name.
const json = {
"width": 440, "height": 260,
"margins": { "top": 16, "right": 16, "bottom": 34, "left": 44 },
"renderer": "canvas",
"data": [
{ "month": "2024-01-01", "price": 420 },
],
"schema": {
// A temporal column is written as ISO strings.
"month": { "type": "temporal", "domain": ["2024-01-01", "2024-10-01"] },
"price": { "type": "quantitative", "domain": [300, 600] }
},
"marks": [
{
"type": "lineY",
"channels": {
"x": { "field": "month" },
"y": { "field": "price", "edit": { "type": "move", "when": "noShift" } }
},
// Shift-click removes a point; a plain drag moves it.
"edits": [{ "type": "remove", "when": "shift" }]
}
],
"axes": {
"x": { "tickFormat": { "type": "time", "specifier": "%b" } },
"y": { "tickFormat": { "type": "prefix", "prefix": "$", "inner": ",.0f" } }
}
};
const chart = Elicit(compile(json));
mount(chart.dom());
Try: Drag a point to move it. Shift-click one to remove it.

Widgets

A widget returns a whole spec, so it sits under widget. Chart keys beside it override the widget's own: { ...widgets.slider(options), caption } is { "widget": { "type": "slider", … }, "caption": … }.

A slider widget

The widget's options sit in its descriptor. The caption is a chart key.

// A widget is a whole spec, so it sits under "widget". Chart keys go beside it.
const json = {
"widget": {
"type": "slider",
"question": "How likely is rain tomorrow?",
"domain": [0, 100],
"value": 40,
"width": 420
},
"caption": "0 means it will stay dry. 100 means it will rain."
};
const chart = Elicit(compile(json));
mount(chart.dom());
Try: Drag the handle.

From JavaScript to JSON

recorder() returns the library's namespaces in recording form: each factory returns its descriptor. Build a spec from them and call toJSON(spec) for the JSON and the functions it names. An arrow function that is a single expression over its own parameters is written as an expr. Any other function is named, after its option or from recorder({ functions }).

Record a spec

The spec is written with factories. The chart is drawn from the JSON the recorder returns.

// Build the spec from the recorder's namespaces, then ask for its JSON.
const rec = recorder();
const spec = {
width: 380, height: 220,
margins: { top: 14, right: 14, bottom: 30, left: 36 },
data: [{ option: "A", votes: 12 }, { option: "B", votes: 30 }],
schema: {
option: { type: "categorical" },
votes: { type: "quantitative", domain: [0, 50] },
},
constraints: [rec.constraints.clamp({ min: 0, max: 50 })],
marks: [
rec.plot.barY({
channels: {
x: { field: "option" },
y: { field: "votes", edit: rec.edit.move() },
// An arrow that is one expression is written as an "expr".
fill: { fn: (d) => d.votes > 25 ? "#EE7B5E" : "#50AEB7" },
},
}),
],
};
const { json, functions } = rec.toJSON(spec);
const chart = Elicit(compile(json, { functions }));
mount(chart.dom());
const shown = document.createElement("pre");
shown.textContent = JSON.stringify(json.marks, null, 2);
shown.style.cssText = "font-size: 11px; margin: 8px 0 0;";
mount(shown);
Try: Drag a bar past 25. The fill is the expression the arrow became.

A JSON Schema for specs

The package ships spec.schema.json, a JSON Schema (draft 2020-12) of the specs compile takes. Import it as elicitjs/spec.schema.json. It is generated from the library's own keyword and option tables, so it matches the version you installed.

It lists every keyword with exactly the options its factory reads, and rejects any other key: an option a mark would ignore with an unknown-option warning fails validation instead. It also checks the spec's top-level keys, channel forms (field, value, datum, fn, expr), field types, and the names when, format and renderer take. It checks shape only: whether a field is declared, whether a value fits its domain, and whether a function name is registered are found when the chart is built.

Validate a spec with any draft 2020-12 validator, such as Ajv:

import Ajv2020 from "ajv/dist/2020.js";
import schema from "elicitjs/spec.schema.json" with { type: "json" };
const validate = new Ajv2020({ strict: false }).compile(schema);
if (!validate(json)) console.log(validate.errors); // e.g. /marks/0 must NOT have additional properties

To have a language model write specs, give it the schema as a tool's input schema, so the tool's input is the spec. Each descriptor closes its key set with additionalProperties: false, so a decoder that enforces the schema cannot invent an option. The schema is about 128 KB, around 35,000 tokens. Providers limit the size and the keywords they accept for constrained decoding, so check yours before turning it on.

What stays in JavaScript

  • The authoring kit. A mark or edit written with authoring.* is code, so a spec that uses one is written in JavaScript.
  • Live objects. A d3 scale or projection instance is registered and named with { "fn": "<name>" }. A ScaleSpec or a projection name is plain JSON.
  • Callbacks after the chart exists. chart.on(…), chart.control(…) and ds.set(…) are calls on the chart.

compile takes these keys as written and reads nothing inside them: data, schema, theme, defaults, geojson, options, a projection's domain, and a channel's value and datum. A row may hold a column called type or fn.

A function reference in an option that takes no function is an error, as is an unknown type. The message gives the path, such as marks[0].channels.fill.expr.