Chart interaction
@fractalboxdev/merlion-view/interact-chart makes a merlion-chart/1 SVG inside <merlion-view> interactive:
- a crosshair reads out every series at one
x; - a tap on a legend key hides or shows that series;
- a drag across a
time,linearorlogx axis reports the range in data units; - charts that share a
linkattribute move their crosshairs together.
Interaction is presentation only. The viewer never re-renders. Every class, element and attribute it adds to the SVG is removed when it clears, so svg.outerHTML after clearing equals its value before the first interaction. A host that wants the brushed range drawn re-renders the chart with that domain itself (Brush).
The module reads the plot box, the axis types and the x domain from the chart’s root (chart.md § SVG). It reads values and series from the data-merlion-* attributes of items and points, and positions from their geometry. ADR-0015 records why the root carries the scale.
Loading
Section titled “Loading”<merlion-view>imports./interact-chart.jsthe first time it adopts an SVG with the classesmerlionandmerlion-chart. It imports./interact.jsfor any other Merlion SVG (viewer.md).interactive="off"runs neither module.import "@fractalboxdev/merlion-view/interact-chart"loads the chart module eagerly.- The chart module activates only for an SVG whose root carries
data-merlion-plotanddata-merlion-axeswith valid values. A chart SVG without them still gets pan, zoom and fullscreen, but no chart interaction.interact.jsnever activates on a chart SVG. - The model is built the first time it is needed while the SVG is rendered: the first pointer move over the host, key press, tap or linked move. Building it reads each entry’s bounding box once, so it costs O(E) for E entries. Adopting an SVG reads only the root’s attributes. An SVG that is not rendered (inside an element with
display: none, such as a closed tab, where every bounding box is empty) builds no model and shows no crosshair; it builds one on the first move after it is rendered. - A late extension registration does not restart the module on hosts already on the page, so the crosshair, the hidden series and the brush survive another module loading.
| Term | Definition |
|---|---|
Plot box P |
data-merlion-plot = {x} {y} {w} {h}, in viewBox units |
| Index axis | y when data-merlion-axes names y as band, else x. The guide is perpendicular to it: vertical for x, horizontal for y |
| Entry | Each item of a bar or dot mark (.merlion-chart-bar > .merlion-chart-item, .merlion-chart-dot > .merlion-chart-item), and each .merlion-chart-point of a line or area mark |
| Key of an entry | The text of its index-axis attribute: data-merlion-x, or data-merlion-y for index axis y |
| Value of an entry | The text of the other position attribute (data-merlion-y, or data-merlion-x for index axis y), followed by – {y2} when the entry carries data-merlion-y2 |
| Series of an entry | data-merlion-series of the entry, or of the item that holds the point; absent for a mark without series |
| Key position | The midpoint, along the index axis, of the union of the bounding boxes of the key’s visible entries. A category’s bars sit centred on the category, and points and dots sit on it, so on a band axis this is the category centre and on a continuous axis it is the circle centre |
| Keys | The distinct keys with at least one visible entry, ordered by position |
- Items of
interval,ruleandspanmarks are not entries. They stay drawn under the guide, and the readout never names them. - Every attribute value is used as text, exactly as written. The readout shows
-2.40for a value written"-2.40".
Crosshair
Section titled “Crosshair”- With a mouse or pen pointer inside
P, the crosshair moves to the key whose position is nearest the pointer along the index axis. On a tie it takes the key earlier in order. Pointer coordinates map to viewBox units through the SVG’s screen transform, so the snap holds at every zoom level and in fullscreen. - Moving the pointer out of
P, or out of the host, hides a crosshair the pointer placed. It does not hide one the keyboard placed. - A tap inside
Pmoves the crosshair to the nearest key and keeps it there when the pointer leaves, so a touch pointer shows it with a tap. A tap outsidePthat is not on a legend key hides the crosshair. - While it shows, a
<line class="merlion-chart-guide">appended to the SVG runs acrossPat the key’s position. Every visible entry of the key has the classmerlion-lit. A lit point’s hit circle fills with its series colour, so the point the readout names is visible. - Readout. The base popover (
host.tip, interaction.md § Placement) anchors to the guide, so it sits beside a vertical guide and below or above a horizontal one. It is built withtextContent:- the heading, in bold, is the key’s text;
- then one row per visible entry of the key, in document order. A row is a swatch
■in the entry’s computedcolor, then{series}: {value}, or{value}when the entry has no series. Rows with the same colour and text show once, so a line drawn with dots on its points reads out once.
- The readout is
aria-hiddenlike every popover. A keyboard move announces it through the live region (host.say) as the key, then each row’s text after.. Pointer moves and linked moves announce nothing.
Keyboard
Section titled “Keyboard”<merlion-view> stays the single tab stop. The module handles keydown on the host in the capture phase when no modifier key is held. It calls preventDefault on every key it consumes, so the base viewer skips those keys (viewer.md § Extension hook).
| Key, host focused | Action |
|---|---|
ArrowRight, ArrowDown |
Move the crosshair to the next key; from none, to the first. Wraps from the last to the first |
ArrowLeft, ArrowUp |
Move it to the previous key; from none, to the last. Wraps |
1–8 |
Toggle the series of the n-th legend key; with fewer than n keys, the key is not consumed |
Esc |
Hide the crosshair and clear the brush; with neither shown, the key passes to the base viewer, which closes fullscreen |
Shift + arrow keys, +, -, 0, Tab |
Unchanged: pan, zoom, reset, leave the chart |
Legend
Section titled “Legend”- A tap on a
.merlion-chart-keytoggles its series, named by the key’sdata-merlion-series. So does a digit key (Keyboard). - While a series is hidden:
- every element inside a
.merlion-chart-markor the.merlion-chart-labelsgroup whose owndata-merlion-seriesnames it has the classmerlion-hidden(display: none). This covers a line’s or area’s points and an item’s label; - its legend key has the class
merlion-chart-off(opacity 0.4) and stays a tap target.
- every element inside a
- Each toggle announces
{series} hiddenor{series} shownthrough the live region. - Axes, domains, grid lines, stack positions and stack totals stay as rendered. A stacked bar with a hidden series keeps a gap where its segment was, and its total stays the sum of every series, as the outline prints it.
- Hidden entries leave the readout. A key whose entries are all hidden leaves the keys, and a crosshair on it hides.
- While any series is hidden, the host has
data-merlion-hidden, so the base viewer shows Show all. Clicking it (merlion-show-all) shows every series.
- A brush is available when
data-merlion-axesnamesxaslinear,logortimeand the root carries a validdata-merlion-x-domain. Alogdomain is valid when both ends are above zero. - A drag brushes when all of these hold:
- it is a primary mouse or pen drag with no modifier key;
- it starts inside
Pand not on<text>; - the drawing fits the box (the host has no
pannableattribute).
- On a pannable drawing a drag pans, as for diagrams. A touch pointer never brushes: one finger scrolls the page or pans.
- The pointer-down of a brush prevents its default action, so the drag selects no text, and focuses the host. Once the pointer has moved 4 CSS px from where it went down, a
<rect class="merlion-chart-brush">appended to the SVG spansP’s height between the twoxpositions, clamped toP. - On release, the brushed range
[a, b](a < b, in viewBox units) converts to data units through thexdomain[d0, d1]:v(p) = d0 + (p − P.x) / P.w × (d1 − d0), or on alogaxisv(p) = 10^(lg d0 + (p − P.x) / P.w × (lg d1 − lg d0))withlg = log₁₀. A position pastPcounts asP’s nearer edge.- On a
linearaxis,fromandtoare numbers withkdecimals: the decimals of one viewBox unit,k = clamp(⌈−log₁₀((d1 − d0) / P.w)⌉, 0, 20). A domain of 0–100 over 600 units givesk = 1. - On a
logaxis,fromandtoare numbers above zero withgsignificant digits: the digits one viewBox unit resolves. One unit spansu = (lg d1 − lg d0) / P.wdecades, which multiplies a value by10^u, andg = clamp(1 + ⌈−log₁₀(10^u − 1)⌉, 1, 17). A domain of 10 to 10,000,000 over 600 units givesu = 0.01andg = 3. - On a
linearorlogaxis,fromrounds down andtorounds up at that precision, so the range holds every value the brush covers: 16.67 to 33.33 reports 16.6 to 33.4. A value within 10⁻¹⁴ of its own magnitude from a rounding step takes that step, so float error never widens a range. An end at or pastP’s edge reports that end ofdata-merlion-x-domainexactly: a brush to the right edge of a domain ending at 316.2 reportsto: 316.2, not 316. - On a
timeaxis,fromandtoare instants asYYYY-MM-DDTHH:MM:SSZstrings, rounded to the nearest second.
- On a
- After the conversion, the host dispatches a
merlion-brushCustomEventthat bubbles and is composed, withdetail: { from, to }. These are the forms anx.domainaccepts (chart.md § Axes), so a host may re-render with"domain": [from, to]. The rect stays drawn. - If
fromequalstoafter rounding, or the pointer is cancelled, no event is dispatched and the previous brush, if any, stays drawn. - A tap inside
PorEscclears an existing brush and dispatchesmerlion-brushwithdetail: null. A new brush replaces the old one with a single event carrying the new range.
Linked hover
Section titled “Linked hover”- Charts whose hosts have the same non-empty
linkattribute form a group. Values are compared as exact strings. A host withoutlinkbelongs to no group. - When the crosshair of a chart in a group moves by pointer, tap or keyboard, every other chart in the group moves its crosshair to the source key, as follows:
bandindex axis: to the key with the same text, or hides when it has none.- Continuous index axis: reads the source key’s text as a number (
linear),log₁₀of a number above zero (log), or a UTC instant (time), and moves to its own key nearest that reading, so on alogaxis the nearest in decades. It hides when the text does not read on its axis, or the reading lies outside itsxdomain on anxindex axis.
- When the source’s crosshair hides, every follower’s crosshair hides. So does removing the source chart while its crosshair shows.
- A chart propagates only a crosshair placed on it. A legend toggle on a chart propagates only when it hides the key that chart’s own crosshair was on; a chart with no crosshair, or one placed by a linked move, moves nothing.
- A follower draws its guide, lit entries and readout. It announces nothing and does not propagate the move.
- The group is read at each move, so changing
linktakes effect on the next move.
Rendering
Section titled “Rendering”The module changes only class tokens on SVG elements and attributes on the host, and appends the guide and the brush rect while they show. Each is removed when it clears:
| Where | Token or element | Meaning |
|---|---|---|
| Host | data-merlion-interactive |
The module is active |
| Host | data-merlion-state |
The crosshair shows |
| Host | data-merlion-hidden |
A series is hidden; the base shows Show all |
| Entries of the crosshair’s key | class merlion-lit |
Read out |
| Elements of a hidden series | class merlion-hidden |
Not drawn |
| Legend key of a hidden series | class merlion-chart-off |
Dimmed |
| SVG | <line class="merlion-chart-guide"> |
The crosshair |
| SVG | <rect class="merlion-chart-brush"> |
The brushed range |
The rules live in the base element’s light-DOM sheet (MerlionView.style), which applies under a CSP without 'unsafe-inline':
[data-merlion-interactive] .merlion-chart-key{cursor:pointer}.merlion-hidden{display:none}.merlion-chart-off{opacity:.4}.merlion-chart-guide,.merlion-chart-brush{pointer-events:none;vector-effect:non-scaling-stroke}.merlion-chart-guide{stroke:var(--merlion-fg,#1f2328);stroke-opacity:.5}.merlion-chart-brush{fill:var(--merlion-highlight,var(--merlion-accent,#0969da));fill-opacity:.12;stroke:var(--merlion-highlight,var(--merlion-accent,#0969da));stroke-opacity:.6}.merlion-chart-point.merlion-lit>circle{fill:currentColor;stroke:var(--merlion-bg,#fff);stroke-width:2}- The guide and the brush rect take no pointer events, so the items’ native
<title>tooltips and the snap keep working under them. - A lit point keeps its series colour from its item’s
color. Bars and dots are not restyled; the guide marks their category. - The guide and the brush rect keep a 1 px stroke at every zoom level (
vector-effect: non-scaling-stroke).
Security
Section titled “Security”- The module adds no markup from chart text. It creates elements with
createElementandcreateElementNSand fills them withtextContent. Attribute values are compared as strings and parsed as numbers. They are never interpolated into a selector, a style or markup. - The module makes no request and reads no URL. It writes only:
- class tokens on the SVG’s elements, and the guide and brush rect, which it removes;
- the host’s attributes;
- the base element’s popover and live region;
- the shared light-DOM sheet;
merlion-brushevents, whosedetailholds only numbers, strings ornull.
Performance and budgets
Section titled “Performance and budgets”| Item | Budget |
|---|---|
@fractalboxdev/merlion-view/interact-chart, minified + gzip |
≤ 3.5 KB, enforced by scripts/size.mjs |
| Model | Built once per adopted SVG on first use, O(E) bounding-box reads for E entries |
| Per pointer move | One screen-transform read, a binary search over the keys, class changes on the previous and the new key’s entries, one popover placement |
| Per linked move | The same, in each follower |
Determinism
Section titled “Determinism”The render is unchanged as a function: the root’s chart attributes depend on the spec and the target width only, and native and WASM output stay byte-identical. Interaction state never reaches the SVG’s bytes, the outline or the chart id.
Testing
Section titled “Testing”Unit (node --test, no DOM), on interact-chart-model.js:
- the nearest-key search: empty, one key, ties, and pointer positions before the first key and after the last;
- the conversion from viewBox units to data units: the
krule at domain spans from 0.001 to 10⁹, thegrule and the conversion in decades on alogaxis, rounding atimerange to whole seconds, and the ISO form; - reading values on a
logaxis aslog₁₀, and rejecting zero, negative values and a domain end at or below zero; - reading each
timevalue form (YYYY,YYYY-MM,YYYY-MM-DD,YYYY-MM-DDTHH:MM[:SS]Z) as a UTC instant; - linked matching: exact text on
band, the nearest key on a continuous axis, in decades on alogaxis, and a value outside the domain or not a number; - parsing the root attributes, where a missing or malformed value leaves the module inactive.
Acceptance (Playwright, headless Chromium, chart fixtures rendered by merlion render --chart and inlined in <merlion-view>):
- On a line chart with a
timex axis, hovering at a point’sxshows one guide and a readout. The readout’s heading and rows equal the points’data-merlion-xand{series}: {data-merlion-y}. - On grouped bars, hovering anywhere in a category’s step shows that category. On bars with a
bandy axis, the guide is horizontal. ArrowRightwalks the keys in order and announces each readout.Eschides the crosshair, and a secondEscin fullscreen closes the dialog.- A tap on a legend key hides exactly the elements carrying its series and dims the key. Show all restores
svg.outerHTMLbyte for byte. Digit2toggles the second series. - A drag across a
timeaxis dispatches onemerlion-brushwhose range matches the dragged positions to one second. A tap then dispatchesdetail: null. Zoomed in, the same drag pans and dispatches nothing. - A drag across the
logx axis oflog-scatterdispatches numbers whoselog₁₀lies within two viewBox units, in decades, of the dragged positions. - Two charts with the same
linkmirror the crosshair. A third with anotherlinkvalue does not move. - After every interaction is cleared,
svg.outerHTMLequals its value before the first one.
TODO(owner): run axe-core over the acceptance pages once it is recorded in licensing.md, as interaction.md also requires.
Out of scope
Section titled “Out of scope”- A brush on
yor on abandaxis, and zooming to the brushed range inside the viewer. - A crosshair on
interval,ruleandspanmarks. - Streaming data, canvas rendering and editing.
- Focusing legend keys one by one with
Tab. The digit keys toggle series instead, and the host stays the single tab stop.