Elicit.js

Getting started

Install Elicit.js, build an elicitation interface with Elicit(spec), make it editable by putting an edit on a channel, and read the answer back through onChange. Every example on these pages runs the code beside it.

Install

Elicit.js is ESM-only. Use it with a bundler (Vite, webpack, Next) or an import map.

npm install elicitjs

d3 v7 is a peer dependency. npm 7+ and pnpm 8+ install it for you; on Yarn, add it yourself with yarn add elicitjs d3.

import { Elicit, plot, edit, constraints } from "elicitjs";

Types ship with the package, so TypeScript needs no separate @types install. elicitjs/dist is a prebuilt single-file bundle if you would rather not bundle the source.

For a plain HTML page, map both names in an import map:

<script type="importmap">
  {
    "imports": {
      "d3": "https://cdn.jsdelivr.net/npm/d3@7/+esm",
      "elicitjs": "https://cdn.jsdelivr.net/npm/elicitjs@alpha/dist/elicit.js"
    }
  }
</script>
<script type="module">
  import { Elicit, plot, edit } from "elicitjs";
</script>

Built through a spec

An elicitation interface is built through a declarative spec. Elicit(spec) takes one object and returns a chart. Append chart.dom() to the page. A spec has three main keys:

  • data — the rows of the dataset. Every mark is a view over them.
  • schema — each field's type and domain. Scales are derived from this, so no mark declares one.
  • marks — how the rows are drawn.

Only schema is required. Leave out data to start from an empty chart. To draw one dataset in several charts, see Datasets & linked charts.

A mark names its columns in channels. x: { field: "cat" } encodes cat on the x position. The schema declares cat as categorical and a bar needs an interval, so that resolves to a band scale.

A static bar chart

A complete spec: data, schema and one mark. Nothing here is editable yet.

const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
// The DATA — one dataset, and every mark is a view over it.
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
// The SCHEMA — what each field IS. Every scale is derived from this.
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
// The MARKS — how the rows are drawn.
marks: [
barY({
fill: "#50AEB7",
channels: { x: { field: "cat" }, y: { field: "n" } },
}),
],
});
mount(chart.dom());

Reading the examples

The examples on this site name each mark, element, constraint and universal edit bare: barY(...), axisX(...), clamp(...), move(). In your code they are members of the namespaces you import. Destructure them to write the same short form:

import { Elicit, plot, elements, edit, constraints } from "elicitjs";
const { barY } = plot;
const { axisX } = elements;
const { clamp } = constraints;
const { move, when } = edit;

Scoped edits, guides, layouts, looks and widgets keep their namespace in the examples, as in edit.line.draw(), guides.rule() and widgets.likert().

mount(node) is the docs page's helper: it places the node beside the code. In your page, write parent.append(chart.dom()).

Make it editable

An edit is the inverse of encoding. A channel encodes data to pixels through a scale. An edit on that channel maps a gesture back through the same scale, and writes the column the channel names.

A mark is inert until an edit names the column it writes.

move() is one of the universal edits, which work on any mark. Others create and delete rows, draw a path, turn a needle, pick a category from a legend, or rewrite a scale's domain. See Editing for the vocabulary, or the API index for every name.

The same chart, now editable

`edit: move()` on the y channel. Dragging a bar inverts the y scale and writes `n`.

const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
marks: [
barY({
fill: "#50AEB7",
channels: {
x: { field: "cat" },
// One added word. `move()` inverts the y scale, so a drag writes `n`.
y: { field: "n", edit: move() },
},
}),
],
});
mount(chart.dom());
Try: Drag any bar up or down.

Read the answer back

Three ways to get the elicited data:

  • onChange(data) fires after every committed edit, with the whole dataset.
  • chart.getData() returns it on demand.
  • chart.on("change", cb) subscribes a listener to the same commits.

The chart also carries getSchema(), setData(), on("stage" | "select", cb), undo(), redo() and destroy(). Call destroy() when you unmount it in a framework, to release its resize observer and pointer handlers.

Reading the elicited data

`onChange` writes the current values under the chart.

const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
// Fires after every committed edit, with the whole dataset.
onChange: (data) => {
readout.textContent = data.map((d) => `${d.cat}: ${Math.round(d.n)}`).join(" ");
},
marks: [
barY({
fill: "#50AEB7",
channels: { x: { field: "cat" }, y: { field: "n", edit: move() } },
}),
],
});
const readout = document.createElement("pre");
readout.style.cssText = "font-size:12px;margin:8px 0 0;color:#6F8294";
readout.textContent = chart.getData().map((d) => `${d.cat}: ${d.n}`).join(" ");
mount(chart.dom());
mount(readout);
Try: Drag a bar — the numbers below follow.

Constrain what can be said

A constraint is a rule over the dataset. It applies to every edit and every mark, so declare it once in constraints: [...] on the spec.

A constraint can reject a proposed change, or repair it by returning corrected rows. See Constraints for the full set.

