FullScreenPicture
Una mappa, una scacchiera, una foto o un grafico richiedono spesso uno sguardo più da vicino di quello che consente una miniatura. FullScreenPicture mostra in piccolo un'immagine dei dati del mondo. Un clic la apre sopra tutta la vista alla dimensione più grande che ci sta con alt come didascalia. La chiudono il pulsante Close, il tasto Esc, un clic in qualsiasi punto dell'overlay e il tasto indietro del telefono.
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';
// The component: copy this part.
/**
* FullScreenPicture: a picture from the data of the world, small in the view,
* that a tap shows over the whole view, as big as it fits. It closes with
* Close, Escape, a tap, or the back button (which would otherwise leave the
* world). A new picture from the world shows at once.
* @param {object} props
* @param {object} props.world - The world, from useWorld.
* @param {string} props.name - The name of the picture in `world.data`.
* @param {string} props.alt - What the picture shows, in words (also its caption when it is big).
* @param {number} [props.height=180] - The height of the small picture, in pixels.
*/
export function FullScreenPicture({ world, name, alt, height = 180 }) {
const [isOpen, setIsOpen] = useState(false);
const openRef = useRef(null);
const closeRef = useRef(null);
// While it is big, it takes the back button and Escape.
// (The effect runs only when the picture opens or closes, because `world.onBack` stays the same at every change of the world.)
useEffect(() => {
if (!isOpen) return undefined;
closeRef.current.focus();
// When the person goes back, the webapp asks this handler first. Returning true means "handled, stay here".
const giveBackButton = world.onBack(() => {
setIsOpen(false);
return true;
});
const onKey = (event) => {
if (event.key === 'Escape') setIsOpen(false);
};
document.addEventListener('keydown', onKey);
return () => {
giveBackButton();
document.removeEventListener('keydown', onKey);
openRef.current?.focus();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen]);
const source = world.data[name];
if (typeof source !== 'string') return <p style={{ opacity: 0.6 }}>No picture yet.</p>;
// Keep clear of the notch and the home bar of the phone (see SafeArea).
const { insets } = world.webapp;
return (
<>
<button ref={openRef} type="button" onClick={() => setIsOpen(true)} aria-label={`Show full screen: ${alt}`}
style={{ position: 'relative', display: 'inline-block', padding: 0, border: 0, borderRadius: 14, background: 'none', cursor: 'zoom-in' }}>
<img src={source} alt="" style={{ display: 'block', height, maxWidth: '100%', borderRadius: 14 }} />
<span aria-hidden="true" style={{ position: 'absolute', right: 8, bottom: 8, padding: '2px 10px', borderRadius: 30, fontSize: 13, color: '#fff', background: 'rgba(0, 0, 0, 0.6)' }}>Full screen</span>
</button>
{isOpen && (
<div role="dialog" aria-modal="true" aria-label={alt} onClick={() => setIsOpen(false)}
style={{
position: 'fixed', inset: 0, zIndex: 10, boxSizing: 'border-box', display: 'grid', gridTemplateRows: 'auto minmax(0, 1fr) auto', gap: 12,
padding: `${16 + insets.top}px ${16 + insets.right}px ${16 + insets.bottom}px ${16 + insets.left}px`, background: 'rgba(0, 0, 0, 0.92)', color: '#fff',
}}>
<button ref={closeRef} type="button" onClick={() => setIsOpen(false)}
style={{ justifySelf: 'end', padding: '6px 14px', borderRadius: 10, border: '1px solid rgba(255, 255, 255, 0.5)', background: 'transparent', color: '#fff', font: 'inherit', cursor: 'pointer' }}>
Close
</button>
<img src={source} alt={alt} style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
<p style={{ margin: 0, textAlign: 'center', fontSize: 14 }}>{alt}</p>
</div>
)}
</>
);
}
// Using it, on a fake world.
/** A map of an island, as an SVG image source. */
const MAP = `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="400" height="260">
<rect width="400" height="260" fill="#9BB7F2"/>
<path d="M80 150 C 70 80, 170 40, 240 60 S 350 110, 320 170 S 180 230, 120 210 S 90 180, 80 150 Z" fill="#8FD89E" stroke="#399D57" stroke-width="3"/>
<circle cx="160" cy="120" r="6" fill="#9F466B"/><circle cx="260" cy="150" r="6" fill="#9F466B"/>
<text x="172" y="116" font-family="sans-serif" font-size="14" fill="#141312">Port</text>
<text x="214" y="176" font-family="sans-serif" font-size="14" fill="#141312">Lighthouse</text></svg>`)}`;
// A fake world to build with: it shows a map in its data.
const island = { name: 'Island', data: { map: MAP } };
export default function App() {
// While building: the fake world. In the webapp: useWorld()
// (A fake world takes the back button and never uses it. Try Close, Escape or a tap.)
const { world, error } = useWorld({ fake: { world: island } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<div style={{ display: 'grid', gap: 12, justifyItems: 'start' }}>
<h2 style={{ margin: 0 }}>{world.name}</h2>
<FullScreenPicture world={world} name="map" alt="The map of the island, with the port and the lighthouse" />
</div>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
/**
* Draws a picture from the data of the world into `container`, small, and a tap
* shows it over the whole view, as big as it fits. It closes with Close,
* Escape, a tap, or the back button (which would otherwise leave the world).
* A new picture from the world shows at once.
* @param {HTMLElement} container - Where to draw the small picture.
* @param {object} world - The world, from connectToHost.
* @param {{name: string, alt: string, height?: number}} options - The name of the picture in `world.data`,
* what it shows in words (also its caption when it is big), and the height of the small picture in pixels (default 180).
* @returns {() => void} Closes it, stops following the world and removes what it drew.
*/
export function fullScreenPicture(container, world, { name, alt, height = 180 }) {
// The small picture, a button that shows it big.
const openButton = document.createElement('button');
openButton.type = 'button';
openButton.setAttribute('aria-label', `Show full screen: ${alt}`);
Object.assign(openButton.style, { position: 'relative', display: 'inline-block', padding: '0', border: '0', borderRadius: '14px', background: 'none', cursor: 'zoom-in' });
const small = document.createElement('img');
small.alt = '';
Object.assign(small.style, { display: 'block', height: `${height}px`, maxWidth: '100%', borderRadius: '14px' });
const mark = document.createElement('span');
mark.setAttribute('aria-hidden', 'true');
mark.textContent = 'Full screen';
Object.assign(mark.style, { position: 'absolute', right: '8px', bottom: '8px', padding: '2px 10px', borderRadius: '30px', fontSize: '13px', color: '#fff', background: 'rgba(0, 0, 0, 0.6)' });
openButton.append(small, mark);
const empty = document.createElement('p');
empty.textContent = 'No picture yet.';
empty.style.opacity = '0.6';
container.append(openButton, empty);
// The big picture, over the whole view.
const overlay = document.createElement('div');
overlay.setAttribute('role', 'dialog');
overlay.setAttribute('aria-modal', 'true');
overlay.setAttribute('aria-label', alt);
Object.assign(overlay.style, { position: 'fixed', inset: '0', zIndex: '10', boxSizing: 'border-box', display: 'grid', gridTemplateRows: 'auto minmax(0, 1fr) auto', gap: '12px', background: 'rgba(0, 0, 0, 0.92)', color: '#fff' });
const closeButton = document.createElement('button');
closeButton.type = 'button';
closeButton.textContent = 'Close';
Object.assign(closeButton.style, { justifySelf: 'end', padding: '6px 14px', borderRadius: '10px', border: '1px solid rgba(255, 255, 255, 0.5)', background: 'transparent', color: '#fff', font: 'inherit', cursor: 'pointer' });
const big = document.createElement('img');
big.alt = alt;
Object.assign(big.style, { width: '100%', height: '100%', objectFit: 'contain' });
const caption = document.createElement('p');
caption.textContent = alt;
Object.assign(caption.style, { margin: '0', textAlign: 'center', fontSize: '14px' });
overlay.append(closeButton, big, caption);
// While it is big, the function that gives the back button back to the webapp.
let giveBackButton = null;
const onKey = (event) => {
if (event.key === 'Escape') close();
};
const open = () => {
if (giveBackButton) return;
document.body.append(overlay);
closeButton.focus();
// When the person goes back, the webapp asks this handler first. Returning true means "handled, stay here".
giveBackButton = world.onBack(() => {
close();
return true;
});
document.addEventListener('keydown', onKey);
};
function close() {
if (!giveBackButton) return;
giveBackButton();
giveBackButton = null;
document.removeEventListener('keydown', onKey);
overlay.remove();
openButton.focus();
}
openButton.onclick = open;
overlay.onclick = close;
// Called at once, then after every change of the world.
const stop = world.subscribe((node) => {
const source = node.data[name];
const hasPicture = typeof source === 'string';
openButton.style.display = hasPicture ? 'inline-block' : 'none';
empty.style.display = hasPicture ? 'none' : 'block';
// Only a new picture goes to the <img>s, to keep the browser from decoding the same one again.
if (hasPicture && small.getAttribute('src') !== source) {
small.src = source;
big.src = source;
}
// Keep clear of the notch and the home bar of the phone (see SafeArea).
const { insets } = node.webapp;
overlay.style.padding = `${16 + insets.top}px ${16 + insets.right}px ${16 + insets.bottom}px ${16 + insets.left}px`;
});
return () => {
close();
stop();
openButton.remove();
empty.remove();
};
}
// Using it, on a fake world.
/** A map of an island, as an SVG image source. */
const MAP = `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="400" height="260">
<rect width="400" height="260" fill="#9BB7F2"/>
<path d="M80 150 C 70 80, 170 40, 240 60 S 350 110, 320 170 S 180 230, 120 210 S 90 180, 80 150 Z" fill="#8FD89E" stroke="#399D57" stroke-width="3"/>
<circle cx="160" cy="120" r="6" fill="#9F466B"/><circle cx="260" cy="150" r="6" fill="#9F466B"/>
<text x="172" y="116" font-family="sans-serif" font-size="14" fill="#141312">Port</text>
<text x="214" y="176" font-family="sans-serif" font-size="14" fill="#141312">Lighthouse</text></svg>`)}`;
// A fake world to build with: it shows a map in its data.
const island = { name: 'Island', data: { map: MAP } };
// While building: the fake world. In the webapp: const world = await connectToHost();
// (A fake world takes the back button and never uses it. Try Close, Escape or a tap.)
const world = await connectToHost({ fake: { world: island } });
const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', justifyItems: 'start' });
const title = document.createElement('h2');
title.style.margin = '0';
title.textContent = world.name;
const place = document.createElement('div');
page.append(title, place);
document.body.append(page);
fullScreenPicture(place, world, { name: 'map', alt: 'The map of the island, with the port and the lighthouse' });L'immagine è l'URL o il data URI in world.data[name]. Un nuovo valore dal mondo la sostituisce subito in tutte e due le dimensioni. Mentre l'overlay è aperto il componente intercetta il tasto indietro con world.onBack. Tornare indietro chiude allora l'overlay invece di uscire dal mondo. Alla chiusura chiama la funzione restituita da onBack per ridare il tasto alla webapp. L'overlay dell'esempio si chiude solo negli altri tre modi perché un mondo finto accetta l'handler senza mai chiamarlo (I link e il tasto indietro).
L'overlay ha un padding pari a world.webapp.insets per tenere l'immagine lontana dal notch e dalla barra home del telefono. È una finestra di dialogo modale con alt come nome accessibile. Il focus passa su Close all'apertura e torna sull'immagine piccola alla chiusura.
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo restituito da useWorld. |
name | (obbligatorio) | Il nome dell'immagine in world.data. |
alt | (obbligatorio) | Il testo alternativo dell'immagine e la didascalia dell'overlay. |
height | 180 | L'altezza dell'immagine piccola in pixel. |
Parametri
fullScreenPicture(container, world, options) disegna l'immagine piccola dentro container. L'overlay si apre sopra tutta la vista.
| Parametro | Che cos'è |
|---|---|
container | L'elemento che riceve l'immagine piccola. |
world | Il mondo con cui si risolve connectToHost. |
options.name | Il nome dell'immagine in world.data. |
options.alt | Il testo alternativo dell'immagine e la didascalia dell'overlay. |
options.height | L'altezza dell'immagine piccola in pixel. Predefinito 180. |
Restituisce una funzione che chiude l'overlay, annulla l'iscrizione al mondo e rimuove l'immagine piccola.
Modificalo
- Copri tutto lo schermo e non solo la vista con
overlay.requestFullscreen()all'apertura edocument.exitFullscreen()alla chiusura. La webapp permette alle viste di usare la Fullscreen API (Mostra un'immagine a schermo intero). - Mostra un'immagine di un messaggio (per esempio ogni immagine di una
MessageList) passando la suaimageal posto diworld.data[name]. - Ingrandisci con un secondo clic lasciando scorrere l'overlay (
overflow: 'auto') e mostrando l'immagine alla sua dimensione naturale (width: 'auto',height: 'auto').