Skip to content

BackPanel ​

On a phone people close a panel with the back button. Inside the webapp the same button leaves the world unless your view intercepts it first. BackPanel renders a button that opens a panel over your view (for the rules, the settings or the details of a player) and intercepts the back button while the panel is open. Going back then closes the panel and the person stays in your view. The Close button of the panel, the Esc key and a click on the backdrop close it too.

jsx
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>
	);
}
js
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 });
Live, on a fake world
Open

When the panel opens, the component registers a handler with world.onBack(handler). While a handler is registered the webapp calls it first whenever the person goes back in the browser, on the phone or with the back arrow of the webapp. The handler closes the panel and returns true to tell the webapp that the event is handled. The webapp then does not leave the world. On close the component calls the function returned by onBack and the webapp gets the back button again (The back button asks your view first covers the other return values). A fake world accepts the handler and never calls it. In the example close the panel in one of the other three ways.

The panel is a modal dialog whose accessible name is its title. Focus moves to Close when the panel opens and returns to the open button when it closes.

Props ​

PropDefaultWhat it is
world(required)The world returned by useWorld.
buttonText(required)The label of the button that opens the panel.
title(required)The title of the panel.
childrenThe content of the panel.

Parameters ​

backPanel(container, world, options) renders the open button into container. The panel opens over the whole view.

ParameterWhat it is
containerThe element that receives the open button.
worldThe world that connectToHost resolves with.
options.buttonTextThe label of the button that opens the panel.
options.titleThe title of the panel.
options.contentThe element shown in the panel.

It returns a function that closes the panel, gives the back button back to the webapp and removes the open button.

Change it ​

  • Open it from elsewhere. In React lift isOpen up to the parent and pass isOpen and onClose as props in place of the open button. The plain JavaScript version can return open and close together with the stop function.
  • Use a side panel on a desktop by aligning the panel to the right (justifyContent: 'flex-end', alignItems: 'stretch') when the view is wide.
  • Keep the panel in the address with world.setPath('/rules') on open and world.setPath('/') on close. A shared link then opens the panel (Keep the open tab in the address).

See also ​

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