Skip to content

L'aspetto della webapp e lo schermo del telefono ​

La tua vista sta dentro la webapp di UNaIVERSE sotto la sua barra in alto. Per sembrare una parte della webapp usa il tema e la lingua della webapp e resta lontana da quello che copre lo schermo di un telefono (il notch, la barra home e la tastiera). La webapp passa questi valori in world.webapp e li passa di nuovo ogni volta che uno di essi cambia. Mentre sviluppi è un mondo finto a simularli tutti.

Che cosa dice la webapp alla tua vista ​

Ogni snapshot del mondo ha un campo webapp:

js
world.webapp;
// {
//   theme: 'dark',                                      'light' or 'dark'
//   language: 'it',                                     the language of the webapp
//   insets: { top: 0, right: 0, bottom: 34, left: 0 }, the safe areas of the screen, in pixels
//   keyboard: 0,                                        the height of the on-screen keyboard, in pixels
//   allowed: ['camera'],                                the browser features the person allowed your view
// }
CampoChe cos'è
themeIl tema della webapp ('light' o 'dark'). Disegna la tua vista nello stesso tema.
languageLa lingua della webapp (per esempio 'it' o 'en').
insetsLe aree sicure dello schermo (notch, angoli arrotondati, barra home) in pixel sui lati dove la tua vista tocca il bordo dello schermo.
keyboardL'altezza in pixel della tastiera a schermo sopra la tua vista. Vale 0 quando la tastiera è chiusa e sempre 0 su un desktop.
allowedLe funzioni del browser (la fotocamera, il microfono, ...) che la persona ha permesso alla tua vista (La fotocamera e il resto del browser).

Questi valori vengono dalle impostazioni della persona nella webapp e non da quelle del dispositivo. Una persona può usare il tema scuro di UNaIVERSE su un telefono in modalità chiara o leggere UNaIVERSE in italiano su un computer in inglese. Per questo la tua vista legge world.webapp invece delle impostazioni del browser.

Disegna tutti e due i temi ​

La vista qui sotto segue il tema e la lingua della webapp. L'esempio rende la webapp finta scura e in italiano con l'opzione webapp di connectToHost (più avanti).

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

// A fake world to build with: no account, no network.
const cafe = { name: 'Café', now: { text: 'Open until 18:00' } };

// Your words, in the languages you support. English is the fallback.
const WORDS = {
	en: { welcome: 'Welcome to', theme: 'Theme' },
	it: { welcome: 'Benvenuto al', theme: 'Tema' },
};

// Your colours, one set per theme.
const COLOURS = {
	light: { background: '#ffffff', text: '#1d1d1f' },
	dark: { background: '#1d1d1f', text: '#f5f5f7' },
};

