Skip to content

Draw a chart from a message ​

A chart sent by a world or an agent carries only data and your view decides how to draw it. Each chart in message.charts has three fields: a kind ('bar', 'line' or 'pie'), a series list (each series with its [x, y] points) and an alt sentence that describes what the chart shows. The example draws bar and line charts as inline SVG with the alt under each one as its caption. Ask the bakery for the sales of the week to see them.

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

// While you build, a fake bakery answers with a bar chart and a line chart.
const bakery = {
	name: 'Bakery',
	onMessage: () => ({
		text: 'The sales of the week.',
		charts: [
			{
				kind: 'bar',
				series: [{ label: 'Loaves', points: [['Mon', 40], ['Tue', 25], ['Wed', 55]] }],
				alt: 'Loaves sold: 40 on Monday, 25 on Tuesday, 55 on Wednesday.',
			},
			{
				kind: 'line',
				series: [
					{ label: 'Bread', points: [['Mon', 40], ['Tue', 25], ['Wed', 55]] },
					{ label: 'Cakes', points: [['Mon', 10], ['Tue', 30], ['Wed', 20]] },
				],
				alt: 'Bread fell on Tuesday and rose on Wednesday; cakes did the opposite.',
			},
		],
	}),
};

// The size of a chart, and a colour for each series.
const WIDTH = 300;
const HEIGHT = 120;
const COLORS = ['#2563eb', '#d35400', '#16a34a'];

// The tallest value of a chart reaches the top.
function topOf(chart) {
	return Math.max(1, ...chart.series.flatMap((series) => series.points.map(([, y]) => y)));
}

// A line chart draws one series as an SVG polyline, with its points spaced evenly from left to right.
function linePoints(series, top) {
	const step = WIDTH / Math.max(series.points.length - 1, 1);
	return series.points.map(([, y], index) => `${index * step},${HEIGHT - (y / top) * HEIGHT}`).join(' ');
}

// A bar chart has a bar for each point, with the series side by side.
function barsOf(chart, top) {
	const bars = [];
	chart.series.forEach((series, which) => {
		const slot = WIDTH / series.points.length;
		const width = slot / (chart.series.length + 1);
		series.points.forEach(([, y], index) => {
			const height = (y / top) * HEIGHT;
			bars.push({ x: index * slot + (which + 0.5) * width, y: HEIGHT - height, width, height, color: COLORS[which % COLORS.length] });
		});
	});
	return bars;
}

// One chart shows the drawing and the names of the series, then its `alt` as the caption.
function ChartView({ chart }) {
	const isDrawn = chart.kind === 'bar' || chart.kind === 'line';
	const top = topOf(chart);
	return (
		<figure style={{ margin: '8px 0' }}>
			{isDrawn && (
				<>
					{/* Screen readers skip the drawing, because the caption already says what the chart shows. */}
					<svg viewBox={`0 0 ${WIDTH} ${HEIGHT}`} width={WIDTH} height={HEIGHT} aria-hidden="true" style={{ border: '1px solid #8888' }}>
						{chart.kind === 'bar' && barsOf(chart, top).map((bar, index) => (
							<rect key={index} x={bar.x} y={bar.y} width={bar.width} height={bar.height} fill={bar.color} />
						))}
						{chart.kind === 'line' && chart.series.map((series, which) => (
							<polyline key={which} points={linePoints(series, top)} fill="none" stroke={COLORS[which % COLORS.length]} strokeWidth="2" />
						))}
					</svg>
					<div>
						{chart.series.map((series, which) => (
							<span key={which} style={{ color: COLORS[which % COLORS.length], marginRight: 12 }}>■ {series.label}</span>
						))}
					</div>
				</>
			)}
			<figcaption>{chart.alt}</figcaption>
		</figure>
	);
}

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			{world.messages.map((message) => (
				<div key={message.id}>
					<p>{message.fromMe ? 'You' : message.from}: {message.text}</p>
					{/* With an older webapp, `charts` is missing and the list is empty. */}
					{(message.charts ?? []).map((chart, index) => <ChartView key={index} chart={chart} />)}
				</div>
			))}
			<button onClick={() => world.send('Show the sales')} disabled={!world.canSend}>Show the sales</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// While you build, a fake bakery answers with a bar chart and a line chart.
