BackPanel
Al telefono le persone chiudono un pannello con il tasto indietro. Dentro la webapp lo stesso tasto fa uscire dal mondo a meno che la tua vista non lo intercetti prima. BackPanel disegna un pulsante che apre un pannello sopra la tua vista (per le regole, le impostazioni o i dettagli di un giocatore) e intercetta il tasto indietro finché il pannello resta aperto. Tornare indietro chiude allora il pannello e la persona resta nella tua vista. Lo chiudono anche il pulsante Close del pannello, il tasto Esc e un clic sullo sfondo.
import { useEffect, useId, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';
// The component: copy this part.
/**
* BackPanel: a button that opens a panel over the view (rules, settings,
* details). The panel closes with its Close button, with Escape, with a tap
* outside it and with the back button. Going back in the browser, on the phone
* or with the arrow of the webapp would otherwise leave the world.
* @param {object} props
* @param {object} props.world - The world, from useWorld.
* @param {string} props.buttonText - The words of the button that opens the panel.
* @param {string} props.title - The title of the panel.
* @param {React.ReactNode} props.children - What the panel shows.
*/
export function BackPanel({ world, buttonText, title, children }) {
const [isOpen, setIsOpen] = useState(false);
const titleId = useId();
const openRef = useRef(null);
const closeRef = useRef(null);
// While the panel is open, it takes the back button and Escape.
// (The effect runs only when the panel 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]);
return (
<>
<button ref={openRef} type="button" onClick={() => setIsOpen(true)} aria-haspopup="dialog">{buttonText}</button>
{isOpen && (
// The dark backdrop. A tap on it closes the panel.
<div onClick={() => setIsOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0, 0, 0, 0.45)', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
<div role="dialog" aria-modal="true" aria-labelledby={titleId} onClick={(event) => event.stopPropagation()}
style={{ width: '100%', maxWidth: 480, maxHeight: '80%', overflowY: 'auto', boxSizing: 'border-box', padding: 20, borderRadius: '16px 16px 0 0', background: 'Canvas', color: 'CanvasText', boxShadow: '0 -4px 24px rgba(0, 0, 0, 0.25)' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
<h2 id={titleId} style={{ margin: 0, fontSize: 18, flex: 1 }}>{title}</h2>
<button ref={closeRef} type="button" onClick={() => setIsOpen(false)}>Close</button>
</div>
{children}
</div>
</div>
)}
</>
);
}
// Using it, on a fake world.
// A fake world to build with: no account, no network.
const quiz = { name: 'Quiz night', now: { text: 'Question 3 of 10' } };
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 outside.)
const { world, error } = useWorld({ fake: { world: quiz } });
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>
<p style={{ margin: 0 }}>{world.now?.text}</p>
<BackPanel world={world} buttonText="Show the rules" title="How to play">
<ol style={{ margin: 0, paddingLeft: 20 }}>
<li>Read the question.</li>
<li>Pick one answer before the time runs out.</li>
<li>A right answer scores one point.</li>
</ol>
</BackPanel>
</div>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
/** A counter for the ids of the panel titles, because each panel is named by the id of its title. */
let panelCount = 0;
/**
* Draws a button into `container` that opens a panel over the view (rules,
* settings, details). The panel closes with its Close button, with Escape,
* with a tap outside it and with the back button. Going back in the browser,
* on the phone or with the arrow of the webapp would otherwise leave the world.
* @param {HTMLElement} container - Where to draw the button.
* @param {object} world - The world, from connectToHost.
* @param {{buttonText: string, title: string, content: HTMLElement}} options - The words of the button,
* the title of the panel and what the panel shows.
* @returns {() => void} Closes the panel and removes what it drew.
*/
export function backPanel(container, world, { buttonText, title, content }) {
panelCount += 1;
const titleId = `back-panel-${panelCount}`;
const openButton = document.createElement('button');
openButton.type = 'button';
openButton.textContent = buttonText;
openButton.setAttribute('aria-haspopup', 'dialog');
container.append(openButton);
// The dark backdrop. A tap on it closes the panel.
const backdrop = document.createElement('div');
Object.assign(backdrop.style, { position: 'fixed', inset: '0', background: 'rgba(0, 0, 0, 0.45)', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' });
const panel = document.createElement('div');
panel.setAttribute('role', 'dialog');
panel.setAttribute('aria-modal', 'true');
panel.setAttribute('aria-labelledby', titleId);
Object.assign(panel.style, { width: '100%', maxWidth: '480px', maxHeight: '80%', overflowY: 'auto', boxSizing: 'border-box', padding: '20px', borderRadius: '16px 16px 0 0', background: 'Canvas', color: 'CanvasText', boxShadow: '0 -4px 24px rgba(0, 0, 0, 0.25)' });
const top = document.createElement('div');
Object.assign(top.style, { display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px' });
const heading = document.createElement('h2');
heading.id = titleId;
heading.textContent = title;
Object.assign(heading.style, { margin: '0', fontSize: '18px', flex: '1' });
const closeButton = document.createElement('button');
closeButton.type = 'button';
closeButton.textContent = 'Close';
top.append(heading, closeButton);
panel.append(top, content);
backdrop.append(panel);
// While the panel is open, 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(backdrop);
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);
backdrop.remove();
openButton.focus();
}
openButton.onclick = open;
closeButton.onclick = close;
backdrop.onclick = (event) => {
if (event.target === backdrop) close();
};
return () => {
close();
openButton.remove();
};
}
// Using it, on a fake world.
// A fake world to build with: no account, no network.
const quiz = { name: 'Quiz night', now: { text: 'Question 3 of 10' } };
// 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 outside.)
const world = await connectToHost({ fake: { world: quiz } });
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 now = document.createElement('p');
now.style.margin = '0';
now.textContent = world.now?.text ?? '';
const place = document.createElement('div');
page.append(title, now, place);
document.body.append(page);
// What the panel shows.
const rules = document.createElement('ol');
Object.assign(rules.style, { margin: '0', paddingLeft: '20px' });
for (const rule of ['Read the question.', 'Pick one answer before the time runs out.', 'A right answer scores one point.']) {
const item = document.createElement('li');
item.textContent = rule;
rules.append(item);
}
backPanel(place, world, { buttonText: 'Show the rules', title: 'How to play', content: rules });Quando il pannello si apre, il componente registra un handler con world.onBack(handler). Finché un handler è registrato la webapp lo chiama per primo ogni volta che la persona torna indietro nel browser, sul telefono o con la freccia indietro della webapp. L'handler chiude il pannello e restituisce true per dire alla webapp che l'evento è gestito. La webapp allora non esce dal mondo. Alla chiusura il componente chiama la funzione restituita da onBack e la webapp riprende il tasto indietro (Il tasto indietro chiede prima alla tua vista tratta gli altri valori restituiti). Un mondo finto accetta l'handler senza chiamarlo mai. Nell'esempio chiudi il pannello in uno degli altri tre modi.
Il pannello è una finestra di dialogo modale il cui nome accessibile è il suo titolo. Il focus passa su Close quando il pannello si apre e torna sul pulsante di apertura quando si chiude.
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo restituito da useWorld. |
buttonText | (obbligatorio) | L'etichetta del pulsante che apre il pannello. |
title | (obbligatorio) | Il titolo del pannello. |
children | Il contenuto del pannello. |
Parametri
backPanel(container, world, options) disegna il pulsante di apertura dentro container. Il pannello si apre sopra tutta la vista.
| Parametro | Che cos'è |
|---|---|
container | L'elemento che riceve il pulsante di apertura. |
world | Il mondo con cui si risolve connectToHost. |
options.buttonText | L'etichetta del pulsante che apre il pannello. |
options.title | Il titolo del pannello. |
options.content | L'elemento mostrato nel pannello. |
Restituisce una funzione che chiude il pannello, ridà il tasto indietro alla webapp e rimuove il pulsante di apertura.
Modificalo
- Aprilo da un altro punto. In React sposta
isOpennel componente genitore e passaisOpeneonClosecome props al posto del pulsante di apertura. La versione in JavaScript semplice può restituireopenecloseinsieme alla funzione di arresto. - Usa un pannello laterale su desktop allineando il pannello a destra (
justifyContent: 'flex-end',alignItems: 'stretch') quando la vista è larga. - Tieni il pannello nell'indirizzo con
world.setPath('/rules')all'apertura eworld.setPath('/')alla chiusura. Un link condiviso apre allora il pannello (Tieni nell'indirizzo la scheda aperta).
Vedi anche
- Chiudi un pannello con il tasto indietro: la stessa idea in poche righe.
onBack: il suo argomento e il valore che restituisce.FullScreenPicture: un'immagine che si chiude con il tasto indietro.