Skip to content

MessageChart ​

MessageChart draws one entry of message.charts (a bar, line or pie chart sent by a world or an agent) as an inline SVG with a colour key and the alt text as its caption. It needs no chart library and your own message list can use it like MessageList does.

jsx
import { useWorld } from './useWorld.js';

// The component: copy this part.

// The size of the drawing (its viewBox). The drawing stretches to the width it is given.
const WIDTH = 320;
const HEIGHT = 170;
// Where the bars and lines go: room above for the highest value, below for the x labels.
const PLOT = { left: 6, right: WIDTH - 6, top: 18, bottom: HEIGHT - 22 };
// One colour per series (or per slice of a pie).
const COLORS = ['#2A54C4', '#F0A54E', '#399D57', '#9F466B', '#7A5CC2', '#2BA3A3'];

/** Rounds a place in the drawing to one decimal, to keep the SVG short. */
const at = (value) => Math.round(value * 10) / 10;

/**
 * Works out where a bar or line chart goes in the drawing: every x value in
 * the order they first appear, evenly spaced, and the height of each y.
 * @param {object} chart - A chart of `message.charts`.
 * @returns {{xs: Array, xOf: (index: number) => number, yOf: (y: number) => number, highest: number, slot: number}} The scales.
 */
function scalesOf(chart) {
	const xs = [...new Set(chart.series.flatMap((series) => series.points.map(([x]) => x)))];
	const ys = chart.series.flatMap((series) => series.points.map(([, y]) => y));
	// Start from 0, to make the height of a bar mean its value.
	const highest = Math.max(0, ...ys);
	const lowest = Math.min(0, ...ys);
	const slot = (PLOT.right - PLOT.left) / Math.max(1, xs.length);
	return {
		xs,
		slot,
		highest,
		xOf: (index) => PLOT.left + slot * (index + 0.5),
		yOf: (y) => PLOT.top + ((highest - y) / (highest - lowest || 1)) * (PLOT.bottom - PLOT.top),
	};
}

/**
 * Works out the slices of a pie, from the first series: one slice per point,
 * as big as its share of the total.
 * @param {object} chart - A pie chart of `message.charts`.
 * @returns {Array<{path: string, color: string, label: string}>} The slices.
 */
function slicesOf(chart) {
	const points = chart.series[0]?.points ?? [];
	const values = points.map(([, y]) => Math.max(0, y));
	const total = values.reduce((sum, value) => sum + value, 0) || 1;
	const [cx, cy, r] = [WIDTH / 2, HEIGHT / 2, HEIGHT / 2 - 4];
	let angle = -Math.PI / 2; // the first slice starts at the top
	return points.map(([x], index) => {
		const share = values[index] / total;
		const start = angle;
		angle += share * 2 * Math.PI;
		const large = share > 0.5 ? 1 : 0;
		// A whole circle is not one arc: draw it as two halves.
		const path = share > 0.999
			? `M${cx - r} ${cy}A${r} ${r} 0 1 1 ${cx + r} ${cy}A${r} ${r} 0 1 1 ${cx - r} ${cy}Z`
			: `M${cx} ${cy}L${at(cx + r * Math.cos(start))} ${at(cy + r * Math.sin(start))}A${r} ${r} 0 ${large} 1 ${at(cx + r * Math.cos(angle))} ${at(cy + r * Math.sin(angle))}Z`;
		return { path, color: COLORS[index % COLORS.length], label: `${x} · ${Math.round(share * 100)}%` };
	});
}

/**
 * MessageChart: a chart that a message shows (`message.charts`), as a small
 * SVG: bars, lines, or a pie. Its `alt` names the drawing for screen readers
 * and is its caption.
 * @param {object} props
 * @param {object} props.chart - One chart of `message.charts`: `{ kind, series, alt }`.
 */
