Skip to content

Tieni nell'indirizzo la scheda aperta ​

Quando la persona ricarica la pagina o ne manda l'indirizzo a un amico, si aspetta di ritrovare aperta la stessa scheda. La tua vista non può cambiare l'indirizzo della webapp. Può però chiedere alla webapp con world.setPath(path) di scrivere in quell'indirizzo un percorso del tuo sito dopo ?gui=. Quando qualcuno apre quell'indirizzo, la webapp carica la tua vista a quel percorso e la vista apre la scheda nominata nel percorso. L'esempio mostra che cosa conterrebbe l'indirizzo della webapp per la scheda che scegli.

jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';

// The fake world needs no account and no network.
const arena = {
	name: 'Arena',
	profile: { description: 'First to three points wins.' },
	now: { text: 'Your move' },
};

const tabs = { board: 'Board', chat: 'Chat', rules: 'Rules' };
// The tab to open first is the one in the address of this page (https://your.site/arena/?tab=rules), or the board.
const asked = new URLSearchParams(location.search).get('tab');
const firstTab = Object.keys(tabs).includes(asked) ? asked : 'board';

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: arena } });
	const [tab, setTab] = useState(firstTab);
	const [address, setAddress] = useState(null);

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	function choose(name) {
		setTab(name);
		// Write the tab into the address of the webapp (…?gui=/arena/?tab=chat). A reload, or a shared link, then opens it.
		const next = `${location.pathname}?tab=${name}`;
		world.setPath(next);
		setAddress(next);
	}

	return (
		<>
			<nav>
				{Object.entries(tabs).map(([name, label]) => (
					<button key={name} onClick={() => choose(name)} style={{ fontWeight: name === tab ? 'bold' : 'normal' }}>
						{label}
					</button>
				))}
			</nav>
			{tab === 'board' && <p>{world.now?.text}</p>}
			{tab === 'chat' && <p>Messages: {world.messages.length}</p>}
			{tab === 'rules' && <p>{world.profile.description}</p>}
			{address && <p>The webapp's address now ends with ?gui={address}</p>}
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The fake world needs no account and no network.
const arena = {
	name: 'Arena',
	profile: { description: 'First to three points wins.' },
	now: { text: 'Your move' },
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });

const tabs = { board: 'Board', chat: 'Chat', rules: 'Rules' };
// The tab to open first is the one in the address of this page (https://your.site/arena/?tab=rules), or the board.
const asked = new URLSearchParams(location.search).get('tab');
let tab = Object.keys(tabs).includes(asked) ? asked : 'board';

const bar = document.createElement('nav');
const content = document.createElement('p');
const address = document.createElement('p');
document.body.append(bar, content, address);

function choose(name) {
	tab = name;
	// Write the tab into the address of the webapp (…?gui=/arena/?tab=chat). A reload, or a shared link, then opens it.
	const path = `${location.pathname}?tab=${name}`;
	world.setPath(path);
	address.textContent = `The webapp's address now ends with ?gui=${path}`;
	draw(world.get());
}

function draw(node) {
	bar.replaceChildren(...Object.entries(tabs).map(([name, label]) => {
		const button = document.createElement('button');
		button.textContent = label;
		button.style.fontWeight = name === tab ? 'bold' : 'normal';
		button.onclick = () => choose(name);
		return button;
	}));
	if (tab === 'board') content.textContent = node.now?.text ?? '';
	if (tab === 'chat') content.textContent = `Messages: ${node.messages.length}`;
	if (tab === 'rules') content.textContent = node.profile.description ?? '';
}

// Called at once, then after every change of the world.
world.subscribe(draw);
Live, on a fake world
Open

Come funziona ​

world.setPath('/arena/?tab=chat') scrive il percorso dopo ?gui= nell'indirizzo della webapp senza aggiungere passi alla cronologia. Il tasto indietro perciò non ripercorre le schede. Quando più tardi la webapp apre un indirizzo con ?gui=/arena/?tab=chat, carica la tua vista a https://your.site/arena/?tab=chat. Lì location.search contiene ?tab=chat e la vista apre quella scheda (o la prima se la scheda non è nota).

  • Il percorso deve essere un percorso del tuo sito che parte dalla sua radice con una sola / iniziale. setPath ignora qualsiasi altra cosa e si risolve con false. Per funzionare ovunque si trovi la tua vista, l'esempio conserva il percorso della tua pagina (location.pathname) e aggiunge la scheda dopo ?.
  • Chiama setPath quando cambia la scheda invece che a ogni scorrimento.
  • Con un mondo finto setPath si risolve con true e non cambia niente. Una prova con l'indirizzo vero richiede di scrivere l'indirizzo della tua vista nel campo Vista propria di un tuo mondo (Andare online). Quel campo accetta anche un indirizzo http://localhost.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.