MessageChart
MessageChart disegna una voce di message.charts (un grafico a barre, a linee o a torta inviato da un mondo o da un agente) come un SVG inline con una legenda dei colori e il testo di alt come didascalia. Non richiede nessuna libreria di grafici e la tua lista di messaggi può usarlo come fa MessageList.
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>
);
}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);
});Un grafico è un GuiChart { kind, series, alt }:
kind:'bar','line'o'pie'series: un array di{ label, points }in cui ogni punto è[x, y]con unaxstringa o numero e unaynumeroalt: una frase che descrive che cosa mostra il grafico.
Dato che le webapp più vecchie non forniscono message.charts, leggilo come message.charts ?? [].
I grafici a barre e a linee mettono i valori distinti di x a intervalli regolari nell'ordine in cui compaiono la prima volta. L'asse y comprende sempre lo 0 in modo che l'altezza di una barra resti proporzionale al suo valore. Sotto l'asse hanno un'etichetta al massimo otto valori di x. Più serie diventano gruppi di barre affiancate oppure una linea ciascuna con una legenda dei colori. Una torta usa solo la prima serie e disegna una fetta per ogni punto con la sua percentuale nella legenda.
L'SVG e la legenda stanno in un elemento role="img" il cui aria-label è alt. alt compare anche come didascalia visibile. La didascalia è aria-hidden in modo che gli screen reader non leggano due volte lo stesso testo. Un buon alt dice il risultato ("most on Tuesday") e non solo il tipo di grafico ("a bar chart").
MessageChart o Chart. Chart segue un numero nei dati del mondo (una temperatura, un prezzo, i giocatori online) e aggiunge ogni nuovo valore. MessageChart invece disegna un grafico che è arrivato completo in un messaggio e non cambia mai.
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
chart | (obbligatorio) | Una voce di message.charts ({ kind, series, alt }). |
Parametri
messageChart(chart) restituisce un nuovo elemento figure da inserire dove deve stare il grafico. La funzione non si iscrive a niente perché il grafico di un messaggio non cambia mai.
| Parametro | Che cos'è |
|---|---|
chart | Una voce di message.charts ({ kind, series, alt }). |
Modificalo
- Un'altra dimensione: il viewBox è 320 per 170 e l'SVG si allarga fino alla larghezza del suo
figure(al massimo 320 pixel). CambiaWIDTHeHEIGHTper un altro rapporto d'aspetto. - Valori numerici di x alle loro distanze reali: per una linea nel tempo, posiziona ogni punto in base alla sua
x(PLOT.left + ((x - first) / (last - first)) * (PLOT.right - PLOT.left)) invece che in base al suo indice inxs. - I valori sulle barre: aggiungi sopra ogni
rectuntextcony.toLocaleString(world.webapp.language). - I tuoi colori: sostituisci
COLORScon colori che restino distinguibili sia nel tema chiaro sia in quello scuro. - Una libreria di grafici: una vista che ne usa già una può passarle le
seriescosì come sono.MessageChartmostra solo come leggerle.
Vedi anche
- Disegna un grafico da un messaggio: la stessa idea in poche righe.
Chart: un numero dei dati del mondo nel tempo.GuiChart: tutti i campi di un grafico.