Mostra video e PDF da un messaggio
Video, suoni, immagini, PDF e link dal web arrivano in message.media, ognuno con un url, un type, un title e una frase alt che lo descrive. Riproduci video e suoni nella pagina ma non lasciare che il browser carichi niente prima che la persona prema play. Offri un PDF come link. Monta un player di YouTube o di Vimeo solo dopo un clic perché il player carica contenuti dal sito del provider appena è sulla pagina. Nell'esempio chiedi al cineclub che cosa danno questa settimana.
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>
</>
);
}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));
}
});Come funziona
kindOf legge il type di ogni elemento e sceglie come mostrarlo: (1) i tipi video/ in un <video>, (2) i tipi audio/ in un <audio>, (3) i tipi image/ in un <img>, (4) 'video/youtube' e 'video/vimeo' nel player del provider e (5) qualsiasi altro tipo ('application/pdf' prima di tutto) come link che si apre in una nuova scheda.
- Un'immagine in
mediasta sul web e non è un data URI come quelle inimages.loading="lazy"la carica solo quando si avvicina al viewport ereferrerPolicy="no-referrer"nasconde a quel sito l'indirizzo della tua pagina. preload="none"impedisce al browser di caricare un video o un suono prima che la persona prema play. L'esempio non usa l'anteprimaposterperché<video poster>carica subito la sua immagine dal web.- Un video di YouTube o di Vimeo parte come pulsante Load the video e solo un clic su quel pulsante mette il player sulla pagina.
playerAddressprende dal messaggio solo l'id del video, lo convalida e costruisce da sé l'indirizzo del player (youtube-nocookie.comper YouTube). Nient'altro del messaggio arriva alla pagina. urlepostersono sempre indirizzihttps:. Quandotitleènulll'esempio usaaltcome didascalia. Per gli screen readeraria-labeldà a video e suoni l'altcome nome.textnon ripete i media.- In JavaScript semplice ogni messaggio viene mostrato una volta e poi lasciato com'è perché mostrarlo di nuovo fermerebbe la riproduzione di un video. React tiene ogni video al suo posto grazie alla
keydel suo messaggio. - Con una webapp più vecchia che non dà
media,message.media ?? []non mostra niente. - In un mondo finto una risposta può portare
media: [{ url, type, title, alt }]come quella dell'esempio. Una risposta del mondo stesso arriva come nota delle sue regole insieme ai suoi media.
Vedi anche
- MediaView: un componente pronto per un video, un suono, un'immagine, un PDF o un link.
- Disegna un grafico da un messaggio
- Mostra i file di un messaggio
GuiMessage