Skip to content

Show videos and PDFs from a message ​

Videos, sounds, pictures, PDFs and links from the web arrive in message.media, each with a url, a type, a title and an alt sentence that describes it. Play videos and sounds in the page but let the browser load nothing before the person presses play. Offer a PDF as a link. Mount a YouTube or Vimeo player only after a click because the player loads content from the site of the provider as soon as it is on the page. Ask the film club in the example what is on this week.

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

// While you build, a fake film club answers with a video, a sound, a PDF and a YouTube video.
// Nothing is loaded from these addresses until the person presses play or opens a link.
const club = {
	name: 'Film club',
	onMessage: () => ({
		text: 'Here is this week.',
		media: [
			{ url: 'https://example.com/club/trailer.mp4', type: 'video/mp4', title: 'The trailer', alt: 'A one-minute trailer of the film of the week.' },
			{ url: 'https://example.com/club/podcast.mp3', type: 'audio/mpeg', title: 'Our podcast', alt: 'Two members talk about the film.' },
			{ url: 'https://example.com/club/programme.pdf', type: 'application/pdf', title: 'The programme', alt: 'The films of the month, with their dates.' },
			{ 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.' },
		],
	}),
};

// The address of a YouTube or Vimeo player, or null. Only the id of the video comes from the
// message. The code checks it, then puts it into an address written here.
function playerAddress(media) {
	const url = new URL(media.url);
	if (media.type === 'video/youtube') {
		const id = url.searchParams.get('v') ?? url.pathname.split('/').pop();
		return /^[\w-]{11}$/.test(id) ? `https://www.youtube-nocookie.com/embed/${id}` : null;
	}
	if (media.type === 'video/vimeo') {
		const id = url.pathname.split('/').pop();
		return /^\d+$/.test(id) ? `https://player.vimeo.com/video/${id}` : null;
	}
	return null;
}

// How to show one item of `media`: a player (after a click), a picture, a video, a sound, or a link (a PDF and any other type).
function kindOf(media) {
	if (media.type === 'video/youtube' || media.type === 'video/vimeo') return playerAddress(media) ? 'player' : 'link';
	if (media.type.startsWith('image/')) return 'image';
	if (media.type.startsWith('video/')) return 'video';
	if (media.type.startsWith('audio/')) return 'audio';
	return 'link';
}

// A YouTube or Vimeo player loads the other site as soon as it is on the page. Show a button first.
function Player({ media }) {
	const [isLoaded, setIsLoaded] = useState(false);
	if (!isLoaded) return <button onClick={() => setIsLoaded(true)}>Load the video</button>;
	return (
		<iframe src={`${playerAddress(media)}?autoplay=1`} title={media.title ?? media.alt}
			allow="autoplay; fullscreen" width="320" height="180" style={{ border: 0 }} />
	);
}

// One video, sound, PDF or link.
function MediaView({ media }) {
	const caption = media.title ?? media.alt;
	const kind = kindOf(media);
	if (kind === 'link') {
		// A PDF, or a type the view does not play, becomes a link that opens it in a new tab.
		return (
			<p>
				<a href={media.url} target="_blank" rel="noreferrer">
					{media.type === 'application/pdf' ? `${caption} (PDF)` : caption}
				</a>
			</p>
		);
	}
	return (
		<figure style={{ margin: '8px 0' }}>
			{kind === 'player' && <Player media={media} />}
			{/* A picture from the web loads when it comes near the screen, without the address of the page. */}
			{kind === 'image' && <img loading="lazy" referrerPolicy="no-referrer" src={media.url} alt={media.alt} width="320" />}
			{/* preload "none" keeps the browser from loading anything until the person presses play. */}
			{kind === 'video' && <video preload="none" src={media.url} controls width="320" aria-label={media.alt} />}
			{kind === 'audio' && <audio preload="none" src={media.url} controls aria-label={media.alt} />}
			<figcaption>{caption}</figcaption>
		</figure>
	);
}

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

	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>
					{/* An older webapp gives no `media`, and the view counts on an empty list instead. */}
					{(message.media ?? []).map((media, index) => <MediaView key={index} media={media} />)}
				</div>
			))}
			<button onClick={() => world.send('Show me the films')} disabled={!world.canSend}>Show me the films</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// While you build, a fake film club answers with a video, a sound, a PDF and a YouTube video.
