Links and the back button
Your view has places of its own such as a tab, a room or a step of a form. A shared link should open the place it was shared from and the back button should close the panel the person just opened instead of leaving the world. Both the address bar and the back button belong to the webapp. Your view reaches them through two calls: (1) world.setPath() writes your place into the address of the webapp and (2) world.onBack() lets your view handle the back button first.
A place in the address of the webapp
The webapp shows a world at an address like https://unaiverse.io/world/7fdb…. As an iframe inside that page, your view never appears in the address bar and a shared link does not contain its address.
world.setPath(path) writes a path of your site into the address of the webapp, after ?gui=:
await world.setPath('/rooms/3');
// The address of the webapp is now https://unaiverse.io/world/7fdb…?gui=/rooms/3Whoever opens that address (the person after a reload, a friend who received the link, a bookmark) gets the world with your view loaded at https://your.site/rooms/3. The view below has two tabs and writes the open one into the address:
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world to build with: no account, no network.
const arena = { name: 'Arena', data: { board: 'X . O', scores: 'Ada 3, Bob 1' } };
// The places of the view: each tab has its own path on your site.
const TABS = [
{ path: '/board', label: 'Board' },
{ path: '/scores', label: 'Scores' },
];
// Start where the link says: the webapp opens your page at the path it carries.
const isKnown = TABS.some((tab) => tab.path === window.location.pathname);
const START = isKnown ? window.location.pathname : '/board';
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: arena } });
const [current, setCurrent] = useState(START);
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
function choose(path) {
setCurrent(path);
// Writes the place into the address of the webapp, with no new step in the history.
world.setPath(path);
}
return (
<>
<div>
{TABS.map((tab) => (
<button key={tab.path} aria-pressed={tab.path === current} onClick={() => choose(tab.path)}>
{tab.label}
</button>
))}
</div>
<p>{current === '/board' ? `Board: ${world.data.board}` : `Scores: ${world.data.scores}`}</p>
<small>The webapp's address ends with ?gui={current}</small>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world to build with: no account, no network.
const arena = { name: 'Arena', data: { board: 'X . O', scores: 'Ada 3, Bob 1' } };
// The places of the view: each tab has its own path on your site.
const TABS = [
{ path: '/board', label: 'Board' },
{ path: '/scores', label: 'Scores' },
];
// Start where the link says: the webapp opens your page at the path it carries.
const isKnown = TABS.some((tab) => tab.path === location.pathname);
let current = isKnown ? location.pathname : '/board';
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
const bar = document.createElement('div');
const panel = document.createElement('p');
const address = document.createElement('small');
document.body.append(bar, panel, address);
function draw(node) {
bar.replaceChildren(...TABS.map((tab) => {
const button = document.createElement('button');
button.textContent = tab.label;
button.setAttribute('aria-pressed', String(tab.path === current));
button.onclick = () => choose(tab.path);
return button;
}));
panel.textContent = current === '/board' ? `Board: ${node.data.board}` : `Scores: ${node.data.scores}`;
address.textContent = `The webapp's address ends with ?gui=${current}`;
}
function choose(path) {
current = path;
draw(world.get());
// Writes the place into the address of the webapp, with no new step in the history.
world.setPath(path);
}
// Called at once, then after every change of the world.
world.subscribe(draw);Four details of setPath matter:
- It adds no step to the history. The call replaces the current address and the back button therefore does not go back through every tab the person opened. To make back undo something, use
onBack. - It takes only a path of your own site of at most 512 characters with one leading
/(not//or/\) and an optional query and hash (/rooms/3?tab=chat#bottom). For any other value the webapp changes nothing and the promise resolves withfalse. - The webapp writes the path only while the person is on the page of the world. On any other page of the webapp the address stays as it is.
- The webapp takes at most 10 paths a second. Above that rate only the last path waits for the next free slot and the ones before it are dropped. Call
setPathwhen the place changes and never on every scroll event.
Open at the place the link names
For an address with ?gui=/rooms/3 the webapp loads https://your.site/rooms/3 in the iframe. Your page reads its own location at startup like any web page and opens at that place:
// https://your.site/rooms/3?tab=chat
const match = location.pathname.match(/^\/rooms\/(\d+)$/);
const room = match ? Number(match[1]) : null; // 3
const tab = new URLSearchParams(location.search).get('tab'); // 'chat'An unknown path (an old link can outlive the place it names) should open the first place of your view instead of an empty page.
Pitfall
Your server must answer at every path you write. For a single-page view (index.html) that writes /rooms/3 the webapp loads https://your.site/rooms/3 and a server that serves only / answers that request with "404 Not Found". In nginx a try_files rule makes the server return your page for those paths:
location / {
try_files $uri /index.html;
}Most hosting services and dev servers have a "single-page app" option with the same effect.
Pitfall
The path is resolved from the root of your site and not from the address of your view. For a view at https://gui.client.example/hotel/ the call setPath('/rooms/3') opens https://gui.client.example/rooms/3 outside /hotel/. Write the whole path instead (setPath('/hotel/rooms/3')).
The webapp reads the path of the link whenever it starts your view (in a new tab, after a reload or from a shared link). A view that is already running in the same tab keeps its place when the address changes.
The webapp also restarts your view by itself at the last path you wrote in two cases: (1) when the person presses Try again after your view did not answer and (2) after the person allows a browser feature (The camera and the rest of the browser). A view that writes every change of place with setPath therefore reopens at its place after such a restart.
What to put in the address
The address holds what a person shares or returns to, such as the open tab, the room, the item or the step of a long form. Leave out what changes every second (a scroll position, a timer) and what makes sense only for a moment (an open menu). Because the address is visible and people share it, never put private data in it.
Do not add steps to the history of the browser
Pitfall
Inside an iframe history.pushState and links that load a new page add entries to the history of the browser among those of the webapp. The back button then goes back through your entries without asking the webapp or your onBack handler and the address of the webapp no longer matches the place of the person.
Your view avoids this in three ways:
- render the new place and write it with
setPath - with a router, use its "replace" mode (
navigate(to, { replace: true })in React Router) or a router that keeps its location in memory - handle the back button with
onBack.
Links out of your view
- A link to another site (your shop, a help page) is
<a href="https://…" target="_blank" rel="noopener">. It opens in a new tab or window and leaves your view as it is. target="_top"andwindow.top.locationdo not work. Your view can never load another page in place of the webapp.- A link to another page of your own site loads that page in the iframe and works when that page also loads the kit and calls
connectToHost(). The person waits for a full page load and the address of the webapp does not change. A single page that renders the new place and writes it withsetPathavoids both.
The back button asks your view first
On a phone back is the most common gesture. A person who presses back with a panel of your view open expects the panel to close and the world to stay. The webapp cannot know that the panel is open. Unless your view handles the back command, the webapp leaves the world.
world.onBack(handler) lets your view answer every back command first (the button of the browser, the back button or gesture of a phone and the back arrows of the webapp). When the person presses back:
- Your handler runs first. A handler that closed something returns
trueand the person stays where they are. - When the handler returns
falseor does not answer within half a second, the webapp goes back as usual.
onBack returns a function that removes the handler. In the example the back button closes a panel:
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world to build with: no account, no network.
const shop = { name: 'Corner shop', data: { hours: '8:00 to 18:00' } };
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: shop } });
const [isOpen, setIsOpen] = useState(false);
const [note, setNote] = useState('');
// The newest isOpen, for the handler of the back button.
const isOpenRef = useRef(isOpen);
isOpenRef.current = isOpen;
// What the back button does: close the panel and keep the person here (true),
// or, with nothing open, let the webapp go back (false).
function pressBack() {
if (!isOpenRef.current) {
setNote('Nothing open: the webapp goes back.');
return false;
}
setIsOpen(false);
return true;
}
// Once connected, the back button asks the view first, and the cleanup gives it back.
// The dependency is not [world], because the world is a new object at every change.
const isConnected = Boolean(world);
useEffect(() => {
if (!isConnected) return undefined;
return world.onBack(() => pressBack());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isConnected]);
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<>
<h2>{world.name}</h2>
<button onClick={() => { setIsOpen(true); setNote(''); }}>Show details</button>
{isOpen && (
<section>
<p>Opening hours: {world.data.hours}</p>
<button onClick={() => setIsOpen(false)}>Close</button>
</section>
)}
<p>{note}</p>
{/* Only while building: a button that pretends the back button, because the fake world never sends it. */}
<button onClick={() => pressBack()}>Pretend the back button</button>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world to build with: no account, no network.
const shop = { name: 'Corner shop', data: { hours: '8:00 to 18:00' } };
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: shop } });
const title = document.createElement('h2');
const open = document.createElement('button');
open.textContent = 'Show details';
const panel = document.createElement('section');
panel.hidden = true;
const details = document.createElement('p');
const close = document.createElement('button');
close.textContent = 'Close';
panel.append(details, close);
const note = document.createElement('p');
// Only while building: a button that pretends the back button, because the fake world never sends it.
const pretend = document.createElement('button');
pretend.textContent = 'Pretend the back button';
document.body.append(title, open, panel, note, pretend);
open.onclick = () => { panel.hidden = false; note.textContent = ''; };
close.onclick = () => { panel.hidden = true; };
// What the back button does: close the panel and keep the person here (true),
// or, with nothing open, let the webapp go back (false).
function pressBack() {
if (panel.hidden) {
note.textContent = 'Nothing open: the webapp goes back.';
return false;
}
panel.hidden = true;
return true;
}
// The back button asks the view first, for as long as the view is shown.
world.onBack(pressBack);
pretend.onclick = () => pressBack();
world.subscribe((node) => {
title.textContent = node.name;
details.textContent = `Opening hours: ${node.data.hours}`;
});The handler returns true only when it changed something visible. With nothing open it returns false and the webapp goes back. Because a fake world never sends a back command, the example adds a button that calls the same handler (While you build).
onBack follows three rules:
- Newest first. With several calls to
onBackthe handlers run from the newest to the oldest until one returnstrue. A dialog opened over a panel registers its own handler that runs first and closes only the dialog. - The handler returns a boolean or a Promise of one. An
asynchandler must resolve within half a second and should not wait for the network. - Remove the handler when you no longer need it. While at least one handler is registered the webapp keeps one extra entry in its history. Call the function returned by
onBackto remove your handler. Once the last handler is removed the back button works for the webapp again.
Pitfall
Never return true without a visible change. Every press of back would then do nothing and the person could not leave your view with the back button. When in doubt, return false.
In React
Register the handler in an effect with two precautions:
- Keep
worldout of the dependencies of the effect. The world is a new object at every change and the effect would remove and register the handler many times a second. Depend on a stable value such asBoolean(world)(as the example does) or on the state that decides whether you need the button (isOpen). - Read your newest state through a ref or register the handler only while it has something to close:
// Only while the panel is open: the cleanup gives the button back when it closes.
const isConnected = Boolean(world);
useEffect(() => {
if (!isConnected || !isOpen) return undefined;
return world.onBack(() => {
setIsOpen(false);
return true;
});
}, [isConnected, isOpen]);Patterns
Panels, dialogs and full-screen pictures. Back closes the topmost open element. Keep a stack with a close function for each open element and close the last one:
const open = []; // what is open, newest last: functions that close it
world.onBack(() => {
const close = open.pop();
if (!close) return false; // nothing open: let the webapp go back
close();
return true;
});Steps of a form. Back goes to the previous step. On the first step the handler returns false and the webapp goes back.
world.onBack(() => {
if (step === 1) return false;
showStep(step - 1);
return true;
});Tabs. In most apps back does not switch tabs because tabs are parallel places and not a sequence the person followed. Write the tab into the address with setPath and leave back to the webapp. In some phone apps, on the other hand, back returns to the first tab from any other tab. A view that does the same returns true only when the person is not on the first tab.
Back and the address together. When back closes the room the person opened, write the address of the place it returns to:
world.onBack(() => {
if (!roomOpen) return false;
closeRoom();
world.setPath('/rooms');
return true;
});While you build
A fake world has no webapp, no address and no back button:
setPathdoes nothing and resolves withtrueonBackaccepts the handler and never calls it.
Test both by hand instead:
- Start paths. Open your page on your computer at the path (for example
http://localhost:5173/rooms/3) and check that the view opens at the place that the webapp would open. - The back button. Like the example, keep the handler in a named function and call it from a test button or from the browser console. Check both results (
truewith something open andfalsewith nothing open).
Then write the address of your view in the Own view field of one of your worlds and test both in the webapp and on a phone (Going live).
Next steps
- The camera and the rest of the browser: the browser features your view may use and the restart after the person allows one.
- Reference:
setPath,onBack. - Recipes: Keep the open tab in the address, Open your view at a place, Close a panel with the back button.