Skip to content

MessageList ​

MessageList mostra world.messages dal messaggio più vecchio al più recente dentro un contenitore scorrevole. I messaggi della persona stanno a destra, quelli degli altri a sinistra e le note delle regole al centro. Ogni messaggio mostra le sue parti in un ordine fisso: (1) le immagini, (2) text, (3) i file come link da scaricare, (4) video, audio, PDF e link attraverso MediaView e (5) i grafici attraverso MessageChart.

jsx
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';

// The component: copy this part. It uses MediaView and MessageChart, further down.

/**
 * A file of a message: a link that saves it, or only its name when its
 * content was not kept (the person's own file, after a reload).
 * @param {object} props
 * @param {object} props.file - A file of `message.files`: `{ name, type, url }`.
 */
function FileLink({ file }) {
	// The files of an agent arrive with no name: say what kind of file it is.
	const name = file.name ?? `a file (${file.type ?? 'unknown type'})`;
	if (!file.url) return <span>{name}</span>;
	// `download` saves the file instead of opening it.
	return <a href={file.url} download={file.name ?? ''} style={{ color: 'inherit', fontWeight: 600 }}>Download {name}</a>;
}

/**
 * What a message shows, in order: its pictures, its words, its files, its
 * videos and sounds, its charts. `?? []` reads the last three as none, because
 * they are missing with an older webapp.
 * @param {object} props
 * @param {object} props.message - A message of `world.messages`.
 * @param {string|null} props.who - Who sent it, for the description of the pictures, or null when it is not shown.
 */
function Parts({ message, who }) {
	const images = message.images ?? (message.image ? [message.image] : []);
	return (
		<>
			{images.length > 0 && (
				<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
					{/* A fixed height keeps the list from jumping when a picture arrives. */}
					{images.map((image, index) => (
						<img key={index} src={image} alt={who ? `Picture from ${who}` : 'Picture'}
							style={{ display: 'block', height: 140, width: 'auto', maxWidth: '100%', objectFit: 'contain', borderRadius: 10 }} />
					))}
				</div>
			)}
			{message.text && <div style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}>{message.text}</div>}
			{(message.files ?? []).map((file, index) => <FileLink key={index} file={file} />)}
			{(message.media ?? []).map((media, index) => <MediaView key={index} media={media} />)}
			{(message.charts ?? []).map((chart, index) => <MessageChart key={index} chart={chart} />)}
		</>
	);
}

/**
 * One message: the person's on the right, the others' on the left, and the
 * notes of the rules in the middle.
 * @param {object} props
 * @param {object} props.message - A message of `world.messages`.
 * @param {string} props.language - The language of the webapp, for the time.
 * @param {boolean} props.showsSenders - False when the world asks not to show who wrote each message.
 */
function Message({ message, language, showsSenders }) {
	const time = new Date(message.time).toLocaleTimeString(language, { hour: '2-digit', minute: '2-digit' });

	if (message.isSystem) {
		return (
			<div style={{ alignSelf: 'center', maxWidth: '90%', display: 'grid', gap: 6, justifyItems: 'center', padding: '4px 12px', borderRadius: 9, fontSize: 13, textAlign: 'center', background: 'rgba(127, 127, 127, 0.1)' }}>
				<Parts message={message} who={null} />
			</div>
		);
	}

	const isMine = message.fromMe;
	// The sender's name, unless the world asks not to show it.
	const sender = showsSenders ? message.from ?? 'Someone' : null;
	let meta = time;
	if (!isMine && sender) meta = `${sender} · ${time}`;
	if (message.status === 'sending') meta = `${time} · Sending…`;
	if (message.status === 'failed') meta = `${time} · Not sent`;

	return (
		<div style={{ alignSelf: isMine ? 'flex-end' : 'flex-start', maxWidth: '80%', display: 'grid', gap: 2, justifyItems: isMine ? 'end' : 'start' }}>
			<span style={{ fontSize: 12, opacity: 0.7 }}>{meta}</span>
			<div style={{
				display: 'grid', gap: 6, padding: '8px 12px', borderRadius: 14,
				background: isMine ? '#2A54C4' : 'rgba(127, 127, 127, 0.14)', color: isMine ? '#fff' : 'inherit',
				opacity: message.status === 'sending' ? 0.7 : 1,
			}}>
				<Parts message={message} who={isMine ? 'you' : sender} />
			</div>
			{/* The person can send their failed message again. */}
			{message.status === 'failed' && message.retry && (
				<button type="button" onClick={() => message.retry().catch(() => {})}
					style={{ font: 'inherit', fontSize: 13, padding: '2px 10px', borderRadius: 9, border: '1px solid rgba(229, 69, 58, 0.6)', background: 'transparent', color: 'inherit', cursor: 'pointer' }}>
					Retry
				</button>
			)}
		</div>
	);
}