// Nothing is loaded from these addresses until the person presses play or opens a link.
const club = {
	name: 'Film club',
	onMessage: () => ({
		text: 'Here is this week.',
		media: [
			{ url: 'https://example.com/club/trailer.mp4', type: 'video/mp4', title: 'The trailer', alt: 'A one-minute trailer of the film of the week.' },
			{ url: 'https://example.com/club/podcast.mp3', type: 'audio/mpeg', title: 'Our podcast', alt: 'Two members talk about the film.' },
			{ url: 'https://example.com/club/programme.pdf', type: 'application/pdf', title: 'The programme', alt: 'The films of the month, with their dates.' },
			{ 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.' },
		],
	}),
};

// The address of a YouTube or Vimeo player, or null. Only the id of the video comes from the
// message. The code checks it, then puts it into an address written here.
function playerAddress(media) {
	const url = new URL(media.url);
	if (media.type === 'video/youtube') {
		const id = url.searchParams.get('v') ?? url.pathname.split('/').pop();
		return /^[\w-]{11}$/.test(id) ? `https://www.youtube-nocookie.com/embed/${id}` : null;
	}
	if (media.type === 'video/vimeo') {
		const id = url.pathname.split('/').pop();
		return /^\d+$/.test(id) ? `https://player.vimeo.com/video/${id}` : null;
	}
	return null;
}

// How to show one item of `media`: a player (after a click), a picture, a video, a sound, or a link (a PDF and any other type).
function kindOf(media) {
	if (media.type === 'video/youtube' || media.type === 'video/vimeo') return playerAddress(media) ? 'player' : 'link';
	if (media.type.startsWith('image/')) return 'image';
	if (media.type.startsWith('video/')) return 'video';
	if (media.type.startsWith('audio/')) return 'audio';
	return 'link';
}

// One video, sound, PDF or link.
function mediaView(media) {
	const caption = media.title ?? media.alt;
	const kind = kindOf(media);
	if (kind === 'link') {
		// A PDF, or a type the view does not play, becomes a link that opens it in a new tab.
		const paragraph = document.createElement('p');
		const link = document.createElement('a');
		link.href = media.url;
		link.target = '_blank';
		link.rel = 'noreferrer';
		link.textContent = media.type === 'application/pdf' ? `${caption} (PDF)` : caption;
		paragraph.append(link);
		return paragraph;
	}
	let shown;
	if (kind === 'player') {
		// A YouTube or Vimeo player loads the other site as soon as it is on the page. Show a button first.
		shown = document.createElement('button');
		shown.textContent = 'Load the video';
		shown.onclick = () => {
			const frame = document.createElement('iframe');
			frame.src = `${playerAddress(media)}?autoplay=1`;
			frame.title = caption;
			frame.allow = 'autoplay; fullscreen';
			frame.width = '320';
			frame.height = '180';
			frame.style.border = '0';
			shown.replaceWith(frame);
		};
	} else if (kind === 'image') {
		// A picture from the web loads when it comes near the screen, without the address of the page.
		shown = document.createElement('img');
		shown.loading = 'lazy';
		shown.referrerPolicy = 'no-referrer';
		shown.src = media.url;
		shown.alt = media.alt;
		shown.width = 320;
	} else {
		// preload "none" keeps the browser from loading anything until the person presses play.
		shown = document.createElement(kind); // 'video' or 'audio'
		shown.preload = 'none';
		shown.src = media.url;
		shown.controls = true;
		shown.setAttribute('aria-label', media.alt);
		if (kind === 'video') shown.width = 320;
	}
	const figure = document.createElement('figure');
	figure.style.margin = '8px 0';
	const figcaption = document.createElement('figcaption');
	figcaption.textContent = caption;
	figure.append(shown, figcaption);
	return figure;
}

// Draws one message, with its sender and its words, then its media.
function messageView(message) {
	const item = document.createElement('div');
	const line = document.createElement('p');
	line.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
	item.append(line);
	// An older webapp gives no `media`, and the view counts on an empty list instead.
	for (const media of message.media ?? []) item.append(mediaView(media));
	return item;
}

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

const list = document.createElement('div');
const ask = document.createElement('button');
ask.textContent = 'Show me the films';
ask.onclick = () => world.send('Show me the films');
document.body.append(list, ask);

// Each message is drawn once, then left alone, because drawing a video again would stop it while it plays.
const drawn = new Set();
world.subscribe((node) => {
	ask.disabled = !node.canSend;
	for (const message of node.messages) {
		if (drawn.has(message.id)) continue;
		drawn.add(message.id);
		list.append(messageView(message));
	}
});
Live, on a fake world
Open

How it works ​

kindOf reads the type of each item and picks its rendering: (1) video/ types in a <video>, (2) audio/ types in an <audio>, (3) image/ types in an <img>, (4) 'video/youtube' and 'video/vimeo' in the player of the provider and (5) any other type ('application/pdf' first of all) as a link that opens in a new tab.

  • A picture in media is an address on the web and not a data URI like those in images. loading="lazy" loads it only when it comes near the viewport and referrerPolicy="no-referrer" hides the address of your page from that site.
  • preload="none" keeps the browser from loading a video or a sound before the person presses play. The example leaves out the poster preview because <video poster> loads its picture from the web at once.
  • A YouTube or Vimeo video starts as a Load the video button and only a click on it puts the player on the page. playerAddress takes only the id of the video from the message, validates it and builds the address of the player on its own (youtube-nocookie.com for YouTube). Nothing else from the message reaches the page.
  • url and poster are always https: addresses. When title is null, the example uses alt as the caption. For screen readers aria-label gives videos and sounds the alt as their name.
  • text does not repeat the media.
  • In plain JavaScript each message is rendered once and then left alone because rendering a video again would stop its playback. React keeps each video in place by the key of its message.
  • With an older webapp that gives no media, message.media ?? [] renders nothing.
  • In a fake world an answer can carry media: [{ url, type, title, alt }] like the one in the example. An answer of the world itself arrives as a note of its rules together with its media.

See also ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.