Chart
Chart reads a number from the data of the world and draws it as a line over time. Use it for a number whose trend matters (a temperature, a price, the accuracy of an agent, the players online). The current value is written above the line and the lowest and highest values below it. The line is an inline SVG that needs no chart library.
import { useEffect, useState } from 'react';
import { useWorld } from './useWorld.js';
// The component: copy this part.
const WIDTH = 320;
/**
* Chart: one number of the data of the world as a line over time (a temperature,
* a price, a score), with its value now, its lowest and its highest. The line
* starts from the recent values that the webapp keeps and then adds each new one.
* @param {object} props
* @param {object} props.world - The world, from useWorld.
* @param {string} props.name - The name of the number in `world.data`.
* @param {string} [props.label] - What the number is (by default, the name).
* @param {string} [props.unit=''] - Written after the numbers, for example '°C'.
* @param {number} [props.maxPoints=60] - How many values the line keeps.
* @param {number} [props.height=120] - The height of the line, in pixels.
*/
export function Chart({ world, name, label = name, unit = '', maxPoints = 60, height = 120 }) {
// The values on the line, oldest first: `{ value, time }`.
const [points, setPoints] = useState([]);
// Once, the recent values and then each new one. (The effect runs again only for another
// name, because `dataHistory` and `onData` stay the same at every change of the world.)
useEffect(() => {
let isActive = true;
const add = (value, time) => setPoints((now) => [...now, { value, time }].slice(-maxPoints));
// The recent values that the webapp keeps for each name fill the line at once.
Promise.resolve(world.dataHistory(name)).then((history) => {
if (!isActive) return;
setPoints((now) => [...history.filter((point) => point.time < (now[0]?.time ?? Infinity)), ...now].slice(-maxPoints));
});
const stop = world.onData(name, (value) => add(value, Date.now()));
return () => {
isActive = false;
stop();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [name]);
const numbers = points.filter((point) => typeof point.value === 'number');
const format = (value) => `${value.toLocaleString(world.webapp.language, { maximumFractionDigits: 1 })}${unit ? ` ${unit}` : ''}`;
if (numbers.length === 0) return <p style={{ opacity: 0.6 }}>No values of {label} yet.</p>;
// Turns values and times into places on the drawing. Time goes right and the value goes up.
const values = numbers.map((point) => point.value);
const lowest = Math.min(...values);
const highest = Math.max(...values);
const span = highest - lowest || 1;
const first = numbers[0].time;
const duration = numbers.at(-1).time - first || 1;
const xy = numbers.map((point) => [((point.time - first) / duration) * WIDTH, 8 + (1 - (point.value - lowest) / span) * (height - 16)]);
const line = xy.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' ');
const [lastX, lastY] = xy.at(-1);
const now = format(values.at(-1));
return (
<figure style={{ margin: 0, display: 'grid', gap: 6, maxWidth: 480 }}>
<figcaption style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
<span style={{ opacity: 0.75 }}>{label}</span>
<strong style={{ fontSize: 24, fontVariantNumeric: 'tabular-nums' }}>{now}</strong>
</figcaption>
<svg viewBox={`0 0 ${WIDTH} ${height}`} preserveAspectRatio="none" role="img"
aria-label={`${label}: now ${now}, lowest ${format(lowest)}, highest ${format(highest)}`}
style={{ width: '100%', height, overflow: 'visible', borderRadius: 10, background: 'rgba(127, 127, 127, 0.08)' }}>
<polygon points={`0,${height} ${line} ${lastX},${height}`} fill="rgba(42, 84, 196, 0.15)" />
<polyline points={line} fill="none" stroke="#2A54C4" strokeWidth="2" vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
{/* The newest value. A line of no length with a round end stays a round dot when the drawing stretches. */}
<line x1={lastX} y1={lastY} x2={lastX} y2={lastY} stroke="#2A54C4" strokeWidth="9" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
</svg>
<span style={{ fontSize: 13, opacity: 0.7 }}>Lowest {format(lowest)} · Highest {format(highest)} · last {Math.round(duration / 1000)} s</span>
</figure>
);
}
// Using it, on a fake world.
// A fake world to build with: a temperature that goes up and down, twice a second.
const greenhouse = {
name: 'Greenhouse',
data: { temperature: { every: 500, value: (time) => 21 + 2 * Math.sin(time / 4000) + Math.random() * 0.3 } },
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: greenhouse } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return <Chart world={world} name="temperature" label="Temperature" unit="°C" />;
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
const WIDTH = 320;
const SVG = 'http://www.w3.org/2000/svg';
/**
* Draws into `container` one number of the data of the world as a line over time
* (a temperature, a price, a score), with its value now, its lowest and its
* highest. The line starts from the recent values that the webapp keeps and
* then adds each new one.
* @param {HTMLElement} container - Where to draw it.
* @param {object} world - The world, from connectToHost.
* @param {object} options - What to draw.
* @param {string} options.name - The name of the number in `world.data`.
* @param {string} [options.label] - What the number is (by default, the name).
* @param {string} [options.unit=''] - Written after the numbers, for example '°C'.
* @param {number} [options.maxPoints=60] - How many values the line keeps.
* @param {number} [options.height=120] - The height of the line, in pixels.
* @returns {() => void} Stops following the number and removes what it drew.
*/
export function chart(container, world, { name, label = name, unit = '', maxPoints = 60, height = 120 }) {
const figure = document.createElement('figure');
Object.assign(figure.style, { margin: '0', display: 'grid', gap: '6px', maxWidth: '480px' });
const caption = document.createElement('figcaption');
Object.assign(caption.style, { display: 'flex', alignItems: 'baseline', gap: '10px' });
const what = document.createElement('span');
what.textContent = label;
what.style.opacity = '0.75';
const now = document.createElement('strong');
Object.assign(now.style, { fontSize: '24px', fontVariantNumeric: 'tabular-nums' });
caption.append(what, now);
// The drawing, an SVG stretched to the width of the page.
const svg = document.createElementNS(SVG, 'svg');
svg.setAttribute('viewBox', `0 0 ${WIDTH} ${height}`);
svg.setAttribute('preserveAspectRatio', 'none');
svg.setAttribute('role', 'img');
Object.assign(svg.style, { width: '100%', height: `${height}px`, overflow: 'visible', borderRadius: '10px', background: 'rgba(127, 127, 127, 0.08)' });
const area = document.createElementNS(SVG, 'polygon');
area.setAttribute('fill', 'rgba(42, 84, 196, 0.15)');
const line = document.createElementNS(SVG, 'polyline');
for (const [key, value] of Object.entries({ fill: 'none', stroke: '#2A54C4', 'stroke-width': '2', 'vector-effect': 'non-scaling-stroke', 'stroke-linejoin': 'round' })) line.setAttribute(key, value);
// The newest value. A line of no length with a round end stays a round dot when the drawing stretches.
const dot = document.createElementNS(SVG, 'line');
for (const [key, value] of Object.entries({ stroke: '#2A54C4', 'stroke-width': '9', 'stroke-linecap': 'round', 'vector-effect': 'non-scaling-stroke' })) dot.setAttribute(key, value);
svg.append(area, line, dot);
const range = document.createElement('span');
Object.assign(range.style, { fontSize: '13px', opacity: '0.7' });
const empty = document.createElement('p');
empty.textContent = `No values of ${label} yet.`;
empty.style.opacity = '0.6';
figure.append(caption, svg, range);
container.append(empty);
// The values on the line, oldest first: `{ value, time }`.
let points = [];
const format = (value) => `${value.toLocaleString(world.get().webapp.language, { maximumFractionDigits: 1 })}${unit ? ` ${unit}` : ''}`;
/** Draws the line from the values. */
const draw = () => {
const numbers = points.filter((point) => typeof point.value === 'number');
if (numbers.length === 0) return;
if (!figure.isConnected) empty.replaceWith(figure);
// Turns values and times into places on the drawing. Time goes right and the value goes up.
const values = numbers.map((point) => point.value);
const lowest = Math.min(...values);
const highest = Math.max(...values);
const span = highest - lowest || 1;
const first = numbers[0].time;
const duration = numbers.at(-1).time - first || 1;
const xy = numbers.map((point) => [((point.time - first) / duration) * WIDTH, 8 + (1 - (point.value - lowest) / span) * (height - 16)]);
const coordinates = xy.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' ');
const [lastX, lastY] = xy.at(-1);
line.setAttribute('points', coordinates);
area.setAttribute('points', `0,${height} ${coordinates} ${lastX},${height}`);
for (const key of ['x1', 'x2']) dot.setAttribute(key, String(lastX));
for (const key of ['y1', 'y2']) dot.setAttribute(key, String(lastY));
now.textContent = format(values.at(-1));
svg.setAttribute('aria-label', `${label}: now ${now.textContent}, lowest ${format(lowest)}, highest ${format(highest)}`);
range.textContent = `Lowest ${format(lowest)} · Highest ${format(highest)} · last ${Math.round(duration / 1000)} s`;
};
// The recent values that the webapp keeps for each name fill the line at once.
let isActive = true;
Promise.resolve(world.dataHistory(name)).then((history) => {
if (!isActive) return;
points = [...history.filter((point) => point.time < (points[0]?.time ?? Infinity)), ...points].slice(-maxPoints);
draw();
});
// Then each new value of this name.
const stop = world.onData(name, (value) => {
points = [...points, { value, time: Date.now() }].slice(-maxPoints);
draw();
});
return () => {
isActive = false;
stop();
figure.remove();
empty.remove();
};
}
// Using it, on a fake world.
// A fake world to build with: a temperature that goes up and down, twice a second.
const greenhouse = {
name: 'Greenhouse',
data: { temperature: { every: 500, value: (time) => 21 + 2 * Math.sin(time / 4000) + Math.random() * 0.3 } },
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: greenhouse } });
const place = document.createElement('div');
document.body.append(place);
chart(place, world, { name: 'temperature', label: 'Temperature', unit: '°C' });On mount the component fills the line from world.dataHistory(name). This array of { value, time } objects holds up to 200 recent values that the webapp kept for that name and goes from the oldest to the newest. world.onData(name, listener) then appends each new value with Date.now() as its time. The component wraps the result of dataHistory in Promise.resolve(...). The same code then handles both the Promise returned by the webapp and the array returned by a fake world (dataHistory and onData). The component skips values that are not numbers and shows "No values of label yet." until the first number arrives.
Numbers are formatted with toLocaleString in the language of the webapp (world.webapp.language) with at most one decimal. The accessible name of the SVG states the current, lowest and highest values.
Props
| Prop | Default | What it is |
|---|---|---|
world | (required) | The world returned by useWorld. |
name | (required) | The name of the number in world.data. |
label | the name | The label written above the line. |
unit | '' | The unit written after each number (for example '°C' or '€'). |
maxPoints | 60 | The number of values the line keeps. Older values drop off the left end. |
height | 120 | The height of the line in pixels. The width follows the container up to 480 pixels. |
Parameters
chart(container, world, options) renders the chart into container and updates it on each new value of options.name.
| Parameter | What it is |
|---|---|
container | The element to render into. |
world | The world that connectToHost resolves with. |
options.name | The name of the number in world.data. |
options.label | The label written above the line. Default: the name. |
options.unit | The unit written after each number. Default ''. |
options.maxPoints | The number of values the line keeps. Default 60. |
options.height | The height of the line in pixels. Default 120. |
It returns a function that removes the onData listener and the chart.
Change it
- Start the axis at zero with
Math.min(0, ...values)aslowest. A small change then no longer fills the whole height. - Draw several lines by keeping one list of points per name and drawing each list as a
polylineof its own colour. - Chart a number of each member by collecting its values yourself in
subscribe. The world gives its past and new values throughdataHistoryandonData. A member has only its currentdata. - Use a full chart library and pass it the same
points. The component only shows how to collect them.
See also
- A chart of a number over time: the same idea in a few lines.
Scoreboard: the numbers of several members side by side.- The data of the world.