export function MessageChart({ chart }) {
	const isPie = chart.kind === 'pie';
	const slices = isPie ? slicesOf(chart) : [];
	const { xs, slot, highest, xOf, yOf } = scalesOf(chart);
	// A label under every x value, or under some of them when there are many.
	const step = Math.ceil(xs.length / 8);
	// The colour key: the slices of a pie, or the series when there are several.
	const legend = isPie
		? slices.map((slice) => ({ label: slice.label, color: slice.color }))
		: chart.series.length > 1 ? chart.series.map((series, index) => ({ label: series.label, color: COLORS[index % COLORS.length] })) : [];

	return (
		<figure style={{ margin: 0, width: 320, maxWidth: '100%' }}>
			{/* Screen readers take the drawing as one picture, named by the alt, and do not read what is inside. */}
			<div role="img" aria-label={chart.alt}>
				<svg viewBox={`0 0 ${WIDTH} ${HEIGHT}`} style={{ display: 'block', width: '100%', height: 'auto', borderRadius: 10, background: 'rgba(127, 127, 127, 0.08)' }}>
					{isPie && slices.map((slice, index) => <path key={index} d={slice.path} fill={slice.color} stroke="Canvas" strokeWidth="1.5" />)}
					{!isPie && (
						<>
							<text x={PLOT.left} y={12} fontSize="10" fill="currentColor" opacity="0.7">{highest.toLocaleString()}</text>
							<line x1={PLOT.left} x2={PLOT.right} y1={yOf(0)} y2={yOf(0)} stroke="currentColor" strokeOpacity="0.3" />
							{xs.map((x, index) => index % step === 0 && (
								<text key={index} x={at(xOf(index))} y={HEIGHT - 7} fontSize="10" textAnchor="middle" fill="currentColor" opacity="0.7">{String(x).slice(0, 10)}</text>
							))}
						</>
					)}
					{chart.kind === 'bar' && chart.series.map((series, s) => {
						// Side by side: each x value has a group of bars, one per series.
						const width = (slot * 0.8) / chart.series.length;
						return series.points.map(([x, y], index) => (
							<rect key={`${s}-${index}`} x={at(xOf(xs.indexOf(x)) - slot * 0.4 + s * width)} y={at(yOf(Math.max(0, y)))}
								width={at(width * 0.9)} height={at(Math.abs(yOf(y) - yOf(0)))} rx="2" fill={COLORS[s % COLORS.length]} />
						));
					})}
					{chart.kind === 'line' && chart.series.map((series, s) => (
						<polyline key={s} fill="none" stroke={COLORS[s % COLORS.length]} strokeWidth="2" strokeLinejoin="round"
							points={series.points.map(([x, y]) => `${at(xOf(xs.indexOf(x)))},${at(yOf(y))}`).join(' ')} />
					))}
				</svg>
				{legend.length > 0 && (
					<ul style={{ listStyle: 'none', margin: '6px 0 0', padding: 0, display: 'flex', flexWrap: 'wrap', gap: '2px 12px', fontSize: 13 }}>
						{legend.map((item, index) => (
							<li key={index} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
								<span style={{ width: 10, height: 10, borderRadius: 2, background: item.color }} />
								{item.label}
							</li>
						))}
					</ul>
				)}
			</div>
			{/* The same words as the name of the drawing, hidden from screen readers because they already say that name. */}
			<figcaption aria-hidden="true" style={{ marginTop: 4, fontSize: 13, opacity: 0.75 }}>{chart.alt}</figcaption>
		</figure>
	);
}

// Using it, on a fake agent.

// A fake agent to build with: it answers with three charts, as a real agent can.
const weather = {
	name: 'Weather',
	onMessage: () => ({
		text: 'Here is the week.',
		charts: [
			{ kind: 'bar', series: [{ label: 'Rain (mm)', points: [['Mon', 4], ['Tue', 12], ['Wed', 0], ['Thu', 7], ['Fri', 2]] }], alt: 'Rain this week: most on Tuesday, 12 mm, none on Wednesday.' },
			{
				kind: 'line',
				series: [
					{ label: 'Today', points: [['6:00', 9], ['9:00', 13], ['12:00', 18], ['15:00', 19], ['18:00', 15]] },
					{ label: 'Yesterday', points: [['6:00', 7], ['9:00', 10], ['12:00', 14], ['15:00', 16], ['18:00', 12]] },
				],
				alt: 'Temperature today and yesterday: today is warmer all day, up to 19 °C at 15:00.',
			},
			{ kind: 'pie', series: [{ label: 'Sky', points: [['Sunny', 3], ['Cloudy', 1], ['Rainy', 1]] }], alt: 'The sky this week: 3 sunny days, 1 cloudy, 1 rainy.' },
		],
	}),
};