/**
 * MessageList: the conversation between the person and the world (or the
 * agent), oldest first, with every picture, file, video, sound and chart. It
 * follows the newest message unless the person has scrolled up to read.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {number|string} [props.height=320] - The height of the list (the messages scroll inside it).
 * @param {string} [props.emptyText='No messages yet.'] - What it says before the first message.
 */
export function MessageList({ world, height = 320, emptyText = 'No messages yet.' }) {
	const listRef = useRef(null);
	// True while the person is at the bottom of the list. Only then does the list follow new messages.
	const isFollowingRef = useRef(true);
	const messages = world.messages;
	const newest = messages.at(-1);
	// Show the senders unless the world asks not to (an older webapp gives no `showsSenders`).
	const showsSenders = world.showsSenders !== false;

	const onScroll = () => {
		const list = listRef.current;
		isFollowingRef.current = list.scrollHeight - list.scrollTop - list.clientHeight < 40;
	};
	// A new message (or a new status of the newest one): follow it.
	useEffect(() => {
		const list = listRef.current;
		if (list && isFollowingRef.current) list.scrollTop = list.scrollHeight;
	}, [messages.length, newest?.id, newest?.status]);

	return (
		<div ref={listRef} onScroll={onScroll} role="log" aria-label="Messages"
			style={{ height, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 10, padding: 12, border: '1px solid rgba(127, 127, 127, 0.3)', borderRadius: 14 }}>
			{messages.length === 0 && <p style={{ margin: 'auto', opacity: 0.6 }}>{emptyText}</p>}
			{messages.map((message) => <Message key={message.id} message={message} language={world.webapp.language} showsSenders={showsSenders} />)}
		</div>
	);
}

// MediaView and MessageChart: the same as on their own pages.

/**
 * Finds the player of a YouTube or Vimeo video from the address of its page,
 * for example 'https://www.youtube.com/watch?v=aqz-KE-bpKQ'. It knows only these two
 * sites and writes the address of the player itself. Anything else gives null (a link is shown).
 * @param {string} url - The address of the video.
 * @returns {string|null} The address of the player, or null.
 */
function playerOf(url) {
	let address;
	try {
		address = new URL(url);
	} catch {
		return null;
	}
	const host = address.hostname.replace(/^(www|m)\./, '');
	const parts = address.pathname.split('/').filter(Boolean);
	if (['youtube.com', 'youtu.be', 'youtube-nocookie.com'].includes(host)) {
		// youtube.com/watch?v=ID, youtu.be/ID, youtube.com/embed/ID, youtube.com/shorts/ID
		const id = address.searchParams.get('v') ?? (host === 'youtu.be' ? parts[0] : parts[1]);
		return /^[\w-]{11}$/.test(id ?? '') ? `https://www.youtube-nocookie.com/embed/${id}?autoplay=1` : null;
	}
	if (host === 'vimeo.com' || host === 'player.vimeo.com') {
		// vimeo.com/ID, player.vimeo.com/video/ID
		const id = parts.find((part) => /^\d+$/.test(part));
		return id ? `https://player.vimeo.com/video/${id}?autoplay=1` : null;
	}
	return null;
}

/** The site of an address without 'www.', such as 'youtube.com'. */
function siteOf(url) {
	try {
		return new URL(url).hostname.replace(/^www\./, '');
	} catch {
		return url;
	}
}

/** A 16 by 9 box, for a video, its player, and the button before it. */
const SCREEN = { display: 'block', width: '100%', aspectRatio: '16 / 9', border: 0, borderRadius: 10, background: 'rgba(127, 127, 127, 0.14)' };

