The look of the webapp and the phone screen
Your view sits inside the UNaIVERSE webapp under its top bar. To look like part of the webapp it uses the theme and the language of the webapp and keeps clear of what covers the screen of a phone (the notch, the home bar and the keyboard). The webapp passes these values in world.webapp and passes them again whenever one changes. While you build, a fake world simulates each of them.
What the webapp tells your view
Every snapshot of the world has a webapp field:
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
// }| Field | What it is |
|---|---|
theme | The theme of the webapp ('light' or 'dark'). Render your view to match. |
language | The language of the webapp (for example 'it' or 'en'). |
insets | The safe areas of the screen (notch, rounded corners, home bar) in pixels on the sides where your view touches the edge of the screen. |
keyboard | The height in pixels of the on-screen keyboard over your view. It is 0 when the keyboard is closed and always 0 on a desktop. |
allowed | The browser features (the camera, the microphone, ...) allowed to your view by the person (The camera and the rest of the browser). |
These values come from the settings of the person in the webapp and not from the settings of the device. A person can use the dark theme of UNaIVERSE on a phone in light mode or read UNaIVERSE in Italian on a computer in English. Your view therefore reads world.webapp instead of the browser settings.
Draw both themes
The view below follows the theme and the language of the webapp. The example makes the fake webapp dark and Italian with the webapp option of connectToHost (below).
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>
</>
);
}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}`;
});Three lines of the example apply the theme and the language:
document.body.style.backgroundandcolorpaint the page in the colours of the theme. Paint a background of your own instead of relying on the background of the webapp behind the iframe.document.documentElement.style.colorScheme = themetells the browser the theme of the page. The controls drawn by the browser (text fields, checkboxes, scrollbars, theCanvasandCanvasTextsystem colours) follow it too. Without this line a dark view can show white text fields.document.documentElement.lang = languagegives the page the language that screen readers, hyphenation and spell checking use.
A real project keeps its colours in a stylesheet instead of JavaScript. Write one attribute on the root element at every change and let CSS select the colours:
world.subscribe((node) => {
document.documentElement.dataset.theme = node.webapp.theme;
});: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);
}Pitfall
Do not choose your theme with the CSS media query prefers-color-scheme (or with matchMedia('(prefers-color-scheme: dark)')). The query returns the theme of the device. With another theme chosen in the webapp your view would be light under a dark top bar. Read world.webapp.theme instead.
A grey that reads well on white can be invisible on black. Check the contrast of your colours in both themes against the ratios in Accessibility.
Speak the language of the webapp
world.webapp.language is the code of the language in which the person reads UNaIVERSE (usually a short code like 'it' or 'en'). The code can also carry a region ('en-GB'). Compare only its first part and fall back to a language your view supports:
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 formats dates, numbers and lists in that language:
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'You translate the text of your view. The text of the world (its name, its messages, now.text), on the other hand, arrives as the world wrote it and the kit never translates it.
TIP
With a translation library (i18next, FormatJS, ...), switch the language of the library inside subscribe whenever webapp.language changes.
Keep clear of the notch and the home bar
On a phone some parts of the screen are covered or curved (the notch or camera hole, the rounded corners and the home bar at the bottom of an iPhone). A button drawn there is hard to see and hard to press.
A top-level web page uses CSS env(safe-area-inset-bottom). Inside an iframe the value is always 0 because the browser gives the safe areas only to the top-level page of the webapp. The webapp measures them and passes them to your view in pixels as world.webapp.insets. Only the sides where your view touches the edge of the screen get a value:
topis usually0because the top bar of the webapp sits above your view and already keeps clear of the notch.bottomis the home bar of a phone held upright (about 34 pixels on an iPhone).leftandrightare not0when the phone is turned sideways with the notch on one side.- On a desktop all four are
0.
Add each inset to the padding of the element that touches that edge. In the example the fake webapp simulates a phone with a home bar of 34 pixels and the message box stays above it.
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>
);
}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);
});Only the element that touches the edge needs the inset. As in the example (where the padding goes on the form and not on the page), keep text and buttons away from the edge and let the background run to the edge of the screen.
Keep the message box above the keyboard
When the person touches a text field on a phone, the on-screen keyboard slides up over the bottom of the screen. The keyboard covers your view without resizing it. It hides the bottom of the view and often the text field that sits there.
world.webapp.keyboard is the height in pixels of the keyboard over your view (0 with the keyboard closed and always 0 on a desktop). Pad the bottom of your view by this height while the keyboard is open. Since the keyboard also covers the home bar, the padding is the larger of the two values instead of their sum:
const bottom = Math.max(world.webapp.insets.bottom, world.webapp.keyboard);
form.style.paddingBottom = `${8 + bottom}px`;The safe-areas example above already applies this padding. When the keyboard opens the webapp sends the new keyboard value, the listener of subscribe runs and the larger padding moves the box above the keyboard.
TIP
After the padding changes, scroll a long list above the box to its end to keep the newest message in sight (Scroll to the newest message and Keep the message box above the keyboard).
Follow every change
None of these values is fixed. When the person switches the webapp to dark, changes its language, turns the phone sideways or opens the keyboard, the webapp sends the new values without reloading your view. The next snapshot that your subscribe listener receives has the new webapp. Code that reads node.webapp inside the listener follows every change with no extra work.
world.subscribe((node) => {
applyTheme(node.webapp.theme);
applyLanguage(node.webapp.language);
layOut(node.webapp.insets, node.webapp.keyboard);
drawTheWorld(node);
});In React the useWorld hook re-renders your component at every change including those of webapp. Read world.webapp during rendering. Like the first example, put what React does not render (the lang attribute, color-scheme, the colours of the body) in a useEffect that depends on the values it uses.
Pitfall
Do not read world.webapp once at the start and keep it in a variable. The world returned by connectToHost is the world at that moment and its fields never change. Read the newest one in subscribe or with world.get().
Pretend the look while you build
A fake world has no webapp around it and the kit builds world.webapp from your own page:
themefollows the colour scheme of your browserlanguageis the language of your browser (navigator.language, for example'en-US')insetsandkeyboardare0allowedlists every feature.
The kit also follows the changes of these browser settings. When you switch your computer to dark mode your view receives 'dark' with no reload. To compare both themes, switch the colour scheme in the developer tools of the browser (in Chrome the option "Emulate CSS media feature prefers-color-scheme" of the Rendering panel).
To simulate a precise case such as a phone with a home bar and the keyboard open, pass connectToHost a webapp option next to fake:
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 takes the same option (useWorld({ fake: { world: arena }, webapp: { theme: 'dark' } })).
Each field you pass replaces the value read from your browser and the fields you leave out keep following the browser. insets is replaced as a whole object and needs all four sides. The fields you pass stay fixed for the whole life of the fake world. To see the view with the keyboard open and then closed, load it twice with two values of keyboard.
Inside the webapp these values come from the webapp itself and connectToHost ignores the webapp option when there is no fake.
Next steps
- Layout and style inside the webapp: the place of your view in the webapp and layouts for phone and desktop.
- Links and the back button: the address in the webapp and the back button of a phone.
- The camera and the rest of the browser: what
webapp.allowedis for. - Recipes: Follow the theme of the webapp, Use the language of the webapp.