export default function App() {
	// While building: the fake agent. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { agent: weather } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	// The messages with charts (`charts` is missing with an older webapp).
	const withCharts = world.messages.filter((message) => (message.charts ?? []).length > 0);
	return (
		<div style={{ display: 'grid', gap: 12 }}>
			<button type="button" disabled={!world.canSend} onClick={() => world.send('How was the week?')} style={{ justifySelf: 'start' }}>Show the charts</button>
			{withCharts.map((message) => (
				<section key={message.id} style={{ display: 'grid', gap: 8 }}>
					<p style={{ margin: 0 }}>{message.text}</p>
					<div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
						{message.charts.map((chart, index) => <MessageChart key={index} chart={chart} />)}
					</div>
				</section>
			))}
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

// The size of the drawing (its viewBox). The drawing stretches to the width it is given.
const WIDTH = 320;
const HEIGHT = 170;
// Where the bars and lines go: room above for the highest value, below for the x labels.
const PLOT = { left: 6, right: WIDTH - 6, top: 18, bottom: HEIGHT - 22 };
// One colour per series (or per slice of a pie).
const COLORS = ['#2A54C4', '#F0A54E', '#399D57', '#9F466B', '#7A5CC2', '#2BA3A3'];
const SVG = 'http://www.w3.org/2000/svg';

/** Rounds a place in the drawing to one decimal, to keep the SVG short. */
const at = (value) => Math.round(value * 10) / 10;

/**
 * Works out where a bar or line chart goes in the drawing: every x value in
 * the order they first appear, evenly spaced, and the height of each y.
 * @param {object} chart - A chart of `message.charts`.
 * @returns {{xs: Array, xOf: (index: number) => number, yOf: (y: number) => number, highest: number, slot: number}} The scales.
 */
function scalesOf(chart) {
	const xs = [...new Set(chart.series.flatMap((series) => series.points.map(([x]) => x)))];
	const ys = chart.series.flatMap((series) => series.points.map(([, y]) => y));
	// Start from 0, to make the height of a bar mean its value.
	const highest = Math.max(0, ...ys);
	const lowest = Math.min(0, ...ys);
	const slot = (PLOT.right - PLOT.left) / Math.max(1, xs.length);
	return {
		xs,
		slot,
		highest,
		xOf: (index) => PLOT.left + slot * (index + 0.5),
		yOf: (y) => PLOT.top + ((highest - y) / (highest - lowest || 1)) * (PLOT.bottom - PLOT.top),
	};
}

/**
 * Works out the slices of a pie, from the first series: one slice per point,
 * as big as its share of the total.
 * @param {object} chart - A pie chart of `message.charts`.
 * @returns {Array<{path: string, color: string, label: string}>} The slices.
 */
function slicesOf(chart) {
	const points = chart.series[0]?.points ?? [];
	const values = points.map(([, y]) => Math.max(0, y));
	const total = values.reduce((sum, value) => sum + value, 0) || 1;
	const [cx, cy, r] = [WIDTH / 2, HEIGHT / 2, HEIGHT / 2 - 4];
	let angle = -Math.PI / 2; // the first slice starts at the top
	return points.map(([x], index) => {
		const share = values[index] / total;
		const start = angle;
		angle += share * 2 * Math.PI;
		const large = share > 0.5 ? 1 : 0;
		// A whole circle is not one arc: draw it as two halves.
		const path = share > 0.999
			? `M${cx - r} ${cy}A${r} ${r} 0 1 1 ${cx + r} ${cy}A${r} ${r} 0 1 1 ${cx - r} ${cy}Z`
			: `M${cx} ${cy}L${at(cx + r * Math.cos(start))} ${at(cy + r * Math.sin(start))}A${r} ${r} 0 ${large} 1 ${at(cx + r * Math.cos(angle))} ${at(cy + r * Math.sin(angle))}Z`;
		return { path, color: COLORS[index % COLORS.length], label: `${x} · ${Math.round(share * 100)}%` };
	});
}

/**
 * Makes an SVG element with its attributes.
 * @param {string} tag - The element, e.g. 'rect'.
 * @param {object} attributes - Its attributes, by name.
 * @returns {SVGElement} The element.
 */
function svgElement(tag, attributes) {
	const element = document.createElementNS(SVG, tag);
	for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, String(value));
	return element;
}

/**
 * Makes the element of a chart that a message shows (`message.charts`), as a
 * small SVG: bars, lines, or a pie. Its `alt` names the drawing for screen
 * readers and is its caption.
 * @param {object} chart - One chart of `message.charts`: `{ kind, series, alt }`.
 * @returns {HTMLElement} The element (a `figure`).
 */
export function messageChart(chart) {
	const isPie = chart.kind === 'pie';
	const slices = isPie ? slicesOf(chart) : [];
	const { xs, slot, highest, xOf, yOf } = scalesOf(chart);

	const svg = svgElement('svg', { viewBox: `0 0 ${WIDTH} ${HEIGHT}` });
	Object.assign(svg.style, { display: 'block', width: '100%', height: 'auto', borderRadius: '10px', background: 'rgba(127, 127, 127, 0.08)' });
	if (isPie) {
		slices.forEach((slice) => svg.append(svgElement('path', { d: slice.path, fill: slice.color, stroke: 'Canvas', 'stroke-width': 1.5 })));
	} else {
		const top = svgElement('text', { x: PLOT.left, y: 12, 'font-size': 10, fill: 'currentColor', opacity: 0.7 });
		top.textContent = highest.toLocaleString();
		svg.append(top, svgElement('line', { x1: PLOT.left, x2: PLOT.right, y1: yOf(0), y2: yOf(0), stroke: 'currentColor', 'stroke-opacity': 0.3 }));
		// A label under every x value, or under some of them when there are many.
		const step = Math.ceil(xs.length / 8);
		xs.forEach((x, index) => {
			if (index % step !== 0) return;
			const label = svgElement('text', { x: at(xOf(index)), y: HEIGHT - 7, 'font-size': 10, 'text-anchor': 'middle', fill: 'currentColor', opacity: 0.7 });
			label.textContent = String(x).slice(0, 10);
			svg.append(label);
		});
	}
	if (chart.kind === 'bar') {
		// Side by side: each x value has a group of bars, one per series.
		const width = (slot * 0.8) / chart.series.length;
		chart.series.forEach((series, s) => {
			series.points.forEach(([x, y]) => svg.append(svgElement('rect', {
				x: at(xOf(xs.indexOf(x)) - slot * 0.4 + s * width), y: at(yOf(Math.max(0, y))),
				width: at(width * 0.9), height: at(Math.abs(yOf(y) - yOf(0))), rx: 2, fill: COLORS[s % COLORS.length],
			})));
		});
	}
	if (chart.kind === 'line') {
		chart.series.forEach((series, s) => svg.append(svgElement('polyline', {
			fill: 'none', stroke: COLORS[s % COLORS.length], 'stroke-width': 2, 'stroke-linejoin': 'round',
			points: series.points.map(([x, y]) => `${at(xOf(xs.indexOf(x)))},${at(yOf(y))}`).join(' '),
		})));
	}

	// Screen readers take the drawing as one picture, named by the alt, and do not read what is inside.
	const picture = document.createElement('div');
	picture.setAttribute('role', 'img');
	picture.setAttribute('aria-label', chart.alt);
	picture.append(svg);

	// The colour key: the slices of a pie, or the series when there are several.
	const legend = isPie
		? slices.map((slice) => ({ label: slice.label, color: slice.color }))
		: chart.series.length > 1 ? chart.series.map((series, index) => ({ label: series.label, color: COLORS[index % COLORS.length] })) : [];
	if (legend.length > 0) {
		const list = document.createElement('ul');
		Object.assign(list.style, { listStyle: 'none', margin: '6px 0 0', padding: '0', display: 'flex', flexWrap: 'wrap', gap: '2px 12px', fontSize: '13px' });
		for (const item of legend) {
			const row = document.createElement('li');
			Object.assign(row.style, { display: 'flex', alignItems: 'center', gap: '6px' });
			const swatch = document.createElement('span');
			Object.assign(swatch.style, { width: '10px', height: '10px', borderRadius: '2px', background: item.color });
			row.append(swatch, document.createTextNode(item.label));
			list.append(row);
		}
		picture.append(list);
	}

	// The same words as the name of the drawing, hidden from screen readers because they already say that name.
	const caption = document.createElement('figcaption');
	caption.setAttribute('aria-hidden', 'true');
	caption.textContent = chart.alt;
	Object.assign(caption.style, { marginTop: '4px', fontSize: '13px', opacity: '0.75' });

	const figure = document.createElement('figure');
	Object.assign(figure.style, { margin: '0', width: '320px', maxWidth: '100%' });
	figure.append(picture, caption);
	return figure;
}

// Using it, on a fake agent.

// A fake agent to build with: it answers with three charts, as a real agent can.
const weather = {
	name: 'Weather',
	onMessage: () => ({
		text: 'Here is the week.',
		charts: [
			{ kind: 'bar', series: [{ label: 'Rain (mm)', points: [['Mon', 4], ['Tue', 12], ['Wed', 0], ['Thu', 7], ['Fri', 2]] }], alt: 'Rain this week: most on Tuesday, 12 mm, none on Wednesday.' },
			{
				kind: 'line',
				series: [
					{ label: 'Today', points: [['6:00', 9], ['9:00', 13], ['12:00', 18], ['15:00', 19], ['18:00', 15]] },
					{ label: 'Yesterday', points: [['6:00', 7], ['9:00', 10], ['12:00', 14], ['15:00', 16], ['18:00', 12]] },
				],
				alt: 'Temperature today and yesterday: today is warmer all day, up to 19 °C at 15:00.',
			},
			{ kind: 'pie', series: [{ label: 'Sky', points: [['Sunny', 3], ['Cloudy', 1], ['Rainy', 1]] }], alt: 'The sky this week: 3 sunny days, 1 cloudy, 1 rainy.' },
		],
	}),
};

// While building: the fake agent. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { agent: weather } });

const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px' });
const ask = document.createElement('button');
ask.textContent = 'Show the charts';
ask.style.justifySelf = 'start';
ask.onclick = () => world.send('How was the week?');
const place = document.createElement('div');
Object.assign(place.style, { display: 'grid', gap: '12px' });
page.append(ask, place);
document.body.append(page);

// Draws the messages with charts again when a message arrives (`charts` is missing with an older webapp).
let shownCount = -1;
world.subscribe((node) => {
	ask.disabled = !node.canSend;
	if (node.messages.length === shownCount) return;
	shownCount = node.messages.length;
	const sections = node.messages.filter((message) => (message.charts ?? []).length > 0).map((message) => {
		const section = document.createElement('section');
		Object.assign(section.style, { display: 'grid', gap: '8px' });
		const words = document.createElement('p');
		words.style.margin = '0';
		words.textContent = message.text ?? '';
		const charts = document.createElement('div');
		Object.assign(charts.style, { display: 'flex', flexWrap: 'wrap', gap: '16px' });
		charts.append(...message.charts.map((chart) => messageChart(chart)));
		section.append(words, charts);
		return section;
	});
	place.replaceChildren(...sections);
});
Live, on a fake world
Open

A chart is a GuiChart { kind, series, alt }:

  • kind: 'bar', 'line' or 'pie'
  • series: an array of { label, points } where each point is [x, y] with a string or number x and a number y
  • alt: a sentence that describes what the chart shows.

Because older webapps do not provide message.charts, read it as message.charts ?? [].

Bar and line charts place the distinct x values at even intervals in the order of their first appearance. The y axis always includes 0 to keep the height of a bar proportional to its value. Under the axis at most eight of the x values get a label. Several series become groups of bars side by side or one line each with a colour key. A pie uses only the first series and draws one slice per point with its percentage in the key.

The SVG and the key sit in a role="img" element whose aria-label is alt. alt also appears as a visible caption. The caption is aria-hidden to keep screen readers from reading the text twice. A good alt states the finding ("most on Tuesday") and not only the kind of chart ("a bar chart").

MessageChart or Chart. Chart follows a number in the data of the world (a temperature, a price, the players online) and appends each new value. MessageChart, on the other hand, draws a chart that arrived complete in a message and never changes.

Props ​

PropDefaultWhat it is
chart(required)One entry of message.charts ({ kind, series, alt }).

Parameters ​

messageChart(chart) returns a new figure element to insert where the chart belongs. The function subscribes to nothing since the chart of a message never changes.

ParameterWhat it is
chartOne entry of message.charts ({ kind, series, alt }).

Change it ​

  • Another size: the viewBox is 320 by 170 and the SVG stretches to the width of its figure (at most 320 pixels). Change WIDTH and HEIGHT for another aspect ratio.
  • Numeric x at true distances: for a line over time, place each point by its x (PLOT.left + ((x - first) / (last - first)) * (PLOT.right - PLOT.left)) instead of by its index in xs.
  • Values on the bars: add a text above each rect with y.toLocaleString(world.webapp.language).
  • Your colours: replace COLORS with colours that stay distinct in both the light and the dark theme.
  • A chart library: a view that already uses one can pass it series unchanged. MessageChart only shows how to read them.

See also ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.