MediaView
The messages of a world or an agent can carry videos, sounds, pictures, PDFs and links in message.media. MediaView renders one of these items. It plays a video or a sound in your view and opens a PDF or a page in a new tab. For a YouTube or Vimeo video it loads the player of that site only when the person asks for it. MessageList already renders each item with MediaView. Your own message list and any other place that shows the media of a message can use it too.
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>
);
}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);
});Each item is a GuiMedia { url, type, title, poster, alt } with an https: URL, a MIME or provider type, a caption or null, a preview picture or null and a sentence that describes the item. Read the field as message.media ?? [] because older webapps do not send it. MediaView picks the element by type:
type | What it renders |
|---|---|
'video/mp4' and every other video/... | a <video> with controls |
'audio/mpeg' and every other audio/... | an <audio> with controls |
'video/youtube', 'video/vimeo' | a Load the video button replaced by the player of that site on click |
'image/png' and every other image/... | an <img> |
'application/pdf' | an Open the PDF link to a new tab |
| any other type | an Open the link link to a new tab |
Nothing loads before the person asks. Each item is hosted on another site that your view should not contact without an action of the person. The <video> and the <audio> therefore have preload="none" and download nothing until the person presses play. Like the webapp in its own view, MediaView mounts a YouTube or Vimeo player (an iframe of that site) only after the click. The component builds the player URL itself from the id of the video in media.url. A URL that playerOf does not recognise never becomes the src of an iframe. As a result only those two sites can load a page inside your view.
Pictures are the exception. An <img> with loading="lazy" and referrerPolicy="no-referrer" loads when it approaches the viewport without sending the URL of the page to the site of the picture.
alt is the accessible name of a video, a sound or a picture. Under a player the caption is title (or alt when title is null) followed by the site of the player. A video or a sound shows the same caption without the site and a picture shows only its title. Under a link the caption is alt because the link text already holds title (or the site when there is no title).
Props
| Prop | Default | What it is |
|---|---|---|
media | (required) | One item of message.media: { url, type, title, poster, alt }. |
Parameters
mediaView(media) subscribes to nothing and returns a new figure element to insert where the item belongs. Create it once per message and keep the same element while the message is on screen. A new element would stop a video that is playing.
| Parameter | What it is |
|---|---|
media | One item of message.media: { url, type, title, poster, alt }. |
Change it
- Make it bigger by changing the
widthof thefigure(320 pixels). The video and the player keep a 16:9 aspect ratio. - Drop the preview picture. The component passes the
posterof a video to the<video>and the browser downloads it at once. Remove that line from a view that must load nothing before a click. - Show the PDF inside your view with an
iframewhosesrcismedia.url. Since theiframeloads the PDF from its site as soon as it is mounted, add it only after a click as for the YouTube player. - Support another video site with a branch in
playerOfthat reads the id of the video and builds the player URL of that site. Never putmedia.urlas it is into aniframe. - Place several items side by side in a row with
flexWrap: 'wrap'as the example does.
See also
- Show videos and PDFs from a message: the same idea in a few lines.
MessageChart: the charts of a message.GuiMedia: every field of a media item.