Un layout per telefono e computer
La webapp mostra la tua vista in un iframe largo su un computer, stretto su un telefono e diverso ancora quando il telefono ruota. Dai alla tua vista due layout (due colonne quando c'è spazio e una colonna sopra l'altra quando non c'è) e scegli fra i due in base alla larghezza. Per vederli entrambi premi Open sopra l'esempio e stringi la finestra sotto i 640 pixel.
jsx
import { useEffect, useState } from 'react';
import { useWorld } from './useWorld.js';
// While you build, the world is a fake game with two players.
const arena = {
name: 'Arena',
now: { text: 'Round 2: your move' },
members: [{ name: 'Ada', role: 'player' }, { name: 'Bob', role: 'player' }],
};
// Matches when the view is wide enough for two columns. In the webapp, the width of the view is the width of its frame.
const wide = window.matchMedia('(min-width: 640px)');
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: arena } });
const [isWide, setIsWide] = useState(wide.matches);
// Draw again when the view gets wider or narrower (a phone turned, a window resized).
useEffect(() => {
const onChange = () => setIsWide(wide.matches);
wide.addEventListener('change', onChange);
return () => wide.removeEventListener('change', onChange);
}, []);
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// The game, with the players beside it (desktop) or under it (phone).
return (
<div style={{ display: 'flex', gap: 16, flexDirection: isWide ? 'row' : 'column' }}>
<main style={{ flex: 1 }}>
<h2>{world.name}</h2>
<p>{world.now?.text}</p>
<p>{isWide ? 'Desktop layout' : 'Phone layout'}</p>
</main>
<aside style={{ width: isWide ? 200 : 'auto', padding: '0 12px', background: 'rgba(127, 127, 127, 0.15)' }}>
<h3>Players</h3>
<ul>
{(world.members ?? []).map((member) => <li key={member.id}>{member.name}</li>)}
</ul>
</aside>
</div>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// While you build, the world is a fake game with two players.
const arena = {
name: 'Arena',
now: { text: 'Round 2: your move' },
members: [{ name: 'Ada', role: 'player' }, { name: 'Bob', role: 'player' }],
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
// The game, with the players beside it (desktop) or under it (phone).
const page = document.createElement('div');
page.style.display = 'flex';
page.style.gap = '16px';
const game = document.createElement('main');
game.style.flex = '1';
const title = document.createElement('h2');
const now = document.createElement('p');
const layoutName = document.createElement('p');
game.append(title, now, layoutName);
const players = document.createElement('aside');
players.style.padding = '0 12px';
players.style.background = 'rgba(127, 127, 127, 0.15)';
const heading = document.createElement('h3');
heading.textContent = 'Players';
const list = document.createElement('ul');
players.append(heading, list);
page.append(game, players);
document.body.append(page);
// Matches when the view is wide enough for two columns. In the webapp, the width of the view is the width of its frame.
const wide = window.matchMedia('(min-width: 640px)');
function layout() {
page.style.flexDirection = wide.matches ? 'row' : 'column';
players.style.width = wide.matches ? '200px' : 'auto';
layoutName.textContent = wide.matches ? 'Desktop layout' : 'Phone layout';
}
wide.addEventListener('change', layout);
layout();
// Called at once, then after every change of the world.
world.subscribe((node) => {
title.textContent = node.name;
now.textContent = node.now?.text ?? '';
list.replaceChildren(...(node.members ?? []).map((member) => {
const item = document.createElement('li');
item.textContent = member.name;
return item;
}));
});Come funziona
window.matchMedia('(min-width: 640px)')controlla la larghezza del tuo documento. Dentro la webapp la larghezza controllata è lo spazio che la tua vista ha davvero nell'iframe e non la larghezza dello schermo.- Gli stili inline non possono contenere una media query come fa un foglio di stile. Il codice legge allora
wide.matches, scrive gli stili e li riscrive a ogni eventochangedella query (una finestra ridimensionata o un telefono che ruota). - Con un foglio di stile una regola CSS
@media (min-width: 640px) { ... }cambia il layout senza JavaScript. - Un iframe può avere qualsiasi larghezza. Metti il breakpoint dove il tuo contenuto smette di starci invece che alla misura di un telefono noto.