Skip to content

SafeArea ​

Su un telefono il notch e gli angoli arrotondati coprono la parte alta dello schermo. In basso la vista è coperta dalla barra home e dalla tastiera sullo schermo mentre la persona scrive. SafeArea aggiunge al suo riquadro un padding pari alla parte coperta di ogni bordo in modo che i tuoi pulsanti e la tua casella dei messaggi restino visibili. Avvolgi nel componente tutta la vista o solo la parte che tocca i bordi dello schermo.

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

// The component: copy this part.

/**
 * SafeArea: keeps its content clear of what covers the screen. On a phone,
 * the notch, the rounded corners and the home bar cover the edges, and the
 * on-screen keyboard covers the bottom while the person types. The webapp
 * says how much is covered, in pixels. SafeArea leaves that much room on each side.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {number} [props.padding=0] - More room on every side, in pixels, on top of the safe areas.
 * @param {object} [props.style] - More style for the box, e.g. `{ minHeight: '100vh' }`.
 * @param {React.ReactNode} props.children - What to keep clear.
 */
export function SafeArea({ world, padding = 0, style, children }) {
	// The safe areas, on the sides where the view touches the edge of the screen (0 on a desktop).
	const { insets, keyboard } = world.webapp;
	// The bottom gets the larger of the keyboard and the home bar, because an open keyboard covers the home bar too.
	const bottom = Math.max(insets.bottom, keyboard);
	return (
		<div style={{
			boxSizing: 'border-box',
			paddingTop: padding + insets.top,
			paddingRight: padding + insets.right,
			paddingBottom: padding + bottom,
			paddingLeft: padding + insets.left,
			transition: 'padding-bottom 150ms ease-out',
			...style,
		}}>
			{children}
		</div>
	);
}

// Using it, on a fake world.

// A fake world to build with: no account, no network.
const harbour = { name: 'Harbour', now: { text: 'Three boats in, one out.' } };