Four bars that always sum to 100

`clamp` keeps values non-negative. `maintainSum` with `strategy: "redistribute"` holds the bar you drag and adjusts the others so the total stays 100.

const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [
{ cat: "A", n: 25 }, { cat: "B", n: 25 },
{ cat: "C", n: 25 }, { cat: "D", n: 25 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 100] },
},
// A rule about the DATA, not about any one mark. It holds for every edit.
constraints: [
clamp({ min: 0 }),
maintainSum({ total: 100, strategy: "redistribute" }),
],
marks: [
barY({
fill: "#50AEB7",
channels: { x: { field: "cat" }, y: { field: "n", edit: move() } },
}),
],
});
mount(chart.dom());
Try: Drag a bar — the others compensate.

Widgets

Common survey instruments are one call each. Each returns a spec you pass to Elicit, so you can start from a widget and edit its spec.

import { Elicit, widgets } from "elicitjs";
const chart = Elicit(widgets.likert({
question: "How confident are you?",
options: ["Not at all", "Slightly", "Moderately", "Very", "Extremely"],
}));
document.body.append(chart.dom());

likert, multipleChoice, slider, matrix, lineCone, ranking, allocation, probabilityTokens, interval, histogram, region, thermometer and labeledValue are documented on Widgets.

API reference

Elicit(spec)

The entry point: import { Elicit } from "elicitjs". Builds a dataset and one chart over it from one spec, and returns the chart. Append chart.dom() to the page. The spec takes the dataset keys and the chart keys below. For several charts over one dataset, call Elicit.dataset and ds.chart instead — see Datasets & linked charts.

Elicit({ schema, data?, marks, width?, height?, … }) → Chart
parent.append(chart.dom())
Elicit.dataset({ schema, data?, … }).chart({ marks, … })   // the same thing, in two calls
Returns / emits

A Chart, which also carries the dataset’s methods. The dataset deep-copies data and owns it; marks re-derive from the committed rows on every render.

Dataset keys

What Elicit.dataset(spec) reads, and the part of an Elicit(spec) spec that describes the data. Every chart over the dataset shares these.

Elicit.dataset({ schema, data?, constraints?, lock?, context?, onChange? }) → Dataset
Options
OptionType · defaultDescription
schema
Schemadefaultrequired
Field → measurement type / domain / default. Owns every field’s data type and domain — marks never declare one. See Data schema.
data
Datum[]default[]
The seed rows. Every mark in every chart is a view over them. May be empty when create will mint rows from the schema.
constraints
Constraint[]default[]
Dataset invariants that gate or repair every edit, from every chart. The only place they go. See Constraints.
lock
LockSpec
Read-only rows. See Locked rows.
context
ContextSpec
Reference rows: drawn, read-only, and left out of getData(). See Context rows.
onChange
(data) => void
Called with the committed data once per commit, whichever chart made it. Hover previews never fire it.

Chart keys

What ds.chart(spec) reads: how one chart draws and edits the dataset. Each chart over a dataset has its own.

ds.chart({ marks, width?, height?, … }) → Chart
Options22
OptionType · defaultDescription
marks
Mark[]default[]
The marks — bar(...), point(...), composite(...), … drawn in array order (later marks on top). Auto-axes and edit guides keep their own layers behind / in front of marks.
elements
ChartElement[]default[]
Scale chrome — axis, grid, legend, axisRadial. Drawn alongside marks; the split only separates chrome from data in your own source.
scales
Record<channel, ScaleSpec>defaultderived
Chart-level scale overrides keyed by channel (x, y, fill, …). Domains stay on the schema. See Scales & channels.
width / height
numberdefault600 / 400
Outer pixel size of the chart.
margins
{top,right,bottom,left}default{20,20,30,40}
Inset around the inner plot (leaves room for axes).
responsive
'fixed' | 'scale' | 'reflow' | truedefault'fixed'
Sizing mode — see Responsive sizing.
motion
false | { duration }default{ duration: 220 }
Eased drawing. A hierarchy's layout, and every mark with motion: true, glides to its new place over duration ms. Effects fade over the same time (see Effects). false draws every change at once. Off when the reader's system asks for reduced motion. See Hierarchy and Ranking.
looks
Look[]defaultnone
Experimental. How the finished chart is drawn: by hand, or through a shader. See Looks.
layout
LayoutSpec[]defaultnone
Spatial layouts. Each settles the marks in pixels after an edit and writes the result back to the rows. See Layout.
clip
boolean | { padding }defaulton with edit.view.zoom or edit.view.pan
Confine the marks to the plot rect, so a zoomed mark stops at the axes. padding grows the rect by that many pixels. See Clip to the plot.

The dataset

What Elicit.dataset returns. It reads and writes the data from outside any chart, and every chart over it redraws on a change. A chart carries the same methods, so chart.getData() is chart.dataset.getData().