/**
 * MediaView: one video, sound, picture, PDF or link of a message (`message.media`).
 * A video or a sound loads nothing until the person presses play, and a YouTube
 * or Vimeo player loads nothing until they press "Load the video".
 * @param {object} props
 * @param {object} props.media - One media of `message.media`: `{ url, type, title, poster, alt }`.
 */
export function MediaView({ media }) {
	// True once the person asked for the YouTube or Vimeo player.
	const [isPlayerOn, setIsPlayerOn] = useState(false);
	const site = siteOf(media.url);
	const player = media.type === 'video/youtube' || media.type === 'video/vimeo' ? playerOf(media.url) : null;
	// Under a player: its title, or what it is. Under a picture: its title. Under a link: what it is.
	let caption = media.title || media.alt;

	let view;
	if (player && isPlayerOn) {
		view = <iframe src={player} title={media.title || media.alt} allow="autoplay; encrypted-media; fullscreen; picture-in-picture" style={SCREEN} />;
	} else if (player) {
		// The player of the other site loads only after the click, to keep that site from learning anything before it.
		view = <button type="button" onClick={() => setIsPlayerOn(true)} style={{ ...SCREEN, font: 'inherit', fontWeight: 600, color: 'inherit', cursor: 'pointer' }}>Load the video</button>;
		caption = `${caption} · from ${site}`;
	} else if (media.type.startsWith('video/')) {
		// `preload="none"` keeps the browser from downloading anything until the person presses play.
		view = <video preload="none" src={media.url} poster={media.poster ?? undefined} controls playsInline aria-label={media.alt} style={SCREEN} />;
	} else if (media.type.startsWith('audio/')) {
		view = <audio preload="none" src={media.url} controls aria-label={media.alt} style={{ display: 'block', width: '100%' }} />;
	} else if (media.type.startsWith('image/')) {
		// A picture from another site loads when it nears the screen and tells that site nothing of this page.
		view = <img src={media.url} alt={media.alt} loading="lazy" referrerPolicy="no-referrer" style={{ display: 'block', maxWidth: '100%', maxHeight: 320, borderRadius: 10 }} />;
		caption = media.title;
	} else {
		// A PDF, a video from another site or a page becomes a link that opens it in a new tab.
		const what = media.type === 'application/pdf' ? 'Open the PDF' : 'Open the link';
		view = <a href={media.url} target="_blank" rel="noopener noreferrer" style={{ fontWeight: 600, color: 'inherit' }}>{what}: {media.title || site}</a>;
		caption = media.alt;
	}

	return (
		<figure style={{ margin: 0, width: 320, maxWidth: '100%' }}>
			{view}
			{caption && <figcaption style={{ marginTop: 4, fontSize: 13, opacity: 0.75 }}>{caption}</figcaption>}
		</figure>
	);
}

// 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.

/** Two small pictures, drawn as SVG image sources. */
const DAY = `data:image/svg+xml,${encodeURIComponent(
	'<svg xmlns="http://www.w3.org/2000/svg" width="240" height="140"><rect width="240" height="140" fill="#9BB7F2"/><circle cx="70" cy="60" r="28" fill="#F0A54E"/><path d="M0 140 L90 70 L150 120 L190 90 L240 140 Z" fill="#2A54C4"/></svg>',
)}`;
const NIGHT = `data:image/svg+xml,${encodeURIComponent(
	'<svg xmlns="http://www.w3.org/2000/svg" width="240" height="140"><rect width="240" height="140" fill="#1D2A4D"/><circle cx="170" cy="50" r="22" fill="#F2E8C9"/><path d="M0 140 L90 70 L150 120 L190 90 L240 140 Z" fill="#0F1730"/></svg>',
)}`;

