Disegna un grafico da un messaggio
Un grafico inviato da un mondo o da un agente porta solo i dati e la tua vista decide come disegnarlo. Ogni grafico in message.charts ha un kind ('bar', 'line' o 'pie'), una lista series (ogni serie con i suoi punti [x, y]) e una frase alt che descrive che cosa mostra. L'esempio disegna i grafici a barre e a linee come SVG inline e sotto ognuno mette il suo alt come didascalia. Chiedi al forno le vendite della settimana per vederli.
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>
</>
);
}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;
}));
});Come funziona
series è una lista di { label, points } i cui punti sono coppie [x, y] con un'etichetta o un numero come x e un numero come y. L'esempio distribuisce i punti a distanze uguali da sinistra a destra nel loro ordine e scala i valori in modo che il più grande arrivi in cima (topOf). Un grafico a barre ha una barra per punto con le serie affiancate (barsOf). In un grafico a linee ogni serie diventa invece una polyline (linePoints). I nomi delle serie compaiono sotto il disegno nei loro colori.
- L'
altva in un<figcaption>che vede ogni lettore. Conaria-hidden="true"sul disegno uno screen reader lo salta e legge la descrizione una volta sola. - Per un grafico a torta l'esempio mostra la didascalia senza disegno. Gli archi SVG o una libreria di grafici caricata dalla tua vista possono disegnarlo.
textcontiene solo il testo scritto del messaggio e il grafico non vi compare mai.- Con una webapp più vecchia
chartsmanca emessage.charts ?? []dà una lista vuota e la vista non disegna niente. - La risposta di un mondo finto può portare
charts: [{ kind, series, alt }]come nell'esempio.
Vedi anche
- MessageChart: grafici a barre, a linee e a torta pronti.
- Un grafico di un numero nel tempo: un grafico da
data. - Mostra video e PDF da un messaggio
GuiMessage