Skip to content

LoadingAndErrors ​

Fra l'avvio della tua vista e l'arrivo del mondo c'è una breve fase di connessione. A volte il mondo non arriva mai perché la pagina è stata aperta direttamente in una scheda del browser invece che dentro la webapp o perché la webapp non accetta la versione del kit della tua vista. LoadingAndErrors mostra "Connecting…" finché la Promise di connectToHost è in sospeso. Se la Promise viene rifiutata mostra la causa e un modo per uscirne. Quando il mondo c'è, disegna la tua vista. Mettilo intorno a tutta la tua vista.

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

// The component: copy this part.

/** What the person reads when the view cannot connect, for each error code. */
const CONNECT_PROBLEMS = {
	'no-host': {
		title: 'This view opens inside UNaIVERSE',
		text: 'Open it from its world, in the UNaIVERSE webapp. If you are there already, the webapp did not answer: try again.',
	},
	unsupported: { title: 'This view needs an update', text: 'The webapp and this view do not speak the same version. Try again later.' },
};

/**
 * LoadingAndErrors: what the person sees before the world arrives and when it
 * cannot arrive, either a "Connecting…" line or the reason in words with a way out.
 * Once the world is here, it draws its children, your view.
 * @param {object} props
 * @param {object|null} props.world - The world, from useWorld (null until it arrives).
 * @param {Error|null} props.error - The error, from useWorld (null when there is none).
 * @param {string} [props.worldUrl] - The address of the world in UNaIVERSE, for a link when the view is opened alone.
 * @param {React.ReactNode} props.children - Your view, drawn once the world is here.
 */
export function LoadingAndErrors({ world, error, worldUrl, children }) {
	const box = { display: 'grid', gap: 8, justifyItems: 'start', padding: 16, borderRadius: 14, border: '1px solid rgba(127, 127, 127, 0.3)' };
	if (error) {
		const problem = CONNECT_PROBLEMS[error.code] ?? { title: 'Could not connect', text: error.message };
		return (
			<div role="alert" style={box}>
				<strong>{problem.title}</strong>
				<span style={{ fontSize: 14, opacity: 0.8 }}>{problem.text}</span>
				<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
					{error.code === 'no-host' && worldUrl && <a href={worldUrl}>Open it in UNaIVERSE</a>}
					{/* Connecting again is loading the page again. */}
					<button type="button" onClick={() => window.location.reload()}>Try again</button>
				</div>
			</div>
		);
	}
	if (!world) {
		return (
			<div role="status" style={box}>
				{/* A progress bar with no value, which the browser shows as busy. */}
				<progress aria-label="Connecting" style={{ width: 160 }} />
				<span>Connecting…</span>
			</div>
		);
	}
	return children;
}

// Using it, on a fake world.

// A fake world to build with: no account, no network.
const arena = { name: 'Arena', now: { text: 'Waiting for players' } };

/** Your view: its own component, drawn only once the world is here. */
function ArenaView({ world }) {
	return <p style={{ margin: 0 }}>Welcome to {world.name}. {world.now?.text}.</p>;
}

