Skip to content

MediaView ​

I messaggi di un mondo o di un agente possono portare in message.media video, audio, immagini, PDF e link. MediaView mostra uno di questi elementi. Riproduce un video o un audio nella tua vista e apre un PDF o una pagina in una nuova scheda. Per un video di YouTube o di Vimeo carica il player di quel sito solo quando la persona lo chiede. MessageList usa già MediaView per ogni elemento. Possono usarlo anche la tua lista di messaggi e qualsiasi altro punto che mostri i media di un messaggio.

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

// The component: copy this part.

/**
 * 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>
	);
}

// Using it, on a fake agent.

// A fake agent to build with: it answers with a video, a sound, a PDF, a YouTube video and a page.
// The addresses are `https:`, as always. Nothing loads from them until the person asks.
const filmClub = {
	name: 'Film club',
	onMessage: () => ({
		text: 'This week at the club:',
		media: [
			{ url: 'https://films.example.com/trailer.mp4', type: 'video/mp4', title: 'Trailer of the week', alt: 'A one-minute trailer of this week\'s film.' },
			{ url: 'https://films.example.com/theme.mp3', type: 'audio/mpeg', title: 'The theme song', alt: 'The film\'s theme song, two minutes.' },
			{ url: 'https://films.example.com/program.pdf', type: 'application/pdf', title: 'This month\'s program', alt: 'The films of the month, with days and times.' },
			{ url: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', type: 'video/youtube', title: 'Big Buck Bunny', alt: 'A short animated film by the Blender Foundation.' },
			{ url: 'https://films.example.com/reviews', type: 'text/html', title: 'Reviews', alt: 'What the members wrote about last week\'s film.' },
		],
	}),
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	// The messages with media (`media` is missing with an older webapp).
	const withMedia = world.messages.filter((message) => (message.media ?? []).length > 0);
	return (
		<div style={{ display: 'grid', gap: 12 }}>
			<button type="button" disabled={!world.canSend} onClick={() => world.send('What is on this week?')} style={{ justifySelf: 'start' }}>Show the media</button>
			{withMedia.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, alignItems: 'start' }}>
						{message.media.map((media, index) => <MediaView key={index} media={media} />)}
					</div>
				</section>
			))}
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/**
 * 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;
}

// Using it, on a fake agent.

// A fake agent to build with: it answers with a video, a sound, a PDF, a YouTube video and a page.
// The addresses are `https:`, as always. Nothing loads from them until the person asks.
const filmClub = {
	name: 'Film club',
	onMessage: () => ({
		text: 'This week at the club:',
		media: [
			{ url: 'https://films.example.com/trailer.mp4', type: 'video/mp4', title: 'Trailer of the week', alt: 'A one-minute trailer of this week\'s film.' },
			{ url: 'https://films.example.com/theme.mp3', type: 'audio/mpeg', title: 'The theme song', alt: 'The film\'s theme song, two minutes.' },
			{ url: 'https://films.example.com/program.pdf', type: 'application/pdf', title: 'This month\'s program', alt: 'The films of the month, with days and times.' },
			{ url: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', type: 'video/youtube', title: 'Big Buck Bunny', alt: 'A short animated film by the Blender Foundation.' },
			{ url: 'https://films.example.com/reviews', type: 'text/html', title: 'Reviews', alt: 'What the members wrote about last week\'s film.' },
		],
	}),
};

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

const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px' });
const ask = document.createElement('button');
ask.textContent = 'Show the media';
ask.style.justifySelf = 'start';
ask.onclick = () => world.send('What is on this 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 media again when a message arrives (`media` 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.media ?? []).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 media = document.createElement('div');
		Object.assign(media.style, { display: 'flex', flexWrap: 'wrap', gap: '16px', alignItems: 'start' });
		media.append(...message.media.map((one) => mediaView(one)));
		section.append(words, media);
		return section;
	});
	place.replaceChildren(...sections);
});
Live, on a fake world
Open

Ogni elemento è un GuiMedia { url, type, title, poster, alt } con un URL https:, un tipo MIME o di provider, una didascalia o null, un'immagine di anteprima o null e una frase che descrive l'elemento. Leggi il campo come message.media ?? [] perché le webapp più vecchie non lo inviano. MediaView sceglie l'elemento HTML in base a type:

typeChe cosa mostra
'video/mp4' e ogni altro video/...un <video> con i controlli
'audio/mpeg' e ogni altro audio/...un <audio> con i controlli
'video/youtube', 'video/vimeo'un pulsante Load the video sostituito al clic dal player di quel sito
'image/png' e ogni altro image/...un <img>
'application/pdf'un link Open the PDF a una nuova scheda
qualsiasi altro tipoun link Open the link a una nuova scheda

Niente si carica prima che la persona lo chieda. Ogni elemento è ospitato su un altro sito che la tua vista non dovrebbe contattare senza un gesto della persona. Per questo <video> e <audio> hanno preload="none" e non scaricano niente finché la persona non preme play. Come fa la webapp nella sua vista, MediaView monta un player di YouTube o di Vimeo (un iframe di quel sito) solo dopo il clic. Il componente costruisce da sé l'URL del player a partire dall'id del video in media.url. Un URL che playerOf non riconosce non diventa mai il src di un iframe. Solo quei due siti possono quindi caricare una pagina dentro la tua vista.

Le immagini sono l'eccezione. Un <img> con loading="lazy" e referrerPolicy="no-referrer" si carica quando si avvicina al viewport senza inviare al sito dell'immagine l'URL della pagina.

alt è il nome accessibile di un video, di un audio o di un'immagine. Sotto un player la didascalia è title (o alt quando title è null) seguito dal sito del player. Un video o un audio mostra la stessa didascalia senza il sito e un'immagine mostra solo il suo title. Sotto un link la didascalia è alt perché il testo del link contiene già title (o il sito quando il titolo manca).

Props ​

PropPredefinitoChe cos'è
media(obbligatorio)Un elemento di message.media: { url, type, title, poster, alt }.

Parametri ​

mediaView(media) non si iscrive a niente e restituisce un nuovo elemento figure da inserire dove va l'elemento. Crealo una volta per messaggio e tieni lo stesso elemento finché il messaggio è sullo schermo. Un elemento nuovo fermerebbe un video in riproduzione.

ParametroChe cos'è
mediaUn elemento di message.media: { url, type, title, poster, alt }.

Modificalo ​

  • Ingrandiscilo cambiando la width del figure (320 pixel). Il video e il player mantengono le proporzioni 16:9.
  • Togli l'immagine di anteprima. Il componente passa il poster di un video al <video> e il browser lo scarica subito. Elimina quella riga da una vista che non deve caricare niente prima di un clic.
  • Mostra il PDF dentro la tua vista con un iframe il cui src è media.url. Visto che l'iframe carica il PDF dal suo sito appena viene montato, aggiungilo solo dopo un clic come per il player di YouTube.
  • Gestisci un altro sito di video con un ramo in playerOf che legge l'id del video e costruisce l'URL del player di quel sito. Non mettere mai media.url così com'è in un iframe.
  • Affianca più elementi in una riga con flexWrap: 'wrap' come fa l'esempio.

Vedi anche ​

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