export default function App() {
	// While building: the fake world, in a webapp that pretends to be dark and in Italian. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: cafe }, webapp: { theme: 'dark', language: 'it' } });
	const theme = world?.webapp.theme ?? 'light';
	const language = world?.webapp.language ?? 'en';

	// The whole page follows the webapp: its language, its colours, its form controls.
	useEffect(() => {
		document.documentElement.lang = language;
		document.documentElement.style.colorScheme = theme;
		document.body.style.background = COLOURS[theme].background;
		document.body.style.color = COLOURS[theme].text;
	}, [theme, language]);

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

	const words = WORDS[language.split('-')[0]] ?? WORDS.en;
	return (
		<>
			<h2>{words.welcome} {world.name}</h2>
			<p>{words.theme}: {theme}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world to build with: no account, no network.
const cafe = { name: 'Café', now: { text: 'Open until 18:00' } };

// Your words, in the languages you support. English is the fallback.
const WORDS = {
	en: { welcome: 'Welcome to', theme: 'Theme' },
	it: { welcome: 'Benvenuto al', theme: 'Tema' },
};

// Your colours, one set per theme.
const COLOURS = {
	light: { background: '#ffffff', text: '#1d1d1f' },
	dark: { background: '#1d1d1f', text: '#f5f5f7' },
};

// While building: the fake world, in a webapp that pretends to be dark and in Italian.
// In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: cafe }, webapp: { theme: 'dark', language: 'it' } });

const title = document.createElement('h2');
const info = document.createElement('p');
document.body.append(title, info);

// Called at once, then after every change of the world,
// including when the person changes the theme or the language of the webapp.
world.subscribe((node) => {
	const { theme, language } = node.webapp;
	const words = WORDS[language.split('-')[0]] ?? WORDS.en;

	// The whole page follows the webapp: its language, its colours, its form controls.
	document.documentElement.lang = language;
	document.documentElement.style.colorScheme = theme;
	document.body.style.background = COLOURS[theme].background;
	document.body.style.color = COLOURS[theme].text;

	title.textContent = `${words.welcome} ${node.name}`;
	info.textContent = `${words.theme}: ${theme}`;
});
Live, on a fake world
Open

Tre righe dell'esempio applicano il tema e la lingua:

  • document.body.style.background e color dipingono la pagina nei colori del tema. Dipingi uno sfondo tuo invece di contare sullo sfondo della webapp dietro l'iframe.
  • document.documentElement.style.colorScheme = theme comunica al browser il tema della pagina. Lo seguono anche i controlli che disegna il browser (campi di testo, checkbox, barre di scorrimento, i colori di sistema Canvas e CanvasText). Senza questa riga una vista scura può mostrare campi di testo bianchi.
  • document.documentElement.lang = language dà alla pagina la lingua che usano i lettori di schermo, la sillabazione e il controllo ortografico.

Un progetto vero tiene i suoi colori in un foglio di stile invece che in JavaScript. A ogni cambiamento scrivi un attributo sull'elemento radice e lascia scegliere i colori al CSS:

js
world.subscribe((node) => {
  document.documentElement.dataset.theme = node.webapp.theme;
});
css
:root {
  color-scheme: light;
  --background: #ffffff;
  --text: #1d1d1f;
  --accent: #2f5bd3;
}
:root[data-theme='dark'] {
  color-scheme: dark;
  --background: #1d1d1f;
  --text: #f5f5f7;
  --accent: #8aa8f5;
}
body {
  background: var(--background);
  color: var(--text);
}

Attenzione

Non scegliere il tuo tema con la media query CSS prefers-color-scheme (né con matchMedia('(prefers-color-scheme: dark)')). La query restituisce il tema del dispositivo. Con un altro tema scelto nella webapp la tua vista sarebbe chiara sotto una barra in alto scura. Leggi invece world.webapp.theme.

Un grigio che si legge bene sul bianco può sparire sul nero. Controlla il contrasto dei tuoi colori in tutti e due i temi rispetto ai rapporti indicati in Accessibilità.

Usa la lingua della webapp ​

world.webapp.language è il codice della lingua in cui la persona legge UNaIVERSE (di solito un codice breve come 'it' o 'en'). Il codice può portare anche una regione ('en-GB'). Confronta solo la sua prima parte e ripiega su una lingua che la tua vista supporta:

js
const WORDS = {
  en: { send: 'Send', empty: 'No messages yet' },
  it: { send: 'Invia', empty: 'Ancora nessun messaggio' },
};

function wordsFor(language) {
  return WORDS[language.split('-')[0]] ?? WORDS.en;
}

Intl formatta date, numeri ed elenchi in quella lingua:

js
const { language } = world.webapp;
new Intl.DateTimeFormat(language, { timeStyle: 'short' }).format(message.time); // '18:05' or '6:05 PM'
new Intl.NumberFormat(language).format(1234.5);                                 // '1.234,5' or '1,234.5'

Il testo della tua vista lo traduci tu. Il testo del mondo (il suo name, i suoi messaggi, now.text) arriva invece così come l'ha scritto il mondo e il kit non lo traduce mai.

TIP

Con una libreria di traduzione (i18next, FormatJS, ...) cambia la lingua della libreria dentro subscribe ogni volta che cambia webapp.language.

Resta lontano dal notch e dalla barra home ​

Su un telefono alcune parti dello schermo sono coperte o curve (il notch o il foro della fotocamera, gli angoli arrotondati e la barra home in fondo a un iPhone). Un pulsante disegnato lì è difficile da vedere e da premere.

Una pagina web di primo livello usa env(safe-area-inset-bottom) del CSS. Dentro un iframe questo valore è sempre 0 perché il browser dà le aree sicure solo alla pagina di primo livello della webapp. La webapp le misura e le passa alla tua vista in pixel come world.webapp.insets. Hanno un valore solo i lati dove la tua vista tocca il bordo dello schermo:

  • top di solito vale 0 perché la barra in alto della webapp sta sopra la tua vista e resta già lontana dal notch.
  • bottom è la barra home di un telefono tenuto in verticale (circa 34 pixel su un iPhone).
  • left e right sono diversi da 0 quando il telefono è girato di lato con il notch su un fianco.
  • Su un desktop valgono 0 tutti e quattro.

Aggiungi ogni inset al padding dell'elemento che tocca quel bordo. Nell'esempio la webapp finta simula un telefono con una barra home di 34 pixel e la casella dei messaggi resta sopra di essa.

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

// A fake world to build with: no account, no network.
const lobby = { name: 'Lobby', onMessage: (message) => `Got it: ${message.text}` };

// A phone with a home bar of 34 px, to pretend while building.
const PHONE = { insets: { top: 0, right: 0, bottom: 34, left: 0 }, keyboard: 0 };

export default function App() {
	// While building: the fake world, in a webapp that pretends to be a phone. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: lobby }, webapp: PHONE });
	const [text, setText] = useState('');

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

	const { insets, keyboard } = world.webapp;
	// Below the box: the home bar, or the keyboard when it is open (it covers the home bar).
	const bottom = Math.max(insets.bottom, keyboard);

	function send(event) {
		event.preventDefault();
		if (text) world.send(text);
		setText('');
	}

	// A column as tall as the view: the messages scroll, the message box stays at the bottom.
	return (
		<div style={{ position: 'fixed', inset: 0, display: 'flex', flexDirection: 'column' }}>
			<div style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: 12 }}>
				<p>Kept free below the box: {bottom} px</p>
				{world.messages.map((message) => (
					<p key={message.id}>{message.from}: {message.text}</p>
				))}
			</div>
			<form
				onSubmit={send}
				style={{
					display: 'flex', gap: 8, borderTop: '1px solid #8886',
					padding: `8px ${12 + insets.right}px ${8 + bottom}px ${12 + insets.left}px`,
				}}
			>
				<input placeholder="Message" value={text} onChange={(event) => setText(event.target.value)} style={{ flex: 1 }} />
				<button>Send</button>
			</form>
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world to build with: no account, no network.
const lobby = { name: 'Lobby', onMessage: (message) => `Got it: ${message.text}` };

// While building: the fake world, in a webapp that pretends to be a phone with a home bar of 34 px.
// In the webapp: const world = await connectToHost();
const world = await connectToHost({
	fake: { world: lobby },
	webapp: { insets: { top: 0, right: 0, bottom: 34, left: 0 }, keyboard: 0 },
});

// A column as tall as the view: the messages scroll, the message box stays at the bottom.
const page = document.createElement('div');
page.style.cssText = 'position: fixed; inset: 0; display: flex; flex-direction: column;';
const list = document.createElement('div');
list.style.cssText = 'flex: 1; min-height: 0; overflow: auto; padding: 12px;';
const form = document.createElement('form');
form.style.cssText = 'display: flex; gap: 8px; padding: 8px 12px; border-top: 1px solid #8886;';
const input = document.createElement('input');
input.placeholder = 'Message';
input.style.flex = '1';
const button = document.createElement('button');
button.textContent = 'Send';
form.append(input, button);
page.append(list, form);
document.body.append(page);

form.onsubmit = (event) => {
	event.preventDefault();
	if (input.value) world.send(input.value);
	input.value = '';
};

world.subscribe((node) => {
	const { insets, keyboard } = node.webapp;
	// Below the box: the home bar, or the keyboard when it is open (it covers the home bar).
	const bottom = Math.max(insets.bottom, keyboard);
	form.style.paddingBottom = `${8 + bottom}px`;
	form.style.paddingLeft = `${12 + insets.left}px`;
	form.style.paddingRight = `${12 + insets.right}px`;

	const note = document.createElement('p');
	note.textContent = `Kept free below the box: ${bottom} px`;
	const lines = node.messages.map((message) => {
		const line = document.createElement('p');
		line.textContent = `${message.from}: ${message.text}`;
		return line;
	});
	list.replaceChildren(note, ...lines);
});
Live, on a fake world
Open

L'inset serve solo all'elemento che tocca il bordo. Come nell'esempio (dove il padding va sul modulo e non sulla pagina), tieni lontani dal bordo testo e pulsanti e lascia arrivare lo sfondo fino al bordo dello schermo.

Tieni la casella dei messaggi sopra la tastiera ​

Quando la persona tocca un campo di testo su un telefono, la tastiera a schermo sale sopra la parte bassa dello schermo. La tastiera copre la tua vista senza ridimensionarla. Ne nasconde la parte bassa e spesso anche il campo di testo che sta proprio lì.

world.webapp.keyboard è l'altezza in pixel della tastiera sopra la tua vista (0 con la tastiera chiusa e sempre 0 su un desktop). Mentre la tastiera è aperta aggiungi questa altezza al padding in basso della tua vista. La tastiera copre anche la barra home e quindi il padding è il maggiore dei due valori invece della loro somma:

js
const bottom = Math.max(world.webapp.insets.bottom, world.webapp.keyboard);
form.style.paddingBottom = `${8 + bottom}px`;

L'esempio delle aree sicure qui sopra applica già questo padding. All'apertura della tastiera la webapp invia il nuovo valore di keyboard, il listener di subscribe gira e il padding più grande porta la casella sopra la tastiera.

TIP

Dopo il cambio del padding fai scorrere fino alla fine una lista lunga sopra la casella in modo che il messaggio più recente resti visibile (Scorri fino al messaggio più recente e Tieni la casella dei messaggi sopra la tastiera).

Segui ogni cambiamento ​

Nessuno di questi valori è fisso. Quando la persona passa la webapp al tema scuro, ne cambia la lingua, gira il telefono di lato o apre la tastiera, la webapp invia i nuovi valori senza ricaricare la tua vista. Il prossimo snapshot che riceve il tuo listener di subscribe ha il nuovo webapp. Un codice che legge node.webapp dentro il listener segue ogni cambiamento senza lavoro in più.

js
world.subscribe((node) => {
  applyTheme(node.webapp.theme);
  applyLanguage(node.webapp.language);
  layOut(node.webapp.insets, node.webapp.keyboard);
  drawTheWorld(node);
});

In React l'hook useWorld fa il re-render del tuo componente a ogni cambiamento del mondo e quindi anche a ogni cambiamento di webapp. Leggi world.webapp durante il render. Come nel primo esempio, metti quello che React non disegna (l'attributo lang, color-scheme, i colori del body) in un useEffect che dipende dai valori che usa.

Attenzione

Non leggere world.webapp una volta sola all'inizio per tenerlo in una variabile. Il world restituito da connectToHost è il mondo in quel momento e i suoi campi non cambiano mai. Leggi quello più recente in subscribe o con world.get().

Simula l'aspetto mentre sviluppi ​

Un mondo finto non ha una webapp intorno e il kit costruisce world.webapp dalla tua pagina:

  • theme segue lo schema di colori del tuo browser
  • language è la lingua del tuo browser (navigator.language, per esempio 'en-US')
  • insets e keyboard valgono 0
  • allowed elenca tutte le funzioni.

Il kit segue anche i cambiamenti di queste impostazioni del browser. Quando passi il computer alla modalità scura la tua vista riceve 'dark' senza ricaricarsi. Per confrontare i due temi cambia lo schema di colori negli strumenti per sviluppatori del browser (in Chrome con l'opzione "Emulate CSS media feature prefers-color-scheme" del pannello Rendering).

Un caso preciso come un telefono con la barra home e la tastiera aperta si simula passando a connectToHost un'opzione webapp accanto a fake:

js
const world = await connectToHost({
  fake: { world: arena },
  webapp: {
    theme: 'dark',
    language: 'it',
    insets: { top: 0, right: 0, bottom: 34, left: 0 },
    keyboard: 300,
  },
});

In React useWorld accetta la stessa opzione (useWorld({ fake: { world: arena }, webapp: { theme: 'dark' } })).

Ogni campo che passi sostituisce il valore letto dal tuo browser e i campi che non passi continuano a seguire il browser. insets viene sostituito come oggetto intero e richiede tutti e quattro i lati. I campi che passi restano fissi per tutta la vita del mondo finto. Per vedere la vista con la tastiera aperta e poi chiusa caricala due volte con due valori di keyboard.

Dentro la webapp questi valori vengono dalla webapp stessa e connectToHost ignora l'opzione webapp quando manca fake.

Prossimi passi ​

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