ds.chart(spec) → Chart
ds.getData() → Datum[]
ds.getSchema() → Schema
ds.setData(data) → void
ds.setDomain(field, domain, { table? }) → boolean
ds.set(field, value, { index?, table? }) → boolean
ds.on("change" | "select" | "hover", cb) → () => void
ds.undo() · ds.redo() · ds.canUndo() · ds.canRedo()
ds.transaction() → () => void
ds.hover(row) · ds.getHover()
ds.select(i) · selectWhere · toggleSelection · selectAll · clearSelection
ds.getSelection() · ds.getSelectionAll()
Options
OptionTypeDescription
chart(spec)
→ Chart
A chart over this dataset. Make as many as you need. See Datasets & linked charts.
getData()
→ Datum[]
A deep copy of the committed data — the elicited answer. Copy, because handing out the live rows would let a caller mutate past every constraint the dataset just enforced.
getSchema()
→ Schema
A deep copy of the dataset’s schema, including any domain an editable axis reshaped. Your original spec.schema is never mutated.
setData(data)
void
Replace the rows and redraw every chart. Bypasses constraints — it is a trusted seed or reset, not an edit — and clears the undo history for the same reason.
setDomain(field, domain)
→ boolean
Set a field’s domain, for a zoom button or a reset. One undo step; null restores the declared domain. Every chart shares the domain. See Zoom & pan.
set(field, value, options?)
→ boolean
Write one cell from outside any chart. Runs the dataset’s constraints and the lock; one undo step. See Write from outside a chart.
on(type, cb)
→ unsubscribe
change fires once per commit with the new data; select fires when the selection moves; hover fires when the linked hover moves. Returns a function that removes the listener.
undo() / redo()
→ boolean
Step one gesture, whichever chart it happened in, and report whether they moved. See History & undo.
transaction()
→ () => void
Hold one undo step open. Every write until you call the returned function undoes as one step. See Several writes, one undo step.
hover(row) / getHover()
→ boolean / row
Set and read the hovered row, which every chart with a linked hover shows. A row of the primary table is its index, another table's row is { table, index }. hover(null) clears it. See Linked hover.
select(i) / selectWhere / toggleSelection / selectAll / clearSelection
→ boolean
Set which rows are selected, by index or by a field match. Every chart shows the selection. See Selection.
getSelection() / getSelectionAll()
→ row | row[]
The selected row (the lowest index), and every selected row. A row of the primary table is its index; a row of another table is { table, index }.
Returns / emits

change is the seam to the rest of your app: a survey posts getData() on submit, a live app writes it through on every commit.

The chart

What Elicit and ds.chart return: a plain object, not a DOM node. dom() is the node to append. It carries every dataset method above, plus its own.

chart.dom() → HTMLDivElement
chart.dataset → Dataset
chart.on("change" | "select" | "hover" | "stage" | "render" | "destroy", cb) → () => void
chart.getStage() · chart.setStage(i) · chart.nextStage() · chart.getStageLabel()
chart.control(name, target?) → EditControl
chart.scene(query?) · chart.hit(point) · chart.scale(channel) · chart.edits(query?)
chart.metrics() · chart.toInner(point) · chart.toClient(point)
chart.theme → Theme
chart.emit(event) → void
chart.destroy() → void
chart.destroyed → boolean
Options
OptionType · defaultDescription
dom()
→ HTMLDivElement
The chart's container. Append it where you like; it is the same node on every call.
dataset
Dataset
The dataset this chart reads and writes. For Elicit(spec), the one built from the same spec.
on("stage" | "render" | "destroy", cb)
→ unsubscribe
stage fires when this chart’s stage changes. render fires after every frame the chart draws, and destroy once when destroy() is called. change, select and hover are the dataset’s.
getStage() / setStage(i) / nextStage() / getStageLabel()
→ number | string | void
Read and drive a multi-step elicitation from outside. Stages are per chart. See Stages.
control(name, target?)
→ EditControl
Replay a gesture on this chart through a named edit (a slider, a picker). Same dispatch as the pointer — constraints, undo, and change all run. target is a row index (default 0), or { index, channel, side } to name one handle of a row. See External controls.
scene() / hit() / scale() / edits()
→ views
Read what the chart draws: the drawn pieces, the piece at a point, a channel’s scale, and the edits that can run now. Every value is a copy. See Reading the chart.
metrics() / toInner(point) / toClient(point)
→ ChartMetrics / Point
The chart’s size and margins, and the conversion between viewport pixels (clientX, clientY) and plot pixels.
theme
Theme
A copy of the chart’s resolved theme: the defaults, then setTheme(), then spec.theme.
emit(event)
void
Low-level: inject a renderer-shaped gesture event (inner pixels). Prefer control unless you already hold pixels.
destroy()
void
Detach the chart from its dataset and stop its observers. Call it when you unmount the chart — a resize-observing chart outlives its node otherwise. Other charts on the dataset keep working.
destroyed
booleandefaultfalse
True once destroy() has run. Read-only.

Where to go next