const bakery = {
	name: 'Bakery',
	onMessage: () => ({
		text: 'The sales of the week.',
		charts: [
			{
				kind: 'bar',
				series: [{ label: 'Loaves', points: [['Mon', 40], ['Tue', 25], ['Wed', 55]] }],
				alt: 'Loaves sold: 40 on Monday, 25 on Tuesday, 55 on Wednesday.',
			},
			{
				kind: 'line',
				series: [
					{ label: 'Bread', points: [['Mon', 40], ['Tue', 25], ['Wed', 55]] },
					{ label: 'Cakes', points: [['Mon', 10], ['Tue', 30], ['Wed', 20]] },
				],
				alt: 'Bread fell on Tuesday and rose on Wednesday; cakes did the opposite.',
			},
		],
	}),
};

// The size of a chart, and a colour for each series.
const WIDTH = 300;
const HEIGHT = 120;
const COLORS = ['#2563eb', '#d35400', '#16a34a'];

// The tallest value of a chart reaches the top.
function topOf(chart) {
	return Math.max(1, ...chart.series.flatMap((series) => series.points.map(([, y]) => y)));
}

// A line chart draws one series as an SVG polyline, with its points spaced evenly from left to right.
function linePoints(series, top) {
	const step = WIDTH / Math.max(series.points.length - 1, 1);
	return series.points.map(([, y], index) => `${index * step},${HEIGHT - (y / top) * HEIGHT}`).join(' ');
}

// A bar chart has a bar for each point, with the series side by side.
function barsOf(chart, top) {
	const bars = [];
	chart.series.forEach((series, which) => {
		const slot = WIDTH / series.points.length;
		const width = slot / (chart.series.length + 1);
		series.points.forEach(([, y], index) => {
			const height = (y / top) * HEIGHT;
			bars.push({ x: index * slot + (which + 0.5) * width, y: HEIGHT - height, width, height, color: COLORS[which % COLORS.length] });
		});
	});
	return bars;
}

// Makes an SVG element with its attributes.
function svgElement(name, attributes) {
	const element = document.createElementNS('http://www.w3.org/2000/svg', name);
	for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, value);
	return element;
}

// One chart shows the drawing and the names of the series, then its `alt` as the caption.
function chartView(chart) {
	const figure = document.createElement('figure');
	figure.style.margin = '8px 0';
	if (chart.kind === 'bar' || chart.kind === 'line') {
		// Screen readers skip the drawing, because the caption already says what the chart shows.
		const svg = svgElement('svg', { viewBox: `0 0 ${WIDTH} ${HEIGHT}`, width: WIDTH, height: HEIGHT, 'aria-hidden': 'true' });
		svg.style.border = '1px solid #8888';
		const top = topOf(chart);
		if (chart.kind === 'bar') {
			for (const bar of barsOf(chart, top)) svg.append(svgElement('rect', { x: bar.x, y: bar.y, width: bar.width, height: bar.height, fill: bar.color }));
		} else {
			chart.series.forEach((series, which) => {
				svg.append(svgElement('polyline', { points: linePoints(series, top), fill: 'none', stroke: COLORS[which % COLORS.length], 'stroke-width': 2 }));
			});
		}
		const legend = document.createElement('div');
		chart.series.forEach((series, which) => {
			const name = document.createElement('span');
			name.style.cssText = `color: ${COLORS[which % COLORS.length]}; margin-right: 12px;`;
			name.textContent = `■ ${series.label}`;
			legend.append(name);
		});
		figure.append(svg, legend);
	}
	const caption = document.createElement('figcaption');
	caption.textContent = chart.alt;
	figure.append(caption);
	return figure;
}

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

const list = document.createElement('div');
const ask = document.createElement('button');
ask.textContent = 'Show the sales';
ask.onclick = () => world.send('Show the sales');
document.body.append(list, ask);

world.subscribe((node) => {
	ask.disabled = !node.canSend;
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('div');
		const line = document.createElement('p');
		line.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
		item.append(line);
		// With an older webapp, `charts` is missing and the list is empty.
		for (const chart of message.charts ?? []) item.append(chartView(chart));
		return item;
	}));
});
Live, on a fake world
Open

How it works ​

series is a list of { label, points } whose points are [x, y] pairs with a label or a number as x and a number as y. The example spaces the points evenly from left to right in their order and scales the values to let the largest one reach the top (topOf). A bar chart gets one bar per point with the series side by side (barsOf). Each series of a line chart becomes one polyline instead (linePoints). The names of the series appear under the drawing in their colours.

  • The alt goes in a <figcaption> that every reader sees. With aria-hidden="true" on the drawing a screen reader skips it and reads the description only once.
  • For a pie chart the example renders the caption without a drawing. SVG arcs or a charting library loaded by your view can draw one.
  • text holds only the written text of the message and the chart never appears in it.
  • With an older webapp charts is missing and message.charts ?? [] gives an empty list and the view draws nothing.
  • The answer of a fake world can carry charts: [{ kind, series, alt }] as in the example.

See also ​

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