The ecosystem · packages/charts
Charts that glide to their data, and then stop
Eight SVG charts for a dashboard, a report or a live tally: bar, stacked bar, line, stacked area, sparkline, donut, scatter and heatmap. The server renders them; the browser hydrates them like any component. When data changes they glide to it, a frame at a time, then nothing runs. Every chart here is live: Randomize gives it new data, Auto (on from the start) does so every 3.3 seconds, and Neon, Blueprint and Paper restyle it with CSS custom properties alone.
Installing it#
Name the package in your app's header (main.roc), by its directory's name:
app [program] { charts: "../packages/charts/main.roc", pf: platform "…/server/platform/main.roc" }rocx generate (which rocx dev and rocx build run first) copies each chart into your app; in a .rocx file, import charts.BarChart imports it (the ecosystem's overview explains why). A chart needs its data and a few words about it:
import charts.BarChart
import charts.Format
<BarChart data!={rain!()} label="Rain each month, in millimetres" format={|mm| Format.num(mm, 0)} />Every chart takes the same three kinds of prop:
data!, an accessor prop: the chart calls it to read the data and follows its changes. Write any expression that reads your signals, likedata!={rain!()}. Values areDec, Roc's decimal.label, what the chart shows, for screen readers (label!on<Sparkline>, an accessor, since it changes with the data).format, which writes a value as text for ticks and readouts:Format.short(1.3k) unless you give your own.<LineChart>also hasformat_x;<ScatterChart>hasformat_xandformat_yinstead;<Sparkline>writes no values.
In use: Plate (each day's energy as bars, weight as a line), the quiz (how the room answered, as bars) and Uptime (response times as a line, failures as a heatmap, a sparkline on each monitor's card).
<BarChart>#
Roc is idle: the bars are where the data says.
import charts.BarChart
import charts.Format
{<BarChart data!={walk!().birds} label="Birds counted on a morning walk, by kind" format={|count| Format.num(count, 0)} padding={Shuffle.pick(look!(), 0.3, 0.55, 0.12)} />}| Prop | Is |
|---|---|
data! : () => List(BarChart.Bar), Bar := { label : Str, value : Dec, color : Str ?? "" } | A bar per item, in order. A bar belongs to its label: a new value glides it to its new height; a new label grows a bar from the axis while the others make room; a gone label's bar shrinks into the axis and fades (its <rect>'s transition:out) as the others close up. A new order slides each bar to its place. A bar is in its color (any CSS colour: "#c0392b", "var(--brand)"), which it keeps when pointed at; left out, it is the chart's. |
label : Str | What the chart shows, for screen readers. |
format : (Dec -> Str) ?? Format.short | A value as text: on the ticks, and on a bar when it is pointed at or focused. |
padding : Dec ?? 0.3 | The share of each bar's slot left empty. Blueprint's thin bars use 0.55, Paper's wide ones 0.12. |
The axis runs from zero (or the least value, if negative) to the greatest, widened to round numbers. Tab reaches each bar; a screen reader reads its label and value. Two items with the same label are two bars.
<StackedBarChart>#
Roc is idle: the columns are where the data says.
import charts.Format
import charts.StackedBarChart
{<StackedBarChart data!={half!().months} series={sources} label="A town's electricity each month, by source, in gigawatt-hours" format={|gwh| Format.num(gwh, 0)} padding={Shuffle.pick(look!(), 0.3, 0.55, 0.12)} />}| Prop | Is |
|---|---|
data! : () => List(StackedBarChart.Column), Column : { label : Str, values : List(Dec) } | A column per item, one value per series stacked from the axis up. A column belongs to its label: its parts glide to their new sizes, a new column grows from the axis while the others make room, and a gone label's column shrinks into the axis and fades. A value below zero counts as zero. |
series : List(Str) | The series' names, bottom one first. The legend over the chart shows each in its colour. |
label : Str | What the chart shows, for screen readers. |
format : (Dec -> Str) ?? Format.short | A value as text: on the ticks, and a column's total when it is pointed at or focused. |
padding : Dec ?? 0.3 | The share of each column's slot left empty. |
The axis runs from zero to the tallest column, widened to round numbers. Tab reaches each column; a screen reader reads its label and each series' value.
<LineChart>#
Roc is idle: the line is where the data says.
import charts.Format
import charts.LineChart
{<LineChart data!={LineChart.evenly(day!().visits)} label="Visits to a site, hour by hour" format_x={|hour| "${Format.num(hour, 0)}:00"} smooth={look!() != Blueprint} />}| Prop | Is |
|---|---|
data! : () => List(LineChart.Point), Point : { x : Dec, y : Dec } | The points, left to right: across by x (a day, an hour, a time in milliseconds), to scale, and up by y. When they change, the line glides to them; if their number changes, it jumps instead. For evenly spaced values, LineChart.evenly(values) puts them one apart, as the demo's hours are. |
label : Str | What the chart shows, for screen readers. |
format : (Dec -> Str) ?? Format.short | A value as text: on the ticks up the side, and over the point under the pointer. |
format_x : (Dec -> Str) ?? Format.short | An x as text: on the ticks along the bottom, and the point's under the pointer. |
smooth : Bool ?? Bool.False | Monotone curves through the points (they never overshoot one) instead of straight segments. |
The side axis runs from the least value to the greatest, widened to round numbers. The bottom one runs from the least x to the greatest, ticked on round numbers, so points on irregular days sit as far apart as the days: Plate draws its weight so, each day a number (Date.days). Pointing along the chart shows the nearest point, its value over the plot and its x on the axis. The pointer finds points by where the data puts them, not where the line is drawn, so a gliding line doesn't move them.
<StackedAreaChart>#
- Search 659
- Social 436
- Email 186
Roc is idle: the bands are where the data says.
import charts.Format
import charts.StackedAreaChart
{<StackedAreaChart data!={fortnight!().orders} label="A shop's orders each day for a fortnight, by where they came from" format={|orders| Format.num(orders, 0)} format_x={|day| "Day ${Format.num(day + 1.0, 0)}"} smooth={look!() != Blueprint} resting={Sum} />}| Prop | Is |
|---|---|
data! : () => StackedAreaChart.Data, Data : { xs : List(Dec), bands : List(StackedAreaChart.Band) }, Band := { label : Str, values : List(Dec), color : Str ?? "" } | The points across (xs, to scale, as a line chart's x) and a band for each part of the whole, a value at each point, stacked from the axis up in order (the first at the bottom), so the top edge is the whole. New values glide the bands to them; with more points or fewer, or other bands, the chart jumps. A value below zero counts as zero. A band is in its color (any CSS colour), it and its line in the legend; left out, it is the chart's colour for its place. |
label : Str | What the chart shows, for screen readers. |
format : (Dec -> Str) ?? Format.short | A value as text: on the ticks up the side, each band's in the legend, and the whole over the point under the pointer. |
format_x : (Dec -> Str) ?? Format.short | An x as text: on the ticks along the bottom, and the point's under the pointer. |
smooth : Bool ?? Bool.False | Monotone curves through the points, as the line chart's. |
resting : [Last, Sum] ?? Last | What the legend says while no point is pointed at: each band's value at the last point (Last, a running total's now), or all its points' added up (Sum, of a count each day the period's, as the demo's fortnight). |
The side axis runs from zero to the highest whole, widened to round numbers; the bottom one as the line chart's. The legend says each band's value and its share of the whole, in whole percents that add up to 100 as a donut's do: at the point you point at, whose whole shows over the plot and whose x on the axis, or, while you point at none, as resting says. To a screen reader the chart is one image, beside the legend's words.
<Sparkline>#
Roc is idle: the lines are where the data says.
import charts.Format
import charts.Sparkline
<Sparkline data!={tile.values} label!={"${tile.name}, ${SparkDemo.trend(tile.values)} over the day"} />| Prop | Is |
|---|---|
data! : () => List(Dec) | The values, left to right. When they change, the line glides to them; if their number changes, it jumps. |
label! : () => Str | What it shows, for screen readers: with no axis, say the trend. An accessor, since it changes with the data. |
A small line with no axis, shaded underneath, with a dot on the last value, to sit beside a number. It spans its values' range, so it shows their shape, not their size. The tiles around these are the demo's, not the package's.
<DonutChart>#
Roc is idle: the slices are where the data says.
import charts.DonutChart
import charts.Format
{<DonutChart data!={project!().lines} label="A project's lines of code, by language" format={Format.short} total="lines" thickness={Shuffle.pick(look!(), 52.0, 24.0, 150.0)} />}| Prop | Is |
|---|---|
data! : () => List(DonutChart.Slice), Slice := { label : Str, value : Dec, color : Str ?? "" } | A slice per item, clockwise from twelve o'clock, its share of the ring its share of the total. A slice belongs to its label: a new value glides it to its new share, a new label grows a slice from nothing while the others make room, and a gone label's slice shrinks to nothing where it was. A value below zero counts as zero. A slice is in its color (any CSS colour), it and its legend line; left out, it is one of the chart's five. |
label : Str | What the chart shows, for screen readers. |
format : (Dec -> Str) ?? Format.short | A value as text: the total, and each slice's value in the legend. |
total : Str ?? "Total" | The word under the total. |
thickness : Dec ?? 52 | The ring's width, out of a radius of 150. Blueprint's 24 is a thin ring; Paper's 150 is a pie. Above 90 there is no room in the middle, so the total isn't shown. |
The middle shows the total, or a slice's share while you point at it, focus it (Tab reaches each) or point at its legend line. Shares are whole percents that add up to 100, and <1% for a value too small to make one. Its slice is still drawn, as a sliver; the legend and the total keep the true values. A slice keeps its colour as others come and go; a new slice takes a colour no other has, unless the data gives each its own.
A bar or a slice may carry its colour in the data, as a slice for each party in its party's: { label: party.name, value: party.seats, color: party.color }. A record written where the data is passed is the chart's type, with color or without; a list already typed as plain records isn't, so name the chart's type in its annotation (List(DonutChart.Slice)), or build the records where you pass them.
<ScatterChart>#
Roc is idle: the dots are where the data says.
import charts.Format
import charts.ScatterChart
<ScatterChart
data!={catch!().birds}
label="Birds, by wingspan and weight"
format_x={|cm| "${Format.num(cm, 0)} cm"}
format_y={|kg| "${Format.num(kg, 2)} kg"}
/>| Prop | Is |
|---|---|
data! : () => List(ScatterChart.Dot), Dot : { label : Str, x : Dec, y : Dec } | A dot per item, across by x and up by y. A dot belongs to its label, so new values glide it to its new place. A new dot swells from nothing; a gone label's dot shrinks away (a transition both ways). |
label : Str | What the chart shows, for screen readers. |
format_x : (Dec -> Str) ?? Format.short | A value across: on the ticks along the bottom, and on a dot when it is pointed at or focused. |
format_y : (Dec -> Str) ?? Format.short | A value up: on the ticks up the side, and on a dot. |
Each axis runs from least to greatest, widened to round numbers. Tab reaches each dot; a screen reader reads its label and values.
<Heatmap>#
Roc is idle: the browser fades the cells.
import charts.Format
import charts.Heatmap
<Heatmap data!={week!().commits} rows={days} columns={hours} label="Commits in a week, by day and hour" format={|count| Format.num(count, 0)} />| Prop | Is |
|---|---|
data! : () => List(List(Dec)) | A list of values for each row, one value per column. A cell's colour goes from --chart-heat-low at zero to --chart-heat-high at the greatest value. |
rows : List(Str) | The rows' labels, down the side. |
columns : List(Str) | The columns' labels. Each appears in the readout; along the bottom, at most eight are shown, evenly spaced. |
label : Str | What the chart shows, for screen readers. |
format : (Dec -> Str) ?? Format.short | A value as text: the scale's ends, and the cell pointed at. |
Under the grid are the colour scale and a readout of the cell under the pointer (row, column, value); that cell's outline is drawn on top, so no neighbour covers it. A new value changes a cell's strength (a custom property), and a CSS transition fades it to its new colour, so Roc runs no frames: the line under the demo stays at zero.
How they move#
A chart keeps what it has drawn in a signal, apart from its data. While the two differ, a hole's if holds an element with an on:frame.ms handler that, once per animation frame, moves the drawing a share of the remaining way (Ease.toward). Once the drawing reaches the data, the if turns false, the element goes, and the frames stop. The line under each demo counts them.
Marks are kept by label, so new data moves the mark you see instead of making another. A mark that comes or goes plays a transition, which the browser runs. The heatmap leaves even the glide to the browser.
The buttons are the demos', not the package's. Randomize sets the data's signal. Auto starts a set_interval! and keeps the clear! it returns in a signal, so pressing Auto again stops it.
The buttons and the looks, and the demos' data: site/Demos/Shuffle.rocx and the eight demos
import pf.Html
import pf.Solid exposing [create_signal_with!, set_interval!]
## A chart on the charts page, with buttons over it. Randomize gives it other data (`roll!`), and
## Auto, on from the start, does every 3.3 seconds, so the chart keeps gliding to new data until
## Auto is pressed again: the interval is Auto's, cleared when it is pressed, and stopped with the
## chart. Neon, Blueprint and Paper restyle it (`look!`, `set_look!`). A look is custom properties
## the chart components read (colours, a font, outlines, a dashed grid, corners, a glow), set here
## on the stage under the buttons, and a prop or two the demo gives its chart by the look
## (`Shuffle.pick`: wider bars, a straight line, a thinner ring).
Shuffle := [].{
Auto : [Off, On(() => {})]
Look : [Neon, Blueprint, Paper]
view! : { roll! : () => {}, look! : () => Shuffle.Look, set_look! : Shuffle.Look => {}, children : List(Html) } => Html
view! = |{ roll!, look!, set_look!, children }| {
(auto!, set_auto!) = create_signal_with!(On(set_interval!(every, roll!)), { equals: |_, _| Bool.False })
toggle! = ||
match auto!() {
On(clear!) => {
clear!()
set_auto!(off)
}
Off => set_auto!(On(set_interval!(every, roll!)))
}
<div class="shuffle">
<div class="buttons">
<button type="button" class="roll" on:click={roll!}>Randomize</button>
<button type="button" class="auto" aria-pressed={pressed(on(auto!()))} on:click={toggle!}>Auto</button>
<span class="looks" role="group" aria-label="Style">
<button type="button" aria-pressed={pressed(look!() == Neon)} on:click={|| set_look!(Neon)}>Neon</button>
<button type="button" aria-pressed={pressed(look!() == Blueprint)} on:click={|| set_look!(Blueprint)}>Blueprint</button>
<button type="button" aria-pressed={pressed(look!() == Paper)} on:click={|| set_look!(Paper)}>Paper</button>
</span>
</div>
<div class="stage" data-look={Shuffle.name(look!())}>{...children}</div>
</div>
}
## The look a demo starts with: the site's.
first : Shuffle.Look
first = Neon
## One of three, by the look: for a prop that changes with it.
pick : Shuffle.Look, a, a, a -> a
pick = |look, neon, blueprint, paper|
match look {
Neon => neon
Blueprint => blueprint
Paper => paper
}
## The look's name, as the stage's `data-look` has it.
name : Shuffle.Look -> Str
name = |look| Shuffle.pick(look, "neon", "blueprint", "paper")
<style>
.shuffle {
display: grid;
gap: var(--space-3);
}
.buttons {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
button {
padding: var(--space-1) var(--space-3);
font-size: var(--size-sm);
}
button[aria-pressed="true"] {
background: var(--accent-soft);
color: var(--accent);
}
.looks {
display: inline-flex;
gap: 2px;
margin-left: auto;
padding: 2px;
border-radius: var(--radius-sm);
background: var(--fill);
}
.looks button {
background: transparent;
}
.looks button[aria-pressed="true"] {
background: var(--accent-soft);
}
.stage {
padding: var(--space-4);
border-radius: var(--radius-md);
transition: background-color 0.3s, color 0.3s;
}
/* The site's own: neon on the dark, and a glow. */
[data-look="neon"] {
--chart-color: var(--accent);
--chart-active: var(--accent-strong);
--chart-grid: var(--rule);
--chart-axis: var(--rule-strong);
--chart-muted: var(--text-faint);
--chart-surface: var(--bg-raised);
--chart-glow: drop-shadow(0 0 5px rgb(46 232 255 / 0.45));
--chart-1: #2ee8ff;
--chart-2: #ff4fd0;
--chart-3: #b6ff4a;
--chart-4: #7b6bff;
--chart-5: #ff8a3d;
--chart-heat-low: rgb(46 232 255 / 0.05);
--chart-heat-high: #2ee8ff;
--chart-up: var(--good);
--chart-down: var(--bad);
}
/* A drawing on blue paper: outlines, a dashed grid, square corners, monospace. */
[data-look="blueprint"] {
background-color: #0d2a4a;
background-image: linear-gradient(rgb(159 211 255 / 0.07) 1px, transparent 1px), linear-gradient(90deg, rgb(159 211 255 / 0.07) 1px, transparent 1px);
background-size: 16px 16px;
color: #e6f1ff;
font-family: var(--mono);
--chart-font: var(--mono);
--chart-color: #9fd3ff;
--chart-active: #ffffff;
--chart-grid: rgb(159 211 255 / 0.25);
--chart-axis: rgb(159 211 255 / 0.7);
--chart-muted: #9fb8d6;
--chart-surface: #0d2a4a;
--chart-fill: 0.2;
--chart-stroke: #9fd3ff;
--chart-stroke-width: 1.5;
--chart-outline: 1;
--chart-radius: 0px;
--chart-grid-dash: 4 4;
--chart-line-width: 1.5;
--chart-area: 0.1;
--chart-dot: 5px;
--chart-1: #5ab0f0;
--chart-2: #ffc94d;
--chart-3: #ff7aa2;
--chart-4: #8fdc7a;
--chart-5: #b49cff;
--chart-heat-low: #0d2a4a;
--chart-heat-high: #9fd3ff;
--chart-up: #8fdc7a;
--chart-down: #ff7aa2;
}
/* A newspaper's: ink on cream, a serif, a dotted grid, no area, flat colours. */
[data-look="paper"] {
background-color: #f4efe6;
color: #1d1b18;
font-family: Georgia, "Iowan Old Style", "Times New Roman", serif;
--chart-font: Georgia, "Iowan Old Style", "Times New Roman", serif;
--chart-color: #c8452c;
--chart-active: #7f2716;
--chart-grid: rgb(29 27 24 / 0.14);
--chart-axis: #1d1b18;
--chart-muted: #6b645a;
--chart-surface: #f4efe6;
--chart-radius: 0px;
--chart-grid-dash: 1 3;
--chart-line-width: 2;
--chart-area: 0;
--chart-dot: 5px;
--chart-1: #c8452c;
--chart-2: #1c63b8;
--chart-3: #c98a0b;
--chart-4: #8a4cb0;
--chart-5: #2f8a43;
--chart-heat-low: #f4efe6;
--chart-heat-high: #1c63b8;
--chart-up: #2f8a43;
--chart-down: #c8452c;
}
</style>
}
## How often Auto gives the chart other data, in milliseconds.
every : U64
every = 3300
off : Shuffle.Auto
off = Off
on : Shuffle.Auto -> Bool
on = |auto|
match auto {
On(_) => Bool.True
Off => Bool.False
}
## A button's `aria-pressed`.
pressed : Bool -> Str
pressed = |yes| if (yes) "true" else "false"import pf.Html
import pf.Solid exposing [create_signal!]
import charts.BarChart
import charts.Format
import Random
import Shuffle
## Birds counted on a morning walk, a bar for each kind, the most first: the charts page's
## `<BarChart>`. Another morning moves each bar to its new count and slides it to its new place; a
## kind not seen this time shrinks into the axis, and one seen again grows back out of it.
BarDemo := [].{
Walk : { seed : U64, birds : List(BarChart.Bar) }
view! : {} => Html
view! = |{}| {
(walk!, set_walk!) = create_signal!(BarDemo.walk(2026))
(look!, set_look!) = create_signal!(Shuffle.first)
<Shuffle roll!={|| set_walk!(BarDemo.walk(walk!().seed))} look!={look!} set_look!={set_look!}>
{<BarChart data!={walk!().birds} label="Birds counted on a morning walk, by kind" format={|count| Format.num(count, 0)} padding={Shuffle.pick(look!(), 0.3, 0.55, 0.12)} />}
</Shuffle>
}
## A morning's counts: each kind seen 5 to 120 times, or, one morning in six, not at all; the
## most first.
walk : U64 -> BarDemo.Walk
walk = |seed| {
var $seed = seed
var $birds = []
for kind in kinds {
seen = Random.below($seed, 6)
count = Random.below(seen.seed, 116)
$seed = count.seed
if seen.value > 0 {
$birds = $birds.append({ label: kind, value: (5 + count.value).to_dec() })
}
}
{ seed: $seed, birds: $birds.sort_with(|a, b| if (a.value > b.value) Before else if (a.value < b.value) After else Same) }
}
}
kinds : List(Str)
kinds = ["Robin", "Wren", "Finch", "Crow", "Owl", "Swift", "Heron", "Kite"]import pf.Html
import pf.Solid exposing [create_signal!]
import charts.Format
import charts.StackedBarChart
import Random
import Shuffle
## A town's electricity, a column for each month and a part for each source: the charts page's
## `<StackedBarChart>`. Another half-year moves each part to its new size; a half-year whose data
## stops early takes its last months away, and they shrink into the axis.
StackDemo := [].{
Half : { seed : U64, months : List({ label : Str, values : List(Dec) }) }
view! : {} => Html
view! = |{}| {
(half!, set_half!) = create_signal!(StackDemo.half(3))
(look!, set_look!) = create_signal!(Shuffle.first)
<Shuffle roll!={|| set_half!(StackDemo.half(half!().seed))} look!={look!} set_look!={set_look!}>
{<StackedBarChart data!={half!().months} series={sources} label="A town's electricity each month, by source, in gigawatt-hours" format={|gwh| Format.num(gwh, 0)} padding={Shuffle.pick(look!(), 0.3, 0.55, 0.12)} />}
</Shuffle>
}
## A half-year: four to six months, each source making 5 to 60 gigawatt-hours of them.
half : U64 -> StackDemo.Half
half = |seed| {
length = Random.below(seed, 3)
var $seed = length.seed
var $months = []
for month in names.take_first(4 + length.value) {
var $values = []
for _ in sources {
made = Random.below($seed, 56)
$seed = made.seed
$values = $values.append((5 + made.value).to_dec())
}
$months = $months.append({ label: month, values: $values })
}
{ seed: $seed, months: $months }
}
}
sources : List(Str)
sources = ["Solar", "Wind", "Hydro"]
names : List(Str)
names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]import pf.Html
import pf.Solid exposing [create_signal!]
import charts.Format
import charts.LineChart
import Random
import Shuffle
## A day of visits to a site, hour by hour: the charts page's `<LineChart>`, the hours one apart
## (`LineChart.evenly`) and named along the bottom. Another day moves each hour's value, and the line
## glides to them; the axis glides to new round numbers when it has to.
LineDemo := [].{
Day : { seed : U64, visits : List(Dec) }
view! : {} => Html
view! = |{}| {
(day!, set_day!) = create_signal!(LineDemo.day(7))
(look!, set_look!) = create_signal!(Shuffle.first)
<Shuffle roll!={|| set_day!(LineDemo.day(day!().seed))} look!={look!} set_look!={set_look!}>
{<LineChart data!={LineChart.evenly(day!().visits)} label="Visits to a site, hour by hour" format_x={|hour| "${Format.num(hour, 0)}:00"} smooth={look!() != Blueprint} />}
</Shuffle>
}
## A day's visits: a quiet or a busy day (60% to 140% of a usual one), and each hour of it 80%
## to 120% of that.
day : U64 -> LineDemo.Day
day = |seed| {
busy = Random.below(seed, 81)
var $seed = busy.seed
var $visits = []
for usual in hourly {
roll = Random.below($seed, 41)
$seed = roll.seed
$visits = $visits.append(Dec.round(usual * (60.0 + busy.value.to_dec()) * (80.0 + roll.value.to_dec()) / 10000.0))
}
{ seed: $seed, visits: $visits }
}
}
## A usual day's visits, from midnight: quiet at night, busy in the morning and the afternoon.
hourly : List(Dec)
hourly = [120.0, 80.0, 50.0, 40.0, 40.0, 70.0, 180.0, 420.0, 700.0, 880.0, 950.0, 920.0, 860.0, 900.0, 980.0, 940.0, 840.0, 760.0, 700.0, 640.0, 520.0, 400.0, 280.0, 180.0]import pf.Html
import pf.Solid exposing [create_signal!]
import charts.Format
import charts.StackedAreaChart
import Random
import Shuffle
## A shop's orders each day for a fortnight, a band for each place they came from: the charts page's
## `<StackedAreaChart>`. The legend says each band's orders over the fortnight (`resting={Sum}`), or
## a day's while one is pointed at. Another fortnight glides each band to its new values.
AreaDemo := [].{
Fortnight : { seed : U64, orders : StackedAreaChart.Data }
view! : {} => Html
view! = |{}| {
(fortnight!, set_fortnight!) = create_signal!(AreaDemo.fortnight(11))
(look!, set_look!) = create_signal!(Shuffle.first)
<Shuffle roll!={|| set_fortnight!(AreaDemo.fortnight(fortnight!().seed))} look!={look!} set_look!={set_look!}>
{<StackedAreaChart data!={fortnight!().orders} label="A shop's orders each day for a fortnight, by where they came from" format={|orders| Format.num(orders, 0)} format_x={|day| "Day ${Format.num(day + 1.0, 0)}"} smooth={look!() != Blueprint} resting={Sum} />}
</Shuffle>
}
## A fortnight's orders: from each place, each day 60% to 140% of its usual, and half as many
## again at the weekend.
fortnight : U64 -> AreaDemo.Fortnight
fortnight = |seed| {
var $seed = seed
var $bands = []
for source in sources {
var $values = []
for day in days {
roll = Random.below($seed, 81)
$seed = roll.seed
weekend = if (day % 7 >= 5) 1.5 else 1.0
$values = $values.append(Dec.round(source.usual * weekend * (60.0 + roll.value.to_dec()) / 100.0))
}
$bands = $bands.append({ label: source.label, values: $values })
}
{ seed: $seed, orders: { xs: days.map(|day| day.to_dec()), bands: $bands } }
}
}
## Where the orders come from, and how many a usual weekday brings.
sources : List({ label : Str, usual : Dec })
sources = [{ label: "Search", usual: 40.0 }, { label: "Social", usual: 25.0 }, { label: "Email", usual: 12.0 }]
## A fortnight's days, from 0.
days : List(I64)
days = List.from_iter(I64.until(0, 14))import pf.Html
import pf.Solid exposing [create_signal!]
import charts.Format
import charts.Sparkline
import Random
import Shuffle
## Three numbers a site watches, each in a tile with how it changed and its last day by the hour:
## the charts page's `<Sparkline>`. Another day moves each line, and the numbers with them.
SparkDemo := [].{
Tile : { name : Str, values : List(Dec) }
Day : { seed : U64, tiles : List(SparkDemo.Tile) }
view! : {} => Html
view! = |{}| {
(day!, set_day!) = create_signal!(SparkDemo.day(4))
(look!, set_look!) = create_signal!(Shuffle.first)
<Shuffle roll!={|| set_day!(SparkDemo.day(day!().seed))} look!={look!} set_look!={set_look!}>
<div class="tiles">
{...day!().tiles.map(|tile|
<div key={tile.name} class="tile">
<span class="name">{tile.name}</span>
<span class="now">{Format.short(tile.values.last() ?? 0.0)}</span>
<span class="change" class:down={SparkDemo.change(tile.values) < 0.0}>
{if (SparkDemo.change(tile.values) < 0.0) "▼ " else "▲ "}
{Format.percent(Dec.abs(SparkDemo.change(tile.values)), 0)}
</span>
<Sparkline data!={tile.values} label!={"${tile.name}, ${SparkDemo.trend(tile.values)} over the day"} />
</div>
)}
</div>
</Shuffle>
}
## A day of each: a walk from where it usually is, each hour up or down by as much as a tenth.
day : U64 -> SparkDemo.Day
day = |seed| {
var $seed = seed
var $tiles = []
for (name, usual) in watched {
var $value = usual
var $values = []
for _ in List.repeat(0, 24).map_with_index(|_, i| i) {
roll = Random.below($seed, 201)
$seed = roll.seed
$value = Dec.max($value * (900.0 + roll.value.to_dec()) / 1000.0, 1.0)
$values = $values.append(Dec.round($value))
}
$tiles = $tiles.append({ name, values: $values })
}
{ seed: $seed, tiles: $tiles }
}
## How much the last value is above the first, as a share of it.
change : List(Dec) -> Dec
change = |values| {
first = values.first() ?? 0.0
if (first == 0.0) 0.0 else ((values.last() ?? 0.0) - first) / first
}
## Up or down, for a screen reader.
trend : List(Dec) -> Str
trend = |values| if (SparkDemo.change(values) < 0.0) "down ${Format.percent(Dec.abs(SparkDemo.change(values)), 0)}" else "up ${Format.percent(SparkDemo.change(values), 0)}"
<style>
.tiles {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, max(10rem, calc((100% - var(--space-4)) / 2))), 1fr));
gap: var(--space-4);
}
.tile {
display: grid;
grid-template-columns: 1fr auto;
align-items: baseline;
gap: var(--space-1) var(--space-3);
padding: var(--space-3) var(--space-4);
border-radius: var(--radius-sm);
background: color-mix(in srgb, currentColor 5%, transparent);
}
.name {
grid-column: 1 / -1;
color: var(--chart-muted);
font-size: var(--size-sm);
}
.now {
font-size: var(--size-xl);
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.change {
color: var(--chart-up);
font-size: var(--size-sm);
font-variant-numeric: tabular-nums;
}
.change.down {
color: var(--chart-down);
}
.tile > :global(svg) {
grid-column: 1 / -1;
}
</style>
}
## What the tiles watch, and where each usually is.
watched : List((Str, Dec))
watched = [("Visitors", 1200.0), ("Sign-ups", 80.0), ("Orders", 300.0)]import pf.Html
import pf.Solid exposing [create_signal!]
import charts.DonutChart
import charts.Format
import Random
import Shuffle
## A project's code, a slice for each language: the charts page's `<DonutChart>`. Another project
## grows or shrinks each slice to its new share; CSS isn't in every one, so its slice comes and goes.
DonutDemo := [].{
Project : { seed : U64, lines : List(DonutChart.Slice) }
view! : {} => Html
view! = |{}| {
(project!, set_project!) = create_signal!(DonutDemo.project(16))
(look!, set_look!) = create_signal!(Shuffle.first)
<Shuffle roll!={|| set_project!(DonutDemo.project(project!().seed))} look!={look!} set_look!={set_look!}>
{<DonutChart data!={project!().lines} label="A project's lines of code, by language" format={Format.short} total="lines" thickness={Shuffle.pick(look!(), 52.0, 24.0, 150.0)} />}
</Shuffle>
}
## A project's lines: 200 to 3,000 of each language, and CSS in two projects of three.
project : U64 -> DonutDemo.Project
project = |seed| {
var $seed = seed
var $lines = []
for language in languages {
lines = Random.below($seed, 2801)
css = Random.below(lines.seed, 3)
$seed = css.seed
if language != "CSS" or css.value > 0 {
$lines = $lines.append({ label: language, value: (200 + lines.value).to_dec() })
}
}
{ seed: $seed, lines: $lines }
}
}
languages : List(Str)
languages = ["Roc", "Zig", "Rust", "JavaScript", "CSS"]import pf.Html
import pf.Solid exposing [create_signal!]
import charts.Format
import charts.ScatterChart
import Random
import Shuffle
## Birds measured, a dot for each: across by its wingspan, up by its weight: the charts page's
## `<ScatterChart>`. Other birds move each dot to its place; one not caught this time shrinks away,
## and one caught again swells back.
ScatterDemo := [].{
Catch : { seed : U64, birds : List({ label : Str, x : Dec, y : Dec }) }
view! : {} => Html
view! = |{}| {
(catch!, set_catch!) = create_signal!(ScatterDemo.catch(5))
(look!, set_look!) = create_signal!(Shuffle.first)
<Shuffle roll!={|| set_catch!(ScatterDemo.catch(catch!().seed))} look!={look!} set_look!={set_look!}>
<ScatterChart
data!={catch!().birds}
label="Birds, by wingspan and weight"
format_x={|cm| "${Format.num(cm, 0)} cm"}
format_y={|kg| "${Format.num(kg, 2)} kg"}
/>
</Shuffle>
}
## Birds caught and measured: each 15 to 190 cm across the wings, and 3 to 8 grams for each of
## those centimetres; one in seven not caught.
catch : U64 -> ScatterDemo.Catch
catch = |seed| {
var $seed = seed
var $birds = []
for kind in kinds {
span = Random.below($seed, 176)
heft = Random.below(span.seed, 6)
caught = Random.below(heft.seed, 7)
$seed = caught.seed
if caught.value > 0 {
cm = (15 + span.value).to_dec()
$birds = $birds.append({ label: kind, x: cm, y: cm * (3 + heft.value).to_dec() / 1000.0 })
}
}
{ seed: $seed, birds: $birds }
}
}
kinds : List(Str)
kinds = ["Robin", "Wren", "Finch", "Crow", "Owl", "Swift", "Heron", "Kite", "Gull", "Jay"]import pf.Html
import pf.Solid exposing [create_signal!]
import charts.Format
import charts.Heatmap
import Random
import Shuffle
## A week of commits, a row for each day and a column for each hour: the charts page's
## `<Heatmap>`. Another week recolours each cell, a CSS transition the browser plays.
HeatDemo := [].{
Week : { seed : U64, commits : List(List(Dec)) }
view! : {} => Html
view! = |{}| {
(week!, set_week!) = create_signal!(HeatDemo.week(9))
(look!, set_look!) = create_signal!(Shuffle.first)
<Shuffle roll!={|| set_week!(HeatDemo.week(week!().seed))} look!={look!} set_look!={set_look!}>
<Heatmap data!={week!().commits} rows={days} columns={hours} label="Commits in a week, by day and hour" format={|count| Format.num(count, 0)} />
</Shuffle>
}
## A week's commits: busy in working hours on weekdays, in the evening at the weekend, each
## hour somewhere from nothing to twice its usual.
week : U64 -> HeatDemo.Week
week = |seed| {
var $seed = seed
var $commits = []
for day in List.repeat(0, 7).map_with_index(|_, i| i) {
var $row = []
for hour in List.repeat(0, 24).map_with_index(|_, i| i) {
roll = Random.below($seed, 201)
$seed = roll.seed
$row = $row.append(Dec.round(usual(day, hour) * roll.value.to_dec() / 100.0))
}
$commits = $commits.append($row)
}
{ seed: $seed, commits: $commits }
}
}
## How many commits an hour usually has: weekdays (0 to 4) from nine to six, the weekend in the
## evening, a few at night.
usual : U64, U64 -> Dec
usual = |day, hour|
if day < 5 and hour >= 9 and hour < 18 {
if (hour == 12 or hour == 13) 5.0 else 9.0
} else if day >= 5 and hour >= 18 and hour < 23 {
6.0
} else if hour >= 7 and hour < 23 {
2.0
} else {
0.5
}
days : List(Str)
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
hours : List(Str)
hours = List.repeat(0, 24).map_with_index(|_, hour| "${hour.to_str()}:00")Styling, three ways#
Each chart is width: 100% (a donut and its legend share it, wrapping when narrow). Colours, lines and font come from CSS custom properties, falling back to the text's colour or a plain default. So a look is a few lines of CSS on any element around the charts. Neon, Blueprint and Paper are three: each one rule on the demo's stage, plus a prop or two the demo changes with it (the bars' padding, the line's smooth, the donut's thickness).
/* A newspaper's: ink on cream, a serif, a dotted grid, no area, flat colours. */
[data-look="paper"] {
background-color: #f4efe6;
color: #1d1b18;
font-family: Georgia, "Iowan Old Style", "Times New Roman", serif;
--chart-font: Georgia, "Iowan Old Style", "Times New Roman", serif;
--chart-color: #c8452c;
--chart-active: #7f2716;
--chart-grid: rgb(29 27 24 / 0.14);
--chart-axis: #1d1b18;
--chart-muted: #6b645a;
--chart-surface: #f4efe6;
--chart-radius: 0px;
--chart-grid-dash: 1 3;
--chart-line-width: 2;
--chart-area: 0;
--chart-dot: 5px;
--chart-1: #c8452c;
--chart-2: #1c63b8;
--chart-3: #c98a0b;
--chart-4: #8a4cb0;
--chart-5: #2f8a43;
--chart-heat-low: #f4efe6;
--chart-heat-high: #1c63b8;
--chart-up: #2f8a43;
--chart-down: #c8452c;
}| Property | Sets |
|---|---|
--chart-color, --chart-active | The colour of bars, lines and dots; the colour of a mark pointed at or focused, of the line chart's point and of the sparkline's last dot. A bar's own color comes first. |
--chart-1 to --chart-5 | The colours of a donut's slices, a stacked bar chart's series and a stacked area chart's bands. A colour stays with its slice or series; a band takes its place's. A slice's or a band's own color comes first. |
--chart-heat-low, --chart-heat-high | A heatmap's colours at zero and at the greatest value. |
--chart-fill, --chart-stroke, --chart-stroke-width, --chart-outline | The marks' fill opacity (a stacked area chart's bands 0.3 unless set) and outline. With --chart-outline: 1, a slice or a part is outlined in its own colour instead of the surface's. |
--chart-radius, --chart-dot, --chart-line-width, --chart-area | Bars' rounded corners, dots' radius, lines' width, and the shading under a line (0 for none). |
--chart-grid, --chart-grid-dash, --chart-axis, --chart-muted | The grid and its dashes, the axis, and the text of ticks and labels. |
--chart-surface, --chart-font, --chart-glow | The background behind the marks (it shows in the gaps between slices and parts), the font, and a filter on the marks (Neon's drop-shadow). |
The arithmetic#
The components draw with plain functions on no platform, which you can use for your own charts. Numbers are Dec, so the ticks from 0 to 1 are exactly 0.2, 0.4, 0.6 and 0.8. roc test packages/charts/main.roc runs their expects; the README lists every function.
| Module | What it does |
|---|---|
Scale | Scale.linear(domain, range) maps values to places: scale.at(value) is a place, scale.invert(place) a value. .nice(count) widens the domain to round numbers, .ticks(count) lists them, and Scale.extent(values) is the least and the greatest. Scale.strips(places, range) gives each place the stretch nearer it than its neighbours (how the line chart's pointer finds points). |
Band | Band.band(count, range, padding) gives a slot to each bar: .at(slot), .width(), .center(slot). A count and a slot may be fractions, as they are while a chart glides from seven bars to six. |
Ticks | About count ticks at 1, 2 or 5 times a power of ten. |
Path | SVG path data: line, smooth (monotone curves), area, smooth_area, and arc (a donut's slice). |
Format | Numbers as labels: num(x, places) ("2.5", not "2.50"), short ("1.3k"), percent, shares (whole percents that add up to 100, as a donut's legend says them), and coord (to hundredths, for SVG). |
Ease | toward(from, to, ms, close): one frame's step of a glide, which finishes once it is within close. |
Keys | What keeps a mark its own: unique (a key per label, Jan#1 for a second Jan), merge (the new keys, with the ones on their way out kept where they were), slots (a colour that stays with its key). |
Limits, for now#
- Values are
Dec, and Roc has noF64toDecconversion yet. Round to an integer and divide:(x * 1000.0).round_to_i64_try(), then.to_dec() / 1000.0. - Stacked bars have five colours, so a sixth series shares one, and so do a donut's sixth slice and a stacked area chart's sixth band unless the data gives them their colours: fold the smallest into "Other". When new data reorders a donut's slices, they jump rather than glide.
- Tab can't reach a heatmap's cells or a line chart's, stacked area chart's or sparkline's points; to a screen reader, each is one image, named by its label.
- A line chart's ticks along the bottom fall on round numbers of its
x: days since 1970 in steps of 1, 2, 5, 10 or 20, not each Monday or the first of each month. - rocx requires HTML tags in lower case, so SVG's camel-cased elements (
<linearGradient>,<clipPath>) can't be written yet.
The bar chart: packages/charts/components/BarChart.rocx
import pf.Html
import pf.Solid exposing [create_memo!, create_signal!, untrack!]
import pf.Transition
import charts.Band
import charts.Ease
import charts.Format
import charts.Keys
import charts.Scale
import charts.Ticks
## A bar for each of `data!`'s values, on an axis from zero (or the least value, when one is
## negative) to the greatest, widened to round numbers, with its ticks on round numbers too. When
## the data changes, the bars and the axis glide to where they go: Roc moves them each animation
## frame until they get there, and then asks for no more frames. A bar is its label's: one that
## comes grows out of the axis as the others make room, one whose label is gone shrinks into the
## axis as it fades (`transition:out`) while the others close up, and sorted, each slides to its
## place. Pointing at a bar, or reaching it with Tab, shows its value. A bar is in the colour the
## data gives it (`color`: any CSS colour, `"#c0392b"` or `"var(--brand)"`), which it keeps when
## pointed at, or, given none, the chart's (`--chart-color`, `--chart-active` when pointed at).
##
## `label` names the chart for screen readers, `format` writes a value (`Format.short` unless said,
## or `|mm| "${Format.num(mm, 0)} mm"`), and `padding` is the share of each bar's slot left empty
## (0.3 unless said).
BarChart := [].{
## A bar: what it is, how much, and its colour, the chart's own when left out.
Bar := { label : Str, value : Dec, color : Str ?? "" }.{
is_eq : _
}
## A bar and its key: its label, numbered when another bar before it has the same one.
Row : { key : Str, bar : BarChart.Bar }
## A bar as drawn: its value, and its slot (0 for the first), on their way to the data's.
Placed : { key : Str, value : Dec, slot : Dec }
## What is drawn: the bars, how many slots there are, and the axis's ends.
Drawn : { bars : List(BarChart.Placed), count : Dec, domain : (Dec, Dec) }
Props := { data! : () => List(BarChart.Bar), label : Str, format : (Dec -> Str) ?? Format.short, padding : Dec ?? 0.3 }
view! : Props => Html
view! = |props| {
data! = props.data!
format = props.format
rows! = create_memo!(|| BarChart.keyed(data!()))
goal! = create_memo!(|| BarChart.place(rows!()))
(drawn!, set_drawn!) = create_signal!(untrack!(goal!))
(hover!, set_hover!) = create_signal!(Err(None))
y! = create_memo!(|| Scale.linear(drawn!().domain, (bottom, top)))
x! = create_memo!(|| Band.band(drawn!().count, (left, right), props.padding))
placed! = |key| BarChart.placed(drawn!(), goal!(), key)
value! = |key| placed!(key).value
# A bar goes from the axis's zero to its value, up or down.
bar_top! = |key| Dec.min(y!().at(value!(key)), y!().at(0.0))
bar_height! = |key| Dec.abs(y!().at(value!(key)) - y!().at(0.0))
# Its value over its end: above a bar that goes up, below one that goes down.
value_y! = |key| if (value!(key) < 0.0) bar_top!(key) + bar_height!(key) + 18.0 else bar_top!(key) - 8.0
<figure class="bar-chart">
<svg viewBox="0 0 640 320" role="group" aria-label={props.label}>
<g class="ticks" aria-hidden="true">
{...BarChart.ticks(goal!()).map(|tick|
<g key={Format.num(tick, 9)} class:out={BarChart.outside(drawn!().domain, tick)}>
<line x1={Format.coord(left)} x2={Format.coord(right)} y1={Format.coord(y!().at(tick))} y2={Format.coord(y!().at(tick))} />
<text x={Format.coord(left - 8.0)} y={Format.coord(y!().at(tick))} dy="0.32em">{format(tick)}</text>
</g>
)}
</g>
{...rows!().map(|row|
<g key={row.key}
class="bar"
class:active={hover!() == Ok(row.key)}
style:--chart-color={row.bar.color}
style:--chart-active={row.bar.color}
role="img"
tabindex="0"
aria-label={"${row.bar.label}: ${format(row.bar.value)}"}
on:pointerenter={|| set_hover!(Ok(row.key))}
on:pointerleave={|| set_hover!(Err(None))}
on:focus={|| set_hover!(Ok(row.key))}
on:blur={|| set_hover!(Err(None))}
>
{# Gone from the data, it shrinks into the axis as it fades. }
<rect
x={Format.coord(x!().at(placed!(row.key).slot))}
y={Format.coord(bar_top!(row.key))}
width={Format.coord(x!().width())}
height={Format.coord(bar_height!(row.key))}
rx="3"
transition:out={Transition.grow(if (row.bar.value < 0.0) Top else Bottom).plus(Transition.fade)}
/>
<text class="value" x={Format.coord(x!().center(placed!(row.key).slot))} y={Format.coord(value_y!(row.key))}>{format(row.bar.value)}</text>
<text class="label" x={Format.coord(x!().center(placed!(row.key).slot))} y={Format.coord(bottom + 20.0)} transition={Transition.fade}>{row.bar.label}</text>
</g>
)}
<line class="axis" x1={Format.coord(left)} x2={Format.coord(right)} y1={Format.coord(y!().at(0.0))} y2={Format.coord(y!().at(0.0))} />
</svg>
{# Frames only while something moves: once the bars are where the data says, none. }
{if drawn!() != goal!() {
<span hidden on:frame.ms={|ms| set_drawn!(BarChart.glide(drawn!(), goal!(), ms))}></span>
}}
</figure>
}
## Each bar with its key: its label, or, after the first bar with that label, the label numbered
## (`Jan#1`), so each bar keeps a row of its own.
keyed : List(BarChart.Bar) -> List(BarChart.Row)
keyed = |bars| List.map2(Keys.unique(bars.map(|bar| bar.label)), bars, |key, bar| { key, bar })
## Where the bars go: each to its value, in its slot, on an axis from zero (or below it) to the
## greatest value, widened to round numbers.
place : List(BarChart.Row) -> BarChart.Drawn
place = |rows| {
values = rows.map(|row| row.bar.value)
(low, high) = Scale.extent(values)
from = Dec.min(low, 0.0)
to = Dec.max(high, 0.0)
domain =
if from == to {
(0.0, 1.0)
} else {
Ticks.nice(from, to, tick_count)
}
{
bars: rows.map_with_index(|row, i| { key: row.key, value: row.bar.value, slot: i.to_dec() }),
count: rows.len().to_dec(),
domain,
}
}
## Where the bar with `key` is drawn now: as drawn, or, not drawn yet, at zero in its slot.
placed : BarChart.Drawn, BarChart.Drawn, Str -> BarChart.Placed
placed = |drawn, goal, key|
match drawn.bars.find_first(|bar| bar.key == key) {
Ok(bar) => bar
Err(_) => {
slot = goal.bars.find_first(|bar| bar.key == key).map_ok(|bar| bar.slot) ?? 0.0
{ key, value: 0.0, slot }
}
}
## A frame's way from `drawn` toward `goal`. A bar that is new starts at zero in its slot, and
## the slots make room for it; one that has gone is gone from here at once (its row shrinks it
## into the axis), and the slots close up.
glide : BarChart.Drawn, BarChart.Drawn, F64 -> BarChart.Drawn
glide = |drawn, goal, ms| {
(d0, d1) = drawn.domain
(g0, g1) = goal.domain
# Within a five-hundredth of the axis is there: under a pixel. So is a hundredth of a slot.
close = (g1 - g0) / 500.0
near = 0.01
{
bars: goal.bars.map(
|bar| {
from = BarChart.placed(drawn, goal, bar.key)
{ key: bar.key, value: Ease.toward(from.value, bar.value, ms, close), slot: Ease.toward(from.slot, bar.slot, ms, near) }
},
),
count: Ease.toward(drawn.count, goal.count, ms, near),
domain: (Ease.toward(d0, g0, ms, close), Ease.toward(d1, g1, ms, close)),
}
}
## The axis's ticks.
ticks : BarChart.Drawn -> List(Dec)
ticks = |drawn| {
(from, to) = drawn.domain
Ticks.between(from, to, tick_count)
}
## Whether a tick is off the axis as drawn: one the axis is gliding toward, faded until it is on.
outside : (Dec, Dec), Dec -> Bool
outside = |(from, to), tick| tick < Dec.min(from, to) or tick > Dec.max(from, to)
<style>
.bar-chart {
margin: 0;
}
svg {
display: block;
width: 100%;
height: auto;
overflow: visible;
font: 12px/1 var(--chart-font, inherit);
}
.ticks line {
stroke: var(--chart-grid, color-mix(in srgb, currentColor 12%, transparent));
stroke-dasharray: var(--chart-grid-dash, none);
}
.ticks g {
transition: opacity 0.2s;
}
.ticks .out {
opacity: 0;
}
.ticks text {
fill: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
text-anchor: end;
font-variant-numeric: tabular-nums;
}
.axis {
stroke: var(--chart-axis, color-mix(in srgb, currentColor 45%, transparent));
}
.bar {
outline: none;
cursor: default;
}
.bar rect {
fill: var(--chart-color, #4f6bed);
fill-opacity: var(--chart-fill, 1);
stroke: var(--chart-stroke, none);
stroke-width: var(--chart-stroke-width, 0);
rx: var(--chart-radius, 3px);
filter: var(--chart-glow, none);
transition: fill 0.15s, fill-opacity 0.15s;
}
.bar.active rect {
fill: var(--chart-active, #2f49c4);
fill-opacity: 1;
}
.bar:focus-visible rect {
stroke: var(--chart-active, #2f49c4);
stroke-width: 2;
}
.bar text {
text-anchor: middle;
fill: currentColor;
}
.bar .label {
fill: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
}
.bar .value {
font-weight: 600;
opacity: 0;
transition: opacity 0.15s;
font-variant-numeric: tabular-nums;
}
.bar.active .value {
opacity: 1;
}
</style>
}
## The plot's edges in the SVG's units (640 by 320): room on the left for the ticks' labels, and
## below for the bars'.
left : Dec
left = 48.0
right : Dec
right = 632.0
top : Dec
top = 16.0
bottom : Dec
bottom = 288.0
tick_count : U64
tick_count = 5
# A bar's colour comes with it from the data; one given none is "".
expect BarChart.keyed([{ label: "Jan", value: 3.0, color: "#7d59dc" }, { label: "Feb", value: 1.0 }]).map(|row| row.bar.color) == ["#7d59dc", ""]The line chart: packages/charts/components/LineChart.rocx
import pf.Html
import pf.Solid exposing [create_memo!, create_signal!, untrack!]
import charts.Ease
import charts.Format
import charts.Path
import charts.Scale
import charts.Ticks
## A line through `data!`'s points, left to right: each across by its `x` (a number: a day, an
## hour, a time in milliseconds), to scale, and up by its `y`, the area under it shaded. The axis up
## the side runs around the values, widened to round numbers; the one along the bottom runs from
## the least `x` to the greatest, its ticks on round numbers. `LineChart.evenly(values)` puts values one
## apart. With `smooth`, the line curves through the points, and never past one (a monotone curve).
## When the data changes, the line glides to it, and the axes' ends with it, a frame at a time; once
## they are there, nothing runs. Pointing along the chart shows the point nearest the pointer: its
## value over the plot, and its `x` on the axis along the bottom.
##
## `label` names the chart for screen readers, `format` writes a value and `format_x` an `x` (each
## `Format.short` unless said), and `smooth` is off unless said.
LineChart := [].{
## A point: across (`x`) and up (`y`).
Point : { x : Dec, y : Dec }
## What is drawn: the points, and the axes' ends, on their way to the data's.
Drawn : { points : List(LineChart.Point), across : (Dec, Dec), up : (Dec, Dec) }
Props := { data! : () => List(LineChart.Point), label : Str, format : (Dec -> Str) ?? Format.short, format_x : (Dec -> Str) ?? Format.short, smooth : Bool ?? Bool.False }
view! : Props => Html
view! = |{ data!, label, format, format_x, smooth }| {
goal! = create_memo!(|| LineChart.place(data!()))
(drawn!, set_drawn!) = create_signal!(untrack!(goal!))
(hover!, set_hover!) = create_signal!(Err(None))
x! = create_memo!(|| Scale.linear(drawn!().across, (left, right)))
y! = create_memo!(|| Scale.linear(drawn!().up, (bottom, top)))
places! = create_memo!(
|| {
(across, up) = (x!(), y!())
drawn!().points.map(|point| (across.at(point.x), up.at(point.y)))
},
)
# The stretch of the plot nearer each point than the others, which the pointer finds it by:
# where the data puts the points, so a line gliding to new values doesn't move them.
strips! = create_memo!(|| LineChart.strips(goal!()))
# The point pointed at: where it is drawn, and the data's point.
spot! = || {
index = match hover!() {
Ok(i) => i
Err(_) => data!().len()
}
match (places!().get(index), data!().get(index)) {
(Ok(at), Ok(point)) => Ok((at, point))
_ => Err(None)
}
}
spotted! = || {
match spot!() {
Ok(_) => Bool.True
Err(_) => Bool.False
}
}
spot_x! = || {
match spot!() {
Ok(((px, _), _)) => px
Err(_) => left
}
}
spot_y! = || {
match spot!() {
Ok(((_, py), _)) => py
Err(_) => bottom
}
}
spot_text! = |write|
match spot!() {
Ok((_, point)) => write(point)
Err(_) => ""
}
<figure class="line-chart">
<svg viewBox="0 0 640 320" role="img" aria-label={label}>
<g class="ticks" class:spotting={spotted!()} aria-hidden="true">
{...LineChart.ticks(goal!().up).map(|tick|
<g key={Format.num(tick, 9)} class:out={LineChart.outside(drawn!().up, tick)}>
<line x1={Format.coord(left)} x2={Format.coord(right)} y1={Format.coord(y!().at(tick))} y2={Format.coord(y!().at(tick))} />
<text class="up" x={Format.coord(left - 8.0)} y={Format.coord(y!().at(tick))} dy="0.32em">{format(tick)}</text>
</g>
)}
{...LineChart.ticks(goal!().across).map(|tick|
<g key={Format.num(tick, 9)} class:out={LineChart.outside(drawn!().across, tick)}>
<text class="across" x={Format.coord(x!().at(tick))} y={Format.coord(bottom + 20.0)}>{format_x(tick)}</text>
</g>
)}
</g>
<path class="area" d={if (smooth) Path.smooth_area(places!(), bottom) else Path.area(places!(), bottom)} />
<path class="line" d={if (smooth) Path.smooth(places!()) else Path.line(places!())} />
<g class="spot" class:shown={spotted!()} aria-hidden="true">
<line x1={Format.coord(spot_x!())} x2={Format.coord(spot_x!())} y1={Format.coord(top)} y2={Format.coord(bottom)} />
<circle cx={Format.coord(spot_x!())} cy={Format.coord(spot_y!())} r="4.5" />
<text x={Format.coord(spot_x!())} y={Format.coord(top - 8.0)}>{spot_text!(|point| format(point.y))}</text>
<text x={Format.coord(spot_x!())} y={Format.coord(bottom + 20.0)}>{spot_text!(|point| format_x(point.x))}</text>
</g>
</svg>
{# A strip of the plot for each point, which the pointer finds it by, from top to bottom. }
<div class="strips" on:pointerleave={|| set_hover!(Err(None))}>
{...strips!().map_with_index(|(from, to), i|
<span key={i} style:left={share(from - left)} style:width={share(to - from)} on:pointerenter={|| set_hover!(Ok(i))}></span>
)}
</div>
{# Frames only while something moves: once the line and the axes are where the data says, none. }
{if drawn!() != goal!() {
<span hidden on:frame.ms={|ms| set_drawn!(LineChart.glide(drawn!(), goal!(), ms))}></span>
}}
</figure>
}
## `values`, one apart: the first at `x` 0, the next at 1, and so on. For values evenly spaced
## (each hour of a day): `data!={LineChart.evenly(visits!())}`.
evenly : List(Dec) -> List(LineChart.Point)
evenly = |values| values.map_with_index(|value, i| { x: i.to_dec(), y: value })
## Where the data puts the line: its points, the axis along the bottom from the least `x` to the
## greatest, and the one up the side around the values (`domain`).
place : List(LineChart.Point) -> LineChart.Drawn
place = |points| {
points,
across: Scale.extent(points.map(|point| point.x)),
up: LineChart.domain(points.map(|point| point.y)),
}
## The axis up the side's ends: the least and the greatest value, widened to round numbers.
domain : List(Dec) -> (Dec, Dec)
domain = |values| {
(low, high) = Scale.extent(values)
if low == high {
(low - 1.0, high + 1.0)
} else {
Ticks.nice(low, high, tick_count)
}
}
## The stretch of the plot nearer each of `goal`'s points than the others, in the SVG's units:
## from halfway to the point before to halfway to the one after, the first from the plot's left
## edge and the last to its right.
strips : LineChart.Drawn -> List((Dec, Dec))
strips = |goal| {
across = Scale.linear(goal.across, (left, right))
Scale.strips(goal.points.map(|point| across.at(point.x)), (left, right))
}
## A frame's way from what is drawn toward the data: each point toward its own, and the axes'
## ends toward theirs. When there are more points or fewer, the line is the data's at once.
glide : LineChart.Drawn, LineChart.Drawn, F64 -> LineChart.Drawn
glide = |drawn, goal, ms| {
(a0, a1) = drawn.across
(ga0, ga1) = goal.across
(u0, u1) = drawn.up
(gu0, gu1) = goal.up
# Within a five-hundredth of an axis is there: under a pixel.
near_x = (ga1 - ga0) / 500.0
near_y = (gu1 - gu0) / 500.0
points =
if drawn.points.len() == goal.points.len() {
List.map2(drawn.points, goal.points, |from, to| { x: Ease.toward(from.x, to.x, ms, near_x), y: Ease.toward(from.y, to.y, ms, near_y) })
} else {
goal.points
}
{
points,
across: (Ease.toward(a0, ga0, ms, near_x), Ease.toward(a1, ga1, ms, near_x)),
up: (Ease.toward(u0, gu0, ms, near_y), Ease.toward(u1, gu1, ms, near_y)),
}
}
## An axis's ticks.
ticks : (Dec, Dec) -> List(Dec)
ticks = |(from, to)| Ticks.between(from, to, tick_count)
## Whether a tick is off its axis as drawn: one the axis is gliding toward, faded until it is on.
outside : (Dec, Dec), Dec -> Bool
outside = |(from, to), tick| tick < Dec.min(from, to) or tick > Dec.max(from, to)
<style>
.line-chart {
position: relative;
margin: 0;
}
svg {
display: block;
width: 100%;
height: auto;
overflow: visible;
font: 12px/1 var(--chart-font, inherit);
}
.ticks line {
stroke: var(--chart-grid, color-mix(in srgb, currentColor 12%, transparent));
stroke-dasharray: var(--chart-grid-dash, none);
}
.ticks g {
transition: opacity 0.2s;
}
.ticks .out {
opacity: 0;
}
.ticks text {
fill: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
font-variant-numeric: tabular-nums;
}
.ticks .up {
text-anchor: end;
}
.ticks .across {
text-anchor: middle;
transition: opacity 0.15s;
}
/* The point's own `x` takes the axis's place while one is pointed at. */
.ticks.spotting .across {
opacity: 0;
}
.line {
fill: none;
stroke: var(--chart-color, #4f6bed);
stroke-width: var(--chart-line-width, 2.5);
filter: var(--chart-glow, none);
stroke-linejoin: round;
stroke-linecap: round;
}
.area {
fill: var(--chart-color, #4f6bed);
opacity: var(--chart-area, 0.12);
}
.spot {
opacity: 0;
transition: opacity 0.15s;
pointer-events: none;
}
.spot.shown {
opacity: 1;
}
.spot line {
stroke: var(--chart-axis, color-mix(in srgb, currentColor 45%, transparent));
stroke-dasharray: 3 3;
}
.spot circle {
fill: var(--chart-active, #2f49c4);
stroke: var(--chart-surface, white);
stroke-width: 2;
}
.spot text {
text-anchor: middle;
font-weight: 600;
fill: currentColor;
font-variant-numeric: tabular-nums;
}
/* Over the plot (48 to 620 of the SVG's 640 across, 24 to 288 of its 320 down); each strip
placed across by Roc, in shares of the plot's width. */
.strips {
position: absolute;
top: 7.5%;
bottom: 10%;
left: 7.5%;
right: 3.125%;
}
.strips span {
position: absolute;
top: 0;
bottom: 0;
}
</style>
}
## The plot's edges in the SVG's units (640 by 320): room on the left for the values' ticks, below
## for the ones across, and on the right for the last one's label.
left : Dec
left = 48.0
right : Dec
right = 620.0
top : Dec
top = 24.0
bottom : Dec
bottom = 288.0
tick_count : U64
tick_count = 5
## A length across, in the SVG's units, as a share of the plot's width: `"50%"` for 286.
share : Dec -> Str
share = |x| "${Format.num(x * 100.0 / (right - left), 3)}%"The donut chart: packages/charts/components/DonutChart.rocx
import pf.Html
import pf.Solid exposing [create_memo!, create_signal!, untrack!]
import pf.Transition
import charts.Ease
import charts.Format
import charts.Keys
import charts.Path
## A ring cut into a slice for each of `data!`'s values, each as big a share of the ring as its
## value is of them all (a value too small to see still a sliver), and a legend beside it: each
## slice's colour, label, value and share, in whole percents that add up to 100 ("<1%" for one too
## small to make one). The middle says the total, or, while a slice or its line in the legend is
## pointed at or focused, that slice's share. When the data changes, the slices glide to their new
## sizes, a frame at a time: a new one grows from nothing, one whose label is gone shrinks to
## nothing where it was, and once they are there, nothing runs.
##
## A slice is its label's, in the colour the data gives it (`color`: any CSS colour,
## `"#c0392b"` or `"var(--brand)"`), or, given none, in one of the chart's five (`--chart-1` to
## `--chart-5`), which it keeps while others come and go, so a sixth slice shares one; fold the
## smallest into "Other".
## `label` names the chart for screen readers, `format` writes a value (`Format.short` unless
## said), `total` is the word under the total ("Total" unless said), and `thickness` is the ring's,
## in the SVG's units, of its 150 radius (52 unless said; 150 is a pie).
DonutChart := [].{
## A slice of the ring: what it is, how much, and its colour, the chart's own when left out.
Slice := { label : Str, value : Dec, color : Str ?? "" }.{
is_eq : _
}
## A slice and its key: its label, numbered when another slice before it has the same one.
Row : { key : Str, slice : DonutChart.Slice }
## A slice as drawn: its value, on its way to the data's, and the colour it was given ("" for
## the chart's own), which one that is going keeps while it shrinks.
Placed : { key : Str, value : Dec, color : Str }
## What is drawn: the slices, in the ring's order (one that is going too, until it has shrunk
## to nothing), and each slice's colour.
Drawn : { slices : List(DonutChart.Placed), slots : List((Str, U64)) }
## Where a slice is drawn, in turns: 0 is twelve o'clock, 1 all the way round.
Arc : { key : Str, from : Dec, to : Dec }
Props := { data! : () => List(DonutChart.Slice), label : Str, format : (Dec -> Str) ?? Format.short, total : Str ?? "Total", thickness : Dec ?? 52.0 }
view! : Props => Html
view! = |props| {
data! = props.data!
format = props.format
rows! = create_memo!(|| DonutChart.keyed(data!()))
goal! = create_memo!(|| DonutChart.visible(rows!().map(|row| { key: row.key, value: Dec.max(row.slice.value, 0.0), color: row.slice.color })))
(drawn!, set_drawn!) = create_signal!(untrack!(|| { slices: goal!(), slots: Keys.slots([], goal!().map(|slice| slice.key)) }))
(hover!, set_hover!) = create_signal!(Err(None))
# The slices drawn: the data's, and each that is going until it has shrunk to nothing.
keys! = create_memo!(|| Keys.merge(drawn!().slices.map(|slice| slice.key), goal!().map(|slice| slice.key)))
slots! = create_memo!(|| Keys.slots(drawn!().slots, keys!()))
arcs! = create_memo!(|| DonutChart.arcs(drawn!().slices))
total! = create_memo!(|| rows!().fold(0.0, |sum, row| sum + Dec.max(row.slice.value, 0.0)))
slot! = |key| (Keys.slot_of(slots!(), key) % colors).to_str()
shares! = create_memo!(|| DonutChart.shares(rows!().map(|row| row.slice.value)))
share_of! = |key| {
said = shares!()
rows!().find_first_index(|row| row.key == key).map_ok(|at| said.get(at) ?? "") ?? ""
}
said! = |row| "${row.slice.label}: ${format(row.slice.value)}, ${share_of!(row.key)}"
row_of! = |key| rows!().find_first(|row| row.key == key)
# The middle: the slice pointed at, or the total.
pointed! = || {
at = hover!()
rows!().find_first(|row| at == Ok(row.key))
}
big! = ||
match pointed!() {
Ok(row) => share_of!(row.key)
Err(_) => format(total!())
}
small! = ||
match pointed!() {
Ok(row) => row.slice.label
Err(_) => props.total
}
<figure class="donut-chart">
<svg viewBox="0 0 320 320" role="group" aria-label={props.label}>
{...keys!().map(|key|
<path key={key}
class="slice"
class:active={hover!() == Ok(key)}
data-slot={slot!(key)}
style:--slice={color_of(drawn!().slices, key)}
d={DonutChart.path(arcs!(), key, Dec.max(outer - props.thickness, 0.0))}
role="img"
tabindex="0"
aria-label={
match row_of!(key) {
Ok(row) => said!(row)
Err(_) => key
}
}
on:pointerenter={|| set_hover!(Ok(key))}
on:pointerleave={|| set_hover!(Err(None))}
on:focus={|| set_hover!(Ok(key))}
on:blur={|| set_hover!(Err(None))}
/>
)}
{# The middle, when the ring leaves room for it: a pie has none. }
<g class="middle" class:gone={props.thickness > 90.0} aria-hidden="true">
<text class="big" x="160" y="160">{big!()}</text>
<text class="small" x="160" y="160" dy="1.9em">{small!()}</text>
</g>
</svg>
<ul class="legend" aria-hidden="true">
{...rows!().map(|row|
<li key={row.key}
class:active={hover!() == Ok(row.key)}
data-slot={slot!(row.key)}
style:--slice={row.slice.color}
on:pointerenter={|| set_hover!(Ok(row.key))}
on:pointerleave={|| set_hover!(Err(None))}
transition={Transition.fade}
>
<span class="swatch"></span>
<span class="name">{row.slice.label}</span>
<span class="amount">{format(row.slice.value)}</span>
<span class="share">{share_of!(row.key)}</span>
</li>
)}
</ul>
{# Frames only while something moves: once the slices are where the data says, none. }
{if drawn!().slices != goal!() {
<span hidden on:frame.ms={|ms| set_drawn!(DonutChart.glide(drawn!(), goal!(), ms))}></span>
}}
</figure>
}
## Each slice with its key: its label, or, after the first slice with that label, the label
## numbered (`Other#1`), so each slice keeps a row of its own.
keyed : List(DonutChart.Slice) -> List(DonutChart.Row)
keyed = |slices| List.map2(Keys.unique(slices.map(|slice| slice.label)), slices, |key, slice| { key, slice })
## Where each slice is drawn: the ring shared out by value, in order. All of them nothing is no
## ring at all.
arcs : List(DonutChart.Placed) -> List(DonutChart.Arc)
arcs = |slices| {
total = slices.fold(0.0, |sum, slice| sum + slice.value)
var $at = 0.0
var $arcs = []
for slice in slices {
share = if (total > 0.0) slice.value / total else 0.0
$arcs = $arcs.append({ key: slice.key, from: $at, to: $at + share })
$at = $at + share
}
$arcs
}
## The slices as drawn: each with something at least a sliver of the ring (`least`), so a value
## too small to see still shows, the others making room.
visible : List(DonutChart.Placed) -> List(DonutChart.Placed)
visible = |slices| {
total = slices.fold(0.0, |sum, slice| sum + slice.value)
slices.map(|slice| if (slice.value > 0.0) { ..slice, value: Dec.max(slice.value, total * least) } else slice)
}
## Each value's share of them all, as whole percents that add up to 100 (`Format.shares`):
## what the legend, the middle and each slice's accessible name say.
shares : List(Dec) -> List(Str)
shares = |values| Format.shares(values)
## The slice with `key`'s path: nothing until it is drawn.
path : List(DonutChart.Arc), Str, Dec -> Str
path = |drawn, key, inner|
match drawn.find_first(|arc| arc.key == key) {
Ok(arc) => Path.arc({ x: 160.0, y: 160.0, inner, outer, from: arc.from, to: arc.to })
Err(_) => ""
}
## A frame's way from `drawn` toward `goal`: each slice's value toward its own, and at once to
## its colour. A new slice starts at nothing; one that has gone shrinks to nothing where it was,
## in the colour it had, and then is gone.
glide : DonutChart.Drawn, List(DonutChart.Placed), F64 -> DonutChart.Drawn
glide = |drawn, goal, ms| {
keys = goal.map(|slice| slice.key)
# Within a thousandth of the whole is there: under a pixel round the ring.
close = goal.fold(0.0, |sum, slice| sum + slice.value) / 1000.0
var $slices = []
for key in Keys.merge(drawn.slices.map(|slice| slice.key), keys) {
was = value_of(drawn.slices, key)
next = Ease.toward(was, value_of(goal, key), ms, close)
if next != 0.0 or keys.contains(key) {
color = goal.find_first(|slice| slice.key == key).map_ok(|slice| slice.color) ?? color_of(drawn.slices, key)
$slices = $slices.append({ key, value: next, color })
}
}
{ slices: $slices, slots: Keys.slots(drawn.slots, $slices.map(|slice| slice.key)) }
}
<style>
/* The ring and its legend share a row; in a narrow box the legend wraps under it and the
ring is centred over it (the legend grows, so on one row this moves nothing). */
.donut-chart {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 1.5rem 2rem;
margin: 0;
}
svg {
display: block;
flex: 0 1 280px;
min-width: 200px;
height: auto;
overflow: visible;
font: 12px/1 var(--chart-font, inherit);
}
[data-slot="0"] {
--slice: var(--chart-1, #2a78d6);
}
[data-slot="1"] {
--slice: var(--chart-2, #eb6834);
}
[data-slot="2"] {
--slice: var(--chart-3, #1baf7a);
}
[data-slot="3"] {
--slice: var(--chart-4, #eda100);
}
[data-slot="4"] {
--slice: var(--chart-5, #e87ba4);
}
/* A gap of the surface's colour between slices; outlined (`--chart-outline: 1`), the slice's. */
.slice {
fill: var(--slice);
fill-opacity: var(--chart-fill, 1);
stroke: color-mix(in srgb, var(--slice) calc(var(--chart-outline, 0) * 100%), var(--chart-surface, white));
stroke-width: var(--chart-stroke-width, 2);
stroke-linejoin: round;
outline: none;
transform-box: view-box;
transform-origin: 160px 160px;
transition: fill 0.3s, opacity 0.15s, scale 0.15s;
}
svg:has(.active) .slice:not(.active) {
opacity: 0.45;
}
.slice.active {
scale: 1.04;
}
.slice:focus-visible {
stroke: var(--chart-active, currentColor);
}
.gone {
display: none;
}
.big {
text-anchor: middle;
font-size: 34px;
font-weight: 700;
fill: currentColor;
font-variant-numeric: tabular-nums;
}
.small {
text-anchor: middle;
font-size: 14px;
fill: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
}
.legend {
display: grid;
flex: 1 1 220px;
grid-template-columns: auto minmax(0, 1fr) auto auto;
gap: 0.15rem 0.75rem;
margin: 0;
padding: 0;
list-style: none;
font-variant-numeric: tabular-nums;
}
.legend li {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
align-items: center;
padding: 0.3rem 0.5rem;
border-radius: 6px;
transition: background 0.15s;
}
.legend li.active {
background: color-mix(in srgb, currentColor 8%, transparent);
}
.swatch {
width: 0.75rem;
height: 0.75rem;
border-radius: 3px;
background: var(--slice);
transition: background 0.3s;
}
.amount,
.share {
text-align: right;
}
.share {
color: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
}
</style>
}
## The ring's outer radius, around the middle of the SVG's 320 by 320: a slice is the band from
## there to `thickness` inside it, or, as thick as that or more, a pie's slice.
outer : Dec
outer = 150.0
## The least share of the ring a slice with something is drawn at, in turns: a sliver that can be
## seen.
least : Dec
least = 0.01
## How many colours the slices have (`--chart-1` to `--chart-5`).
colors : U64
colors = 5
## The value of the slice with `key`: nothing when there is none.
value_of : List(DonutChart.Placed), Str -> Dec
value_of = |slices, key| slices.find_first(|slice| slice.key == key).map_ok(|slice| slice.value) ?? 0.0
## The colour the slice with `key` was given: "" (the chart's own) when none, or there is no such slice.
color_of : List(DonutChart.Placed), Str -> Str
color_of = |slices, key| slices.find_first(|slice| slice.key == key).map_ok(|slice| slice.color) ?? ""
# A slice's colour comes with it from the data; one given none is "".
expect DonutChart.keyed([{ label: "Roc", value: 3.0, color: "#7d59dc" }, { label: "Zig", value: 1.0 }]).map(|row| row.slice.color) == ["#7d59dc", ""]
# A colour is taken at once; a slice that is going keeps its own while it shrinks.
expect {
drawn = { slices: [{ key: "Roc", value: 3.0, color: "#7d59dc" }, { key: "Zig", value: 1.0, color: "orange" }], slots: [] }
next = DonutChart.glide(drawn, [{ key: "Roc", value: 3.0, color: "purple" }], 16.0)
next.slices.map(|slice| slice.color) == ["purple", "orange"]
}
# The legend's shares are Format.shares': whole percents that add up to 100, "<1%" for a sliver.
expect DonutChart.shares([2.0, 1.0, 1989.0]) == ["<1%", "<1%", "100%"]
# A value too small to see is drawn as a sliver; nothing stays nothing.
expect DonutChart.visible([{ key: "a", value: 1.0, color: "" }, { key: "b", value: 999.0, color: "" }, { key: "c", value: 0.0, color: "" }]).map(|slice| slice.value) == [10.0, 999.0, 0.0]The scatter chart: packages/charts/components/ScatterChart.rocx
import pf.Html
import pf.Solid exposing [create_memo!, create_signal!, untrack!]
import pf.Transition
import charts.Ease
import charts.Format
import charts.Keys
import charts.Scale
import charts.Ticks
## A dot for each of `data!`'s points, across by its `x` and up by its `y`, on two axes around them
## widened to round numbers. When the data changes, the dots and the axes glide to where they go,
## a frame at a time: a dot is its label's, so a new `x` or `y` moves it; a new one swells from
## nothing where it goes, and one whose label is gone shrinks to nothing as it fades. Once they
## are there, nothing runs. Pointing at a dot, or reaching it with Tab, shows its label and values.
##
## `label` names the chart for screen readers; `format_x` and `format_y` write the values across
## and up (`Format.short` unless said).
ScatterChart := [].{
## A dot: its label, across (`x`) and up (`y`).
Dot : { label : Str, x : Dec, y : Dec }
## A dot and its key: its label, numbered when another dot before it has the same one.
Row : { key : Str, dot : ScatterChart.Dot }
## A dot as drawn, on its way to the data's place for it.
Placed : { key : Str, x : Dec, y : Dec }
## What is drawn: the dots, and the axes' ends.
Drawn : { dots : List(ScatterChart.Placed), across : (Dec, Dec), up : (Dec, Dec) }
Props := { data! : () => List(ScatterChart.Dot), label : Str, format_x : (Dec -> Str) ?? Format.short, format_y : (Dec -> Str) ?? Format.short }
view! : Props => Html
view! = |{ data!, label, format_x, format_y }| {
rows! = create_memo!(|| ScatterChart.keyed(data!()))
goal! = create_memo!(|| ScatterChart.place(rows!()))
(drawn!, set_drawn!) = create_signal!(untrack!(goal!))
(hover!, set_hover!) = create_signal!(Err(None))
x! = create_memo!(|| Scale.linear(drawn!().across, (left, right)))
y! = create_memo!(|| Scale.linear(drawn!().up, (bottom, top)))
placed! = |key| ScatterChart.placed(drawn!(), goal!(), key)
dot_x! = |key| x!().at(placed!(key).x)
dot_y! = |key| y!().at(placed!(key).y)
said! = |dot| "${dot.label}: ${format_x(dot.x)}, ${format_y(dot.y)}"
# The dot pointed at: its label and values, over it.
pointed! = || {
at = hover!()
rows!().find_first(|row| at == Ok(row.key))
}
spot! = |at|
match pointed!() {
Ok(row) => at(row)
Err(_) => 0.0
}
<figure class="scatter-chart">
<svg viewBox="0 0 640 320" role="group" aria-label={label}>
<g class="ticks" aria-hidden="true">
{...Ticks.between(goal!().up.0, goal!().up.1, tick_count).map(|tick|
<g key={Format.num(tick, 9)} class:out={ScatterChart.outside(drawn!().up, tick)}>
<line x1={Format.coord(left)} x2={Format.coord(right)} y1={Format.coord(y!().at(tick))} y2={Format.coord(y!().at(tick))} />
<text class="up" x={Format.coord(left - 8.0)} y={Format.coord(y!().at(tick))} dy="0.32em">{format_y(tick)}</text>
</g>
)}
{...Ticks.between(goal!().across.0, goal!().across.1, tick_count).map(|tick|
<g key={Format.num(tick, 9)} class:out={ScatterChart.outside(drawn!().across, tick)}>
<line x1={Format.coord(x!().at(tick))} x2={Format.coord(x!().at(tick))} y1={Format.coord(top)} y2={Format.coord(bottom)} />
<text class="across" x={Format.coord(x!().at(tick))} y={Format.coord(bottom + 20.0)}>{format_x(tick)}</text>
</g>
)}
</g>
{...rows!().map(|row|
<circle key={row.key}
class="dot"
class:active={hover!() == Ok(row.key)}
cx={Format.coord(dot_x!(row.key))}
cy={Format.coord(dot_y!(row.key))}
r="6"
role="img"
tabindex="0"
aria-label={said!(row.dot)}
on:pointerenter={|| set_hover!(Ok(row.key))}
on:pointerleave={|| set_hover!(Err(None))}
on:focus={|| set_hover!(Ok(row.key))}
on:blur={|| set_hover!(Err(None))}
transition={Transition.scale(0.0)}
/>
)}
<text
class="spot"
class:shown={hover!() != Err(None)}
x={Format.coord(spot!(|row| dot_x!(row.key)))}
y={Format.coord(spot!(|row| dot_y!(row.key)) - 14.0)}
aria-hidden="true"
>
{match pointed!() {
Ok(row) => said!(row.dot)
Err(_) => ""
}}
</text>
</svg>
{# Frames only while something moves: once the dots are where the data says, none. }
{if drawn!() != goal!() {
<span hidden on:frame.ms={|ms| set_drawn!(ScatterChart.glide(drawn!(), goal!(), ms))}></span>
}}
</figure>
}
## Each dot with its key: its label, or, after the first dot with that label, the label
## numbered (`Wren#1`), so each dot keeps a row of its own.
keyed : List(ScatterChart.Dot) -> List(ScatterChart.Row)
keyed = |dots| List.map2(Keys.unique(dots.map(|dot| dot.label)), dots, |key, dot| { key, dot })
## Where the dots go, on axes from the least value to the greatest, widened to round numbers.
place : List(ScatterChart.Row) -> ScatterChart.Drawn
place = |rows| {
{
dots: rows.map(|row| { key: row.key, x: row.dot.x, y: row.dot.y }),
across: ends(rows.map(|row| row.dot.x)),
up: ends(rows.map(|row| row.dot.y)),
}
}
## Where the dot with `key` is drawn now: as drawn, or, not drawn yet, where it goes.
placed : ScatterChart.Drawn, ScatterChart.Drawn, Str -> ScatterChart.Placed
placed = |drawn, goal, key|
match drawn.dots.find_first(|dot| dot.key == key) {
Ok(dot) => dot
Err(_) => goal.dots.find_first(|dot| dot.key == key) ?? { key, x: 0.0, y: 0.0 }
}
## A frame's way from `drawn` toward `goal`: each dot toward its place, and the axes' ends
## toward theirs. A new dot is where it goes at once (it swells there); one that has gone is gone.
glide : ScatterChart.Drawn, ScatterChart.Drawn, F64 -> ScatterChart.Drawn
glide = |drawn, goal, ms| {
(a0, a1) = drawn.across
(ga0, ga1) = goal.across
(u0, u1) = drawn.up
(gu0, gu1) = goal.up
# Within a five-hundredth of an axis is there: under a pixel.
near_x = (ga1 - ga0) / 500.0
near_y = (gu1 - gu0) / 500.0
{
dots: goal.dots.map(
|dot| {
from = ScatterChart.placed(drawn, goal, dot.key)
{ key: dot.key, x: Ease.toward(from.x, dot.x, ms, near_x), y: Ease.toward(from.y, dot.y, ms, near_y) }
},
),
across: (Ease.toward(a0, ga0, ms, near_x), Ease.toward(a1, ga1, ms, near_x)),
up: (Ease.toward(u0, gu0, ms, near_y), Ease.toward(u1, gu1, ms, near_y)),
}
}
## Whether a tick is off its axis as drawn: one the axis is gliding toward, faded until it is on.
outside : (Dec, Dec), Dec -> Bool
outside = |(from, to), tick| tick < Dec.min(from, to) or tick > Dec.max(from, to)
<style>
.scatter-chart {
margin: 0;
}
svg {
display: block;
width: 100%;
height: auto;
overflow: visible;
font: 12px/1 var(--chart-font, inherit);
}
.ticks line {
stroke: var(--chart-grid, color-mix(in srgb, currentColor 12%, transparent));
stroke-dasharray: var(--chart-grid-dash, none);
}
.ticks g {
transition: opacity 0.2s;
}
.ticks .out {
opacity: 0;
}
.ticks text {
fill: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
font-variant-numeric: tabular-nums;
}
.ticks .up {
text-anchor: end;
}
.ticks .across {
text-anchor: middle;
}
.dot {
r: var(--chart-dot, 6px);
fill: var(--chart-color, #4f6bed);
fill-opacity: var(--chart-fill, 0.85);
stroke: var(--chart-stroke, var(--chart-surface, white));
stroke-width: var(--chart-stroke-width, 2);
filter: var(--chart-glow, none);
outline: none;
cursor: default;
transition: fill 0.15s, r 0.15s;
}
.dot.active {
fill: var(--chart-active, #2f49c4);
fill-opacity: 1;
r: calc(var(--chart-dot, 6px) + 2px);
}
.dot:focus-visible {
stroke: var(--chart-active, #2f49c4);
}
.spot {
text-anchor: middle;
font-weight: 600;
fill: currentColor;
paint-order: stroke;
stroke: var(--chart-surface, white);
stroke-width: 4px;
stroke-linejoin: round;
opacity: 0;
transition: opacity 0.15s;
pointer-events: none;
font-variant-numeric: tabular-nums;
}
.spot.shown {
opacity: 1;
}
</style>
}
## The plot's edges in the SVG's units (640 by 320): room on the left for the ticks' labels, and
## below for the ones across.
left : Dec
left = 48.0
right : Dec
right = 620.0
top : Dec
top = 16.0
bottom : Dec
bottom = 288.0
tick_count : U64
tick_count = 5
## An axis's ends: the least value and the greatest, widened to round numbers; one value alone,
## a unit either side of it.
ends : List(Dec) -> (Dec, Dec)
ends = |values| {
(low, high) = Scale.extent(values)
if low == high {
(low - 1.0, high + 1.0)
} else {
Ticks.nice(low, high, tick_count)
}
}The stacked bar chart: packages/charts/components/StackedBarChart.rocx
import pf.Html
import pf.Solid exposing [create_memo!, create_signal!, untrack!]
import pf.Transition
import charts.Band
import charts.Ease
import charts.Format
import charts.Keys
import charts.Scale
import charts.Ticks
## A column for each of `data!`'s entries, its values stacked from the axis up, one for each of
## `series` (the first at the bottom), each series in its own colour, named in a legend over the
## chart. The axis goes from zero to the tallest column, widened to round numbers. When the data
## changes, each part of each column glides to its new size, a frame at a time: a column is its
## label's, so a new one grows from the axis as the others make room, and one whose label is gone
## shrinks into the axis as it fades. Once they are there, nothing runs. Pointing at a column, or
## reaching it with Tab, shows its total.
##
## `label` names the chart for screen readers, `format` writes a value (`Format.short` unless
## said), and `padding` is the share of each column's slot left empty (0.3 unless said). Five
## colours (`--chart-1` to `--chart-5`): a sixth series shares one. A value below zero counts as
## zero.
StackedBarChart := [].{
## A column: its label, and a value for each series, the first at the bottom.
Column : { label : Str, values : List(Dec) }
## A column and its key: its label, numbered when another column before it has the same one.
Row : { key : Str, column : StackedBarChart.Column }
## A column as drawn: its values, and its slot (0 for the first), on their way to the data's.
Placed : { key : Str, values : List(Dec), slot : Dec }
## What is drawn: the columns, how many slots there are, and the axis's ends.
Drawn : { columns : List(StackedBarChart.Placed), count : Dec, domain : (Dec, Dec) }
Props := { data! : () => List(StackedBarChart.Column), series : List(Str), label : Str, format : (Dec -> Str) ?? Format.short, padding : Dec ?? 0.3 }
view! : Props => Html
view! = |props| {
data! = props.data!
format = props.format
parts = props.series.len()
rows! = create_memo!(|| StackedBarChart.keyed(data!(), parts))
goal! = create_memo!(|| StackedBarChart.place(rows!()))
(drawn!, set_drawn!) = create_signal!(untrack!(goal!))
(hover!, set_hover!) = create_signal!(Err(None))
y! = create_memo!(|| Scale.linear(drawn!().domain, (bottom, top)))
x! = create_memo!(|| Band.band(drawn!().count, (left, right), props.padding))
placed! = |key| StackedBarChart.placed(drawn!(), goal!(), key, parts)
# A part goes from what is under it to that and its own value.
under! = |key, part| placed!(key).values.take_first(part).fold(0.0, |sum, value| sum + value)
own! = |key, part| placed!(key).values.get(part) ?? 0.0
part_top! = |key, part| y!().at(under!(key, part) + own!(key, part))
part_height! = |key, part| y!().at(under!(key, part)) - part_top!(key, part)
total! = |key| placed!(key).values.fold(0.0, |sum, value| sum + value)
said! = |row| {
parted = List.map2(props.series, row.column.values, |name, value| "${name} ${format(value)}")
"${row.column.label}: ${Str.join_with(parted, ", ")}"
}
<figure class="stacked-chart">
<ul class="legend" aria-hidden="true">
{...props.series.map_with_index(|name, i|
<li key={i} data-slot={(i % colors).to_str()}><span class="swatch"></span>{name}</li>
)}
</ul>
<svg viewBox="0 0 640 320" role="group" aria-label={props.label}>
<g class="ticks" aria-hidden="true">
{...StackedBarChart.ticks(goal!()).map(|tick|
<g key={Format.num(tick, 9)} class:out={StackedBarChart.outside(drawn!().domain, tick)}>
<line x1={Format.coord(left)} x2={Format.coord(right)} y1={Format.coord(y!().at(tick))} y2={Format.coord(y!().at(tick))} />
<text x={Format.coord(left - 8.0)} y={Format.coord(y!().at(tick))} dy="0.32em">{format(tick)}</text>
</g>
)}
</g>
{# Each part of each column: kept by its column's key and its place in the column. }
{...StackedBarChart.pieces(rows!(), parts).map(|piece|
<rect key={"${piece.key}|${piece.part.to_str()}"}
class="part"
class:active={hover!() == Ok(piece.key)}
data-slot={(piece.part % colors).to_str()}
x={Format.coord(x!().at(placed!(piece.key).slot))}
y={Format.coord(part_top!(piece.key, piece.part))}
width={Format.coord(x!().width())}
height={Format.coord(Dec.max(part_height!(piece.key, piece.part), 0.0))}
transition:out={Transition.grow(Bottom).plus(Transition.fade)}
/>
)}
{# Each column: what the pointer and Tab find it by, its total and its label. }
{...rows!().map(|row|
<g key={row.key}
class="column"
class:active={hover!() == Ok(row.key)}
role="img"
tabindex="0"
aria-label={said!(row)}
on:pointerenter={|| set_hover!(Ok(row.key))}
on:pointerleave={|| set_hover!(Err(None))}
on:focus={|| set_hover!(Ok(row.key))}
on:blur={|| set_hover!(Err(None))}
transition:out={Transition.fade}
>
<rect class="hit" x={Format.coord(x!().at(placed!(row.key).slot))} y={Format.coord(top)} width={Format.coord(x!().width())} height={Format.coord(bottom - top)} />
<text class="total" x={Format.coord(x!().center(placed!(row.key).slot))} y={Format.coord(y!().at(total!(row.key)) - 8.0)}>{format(total!(row.key))}</text>
<text class="label" x={Format.coord(x!().center(placed!(row.key).slot))} y={Format.coord(bottom + 20.0)}>{row.column.label}</text>
</g>
)}
<line class="axis" x1={Format.coord(left)} x2={Format.coord(right)} y1={Format.coord(bottom)} y2={Format.coord(bottom)} />
</svg>
{# Frames only while something moves: once the columns are where the data says, none. }
{if drawn!() != goal!() {
<span hidden on:frame.ms={|ms| set_drawn!(StackedBarChart.glide(drawn!(), goal!(), ms, parts))}></span>
}}
</figure>
}
## Each column with its key, and as many values as there are series (a missing one is zero, a
## value below zero counts as zero).
keyed : List(StackedBarChart.Column), U64 -> List(StackedBarChart.Row)
keyed = |columns, parts| {
fitted = columns.map(|column| { label: column.label, values: List.repeat(0.0, parts).map_with_index(|_, i| Dec.max(column.values.get(i) ?? 0.0, 0.0)) })
List.map2(Keys.unique(fitted.map(|column| column.label)), fitted, |key, column| { key, column })
}
## Each column's parts, the first (the bottom one) first.
pieces : List(StackedBarChart.Row), U64 -> List({ key : Str, part : U64 })
pieces = |rows, parts| rows.join_map(|row| List.repeat(row.key, parts).map_with_index(|key, part| { key, part }))
## Where the columns go: each in its slot, on an axis from zero to the tallest, widened to round
## numbers.
place : List(StackedBarChart.Row) -> StackedBarChart.Drawn
place = |rows| {
tallest = rows.fold(0.0, |most, row| Dec.max(most, row.column.values.fold(0.0, |sum, value| sum + value)))
domain = if (tallest > 0.0) Ticks.nice(0.0, tallest, tick_count) else (0.0, 1.0)
{
columns: rows.map_with_index(|row, i| { key: row.key, values: row.column.values, slot: i.to_dec() }),
count: rows.len().to_dec(),
domain,
}
}
## Where the column with `key` is drawn now: as drawn, or, not drawn yet, nothing in its slot.
placed : StackedBarChart.Drawn, StackedBarChart.Drawn, Str, U64 -> StackedBarChart.Placed
placed = |drawn, goal, key, parts|
match drawn.columns.find_first(|column| column.key == key) {
Ok(column) => column
Err(_) => {
slot = goal.columns.find_first(|column| column.key == key).map_ok(|column| column.slot) ?? 0.0
{ key, values: List.repeat(0.0, parts), slot }
}
}
## A frame's way from `drawn` toward `goal`: each part toward its value, each column toward its
## slot, and the axis toward its ends.
glide : StackedBarChart.Drawn, StackedBarChart.Drawn, F64, U64 -> StackedBarChart.Drawn
glide = |drawn, goal, ms, parts| {
(d0, d1) = drawn.domain
(g0, g1) = goal.domain
# Within a five-hundredth of the axis is there: under a pixel. So is a hundredth of a slot.
close = (g1 - g0) / 500.0
near = 0.01
{
columns: goal.columns.map(
|column| {
from = StackedBarChart.placed(drawn, goal, column.key, parts)
{
key: column.key,
values: List.map2(from.values, column.values, |was, value| Ease.toward(was, value, ms, close)),
slot: Ease.toward(from.slot, column.slot, ms, near),
}
},
),
count: Ease.toward(drawn.count, goal.count, ms, near),
domain: (Ease.toward(d0, g0, ms, close), Ease.toward(d1, g1, ms, close)),
}
}
## The axis's ticks.
ticks : StackedBarChart.Drawn -> List(Dec)
ticks = |drawn| {
(from, to) = drawn.domain
Ticks.between(from, to, tick_count)
}
## Whether a tick is off the axis as drawn: one the axis is gliding toward, faded until it is on.
outside : (Dec, Dec), Dec -> Bool
outside = |(from, to), tick| tick < Dec.min(from, to) or tick > Dec.max(from, to)
<style>
.stacked-chart {
display: grid;
gap: 0.75rem;
margin: 0;
}
svg {
display: block;
width: 100%;
height: auto;
overflow: visible;
font: 12px/1 var(--chart-font, inherit);
}
.ticks line {
stroke: var(--chart-grid, color-mix(in srgb, currentColor 12%, transparent));
stroke-dasharray: var(--chart-grid-dash, none);
}
.ticks g {
transition: opacity 0.2s;
}
.ticks .out {
opacity: 0;
}
.ticks text {
fill: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
text-anchor: end;
font-variant-numeric: tabular-nums;
}
.axis {
stroke: var(--chart-axis, color-mix(in srgb, currentColor 45%, transparent));
}
[data-slot="0"] {
--part: var(--chart-1, #2a78d6);
}
[data-slot="1"] {
--part: var(--chart-2, #eb6834);
}
[data-slot="2"] {
--part: var(--chart-3, #1baf7a);
}
[data-slot="3"] {
--part: var(--chart-4, #eda100);
}
[data-slot="4"] {
--part: var(--chart-5, #e87ba4);
}
.column {
outline: none;
cursor: default;
}
/* A gap of the surface's colour between parts; outlined (`--chart-outline: 1`), the part's. */
.part {
fill: var(--part);
fill-opacity: var(--chart-fill, 1);
stroke: color-mix(in srgb, var(--part) calc(var(--chart-outline, 0) * 100%), var(--chart-surface, white));
stroke-width: var(--chart-stroke-width, 1.5);
filter: var(--chart-glow, none);
transition: fill-opacity 0.15s;
}
svg:has(.part.active) .part:not(.active) {
fill-opacity: calc(var(--chart-fill, 1) * 0.45);
}
.hit {
fill: transparent;
}
.column:focus-visible .hit {
stroke: var(--chart-active, currentColor);
stroke-width: 2;
}
.column text {
text-anchor: middle;
fill: currentColor;
}
.label {
fill: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
}
.total {
font-weight: 600;
opacity: 0;
transition: opacity 0.15s;
font-variant-numeric: tabular-nums;
}
.column.active .total {
opacity: 1;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 0.25rem 1rem;
margin: 0;
padding: 0;
list-style: none;
font-size: 0.875em;
}
.legend li {
display: flex;
align-items: center;
gap: 0.4rem;
}
.swatch {
width: 0.75rem;
height: 0.75rem;
border-radius: 3px;
background: var(--part);
}
</style>
}
## The plot's edges in the SVG's units (640 by 320): room on the left for the ticks' labels, and
## below for the columns'.
left : Dec
left = 48.0
right : Dec
right = 632.0
top : Dec
top = 16.0
bottom : Dec
bottom = 288.0
tick_count : U64
tick_count = 5
## How many colours the series have (`--chart-1` to `--chart-5`).
colors : U64
colors = 5The stacked area chart: packages/charts/components/StackedAreaChart.rocx
import pf.Html
import pf.Solid exposing [create_memo!, create_signal!, untrack!]
import charts.Ease
import charts.Format
import charts.Keys
import charts.Path
import charts.Scale
import charts.Ticks
## A value over time split into parts (visits by source, sales by region): a band for each of
## `data!`'s `bands`, stacked from the axis up in the order given (the first at the bottom), so the
## top edge is the whole and each band's height its part of it. Across, the points are to scale by
## their `x` (`xs`), as `<LineChart>`'s are; up, the axis runs from zero to the highest whole,
## widened to round numbers. A legend over the chart says each band's label, its value and, with
## more than one band, its share of the whole (whole percents that add up to 100, as a donut's): at
## the point nearest the pointer, whose whole shows over the plot and whose `x` on the axis along the
## bottom, and while none is, as `resting` says. When the data changes, the bands glide to it a
## frame at a time, as `<LineChart>`'s line does; once they are there, nothing runs.
##
## A band is in the colour the data gives it (`color`: any CSS colour, `"#c0392b"` or
## `"var(--brand)"`), or, given none, the chart's for its place (`--chart-1` for the first, to
## `--chart-5`), as a stacked bar chart's series are. `label` names the chart for screen readers,
## `format` writes a value and `format_x` an `x` (each `Format.short` unless said), `smooth` curves
## the edges (monotone, as `<LineChart>`'s), and `resting` is what the legend says while no point is
## pointed at: the bands' values at the last point (`Last`, unless said: a running total's now), or
## all their points' added up (`Sum`: of a count each day, the whole period's). A value below zero
## counts as zero, and a missing one as zero too.
StackedAreaChart := [].{
## A band: what it is, its value at each of the points (left to right), and its colour, the
## chart's own when left out.
Band := { label : Str, values : List(Dec), color : Str ?? "" }.{
is_eq : _
}
## The points across (`xs`) and each band over them.
Data : { xs : List(Dec), bands : List(StackedAreaChart.Band) }
## A band as drawn: its key (its label, numbered when another band before it has the same one),
## its label, a value (zero or more) for every point, and its colour (`""` for the chart's own).
Layer : { key : Str, label : Str, values : List(Dec), color : Str }
## What is drawn: the points, the bands, and the axes' ends, on their way to the data's.
Drawn : { xs : List(Dec), layers : List(StackedAreaChart.Layer), across : (Dec, Dec), up : (Dec, Dec) }
## A band's edges where they are drawn, in the SVG's units: the top of the bands under it, and
## that with its own values on it.
Edges : { key : Str, lower : List((Dec, Dec)), upper : List((Dec, Dec)) }
## What a band says in the legend.
Said : { key : Str, value : Str, share : Str }
Props := { data! : () => StackedAreaChart.Data, label : Str, format : (Dec -> Str) ?? Format.short, format_x : (Dec -> Str) ?? Format.short, smooth : Bool ?? Bool.False, resting : [Last, Sum] ?? Last }
view! : Props => Html
view! = |{ data!, label, format, format_x, smooth, resting }| {
goal! = create_memo!(|| StackedAreaChart.place(data!()))
(drawn!, set_drawn!) = create_signal!(untrack!(goal!))
(hover!, set_hover!) = create_signal!(Err(None))
x! = create_memo!(|| Scale.linear(drawn!().across, (left, right)))
y! = create_memo!(|| Scale.linear(drawn!().up, (bottom, top)))
edges! = create_memo!(|| StackedAreaChart.edges(drawn!()))
keys! = create_memo!(|| goal!().layers.map(|layer| layer.key))
layer_of! = |key| goal!().layers.find_first(|layer| layer.key == key) ?? { key, label: key, values: [], color: "" }
slot_of! = |key| ((goal!().layers.find_first_index(|layer| layer.key == key) ?? 0) % colors).to_str()
edges_of! = |key| edges!().find_first(|edge| edge.key == key) ?? { key, lower: [], upper: [] }
# The strip of the plot nearer each point than the others, which the pointer finds it by:
# where the data puts the points, so bands gliding to new values don't move them.
strips! = create_memo!(|| StackedAreaChart.strips(goal!()))
said! = create_memo!(|| StackedAreaChart.said(goal!(), hover!(), resting, format))
said_of! = |key| said!().find_first(|entry| entry.key == key) ?? { key, value: "", share: "" }
# The point pointed at, while one is.
spot! = || {
match hover!() {
Ok(i) =>
match drawn!().xs.get(i) {
Ok(at) => Ok((i, x!().at(at)))
Err(_) => Err(None)
}
Err(_) => Err(None)
}
}
spotted! = || {
match spot!() {
Ok(_) => Bool.True
Err(_) => Bool.False
}
}
spot_x! = || {
match spot!() {
Ok((_, px)) => px
Err(_) => left
}
}
# Where a band's top is at the point pointed at.
spot_y! = |key| {
match spot!() {
Ok((i, _)) =>
match edges_of!(key).upper.get(i) {
Ok((_, py)) => py
Err(_) => bottom
}
Err(_) => bottom
}
}
spot_text! = |write|
match hover!() {
Ok(i) =>
match goal!().xs.get(i) {
Ok(at) => write(i, at)
Err(_) => ""
}
Err(_) => ""
}
<figure class="area-chart">
<ul class="legend">
{...keys!().map(|key|
<li key={key} data-slot={slot_of!(key)} style:--band={layer_of!(key).color}>
<span class="swatch"></span>
<span class="name">{layer_of!(key).label}</span>
<strong class="amount">{said_of!(key).value}</strong>
<span class="share">{said_of!(key).share}</span>
</li>
)}
</ul>
<div class="plot">
<svg viewBox="0 0 640 320" role="img" aria-label={label}>
<g class="ticks" class:spotting={spotted!()} aria-hidden="true">
{...StackedAreaChart.ticks(goal!().up).map(|tick|
<g key={Format.num(tick, 9)} class:out={StackedAreaChart.outside(drawn!().up, tick)}>
<line x1={Format.coord(left)} x2={Format.coord(right)} y1={Format.coord(y!().at(tick))} y2={Format.coord(y!().at(tick))} />
<text class="up" x={Format.coord(left - 8.0)} y={Format.coord(y!().at(tick))} dy="0.32em">{format(tick)}</text>
</g>
)}
{...StackedAreaChart.ticks(goal!().across).map(|tick|
<g key={Format.num(tick, 9)} class:out={StackedAreaChart.outside(drawn!().across, tick)}>
<text class="across" x={Format.coord(x!().at(tick))} y={Format.coord(bottom + 20.0)}>{format_x(tick)}</text>
</g>
)}
</g>
{# Each band, then each band's top edge over all of them, so no band's fill tints an edge. }
{...keys!().map(|key|
<path key={key} class="band" data-slot={slot_of!(key)} style:--band={layer_of!(key).color} d={StackedAreaChart.outline(edges_of!(key), smooth)} />
)}
{...keys!().map(|key|
<path key={key} class="edge" data-slot={slot_of!(key)} style:--band={layer_of!(key).color} d={StackedAreaChart.curve(edges_of!(key).upper, smooth)} />
)}
<g class="spot" class:shown={spotted!()} aria-hidden="true">
<line x1={Format.coord(spot_x!())} x2={Format.coord(spot_x!())} y1={Format.coord(top)} y2={Format.coord(bottom)} />
{...keys!().map(|key|
<circle key={key} class="dot" data-slot={slot_of!(key)} style:--band={layer_of!(key).color} cx={Format.coord(spot_x!())} cy={Format.coord(spot_y!(key))} r="4" />
)}
<text x={Format.coord(spot_x!())} y={Format.coord(top - 8.0)}>{spot_text!(|i, _| format(StackedAreaChart.whole(goal!(), i)))}</text>
<text x={Format.coord(spot_x!())} y={Format.coord(bottom + 20.0)}>{spot_text!(|_, at| format_x(at))}</text>
</g>
</svg>
{# A strip of the plot for each point, which the pointer finds it by, from top to bottom. }
<div class="strips" on:pointerleave={|| set_hover!(Err(None))}>
{...strips!().map_with_index(|(from, to), i|
<span key={i} style:left={share(from - left)} style:width={share(to - from)} on:pointerenter={|| set_hover!(Ok(i))}></span>
)}
</div>
</div>
{# Frames only while something moves: once the bands and the axes are where the data says, none. }
{if drawn!() != goal!() {
<span hidden on:frame.ms={|ms| set_drawn!(StackedAreaChart.glide(drawn!(), goal!(), ms))}></span>
}}
</figure>
}
## Where the data puts the bands: each keyed by its label, with a value (zero or more) for every
## point, the axis along the bottom from the least `x` to the greatest, and the one up the side
## from zero to the highest whole, widened to round numbers.
place : StackedAreaChart.Data -> StackedAreaChart.Drawn
place = |data| {
count = data.xs.len()
layers = List.map2(
Keys.unique(data.bands.map(|band| band.label)),
data.bands,
|key, band| { key, label: band.label, color: band.color, values: List.repeat(0.0, count).map_with_index(|_, i| Dec.max(band.values.get(i) ?? 0.0, 0.0)) },
)
highest = List.repeat(0.0, count).map_with_index(|_, i| layers.fold(0.0, |sum, layer| sum + (layer.values.get(i) ?? 0.0))).fold(0.0, |most, here| Dec.max(most, here))
{
xs: data.xs,
layers,
across: Scale.extent(data.xs),
up: if (highest > 0.0) Ticks.nice(0.0, highest, tick_count) else (0.0, 1.0),
}
}
## Each band's edges as `drawn` puts them: the first's lower edge on the axis, each next one's
## on the one under it.
edges : StackedAreaChart.Drawn -> List(StackedAreaChart.Edges)
edges = |drawn| {
across = Scale.linear(drawn.across, (left, right))
up = Scale.linear(drawn.up, (bottom, top))
places = |sums| List.map2(drawn.xs, sums, |x, y| (across.at(x), up.at(y)))
(_, stacked) = drawn.layers.fold(
(drawn.xs.map(|_| 0.0), []),
|(under, done), layer| {
over = List.map2(under, layer.values, |below, own| below + own)
(over, done.append({ key: layer.key, lower: places(under), upper: places(over) }))
},
)
stacked
}
## A line through `points`: straight segments, or with `smooth` monotone curves.
curve : List((Dec, Dec)), Bool -> Str
curve = |points, smooth| if (smooth) Path.smooth(points) else Path.line(points)
## A band's outline: along its top edge, left to right, then back along its lower edge (a
## monotone curve is the same curve either way). Nothing to draw is `""`.
outline : StackedAreaChart.Edges, Bool -> Str
outline = |sides, smooth|
if sides.upper.is_empty() or sides.lower.is_empty() {
""
} else {
"${StackedAreaChart.curve(sides.upper, smooth)}L${StackedAreaChart.curve(sides.lower.rev(), smooth).drop_prefix("M")}Z"
}
## What each band says in the legend: its value at the point pointed at (`hover`), or while none
## is, at the last point or all its points' added up (`resting`), and its share of the whole there
## (`Format.shares`; none when it is alone).
said : StackedAreaChart.Drawn, Try(U64, [None]), [Last, Sum], (Dec -> Str) -> List(StackedAreaChart.Said)
said = |goal, hover, resting, format| {
values = goal.layers.map(
|layer|
match hover {
Ok(i) => layer.values.get(i) ?? 0.0
Err(_) =>
match resting {
Last => layer.values.last() ?? 0.0
Sum => layer.values.fold(0.0, |sum, value| sum + value)
}
},
)
shares = Format.shares(values)
alone = goal.layers.len() < 2
goal.layers.map_with_index(|layer, i| { key: layer.key, value: format(values.get(i) ?? 0.0), share: if (alone) "" else shares.get(i) ?? "" })
}
## The whole at the `i`th point: every band's value there.
whole : StackedAreaChart.Drawn, U64 -> Dec
whole = |drawn, i| drawn.layers.fold(0.0, |sum, layer| sum + (layer.values.get(i) ?? 0.0))
## The stretch of the plot nearer each of `goal`'s points than the others, in the SVG's units.
strips : StackedAreaChart.Drawn -> List((Dec, Dec))
strips = |goal| {
across = Scale.linear(goal.across, (left, right))
Scale.strips(goal.xs.map(|x| across.at(x)), (left, right))
}
## A frame's way from what is drawn toward the data: each value toward its own, and the axes'
## ends toward theirs. With more points or fewer, or other bands, the bands are the data's at once.
glide : StackedAreaChart.Drawn, StackedAreaChart.Drawn, F64 -> StackedAreaChart.Drawn
glide = |drawn, goal, ms| {
(a0, a1) = drawn.across
(ga0, ga1) = goal.across
(u0, u1) = drawn.up
(gu0, gu1) = goal.up
# Within a five-hundredth of an axis is there: under a pixel.
near_x = (ga1 - ga0) / 500.0
near_y = (gu1 - gu0) / 500.0
same = drawn.xs.len() == goal.xs.len() and drawn.layers.map(|layer| layer.key) == goal.layers.map(|layer| layer.key)
if same {
{
xs: List.map2(drawn.xs, goal.xs, |from, to| Ease.toward(from, to, ms, near_x)),
layers: List.map2(drawn.layers, goal.layers, |from, to| { ..to, values: List.map2(from.values, to.values, |was, now| Ease.toward(was, now, ms, near_y)) }),
across: (Ease.toward(a0, ga0, ms, near_x), Ease.toward(a1, ga1, ms, near_x)),
up: (Ease.toward(u0, gu0, ms, near_y), Ease.toward(u1, gu1, ms, near_y)),
}
} else {
goal
}
}
## An axis's ticks.
ticks : (Dec, Dec) -> List(Dec)
ticks = |(from, to)| Ticks.between(from, to, tick_count)
## Whether a tick is off its axis as drawn: one the axis is gliding toward, faded until it is on.
outside : (Dec, Dec), Dec -> Bool
outside = |(from, to), tick| tick < Dec.min(from, to) or tick > Dec.max(from, to)
<style>
.area-chart {
margin: 0;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 0.25rem 1.1rem;
margin: 0 0 0.6rem;
padding: 0;
list-style: none;
font-size: 0.875em;
}
.legend li {
display: inline-flex;
align-items: center;
gap: 0.4rem;
}
.swatch {
width: 0.75rem;
height: 0.75rem;
border-radius: 3px;
background: var(--band);
}
.name,
.share {
color: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
}
.amount {
font-weight: 650;
font-variant-numeric: tabular-nums;
}
.share {
font-variant-numeric: tabular-nums;
}
.share:empty {
display: none;
}
svg {
display: block;
width: 100%;
height: auto;
overflow: visible;
font: 12px/1 var(--chart-font, inherit);
}
.ticks line {
stroke: var(--chart-grid, color-mix(in srgb, currentColor 12%, transparent));
stroke-dasharray: var(--chart-grid-dash, none);
}
.ticks g {
transition: opacity 0.2s;
}
.ticks .out {
opacity: 0;
}
.ticks text {
fill: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
font-variant-numeric: tabular-nums;
}
.ticks .up {
text-anchor: end;
}
.ticks .across {
text-anchor: middle;
transition: opacity 0.15s;
}
/* The point's own `x` takes the axis's place while one is pointed at. */
.ticks.spotting .across {
opacity: 0;
}
/* A band's colour for its place, unless the data gives it one (`--band`, set on it). */
[data-slot="0"] {
--band: var(--chart-1, #2a78d6);
}
[data-slot="1"] {
--band: var(--chart-2, #eb6834);
}
[data-slot="2"] {
--band: var(--chart-3, #1baf7a);
}
[data-slot="3"] {
--band: var(--chart-4, #eda100);
}
[data-slot="4"] {
--band: var(--chart-5, #e87ba4);
}
.band {
fill: var(--band);
fill-opacity: var(--chart-fill, 0.3);
}
.edge {
fill: none;
stroke: var(--band);
stroke-width: var(--chart-line-width, 2);
filter: var(--chart-glow, none);
stroke-linejoin: round;
stroke-linecap: round;
}
.spot {
opacity: 0;
transition: opacity 0.15s;
pointer-events: none;
}
.spot.shown {
opacity: 1;
}
.spot line {
stroke: var(--chart-axis, color-mix(in srgb, currentColor 45%, transparent));
stroke-dasharray: 3 3;
}
.spot .dot {
fill: var(--band);
stroke: var(--chart-surface, white);
stroke-width: 2;
}
.spot text {
text-anchor: middle;
font-weight: 600;
fill: currentColor;
font-variant-numeric: tabular-nums;
}
.plot {
position: relative;
}
/* Over the plot (48 to 620 of the SVG's 640 across, 24 to 288 of its 320 down); each strip
placed across by Roc, in shares of the plot's width. */
.strips {
position: absolute;
top: 7.5%;
bottom: 10%;
left: 7.5%;
right: 3.125%;
}
.strips span {
position: absolute;
top: 0;
bottom: 0;
}
</style>
}
## The plot's edges in the SVG's units (640 by 320), as `<LineChart>`'s: room on the left for the
## values' ticks, below for the ones across, and on the right for the last one's label.
left : Dec
left = 48.0
right : Dec
right = 620.0
top : Dec
top = 24.0
bottom : Dec
bottom = 288.0
tick_count : U64
tick_count = 5
## How many colours the bands have for their places (`--chart-1` to `--chart-5`).
colors : U64
colors = 5
## A length across, in the SVG's units, as a share of the plot's width: `"50%"` for 286.
share : Dec -> Str
share = |x| "${Format.num(x * 100.0 / (right - left), 3)}%"
# Two bands over three points: the second sits on the first, and the top edge is the whole.
expect {
drawn = StackedAreaChart.place({ xs: [0.0, 1.0, 2.0], bands: [{ label: "Wind", values: [0.0, 10.0, 20.0] }, { label: "Solar", values: [0.0, 30.0, 60.0] }] })
stacked = StackedAreaChart.edges(drawn)
tops = stacked.map(|edge| edge.upper.map(|(_, y)| y))
drawn.up == (0.0, 80.0) and (stacked.get(1) ?? { key: "", lower: [], upper: [] }).lower == (stacked.get(0) ?? { key: "", lower: [], upper: [] }).upper and tops.get(1) == Ok([bottom, bottom - 132.0, bottom - 264.0])
}
# A value below zero counts as zero, a missing one too; the axis of nothing is zero to one.
expect {
drawn = StackedAreaChart.place({ xs: [0.0, 1.0], bands: [{ label: "Hydro", values: [-5.0] }] })
drawn.layers == [{ key: "Hydro", label: "Hydro", values: [0.0, 0.0], color: "" }] and drawn.up == (0.0, 1.0)
}
# A band keeps the colour the data gives it; two with one label are two bands.
expect {
drawn = StackedAreaChart.place({ xs: [0.0], bands: [{ label: "Roc", values: [1.0], color: "#7d59dc" }, { label: "Roc", values: [2.0] }] })
drawn.layers.map(|layer| (layer.key, layer.color)) == [("Roc", "#7d59dc"), ("Roc#1", "")]
}
# A band's outline goes along its top, back along its bottom, and closes.
expect StackedAreaChart.outline({ key: "a", lower: [(0.0, 10.0), (5.0, 10.0)], upper: [(0.0, 4.0), (5.0, 2.0)] }, Bool.False) == "M0,4L5,2L5,10L0,10Z"
# Each band says its value and its share, at the last point or the one pointed at.
expect {
drawn = StackedAreaChart.place({ xs: [0.0, 1.0], bands: [{ label: "Wind", values: [10.0, 25.0] }, { label: "Solar", values: [30.0, 75.0] }] })
last = StackedAreaChart.said(drawn, Err(None), Last, |value| Format.num(value, 0)).map(|entry| (entry.value, entry.share))
first = StackedAreaChart.said(drawn, Ok(0), Last, |value| Format.num(value, 0)).map(|entry| entry.share)
last == [("25", "25%"), ("75", "75%")] and first == ["25%", "75%"] and StackedAreaChart.whole(drawn, 1) == 100.0
}
# Resting on the sum, each band says all its points' added up; a point pointed at, that one's.
expect {
drawn = StackedAreaChart.place({ xs: [0.0, 1.0], bands: [{ label: "Wind", values: [10.0, 15.0] }, { label: "Solar", values: [70.0, 5.0] }] })
said = |hover| StackedAreaChart.said(drawn, hover, Sum, |value| Format.num(value, 0)).map(|entry| (entry.value, entry.share))
said(Err(None)) == [("25", "25%"), ("75", "75%")] and said(Ok(1)) == [("15", "75%"), ("5", "25%")]
}
# A band alone says its value, not its share of itself.
expect {
drawn = StackedAreaChart.place({ xs: [0.0, 1.0], bands: [{ label: "Wind", values: [3.0, 848.0] }] })
StackedAreaChart.said(drawn, Err(None), Last, |value| Format.num(value, 0)) == [{ key: "Wind", value: "848", share: "" }]
}
# Gliding keeps the bands while they are the same ones; other bands are the data's at once.
expect {
from = StackedAreaChart.place({ xs: [0.0, 1.0], bands: [{ label: "Wind", values: [0.0, 100.0] }] })
to = StackedAreaChart.place({ xs: [0.0, 1.0], bands: [{ label: "Wind", values: [0.0, 50.0] }] })
other = StackedAreaChart.place({ xs: [0.0, 1.0], bands: [{ label: "Solar", values: [0.0, 50.0] }] })
halfway = StackedAreaChart.glide(from, to, 16.0)
moved = (halfway.layers.first() ?? { key: "", label: "", values: [], color: "" }).values
moved.get(1) == Ok(90.0) and StackedAreaChart.glide(from, other, 16.0) == other
}The sparkline: packages/charts/components/Sparkline.rocx
import pf.Html
import pf.Solid exposing [create_memo!, create_signal!, untrack!]
import charts.Ease
import charts.Format
import charts.Path
import charts.Scale
## A small line through `data!`'s values, with no axis, the area under it shaded and a dot on the
## last: for beside a number, in a line of text or a tile. It spans its values' range, so it shows
## their shape, not their size. When the values change, the line glides to them, a frame at a time,
## and once it is there, nothing runs.
##
## `label!` says what it shows, for screen readers: the trend, since there is no number to read. It
## is an accessor, as `data!` is, since it changes with the data.
Sparkline := [].{
view! : { data! : () => List(Dec), label! : () => Str } => Html
view! = |{ data!, label! }| {
(drawn!, set_drawn!) = create_signal!(untrack!(data!))
points! = create_memo!(
|| {
values = drawn!()
(low, high) = Scale.extent(values)
up = Scale.linear(if (low == high) (low - 1.0, high + 1.0) else (low, high), (bottom, top))
across = Scale.linear((0.0, Dec.max(values.len().to_dec() - 1.0, 1.0)), (left, right))
values.map_with_index(|value, i| (across.at(i.to_dec()), up.at(value)))
},
)
last! = || points!().last() ?? (right, bottom)
<svg class="sparkline" viewBox="0 0 120 32" role="img" aria-label={label!()}>
<path class="area" d={Path.smooth_area(points!(), 32.0)} />
<path class="line" d={Path.smooth(points!())} />
<circle cx={Format.coord(last!().0)} cy={Format.coord(last!().1)} r="2.5" />
{# Frames only while the line moves. }
{if drawn!() != data!() {
<g on:frame.ms={|ms| set_drawn!(Sparkline.glide(drawn!(), data!(), ms))}></g>
}}
</svg>
}
## A frame's way from the values drawn toward the data's: each toward its own. When there are
## more values or fewer, the line is the data's at once.
glide : List(Dec), List(Dec), F64 -> List(Dec)
glide = |drawn, goal, ms| {
(low, high) = Scale.extent(goal)
# Within a two-hundredth of the range is there: under a pixel, this small.
close = Dec.max(high - low, 1.0) / 200.0
if drawn.len() == goal.len() {
List.map2(drawn, goal, |from, to| Ease.toward(from, to, ms, close))
} else {
goal
}
}
<style>
.sparkline {
display: block;
width: 100%;
height: auto;
overflow: visible;
}
.line {
fill: none;
stroke: var(--chart-color, currentColor);
stroke-width: calc(var(--chart-line-width, 2.5) * 0.6);
stroke-linejoin: round;
stroke-linecap: round;
filter: var(--chart-glow, none);
}
.area {
fill: var(--chart-color, currentColor);
opacity: var(--chart-area, 0.12);
}
circle {
fill: var(--chart-active, currentColor);
}
</style>
}
## The line's edges in the SVG's units (120 by 32), leaving room for the dot.
left : Dec
left = 2.0
right : Dec
right = 116.0
top : Dec
top = 3.0
bottom : Dec
bottom = 29.0The heatmap: packages/charts/components/Heatmap.rocx
import pf.Html
import pf.Solid exposing [create_memo!, create_signal!]
import charts.Format
## A grid of cells, a row for each of `rows` and a column for each of `columns`, each cell coloured
## by its value in `data!` (a list for each row): from `--chart-heat-low` at zero to
## `--chart-heat-high` at the greatest value, one hue getting stronger. Under it, the scale, and
## the cell pointed at: its row, its column and its value. When the data changes, the browser
## fades each cell to its new colour (a CSS transition), so Roc runs no frames at all.
##
## `label` names the chart for screen readers, and `format` writes a value (`Format.short` unless
## said). Every column's label is in the readout; along the bottom, at most eight are, evenly
## spaced.
Heatmap := [].{
Props := { data! : () => List(List(Dec)), rows : List(Str), columns : List(Str), label : Str, format : (Dec -> Str) ?? Format.short }
view! : Props => Html
view! = |{ data!, rows, columns, label, format }| {
(hover!, set_hover!) = create_signal!(Err(None))
most! = create_memo!(|| data!().fold(0.0, |most, row| row.fold(most, |m, value| Dec.max(m, value))))
value! = |r, c| (data!().get(r) ?? []).get(c) ?? 0.0
# How strong a cell is: its share of the greatest value, 0 to 1.
strength! = |r, c| if (most!() > 0.0) Format.num(Dec.max(value!(r, c), 0.0) / most!(), 3) else "0"
# Each cell, a row and a column, row by row.
cells = rows.map_with_index(|_, r| r).join_map(|r| columns.map_with_index(|_, c| (r, c)))
width = (right - left) / Dec.max(columns.len().to_dec(), 1.0)
height = (bottom - top) / Dec.max(rows.len().to_dec(), 1.0)
said! = ||
match hover!() {
Ok((r, c)) => "${rows.get(r) ?? ""} ${columns.get(c) ?? ""} — ${format(value!(r, c))}"
Err(_) => ""
}
# Where the cell pointed at is, row and column: its outline is drawn over the grid, since a
# cell's own would be under the cells after it, to its right and below.
pointed! = |at|
match hover!() {
Ok(cell) => at(cell)
Err(_) => 0.0
}
# Along the bottom, a label every `step` columns: about eight at most.
step = U64.max((columns.len() + 7) // 8, 1)
<figure class="heatmap">
<svg viewBox="0 0 640 260" role="img" aria-label={label} on:pointerleave={|| set_hover!(Err(None))}>
{...rows.map_with_index(|row, r|
<text key={r} class="row" x={Format.coord(left - 8.0)} y={Format.coord(top + height * (r.to_dec() + 0.5))} dy="0.32em">{row}</text>
)}
{...cells.map_with_index(|cell, i|
<rect key={i}
class="cell"
x={Format.coord(left + width * cell.1.to_dec())}
y={Format.coord(top + height * cell.0.to_dec())}
width={Format.coord(width)}
height={Format.coord(height)}
style:--strength={strength!(cell.0, cell.1)}
on:pointerenter={|| set_hover!(Ok(cell))}
/>
)}
<rect
class="pointed"
class:shown={hover!() != Err(None)}
x={Format.coord(left + width * pointed!(|(_, c)| c.to_dec()))}
y={Format.coord(top + height * pointed!(|(r, _)| r.to_dec()))}
width={Format.coord(width)}
height={Format.coord(height)}
/>
{...columns.map_with_index(|column, c|
<text key={c} class="column" x={Format.coord(left + width * (c.to_dec() + 0.5))} y={Format.coord(bottom + 18.0)}>
{if (c % step == 0) column else ""}
</text>
)}
</svg>
<figcaption aria-hidden="true">
<span class="scale">
{format(0.0)}
<span class="ramp"></span>
{format(most!())}
</span>
<span class="said">{said!()}</span>
</figcaption>
</figure>
}
<style>
.heatmap {
display: grid;
gap: 0.5rem;
margin: 0;
}
svg {
display: block;
width: 100%;
height: auto;
overflow: visible;
font: 12px/1 var(--chart-font, inherit);
}
.cell {
fill: color-mix(in oklab, var(--chart-heat-high, currentColor) calc(var(--strength) * 100%), var(--chart-heat-low, transparent));
stroke: var(--chart-surface, white);
stroke-width: 2;
transition: fill 0.6s;
}
/* Over the grid, so all four sides show: a cell's own outline is under its neighbours. */
.pointed {
fill: none;
stroke: var(--chart-active, currentColor);
stroke-width: 2;
opacity: 0;
pointer-events: none;
}
.pointed.shown {
opacity: 1;
}
text {
fill: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
}
.row {
text-anchor: end;
}
.column {
text-anchor: middle;
}
figcaption {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 0.5rem 1rem;
color: var(--chart-muted, color-mix(in srgb, currentColor 60%, transparent));
font: 0.8rem/1.4 var(--chart-font, inherit);
font-variant-numeric: tabular-nums;
}
.scale {
display: inline-flex;
align-items: center;
gap: 0.5rem;
}
.ramp {
width: 7rem;
height: 0.6rem;
border-radius: 3px;
background: linear-gradient(to right, var(--chart-heat-low, transparent), var(--chart-heat-high, currentColor));
}
.said {
color: currentColor;
font-weight: 600;
}
</style>
}
## The grid's edges in the SVG's units (640 by 260): room on the left for the rows' labels, and
## below for the columns'.
left : Dec
left = 48.0
right : Dec
right = 632.0
top : Dec
top = 4.0
bottom : Dec
bottom = 236.0