Skip to content

Chart ​

Chart legge un numero dai dati del mondo e lo disegna come una linea nel tempo. Usalo per un numero di cui conta l'andamento (una temperatura, un prezzo, l'accuratezza di un agente, i giocatori online). Il valore attuale è scritto sopra la linea e i valori minimo e massimo sotto di essa. La linea è un SVG inline che non richiede nessuna libreria di grafici.

jsx
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" />;
}
js
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' });
Live, on a fake world
Open

Al montaggio la linea si riempie con l'array restituito da world.dataHistory(name). L'array contiene fino a 200 oggetti { value, time } con i valori recenti che la webapp conserva per quel nome e va dal più vecchio al più recente. Poi world.onData(name, listener) aggiunge ogni nuovo valore con Date.now() come momento. Il componente avvolge il risultato di dataHistory in Promise.resolve(...). Lo stesso codice gestisce così sia la Promise restituita dalla webapp sia l'array restituito da un mondo finto (dataHistory e onData). I valori che non sono numeri vengono saltati e finché non arriva il primo numero il componente mostra "No values of label yet.".

I numeri sono formattati con toLocaleString nella lingua della webapp (world.webapp.language) con al massimo un decimale. Il nome accessibile dell'SVG riporta il valore attuale, il minimo e il massimo.

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo restituito da useWorld.
name(obbligatorio)Il nome del numero in world.data.
labelil nomeL'etichetta scritta sopra la linea.
unit''L'unità scritta dopo ogni numero (per esempio '°C' o '€').
maxPoints60Il numero di valori che la linea conserva. I valori più vecchi escono dall'estremità sinistra.
height120L'altezza della linea in pixel. La larghezza segue il contenitore fino a 480 pixel.

Parametri ​

chart(container, world, options) disegna il grafico dentro container e lo aggiorna a ogni nuovo valore di options.name.

ParametroChe cos'è
containerL'elemento in cui disegnare.
worldIl mondo con cui si risolve connectToHost.
options.nameIl nome del numero in world.data.
options.labelL'etichetta scritta sopra la linea. Predefinito il nome.
options.unitL'unità scritta dopo ogni numero. Predefinito ''.
options.maxPointsIl numero di valori che la linea conserva. Predefinito 60.
options.heightL'altezza della linea in pixel. Predefinito 120.

Restituisce una funzione che rimuove il listener di onData e il grafico.

Modificalo ​

  • Fai partire l'asse da zero con Math.min(0, ...values) come lowest. Una piccola variazione allora non occupa più tutta l'altezza.
  • Disegna più linee in polyline di colori diversi a partire da una lista di punti per ogni nome.
  • Disegna un numero di ogni membro raccogliendone tu i valori in subscribe. Il mondo fornisce i valori passati e quelli nuovi con dataHistory e onData. Un membro ha solo i suoi data attuali.
  • Usa una libreria di grafici completa passandole gli stessi points. Il componente mostra solo come raccoglierli.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.