/** The error a view gets when it is opened alone, outside the webapp. */
const OUTSIDE = Object.assign(new Error('This view is not inside the UNaIVERSE webapp'), { code: 'no-host' });

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: arena } });

	// The three things a person can see. The first two pretend, and the last one is the real connection.
	return (
		<div style={{ display: 'grid', gap: 12, maxWidth: 480 }}>
			<LoadingAndErrors world={null} error={null} />
			<LoadingAndErrors world={null} error={OUTSIDE} worldUrl="https://unaiverse.io" />
			<LoadingAndErrors world={world} error={error}>
				<ArenaView world={world} />
			</LoadingAndErrors>
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/** What the person reads when the view cannot connect, for each error code. */
const CONNECT_PROBLEMS = {
	'no-host': {
		title: 'This view opens inside UNaIVERSE',
		text: 'Open it from its world, in the UNaIVERSE webapp. If you are there already, the webapp did not answer: try again.',
	},
	unsupported: { title: 'This view needs an update', text: 'The webapp and this view do not speak the same version. Try again later.' },
};

/**
 * Shows in `container` what the person sees before the world arrives and when it
 * cannot arrive, either a "Connecting…" line or the reason in words with a way
 * out. Unlike the other components, it runs before there is a world and therefore
 * takes the connection itself, the promise that `connectToHost()` returns.
 * @param {HTMLElement} container - Where to draw it.
 * @param {Promise<object>} connecting - The connection, from connectToHost.
 * @param {{worldUrl?: string}} [options] - The address of the world in UNaIVERSE, for a link when the view is opened alone.
 * @returns {Promise<object>} The world, once it is here (it then removes what it drew). When the
 *   connection fails, it shows why and never resolves, to keep the code after it from running.
 */
export function loadingAndErrors(container, connecting, { worldUrl } = {}) {
	const box = document.createElement('div');
	box.setAttribute('role', 'status');
	Object.assign(box.style, { display: 'grid', gap: '8px', justifyItems: 'start', padding: '16px', borderRadius: '14px', border: '1px solid rgba(127, 127, 127, 0.3)' });
	// A progress bar with no value, which the browser shows as busy.
	const progress = document.createElement('progress');
	progress.setAttribute('aria-label', 'Connecting');
	progress.style.width = '160px';
	const words = document.createElement('span');
	words.textContent = 'Connecting…';
	box.append(progress, words);
	container.append(box);

	const showProblem = (error) => {
		const problem = CONNECT_PROBLEMS[error.code] ?? { title: 'Could not connect', text: error.message };
		box.setAttribute('role', 'alert');
		const title = document.createElement('strong');
		title.textContent = problem.title;
		const text = document.createElement('span');
		text.textContent = problem.text;
		Object.assign(text.style, { fontSize: '14px', opacity: '0.8' });
		const row = document.createElement('div');
		Object.assign(row.style, { display: 'flex', alignItems: 'center', gap: '12px' });
		if (error.code === 'no-host' && worldUrl) {
			const link = document.createElement('a');
			link.href = worldUrl;
			link.textContent = 'Open it in UNaIVERSE';
			row.append(link);
		}
		// Connecting again is loading the page again.
		const again = document.createElement('button');
		again.type = 'button';
		again.textContent = 'Try again';
		again.onclick = () => window.location.reload();
		row.append(again);
		box.replaceChildren(title, text, row);
	};

	return connecting.then(
		(world) => {
			box.remove();
			return world;
		},
		(error) => {
			showProblem(error);
			return new Promise(() => {});
		},
	);
}

// Using it, on a fake world.

// A fake world to build with: no account, no network.
const arena = { name: 'Arena', now: { text: 'Waiting for players' } };

/** The error a view gets when it is opened alone, outside the webapp. */
const OUTSIDE = Object.assign(new Error('This view is not inside the UNaIVERSE webapp'), { code: 'no-host' });

// The three things a person can see. The first two pretend, and the last one is the real connection.
const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', maxWidth: '480px' });
const [connectingBox, outsideBox, worldBox] = [1, 2, 3].map(() => document.createElement('div'));
page.append(connectingBox, outsideBox, worldBox);
document.body.append(page);

loadingAndErrors(connectingBox, new Promise(() => {}));
loadingAndErrors(outsideBox, Promise.reject(OUTSIDE), { worldUrl: 'https://unaiverse.io' });

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

// Your view, drawn only once the world is here.
const welcome = document.createElement('p');
welcome.style.margin = '0';
worldBox.append(welcome);
world.subscribe((node) => {
	welcome.textContent = `Welcome to ${node.name}. ${node.now?.text}.`;
});
Live, on a fake world
Open

L'esempio mette uno sotto l'altro i tre stati che una persona può vedere: (1) una connessione che non finisce mai, (2) l'errore mostrato quando la pagina è aperta fuori dalla webapp (tutti e due simulati) e (3) la connessione vera al mondo finto.

connectToHost() viene rifiutata con un errore il cui code dà la causa (useWorld restituisce lo stesso errore in error):

CodiceQuandoChe cosa legge la persona
'no-host'La pagina non è dentro la webapp (è stata aperta direttamente in una scheda del browser) o la webapp non ha risposto in tempo.This view opens inside UNaIVERSE (con un link al mondo quando passi worldUrl).
'unsupported'La webapp non accetta la versione del tuo kit.This view needs an update.

Qualsiasi altro errore mostra Could not connect con il message dell'errore. Try again ricarica la pagina e fa quindi ripartire la connessione (Gli errori e i controlli della persona e connectToHost).

In React metti la tua vista in un componente a sé dentro LoadingAndErrors (ArenaView nell'esempio). LoadingAndErrors disegna i suoi figli solo dopo l'arrivo del mondo e la tua vista non riceve quindi mai un mondo null.

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo da useWorld (null finché non arriva).
error(obbligatorio)L'errore da useWorld (null quando non c'è).
worldUrlnessunoL'indirizzo del mondo in UNaIVERSE. Una pagina aperta fuori dalla webapp mostra un link a questo indirizzo.
childrenLa tua vista disegnata solo dopo l'arrivo del mondo.

Parametri ​

Gli altri componenti ricevono il mondo come argomento. loadingAndErrors(container, connecting, options) invece parte prima che il mondo esista e riceve la connessione in corso:

js
const world = await loadingAndErrors(document.body, connectToHost());
ParametroChe cos'è
containerL'elemento in cui disegnare.
connectingLa Promise restituita da connectToHost().
options.worldUrlL'indirizzo del mondo in UNaIVERSE per il link mostrato quando la pagina è aperta fuori dalla webapp.

Restituisce una Promise. Quando la connessione riesce il componente rimuove quello che ha disegnato e la Promise si risolve con il mondo. Se la connessione fallisce mostra la causa e la Promise non si risolve mai in modo che il codice dopo l'await non venga eseguito.

Modificalo ​

  • Mostra una tua schermata di caricamento con il tuo logo o uno scheletro della tua vista al posto della barra di avanzamento (Mostra una schermata di caricamento).
  • Rendi utile la pagina aperta fuori dalla webapp. Per 'no-host' disegna una tua pagina pubblica (che cos'è il mondo, come entrarci) al posto del messaggio (Mostra un messaggio fuori dalla webapp).
  • Gestisci la fine del mondo. Dopo la connessione world.status può diventare 'ended' o 'unreachable' e WorldStatus lo mostra.

Vedi anche ​

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