Skip to content

FollowTheme ​

La tua vista sta in un iframe dentro la webapp sotto la sua barra in alto. Con il tema scuro della webapp una vista bianca risalta come un blocco luminoso in una pagina scura. FollowTheme dà al suo contenuto i colori di sfondo e di testo del tema attuale della webapp (chiaro o scuro) e li cambia appena la persona cambia tema. Avvolgi in questo componente tutta la tua vista.

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

// The component: copy this part.

/** The colours for each theme of the webapp: its own background and text. */
const THEME_COLORS = {
	light: { background: '#F1F0EF', text: '#141312' },
	dark: { background: '#0D0D0D', text: '#F7F6F5' },
};

/**
 * FollowTheme: draws its content in the theme of the webapp, light or dark, and
 * switches when the person switches the theme of the webapp. The fields, buttons
 * and scrollbars that the browser draws inside it follow too.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {{light: {background: string, text: string}, dark: {background: string, text: string}}} [props.colors] - Your colours for each theme.
 * @param {object} [props.style] - More style for the box, for example `{ minHeight: '100vh' }` to fill the view.
 * @param {React.ReactNode} props.children - What to draw in the theme.
 */
export function FollowTheme({ world, colors = THEME_COLORS, style, children }) {
	// 'light' or 'dark'. The webapp says which, and says it again when it changes.
	const theme = world.webapp.theme;
	const look = colors[theme] ?? colors.light;
	return (
		<div style={{ colorScheme: theme, background: look.background, color: look.text, ...style }}>
			{children}
		</div>
	);
}

// Using it, on a fake world.

// A fake world to build with: no account, no network.
const studio = { name: 'Studio' };

export default function App() {
	// While building: the fake world, in a webapp that pretends to be dark. In the webapp: useWorld()
	// (Leave out `webapp`, and the fake webapp follows the colour scheme of your page.)
	const { world, error } = useWorld({ fake: { world: studio }, webapp: { theme: 'dark' } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<FollowTheme world={world} style={{ padding: 16, borderRadius: 14 }}>
			<h2 style={{ marginTop: 0 }}>{world.name}</h2>
			<p>The webapp's theme: {world.webapp.theme}</p>
			<div style={{ display: 'flex', gap: 8 }}>
				<input placeholder="A field of the browser" />
				<button type="button">A button</button>
			</div>
		</FollowTheme>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/** The colours for each theme of the webapp: its own background and text. */
const THEME_COLORS = {
	light: { background: '#F1F0EF', text: '#141312' },
	dark: { background: '#0D0D0D', text: '#F7F6F5' },
};

/**
 * Draws `container` in the theme of the webapp, light or dark, and switches when
 * the person switches the theme of the webapp. The fields, buttons and scrollbars
 * that the browser draws inside it follow too. Pass `document.body` for the whole view.
 * @param {HTMLElement} container - The element to colour.
 * @param {object} world - The world, from connectToHost.
 * @param {{colors?: object}} [options] - Your colours for each theme: `{ light: { background, text }, dark: {...} }`.
 * @returns {() => void} Stops following the world and gives `container` its colours back.
 */
export function followTheme(container, world, { colors = THEME_COLORS } = {}) {
	const before = { colorScheme: container.style.colorScheme, background: container.style.background, color: container.style.color };

	// Called at once, then after every change of the world (the theme is part of it).
	const stop = world.subscribe((node) => {
		// 'light' or 'dark'. The webapp says which, and says it again when it changes.
		const theme = node.webapp.theme;
		const look = colors[theme] ?? colors.light;
		container.style.colorScheme = theme;
		container.style.background = look.background;
		container.style.color = look.text;
	});

	return () => {
		stop();
		Object.assign(container.style, before);
	};
}

// Using it, on a fake world.

// A fake world to build with: no account, no network.
const studio = { name: 'Studio' };

// While building: the fake world, in a webapp that pretends to be dark. In the webapp: const world = await connectToHost();
// (Leave out `webapp`, and the fake webapp follows the colour scheme of your page.)
const world = await connectToHost({ fake: { world: studio }, webapp: { theme: 'dark' } });

const box = document.createElement('div');
box.style.padding = '16px';
box.style.borderRadius = '14px';
const title = document.createElement('h2');
title.style.marginTop = '0';
const words = document.createElement('p');
const row = document.createElement('div');
Object.assign(row.style, { display: 'flex', gap: '8px' });
const field = document.createElement('input');
field.placeholder = 'A field of the browser';
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'A button';
row.append(field, button);
box.append(title, words, row);
document.body.append(box);

followTheme(box, world);
world.subscribe((node) => {
	title.textContent = node.name;
	words.textContent = `The webapp's theme: ${node.webapp.theme}`;
});
Live, on a fake world
Open

L'esempio passa a connectToHost (o a useWorld) webapp: { theme: 'dark' } insieme all'opzione fake. Il riquadro è quindi scuro qualunque sia lo schema di colori della tua pagina. Senza webapp il mondo finto usa lo schema di colori della tua pagina. Dentro la webapp vera il tema è quello scelto dalla persona.

Il tema è world.webapp.theme ('light' o 'dark'). Un cambio di tema conta come cambiamento del mondo. La callback di subscribe viene chiamata di nuovo e il componente vi applica i nuovi colori. Il componente scrive anche la proprietà CSS color-scheme del contenitore in modo che il browser disegni i suoi input, pulsanti e barre di scorrimento nello stesso tema (L'aspetto della webapp e lo schermo del telefono).

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo restituito da useWorld.
colorsquelli della webappI tuoi colori per ogni tema come { light: { background, text }, dark: { background, text } }.
stylenessunoStili in più per il riquadro (per esempio { minHeight: '100vh' } per riempire la vista).
childrenIl contenuto da disegnare nel tema (di solito tutta la tua vista).

Parametri ​

followTheme(container, world, options) colora container e lo colora di nuovo ogni volta che il tema della webapp cambia. Passa document.body per colorare tutta la vista.

ParametroChe cos'è
containerL'elemento da colorare.
worldIl mondo con cui si risolve connectToHost.
options.colorsI tuoi colori per ogni tema nella stessa forma della prop.

Restituisce una funzione che annulla l'iscrizione al mondo e ripristina i valori inline di color-scheme, background e color che container aveva prima.

Modificalo ​

  • Colora tutta la vista. In React aggiungi minHeight: '100vh' a style e togli il margine della pagina (body { margin: 0 }). La versione in JavaScript semplice prende document.body come container.
  • Usa i colori del tuo brand attraverso colors con un contrasto alto fra testo e sfondo in tutti e due i temi.
  • Aggiungi altri colori come accent, border o muted a ogni tema in colors ed esponili al resto della tua vista come variabili CSS ('--accent': look.accent nello stile).
  • Segui anche la lingua della webapp leggendo world.webapp.language (Usa la lingua della webapp).

Vedi anche ​

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