// A fake agent to build with: it answers with words, pictures, a file and a chart, or videos.
// Its file arrives with no name, as from a real agent. The videos load nothing until the person asks.
const echo = {
	name: 'Echo',
	onMessage: (message) => {
		if (message.text === 'pictures') return { images: [DAY, NIGHT], text: 'Here are two pictures.' };
		if (message.text === 'report') {
			return {
				text: 'Here is the report.',
				files: [{ name: 'visits.csv', type: 'text/csv', url: 'data:text/csv;base64,ZGF5LHZpc2l0cwpNb24sMTIKVHVlLDE4CldlZCw5Cg==' }],
				charts: [{ kind: 'bar', series: [{ label: 'Visits', points: [['Mon', 12], ['Tue', 18], ['Wed', 9]] }], alt: 'Visits per day: 12 on Monday, 18 on Tuesday, 9 on Wednesday.' }],
			};
		}
		if (message.text === 'videos') {
			return {
				text: 'Here are two videos.',
				media: [
					{ url: 'https://videos.example.com/sunrise.mp4', type: 'video/mp4', title: 'Sunrise', alt: 'The sun rising over the sea, in ten seconds.' },
					{ url: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', type: 'video/youtube', title: 'Big Buck Bunny', alt: 'A short animated film.' },
				],
			};
		}
		return `You said: ${message.text}`;
	},
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<div style={{ display: 'grid', gap: 8, maxWidth: 520 }}>
			<MessageList world={world} height={320} />
			{/* The buttons wait until the agent can take a message. */}
			<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
				<button type="button" disabled={!world.canSend} onClick={() => world.send('hello')}>Say hello</button>
				<button type="button" disabled={!world.canSend} onClick={() => world.send('pictures')}>Ask for pictures</button>
				<button type="button" disabled={!world.canSend} onClick={() => world.send('report')}>Ask for a report</button>
				<button type="button" disabled={!world.canSend} onClick={() => world.send('videos')}>Ask for videos</button>
			</div>
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part. It uses mediaView and messageChart, further down.

/**
 * Makes the element of a file of a message: a link that saves it, or only
 * its name when its content was not kept (the person's own file, after a reload).
 * @param {object} file - A file of `message.files`: `{ name, type, url }`.
 * @returns {HTMLElement} The element.
 */
function fileLink(file) {
	// The files of an agent arrive with no name: say what kind of file it is.
	const name = file.name ?? `a file (${file.type ?? 'unknown type'})`;
	if (!file.url) {
		const plain = document.createElement('span');
		plain.textContent = name;
		return plain;
	}
	const link = document.createElement('a');
	link.href = file.url;
	// `download` saves the file instead of opening it.
	link.download = file.name ?? '';
	link.textContent = `Download ${name}`;
	Object.assign(link.style, { color: 'inherit', fontWeight: '600' });
	return link;
}

/**
 * Makes the elements of what a message shows, in order: its pictures, its
 * words, its files, its videos and sounds, its charts. `?? []` reads the last
 * three as none, because they are missing with an older webapp.
 * @param {object} message - A message of `world.messages`.
 * @param {string|null} who - Who sent it, for the description of the pictures, or null when it is not shown.
 * @returns {HTMLElement[]} The elements.
 */
function partsOf(message, who) {
	const parts = [];
	const images = message.images ?? (message.image ? [message.image] : []);
	if (images.length > 0) {
		const pictures = document.createElement('div');
		Object.assign(pictures.style, { display: 'flex', flexWrap: 'wrap', gap: '6px' });
		for (const image of images) {
			// A fixed height keeps the list from jumping when a picture arrives.
			const picture = document.createElement('img');
			picture.src = image;
			picture.alt = who ? `Picture from ${who}` : 'Picture';
			Object.assign(picture.style, { display: 'block', height: '140px', width: 'auto', maxWidth: '100%', objectFit: 'contain', borderRadius: '10px' });
			pictures.append(picture);
		}
		parts.push(pictures);
	}
	if (message.text) {
		// The words of the world go in as text, never as HTML.
		const words = document.createElement('div');
		words.textContent = message.text;
		Object.assign(words.style, { whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' });
		parts.push(words);
	}
	(message.files ?? []).forEach((file) => parts.push(fileLink(file)));
	(message.media ?? []).forEach((media) => parts.push(mediaView(media)));
	(message.charts ?? []).forEach((chart) => parts.push(messageChart(chart)));
	return parts;
}

/**
 * Makes the element of one message: the person's on the right, the others'
 * on the left, and the notes of the rules in the middle.
 * @param {object} message - A message of `world.messages`.
 * @param {string} language - The language of the webapp, for the time.
 * @param {boolean} showsSenders - False when the world asks not to show who wrote each message.
 * @returns {HTMLElement} The element.
 */
function messageElement(message, language, showsSenders) {
	const time = new Date(message.time).toLocaleTimeString(language, { hour: '2-digit', minute: '2-digit' });

	if (message.isSystem) {
		const note = document.createElement('div');
		note.append(...partsOf(message, null));
		Object.assign(note.style, { alignSelf: 'center', maxWidth: '90%', display: 'grid', gap: '6px', justifyItems: 'center', padding: '4px 12px', borderRadius: '9px', fontSize: '13px', textAlign: 'center', background: 'rgba(127, 127, 127, 0.1)' });
		return note;
	}

	const isMine = message.fromMe;
	// The sender's name, unless the world asks not to show it.
	const sender = showsSenders ? message.from ?? 'Someone' : null;
	let meta = time;
	if (!isMine && sender) meta = `${sender} · ${time}`;
	if (message.status === 'sending') meta = `${time} · Sending…`;
	if (message.status === 'failed') meta = `${time} · Not sent`;

	const row = document.createElement('div');
	Object.assign(row.style, { alignSelf: isMine ? 'flex-end' : 'flex-start', maxWidth: '80%', display: 'grid', gap: '2px', justifyItems: isMine ? 'end' : 'start' });
	const metaLine = document.createElement('span');
	metaLine.textContent = meta;
	Object.assign(metaLine.style, { fontSize: '12px', opacity: '0.7' });
	const bubble = document.createElement('div');
	Object.assign(bubble.style, {
		display: 'grid', gap: '6px', padding: '8px 12px', borderRadius: '14px',
		background: isMine ? '#2A54C4' : 'rgba(127, 127, 127, 0.14)', color: isMine ? '#fff' : 'inherit',
		opacity: message.status === 'sending' ? '0.7' : '1',
	});
	bubble.append(...partsOf(message, isMine ? 'you' : sender));
	row.append(metaLine, bubble);

	// The person can send their failed message again.
	if (message.status === 'failed' && message.retry) {
		const retry = document.createElement('button');
		retry.type = 'button';
		retry.textContent = 'Retry';
		retry.onclick = () => message.retry().catch(() => {});
		Object.assign(retry.style, { font: 'inherit', fontSize: '13px', padding: '2px 10px', borderRadius: '9px', border: '1px solid rgba(229, 69, 58, 0.6)', background: 'transparent', color: 'inherit', cursor: 'pointer' });
		row.append(retry);
	}
	return row;
}

/**
 * Draws the conversation between the person and the world (or the agent)
 * into `container`, oldest first, with every picture, file, video, sound and
 * chart, then draws it again at every change. It follows the newest message
 * unless the person has scrolled up to read.
 * @param {HTMLElement} container - Where to draw it.
 * @param {object} world - The world, from connectToHost.
 * @param {{height?: string, emptyText?: string}} [options] - The height of the list (the messages scroll inside it), and what it says before the first message.
 * @returns {() => void} Stops following the world and removes what it drew.
 */
export function messageList(container, world, { height = '320px', emptyText = 'No messages yet.' } = {}) {
	const list = document.createElement('div');
	list.setAttribute('role', 'log');
	list.setAttribute('aria-label', 'Messages');
	Object.assign(list.style, { height, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '10px', padding: '12px', border: '1px solid rgba(127, 127, 127, 0.3)', borderRadius: '14px' });
	const empty = document.createElement('p');
	empty.textContent = emptyText;
	Object.assign(empty.style, { margin: 'auto', opacity: '0.6' });
	container.append(list);

	// The element of each message, kept by id. The list makes only a new or changed
	// message again, to let a video that plays keep playing.
	const made = new Map();
	const stop = world.subscribe((node) => {
		// Show the senders unless the world asks not to (an older webapp gives no `showsSenders`).
		const showsSenders = node.showsSenders !== false;
		const elements = node.messages.map((message) => {
			const version = `${message.status}|${message.isAnswered}|${showsSenders}`;
			const old = made.get(message.id);
			if (old && old.version === version) return old.element;
			const element = messageElement(message, node.webapp.language, showsSenders);
			made.set(message.id, { element, version });
			return element;
		});
		const wanted = elements.length > 0 ? elements : [empty];

		// The world changed, but not its messages: leave the list as it is.
		const shown = [...list.children];
		if (wanted.length === shown.length && wanted.every((element, index) => element === shown[index])) return;

		// Follow the new messages only if the person is at the bottom now.
		const isAtBottom = list.scrollHeight - list.scrollTop - list.clientHeight < 40;
		list.replaceChildren(...wanted);
		if (isAtBottom) list.scrollTop = list.scrollHeight;
	});

	return () => {
		stop();
		list.remove();
	};
}

// mediaView and messageChart: the same as on their own pages.

/**
 * Finds the player of a YouTube or Vimeo video from the address of its page,
 * for example 'https://www.youtube.com/watch?v=aqz-KE-bpKQ'. It knows only these two
 * sites and writes the address of the player itself. Anything else gives null (a link is shown).
 * @param {string} url - The address of the video.
 * @returns {string|null} The address of the player, or null.
 */
function playerOf(url) {
	let address;
	try {
		address = new URL(url);
	} catch {
		return null;
	}
	const host = address.hostname.replace(/^(www|m)\./, '');
	const parts = address.pathname.split('/').filter(Boolean);
	if (['youtube.com', 'youtu.be', 'youtube-nocookie.com'].includes(host)) {
		// youtube.com/watch?v=ID, youtu.be/ID, youtube.com/embed/ID, youtube.com/shorts/ID
		const id = address.searchParams.get('v') ?? (host === 'youtu.be' ? parts[0] : parts[1]);
		return /^[\w-]{11}$/.test(id ?? '') ? `https://www.youtube-nocookie.com/embed/${id}?autoplay=1` : null;
	}
	if (host === 'vimeo.com' || host === 'player.vimeo.com') {
		// vimeo.com/ID, player.vimeo.com/video/ID
		const id = parts.find((part) => /^\d+$/.test(part));
		return id ? `https://player.vimeo.com/video/${id}?autoplay=1` : null;
	}
	return null;
}

/** The site of an address without 'www.', such as 'youtube.com'. */
function siteOf(url) {
	try {
		return new URL(url).hostname.replace(/^www\./, '');
	} catch {
		return url;
	}
}

/** A 16 by 9 box, for a video, its player, and the button before it. */
const SCREEN = { display: 'block', width: '100%', aspectRatio: '16 / 9', border: '0', borderRadius: '10px', background: 'rgba(127, 127, 127, 0.14)' };

/**
 * Makes the element of one video, sound, picture, PDF or link of a message
 * (`message.media`). A video or a sound loads nothing until the person presses play,
 * and a YouTube or Vimeo player loads nothing until they press "Load the video".
 * @param {object} media - One media of `message.media`: `{ url, type, title, poster, alt }`.
 * @returns {HTMLElement} The element (a `figure`).
 */
export function mediaView(media) {
	const figure = document.createElement('figure');
	Object.assign(figure.style, { margin: '0', width: '320px', maxWidth: '100%' });
	const site = siteOf(media.url);
	const player = media.type === 'video/youtube' || media.type === 'video/vimeo' ? playerOf(media.url) : null;
	// Under a player: its title, or what it is. Under a picture: its title. Under a link: what it is.
	let caption = media.title || media.alt;

	let view;
	if (player) {
		// The player of the other site loads only after the click, to keep that site from learning anything before it.
		view = document.createElement('button');
		view.type = 'button';
		view.textContent = 'Load the video';
		Object.assign(view.style, SCREEN, { font: 'inherit', fontWeight: '600', color: 'inherit', cursor: 'pointer' });
		view.onclick = () => {
			const frame = document.createElement('iframe');
			frame.src = player;
			frame.title = media.title || media.alt;
			frame.allow = 'autoplay; encrypted-media; fullscreen; picture-in-picture';
			Object.assign(frame.style, SCREEN);
			view.replaceWith(frame);
		};
		caption = `${caption} · from ${site}`;
	} else if (media.type.startsWith('video/') || media.type.startsWith('audio/')) {
		const isVideo = media.type.startsWith('video/');
		view = document.createElement(isVideo ? 'video' : 'audio');
		// `preload = 'none'` keeps the browser from downloading anything until the person presses play.
		view.preload = 'none';
		view.controls = true;
		view.src = media.url;
		view.setAttribute('aria-label', media.alt);
		if (isVideo) {
			view.playsInline = true;
			if (media.poster) view.poster = media.poster;
			Object.assign(view.style, SCREEN);
		} else {
			Object.assign(view.style, { display: 'block', width: '100%' });
		}
	} else if (media.type.startsWith('image/')) {
		// A picture from another site loads when it nears the screen and tells that site nothing of this page.
		view = document.createElement('img');
		view.loading = 'lazy';
		view.referrerPolicy = 'no-referrer';
		view.src = media.url;
		view.alt = media.alt;
		Object.assign(view.style, { display: 'block', maxWidth: '100%', maxHeight: '320px', borderRadius: '10px' });
		caption = media.title;
	} else {
		// A PDF, a video from another site or a page becomes a link that opens it in a new tab.
		view = document.createElement('a');
		view.href = media.url;
		view.target = '_blank';
		view.rel = 'noopener noreferrer';
		view.textContent = `${media.type === 'application/pdf' ? 'Open the PDF' : 'Open the link'}: ${media.title || site}`;
		Object.assign(view.style, { fontWeight: '600', color: 'inherit' });
		caption = media.alt;
	}
	figure.append(view);

	if (caption) {
		const words = document.createElement('figcaption');
		words.textContent = caption;
		Object.assign(words.style, { marginTop: '4px', fontSize: '13px', opacity: '0.75' });
		figure.append(words);
	}
	return figure;
}

// 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.

/** Two small pictures, drawn as SVG image sources. */
const DAY = `data:image/svg+xml,${encodeURIComponent(
	'<svg xmlns="http://www.w3.org/2000/svg" width="240" height="140"><rect width="240" height="140" fill="#9BB7F2"/><circle cx="70" cy="60" r="28" fill="#F0A54E"/><path d="M0 140 L90 70 L150 120 L190 90 L240 140 Z" fill="#2A54C4"/></svg>',
)}`;
const NIGHT = `data:image/svg+xml,${encodeURIComponent(
	'<svg xmlns="http://www.w3.org/2000/svg" width="240" height="140"><rect width="240" height="140" fill="#1D2A4D"/><circle cx="170" cy="50" r="22" fill="#F2E8C9"/><path d="M0 140 L90 70 L150 120 L190 90 L240 140 Z" fill="#0F1730"/></svg>',
)}`;

// A fake agent to build with: it answers with words, pictures, a file and a chart, or videos.
// Its file arrives with no name, as from a real agent. The videos load nothing until the person asks.
const echo = {
	name: 'Echo',
	onMessage: (message) => {
		if (message.text === 'pictures') return { images: [DAY, NIGHT], text: 'Here are two pictures.' };
		if (message.text === 'report') {
			return {
				text: 'Here is the report.',
				files: [{ name: 'visits.csv', type: 'text/csv', url: 'data:text/csv;base64,ZGF5LHZpc2l0cwpNb24sMTIKVHVlLDE4CldlZCw5Cg==' }],
				charts: [{ kind: 'bar', series: [{ label: 'Visits', points: [['Mon', 12], ['Tue', 18], ['Wed', 9]] }], alt: 'Visits per day: 12 on Monday, 18 on Tuesday, 9 on Wednesday.' }],
			};
		}
		if (message.text === 'videos') {
			return {
				text: 'Here are two videos.',
				media: [
					{ url: 'https://videos.example.com/sunrise.mp4', type: 'video/mp4', title: 'Sunrise', alt: 'The sun rising over the sea, in ten seconds.' },
					{ url: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', type: 'video/youtube', title: 'Big Buck Bunny', alt: 'A short animated film.' },
				],
			};
		}
		return `You said: ${message.text}`;
	},
};

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

const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '8px', maxWidth: '520px' });
const place = document.createElement('div');
const buttons = document.createElement('div');
Object.assign(buttons.style, { display: 'flex', flexWrap: 'wrap', gap: '8px' });
const asks = [['Say hello', 'hello'], ['Ask for pictures', 'pictures'], ['Ask for a report', 'report'], ['Ask for videos', 'videos']].map(([label, text]) => {
	const button = document.createElement('button');
	button.textContent = label;
	button.onclick = () => world.send(text);
	return button;
});
buttons.append(...asks);
page.append(place, buttons);
document.body.append(page);

messageList(place, world, { height: '320px' });
// The buttons wait until the agent can take a message.
world.subscribe((node) => {
	asks.forEach((button) => {
		button.disabled = !node.canSend;
	});
});
Live, on a fake world
Open

Sopra ogni messaggio che non sia una nota compare una riga con l'ora. Per i messaggi degli altri la riga aggiunge from e per quelli della persona Sending… o Not sent. Sotto un messaggio fallito un pulsante Retry chiama message.retry().

Il file dell'esempio contiene anche MediaView e MessageChart identici a quelli delle loro pagine. Se il tuo progetto li ha già, tienine una sola copia.

La lista legge questi campi di ogni messaggio (GuiMessage):

  • il contenuto in text, images (il cui primo elemento è anche in image), files, media e charts
  • il mittente e l'ora in from e time
  • i flag che decidono la disposizione (fromMe per i messaggi della persona, isSystem per le note delle regole e status con 'sending', 'sent' o 'failed' sui messaggi della persona).

Le webapp più vecchie non forniscono images, files, media e charts. La lista li legge con ?? [] e quando manca images ripiega su image (Messaggi e domande).

  • I file sono oggetti { name, type, url } il cui url (un data URI) diventa l'href di un link Download con l'attributo download. Un file inviato da un agente ha name: null e riceve un'etichetta con il suo tipo (a file (application/pdf)). Dopo un ricaricamento un file inviato dalla persona ha url: null e la lista ne mostra il nome senza link.
  • I media si caricano su richiesta. Un <video> o un <audio> ha preload="none" e non scarica niente prima che la persona prema play. Un player di YouTube o di Vimeo viene montato solo quando la persona preme Load the video (MediaView).
  • I mittenti: quando world.showsSenders è false la riga sopra i messaggi degli altri mostra solo l'ora e l'alt delle loro immagini non contiene il nome. Una webapp più vecchia non fornisce showsSenders e in quel caso la lista mostra i nomi.

Gli screen reader annunciano ogni nuovo messaggio appena arriva perché il contenitore è una regione role="log". Quando i messaggi cambiano il contenitore scorre fino alla fine solo se era già a meno di 40 pixel dalla fine (Scorri fino al messaggio più recente).

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo (o l'agente), da useWorld.
height320L'altezza del contenitore in pixel o come lunghezza CSS. I messaggi scorrono al suo interno.
emptyText'No messages yet.'Il testo mostrato prima del primo messaggio.

Parametri ​

messageList(container, world, options) disegna la lista dentro container e si iscrive al mondo. Per non interrompere un video in riproduzione ricostruisce l'elemento di un messaggio solo quando il messaggio è nuovo o quando cambiano il suo status, il suo isAnswered o showsSenders.

ParametroChe cos'è
containerL'elemento in cui disegnare.
worldIl mondo (o l'agente), da connectToHost.
options.heightL'altezza del contenitore come lunghezza CSS. Predefinito '320px'.
options.emptyTextIl testo mostrato prima del primo messaggio. Predefinito 'No messages yet.'.

Restituisce una funzione che annulla l'iscrizione al mondo e rimuove la lista.

Modificalo ​

  • Riempire la pagina: invece di un'height fissa dai alla lista flex: 1 dentro una colonna alta quanto la pagina. SafeArea la tiene libera dalla tastiera del telefono.
  • Un nome cliccabile: mostra MemberName al posto di from. Il componente mostra il ruolo del membro, apre la sua scheda del profilo nella webapp e rispetta showsSenders.
  • Raggruppare i messaggi per mittente: ometti il nome quando il messaggio precedente ha lo stesso fromId (Raggruppa i messaggi per mittente).
  • Messaggi più vecchi: aggiungi in cima un pulsante che chiama world.loadMore() (Carica i messaggi precedenti).
  • Nascondere le note delle regole: salta i messaggi con isSystem quando un'altra parte della tua vista mostra lo stato del mondo (per esempio WorldStatus).
  • Ingrandire un'immagine: avvolgi ogni img in un pulsante che la apre come fa FullScreenPicture.
  • Meno tipi di contenuto: una vista che non riceve mai grafici o media può togliere MessageChart o MediaView insieme alla riga di Parts (partsOf in JavaScript semplice) che lo chiama.

Vedi anche ​

  • MessageBox: la casella sotto la lista.
  • FileButton: un pulsante che invia un file scelto dalla persona.
  • QuestionForm: un modulo che risponde alle domande del mondo.
  • SentToast: un breve avviso che dice se un messaggio è stato consegnato.

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