export default function App() {
	// While building: the fake world, in a webapp that pretends to be a phone with a notch
	// and a home bar. In the webapp: useWorld()
	const { world, error } = useWorld({
		fake: { world: harbour },
		webapp: { insets: { top: 44, right: 0, bottom: 34, left: 0 }, keyboard: 0 },
	});

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	const { insets, keyboard } = world.webapp;
	return (
		// The tinted band is the room that SafeArea leaves. Your view is the plain box inside.
		<SafeArea world={world} style={{ maxWidth: 360, borderRadius: 14, background: 'rgba(240, 165, 78, 0.3)' }}>
			<div style={{ padding: 12, background: 'Canvas', display: 'grid', gap: 6 }}>
				<strong>{world.name}</strong>
				<span>{world.now?.text}</span>
				<span style={{ fontSize: 13, opacity: 0.75 }}>
					Safe areas: top {insets.top}px, right {insets.right}px, bottom {insets.bottom}px, left {insets.left}px
				</span>
				<span style={{ fontSize: 13, opacity: 0.75 }}>Keyboard: {keyboard}px</span>
			</div>
		</SafeArea>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/**
 * Keeps the content of `container` clear of what covers the screen. On a
 * phone, the notch, the rounded corners and the home bar cover the edges,
 * and the on-screen keyboard covers the bottom while the person types. The
 * webapp says how much is covered, in pixels. This function leaves that much
 * room on each side of `container` and changes it whenever the webapp says so.
 * @param {HTMLElement} container - The element to keep clear (often your whole view).
 * @param {object} world - The world, from connectToHost.
 * @param {{padding?: number}} [options] - More room on every side, in pixels, on top of the safe areas.
 * @returns {() => void} Stops following the world and gives `container` its padding back.
 */
export function safeArea(container, world, { padding = 0 } = {}) {
	const before = container.style.padding;
	container.style.boxSizing = 'border-box';
	container.style.transition = 'padding-bottom 150ms ease-out';

	// Called at once, then after every change of the world (the screen is part of it).
	const stop = world.subscribe((node) => {
		// The safe areas, on the sides where the view touches the edge of the screen (0 on a desktop).
		const { insets, keyboard } = node.webapp;
		// The bottom gets the larger of the keyboard and the home bar, because an open keyboard covers the home bar too.
		const bottom = Math.max(insets.bottom, keyboard);
		container.style.padding = `${padding + insets.top}px ${padding + insets.right}px ${padding + bottom}px ${padding + insets.left}px`;
	});

	return () => {
		stop();
		container.style.padding = before;
	};
}

// Using it, on a fake world.

// A fake world to build with: no account, no network.
const harbour = { name: 'Harbour', now: { text: 'Three boats in, one out.' } };

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

// The tinted band is the room that safeArea leaves. Your view is the plain box inside.
const view = document.createElement('div');
Object.assign(view.style, { maxWidth: '360px', borderRadius: '14px', background: 'rgba(240, 165, 78, 0.3)' });
const inside = document.createElement('div');
Object.assign(inside.style, { padding: '12px', background: 'Canvas', display: 'grid', gap: '6px' });
const name = document.createElement('strong');
const now = document.createElement('span');
const sides = document.createElement('span');
const keyboard = document.createElement('span');
for (const small of [sides, keyboard]) Object.assign(small.style, { fontSize: '13px', opacity: '0.75' });
inside.append(name, now, sides, keyboard);
view.append(inside);
document.body.append(view);

safeArea(view, world);
world.subscribe((node) => {
	const { insets } = node.webapp;
	name.textContent = node.name;
	now.textContent = node.now?.text ?? '';
	sides.textContent = `Safe areas: top ${insets.top}px, right ${insets.right}px, bottom ${insets.bottom}px, left ${insets.left}px`;
	keyboard.textContent = `Keyboard: ${node.webapp.keyboard}px`;
});
Live, on a fake world
Open

La webapp finta dell'esempio ha un notch di 44 pixel in alto e una barra home di 34 pixel in basso. Le fasce colorate sono il padding che aggiunge SafeArea.

La webapp indica in pixel le dimensioni coperte in due campi di world.webapp:

  • insets contiene top, right, bottom e left per i lati in cui la vista tocca il bordo dello schermo
  • keyboard è l'altezza della tastiera sopra la vista (0 quando è chiusa e sempre 0 su desktop).

Entrambi i campi arrivano a subscribe come qualsiasi altro cambiamento del mondo. Il padding in basso segue la tastiera con una transizione di 150 ms. In basso il componente usa il maggiore fra insets.bottom e keyboard (una tastiera aperta copre anche la barra home) invece della loro somma (L'aspetto della webapp e lo schermo del telefono).

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo, da useWorld.
padding0Un padding aggiuntivo in pixel che ogni lato somma alla sua area sicura.
stylenessunoUno stile aggiuntivo per il riquadro, per esempio { minHeight: '100vh' } o una colonna flex.
childrenIl contenuto da tenere libero.

Parametri ​

safeArea(container, world, options) si iscrive al mondo e a ogni cambiamento ricalcola il padding di container.

ParametroChe cos'è
containerL'elemento da tenere libero (spesso tutta la vista).
worldIl mondo, da connectToHost.
options.paddingUn padding aggiuntivo in pixel su ogni lato. Predefinito 0.

Restituisce una funzione che annulla l'iscrizione al mondo e ridà a container il padding che aveva prima.

Modificalo ​

  • Una chat che riempie il telefono: fai del riquadro una colonna alta quanto la pagina (height: '100vh', display: 'flex' e flexDirection: 'column' nel suo style) con la MessageList che occupa lo spazio libero (flex: 1) e la MessageBox in basso. Quando la tastiera si apre, la lista si accorcia e la casella resta subito sopra la tastiera.
  • Solo in basso: quando la tua vista ha una sua intestazione, tieni paddingBottom e togli gli altri tre lati.
  • Provare una tastiera durante lo sviluppo: passa webapp: { keyboard: 300 } a connectToHost insieme al tuo mondo finto.

Vedi anche ​

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