chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.4.0 Latest 5 packages
0
0
// Whether the renderer draws on a server as a browser hydrates it: each
// tree in trees/ (Grain's screens, made by `just ssr-data`), drawn by the
// renderer's `Tree` compiled for the server (server.ts) with Svelte's
// `render` in Node, with no browser's globals (no window, document,
// navigator or storage: one touched as the code loads or draws throws),
// given `now` and an `hrefOf` as an app drawing pages would; then
// hydrated, compiled for the browser in development (client.ts), with
// Svelte's `hydrate` in a document of happy-dom's, with the same props.
//
// cd web && npm run ssr `just check` runs it, and CI's web job
//
// It fails where a tree's drawing throws, draws nothing, draws otherwise a
// second time, has no link (`<a href>`) to a call it opens, or puts a link
// or button inside another; where its hero (`ui.hero`, the first picture
// drawn large) is not loaded at once and first (`loading="eager"`,
// `fetchpriority="high"`); where a picture first on the screen by its
// place (the tree's top, a list's first item, the pane shown: there an
// Image, a gallery's first picture) is not loaded at once, at low
// priority beside a hero (with none of its own in a tree without one),
// or another is not lazy; Home (a strip of
// stories over a feed, its hero the first card's first photo, as the
// server names it past the strip) fails where its first card's face and
// its first story's are not those loaded at once; where a
// carousel draws a picture past its second, or the gallery's photos lack
// their sizes (`srcset`, with `sizes` the `Tree`'s area, `auto` first for
// one drawn lazily, its hero's as `ui.heroSrcset`; a cover's its tile's),
// or `heroPreload` would
// preload its hero otherwise than it is drawn; or where hydrating it warns
// (Svelte's
// hydration_mismatch and the rest), throws, or changes what the server
// drew (a text, an attribute). A tree with a `Bar` over it (the profile's,
// a Share button in it) is drawn as an app with a bar of its own draws it
// too, `bar: 'apart'` and `bar: 'only'`, and fails where the tree still
// draws its Bar or the bar draws anything but its buttons; each hydrated
// as the rest. A clamped text the server cut (a Text's or RichText's
// `shownRuns` or `shownBlocks`) fails where the server does not draw it
// cut with its "more" button after it, where hydrated it draws more than
// the cut, and where its button, clicked, does not draw it whole. A
// screen opened at its form (an empty story screen's Add to your story,
// `open`) fails where the server draws the form open, hydrating it
// changes it, or once hydrated it does not open by itself. Stories fail
// where the server draws a picture but the one showing, or draws it
// without its sizes, or hydrated they do not load the next two ahead with
// theirs (a page drawn ahead in a pager, the one it starts from alone), or
// their bar fills before its picture loads, or
// not once it loads or fails; a carousel near the screen, where it does
// not load its next photo ahead at its width. A feed's card fails where a
// tap on it does not open it, or a tap on its carousel, a touch that moved
// or one that came as its page scrolled does, or a mouse's click does not.
// A form opened from a menu's row fails where an @ typed in its text does
// not ask for accounts and list them in a popover, or one picked by a
// press does not take the @'s place or closes the menu and its form.
// A profile's ⋯ menu in its Bar, with the build's stylesheet, fails where
// a row (a Link, an Action however deep in Stacks, a Compose, a Toggle) is
// not the whole width with its words from the start at the inset the
// others have, a Stack in it puts a gap between rows, an icon's words are
// hidden, Block is not in the danger colour, or Report is marked as the
// Bar's own form.
// A place's header fails where a Stack with gap none is drawn otherwise,
// or once mounted its Map draws a pin with pins false, or none without.
// Profile's panes, at a phone's width with the build's stylesheet, fail
// where two covers picked draw a bar other than Cancel, 2 selected and
// Delete 2, or one not sticky, or in a box that scrolls or hides it (the
// strip of panes, which would hold it to its own bottom, off the screen),
// or where Cancel leaves the strip not scrolling again. The feed fails
// where a page's translation may touch its ALT badge or a byline's
// @handle (no `translate="no"` on them or around them), or may not its
// Spanish caption; or where it may touch a link that shows its address,
// or the line break and the space beside it in a caption, or may not
// that caption's words.
// Both builds go to a directory of their own in the system's temporary
// directory, taken away after.
import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { build, defaultClientConditions, defaultServerConditions } from 'vite';
const here = dirname(fileURLToPath(import.meta.url));
const web = resolve(here, '../..');
const trees = join(here, 'trees');
const out = mkdtempSync(join(tmpdir(), 'hud-ssr-'));
const say = (line) => console.log(`==> ${line}`);
const problems = [];
// The server in one time zone, the browser in another a day away: a date written in either's own, before the page is mounted, differs.
process.env.TZ = 'America/Los_Angeles';
/** The moment the trees are drawn at, the same on the server and in the browser. */
const NOW = Date.parse('2026-11-18T12:00:00.000Z');
/** Where an app drawing pages would put each call: a path of its own. */
const hrefOf = (call) => `/open/${call.name}?${new URLSearchParams({ args: JSON.stringify(call.args) })}`;
/** How wide the app draws the tree's main area, as Grain's does: its column, up to 1200 pixels right of its 245-pixel sidebar above a 600-pixel screen, the screen below. */
const SLOT = '(min-width: 601px) min(1200px, 100vw - 245px), 100vw';
/** A picture's sizes in a tile of a grid three across at most, none under 6rem (`sm`), 0.75rem apart, in that slot. */
const TILE =
'(min-width: 601px) min(min(1200px, 100vw - 245px), max(2 * 6rem + 0.75rem, (min(1200px, 100vw - 245px) - 2 * 0.75rem) / 3)), min(100vw, max(2 * 6rem + 0.75rem, (100vw - 2 * 0.75rem) / 3))';
/** A cover's sizes in a tile of tiles three across at most, none under 6rem, 0.125rem apart (../src/Covers.svelte), in that slot. */
const COVER =
'(min-width: 601px) min(min(1200px, 100vw - 245px), max(2 * 6rem + 0.125rem, (min(1200px, 100vw - 245px) - 2 * 0.125rem) / 3)), min(100vw, max(2 * 6rem + 0.125rem, (100vw - 2 * 0.125rem) / 3))';
/** Parts that lay out by their box: a Split (its aside first) in a Stack held to reading width, a Profile in it, a grid of carousels three across at most, tiles likewise, and one pane whose row a wide box draws; drawn too in boxes of a phone's, a column's and a wide screen's width. */
const photo = (n) => ({ src: { src: `https://cdn.test/p${n}.jpg`, fallback: null }, alt: '', ratio: 1, srcset: `https://cdn.test/p${n}-small.jpg 1000w, https://cdn.test/p${n}.jpg 2000w` });
const opening = (n) => ({ call: { name: 'query', args: { method: 'test.layout.get', params: { n } } } });
const LAYOUT = {
v: 1,
trusted: true,
measure: 'wide',
root: {
c: 'Stack',
p: { gap: 'md' },
k: [
{ c: 'Stack', p: { gap: 'md', measure: 'content' }, k: [{ c: 'Split', p: { side: 'start', aside: 'sm' }, k: [{ c: 'Text', p: { runs: [{ text: 'Beside' }], style: 'body' } }, { c: 'Profile', p: { name: 'Alice', handle: 'alice.test', avatar: null, banner: null } }] }] },
{ c: 'List', p: { style: 'grid', min: 'sm', columns: 3 }, items: [1, 2, 3, 4].map((n) => ({ open: opening(n), k: [{ c: 'Gallery', p: { style: 'carousel' }, items: [photo(n), photo(n + 10)] }] })) },
{ c: 'Covers', p: { style: 'tiles', min: 'sm', columns: 3 }, items: [1, 2].map((n) => ({ src: { src: `https://cdn.test/c${n}.jpg`, fallback: null }, title: `C${n}`, count: '1', stat: null, date: null, labels: [], open: opening(n), srcset: `https://cdn.test/c${n}-640.jpg 640w, https://cdn.test/c${n}.jpg 1000w` })) },
{ c: 'Panes', k: [{ c: 'Pane', p: { label: 'Galleries', icon: 'grid' }, k: [{ c: 'Text', p: { runs: [{ text: 'Alone' }], style: 'body' } }] }] }
]
}
};
/** One's own profile's panes: its galleries, which may be picked, its favorites and its stories. */
const pick = { label: 'Select', action: 'Delete', one: 'gallery', many: 'galleries', method: 'test.gallery.delete', service: 'did:web:test' };
const paneOf = (label, icon, k) => ({ c: 'Pane', p: { label, icon }, k: [{ c: 'Text', p: { runs: [{ text: `${label} here` }], style: 'body' } }, ...k] });
const PANES = {
v: 1,
trusted: true,
root: {
c: 'Panes',
k: [
paneOf('Galleries', 'grid', [{ c: 'Covers', p: { style: 'tiles', select: pick }, items: [1, 2].map((n) => ({ src: { src: `https://cdn.test/g${n}.jpg`, fallback: null }, title: `G${n}`, count: '1', stat: null, date: null, labels: [], open: opening(n), pick: { n } })) }]),
paneOf('Favorites', 'heart', []),
paneOf('Stories', 'clock', [])
]
}
};
/** Home as Grain draws it: a strip of stories over a feed of cards, each a face and a carousel of three; its hero the first card's first photo, as the server names it past the strip (crates/hud-core's `ui::hero`). */
const face = (name) => ({ src: { src: `https://cdn.test/${name}.jpg`, fallback: null }, alt: '', ratio: 1 });
const card = (n) => ({ open: opening(n), k: [{ c: 'Row', k: [{ c: 'Image', p: { ...face(`face${n}`), size: 'face' } }] }, { c: 'Gallery', p: { style: 'carousel' }, items: [photo(n), photo(n + 10), photo(n + 20)] }] });
const HOME = {
v: 1,
trusted: true,
hero: photo(1).src.src,
heroSrcset: photo(1).srcset,
root: {
c: 'Stack',
k: [
{ c: 'List', p: { style: 'strip' }, items: [1, 2].map((n) => ({ open: opening(n + 100), k: [{ c: 'Image', p: { ...face(`story${n}`), size: 'large' } }] })) },
{ c: 'List', p: { style: 'rows' }, items: [1, 2, 3].map(card) }
]
}
};
const BOXES = ['360px', '600px', '1200px'];
const props = (ui, bar = 'here', root = true) => ({
ui,
bar,
root,
now: NOW,
hrefOf,
area: SLOT,
oncall: () => {},
onreplace: () => {},
onopenlink: () => {},
onaction: async () => ({ uri: null })
});
/** Where `a` and `b` first differ, a little of each around it. */
function difference(a, b) {
let i = 0;
while (i < a.length && a[i] === b[i]) i++;
const at = Math.max(0, i - 80);
return `server: …${a.slice(at, i + 80)}…\n hydrated: …${b.slice(at, i + 80)}…`;
}
/** Text as Svelte's server writes it between tags. */
const escaped = (text) => text.replaceAll('&', '&').replaceAll('<', '<');
/** The texts of runs, or of blocks' runs, in order. */
const texts = (v) => (Array.isArray(v) ? v.flatMap(texts) : v && typeof v === 'object' ? (typeof v.text === 'string' ? [v.text] : Object.values(v).flatMap(texts)) : []);
/** Each Text and RichText in a tree the server cut: its button's words, what it shows until opened and its whole, each as its texts. */
function clamped(v, found = []) {
if (Array.isArray(v)) v.forEach((x) => clamped(x, found));
else if (v && typeof v === 'object') {
const shown = v.p?.shownRuns ?? v.p?.shownBlocks;
if ((v.c === 'Text' || v.c === 'RichText') && shown) found.push({ more: v.c === 'Text' ? 'more' : 'Show more', shown: texts(shown), whole: texts(v.p.runs ?? v.p.blocks) });
Object.values(v).forEach((x) => clamped(x, found));
}
return found;
}
/** The pictures a tree draws first on the screen by their place, and those it draws later, by src (../src/hero.ts): first are the tree's top, a list's first item and the pane shown, and in them an Image and the first picture of a Gallery (a Covers' wait, but its hero: one under a gallery is far down its page). */
function byPlace(v, first = true, found = { first: new Set(), later: new Set() }) {
const put = (src, at) => src && found[at ? 'first' : 'later'].add(src);
if (Array.isArray(v)) v.forEach((x) => byPlace(x, first, found));
else if (v && typeof v === 'object') {
if (v.c === 'Image') put(v.p?.src?.src, first);
if (v.c === 'Gallery') (v.items ?? []).forEach((item, i) => put(item.src?.src, first && i === 0));
else if (v.c === 'List') (v.items ?? []).forEach((item, i) => byPlace(item, first && i === 0, found));
else if (v.c === 'Panes') (v.k ?? []).filter((pane) => pane.c === 'Pane').forEach((pane, i) => byPlace(pane, first && i === 0, found));
else Object.entries(v).forEach(([key, x]) => key !== 'p' && byPlace(x, first, found));
}
return found;
}
try {
// Each build its own Svelte plugin: one compiles for the server, the
// other for the browser; HUD's packages as their source (vite.config.ts).
const options = () => ({ configFile: false, root: web, publicDir: false, logLevel: 'warn', resolve: { conditions: ['@hud/source', ...defaultClientConditions] }, plugins: [svelte({ compilerOptions: { runes: true } })] });
await build({
...options(),
ssr: { noExternal: true, resolve: { conditions: ['@hud/source', ...defaultServerConditions] } },
build: { ssr: join(here, 'server.ts'), outDir: join(out, 'server'), emptyOutDir: true, minify: false, rollupOptions: { output: { entryFileNames: 'server.mjs' } } }
});
// Svelte's development build, which says what does not hydrate as drawn.
process.env.NODE_ENV = 'development';
await build({
...options(),
mode: 'development',
build: { outDir: join(out, 'client'), emptyOutDir: true, minify: false, lib: { entry: join(here, 'client.ts'), formats: ['es'], fileName: 'client' } }
});
// The server's in development too, as the browser's: a component unknown to the renderer draws otherwise there (unknown.ts), the same on both.
await build({
...options(),
mode: 'development',
ssr: { noExternal: true, resolve: { conditions: ['@hud/source', ...defaultServerConditions] } },
build: { ssr: join(here, 'server.ts'), outDir: join(out, 'server-dev'), emptyOutDir: true, minify: false, rollupOptions: { output: { entryFileNames: 'server.mjs' } } }
});
// A server has no browser: Node's own navigator (and storage, where it has it) taken away too.
for (const name of ['navigator', 'localStorage', 'sessionStorage']) Reflect.deleteProperty(globalThis, name);
for (const name of ['window', 'document', 'navigator', 'localStorage']) if (typeof globalThis[name] !== 'undefined') throw new Error(`${name} is still there`);
const server = await import(pathToFileURL(join(out, 'server/server.mjs')).href);
const drawn = [];
const sources = readdirSync(trees)
.filter((f) => f.endsWith('.json'))
.sort()
.map((file) => ({ name: file.slice(0, -5), ui: JSON.parse(readFileSync(join(trees, file), 'utf8')) }));
for (const { name, ui } of [...sources, { name: 'layout', ui: LAYOUT }, { name: 'home', ui: HOME }]) {
let body;
try {
body = server.render(server.Tree, { props: props(ui) }).body;
} catch (e) {
problems.push(`${name}: drawing it threw: ${e.stack}`);
continue;
}
if (body.replace(/<!--.*?-->/gs, '').trim() === '') problems.push(`${name}: it drew nothing`);
if (server.render(server.Tree, { props: props(ui) }).body !== body) problems.push(`${name}: drawn again, it drew otherwise`);
const links = (body.match(/<a [^>]*href="\/open\//g) ?? []).length;
if (links === 0) problems.push(`${name}: no link to a call it opens`);
const open = [];
for (const [, close, tag] of body.matchAll(/<(\/?)(a|button)\b[^>]*>/g)) {
if (close) open.pop();
else {
if (open.length) problems.push(`${name}: an <${tag}> inside an <${open.at(-1)}>`);
open.push(tag);
}
}
const pictures = [...body.matchAll(/<img\b[^>]*>/g)].map(([tag]) => ({
src: tag.match(/ src="([^"]*)"/)?.[1]?.replaceAll('&', '&'),
srcset: tag.match(/ srcset="([^"]*)"/)?.[1]?.replaceAll('&', '&'),
sizes: tag.match(/ sizes="([^"]*)"/)?.[1],
first: / loading="eager"/.test(tag) && / fetchpriority="high"/.test(tag),
atOnce: / loading="eager"/.test(tag) && (ui.hero === undefined ? !/ fetchpriority=/.test(tag) : / fetchpriority="low"/.test(tag)),
lazy: / loading="lazy"/.test(tag) && !/ fetchpriority=/.test(tag)
}));
const heroes = pictures.filter((p) => ui.hero !== undefined && p.src === ui.hero);
if (ui.hero !== undefined && (heroes.length === 0 || !heroes.every((p) => p.first))) problems.push(`${name}: its hero is not loaded at once and first`);
if (heroes.some((p) => p.srcset !== ui.heroSrcset)) problems.push(`${name}: its hero is drawn with other sizes than ui.heroSrcset`);
const preload = server.heroPreload(ui, SLOT);
const drawnAs = heroes[0] && { href: heroes[0].src, imagesrcset: heroes[0].srcset, imagesizes: heroes[0].srcset && heroes[0].sizes, fetchpriority: 'high' };
if (drawnAs && JSON.stringify(preload) !== JSON.stringify(Object.fromEntries(Object.entries(drawnAs).filter(([, v]) => v !== undefined))))
problems.push(`${name}: its hero is preloaded as ${JSON.stringify(preload)}, drawn as ${JSON.stringify(drawnAs)}`);
// Past the hero, a picture first on the screen by its place loads at once, at low priority beside a hero, and the rest lazily; one drawn both first and later (an account's face on two cards) is either.
const placed = byPlace(ui.root);
for (const p of pictures.filter((p) => !heroes.includes(p))) {
const first = placed.first.has(p.src);
const later = placed.later.has(p.src);
if (first && !later && !p.atOnce) problems.push(`${name}: a picture first on the screen by its place is not loaded at once, at low priority beside a hero: ${p.src}`);
if (!first && !p.lazy) problems.push(`${name}: a picture not first on the screen by its place is not lazy: ${p.src}`);
}
if (name === 'home') {
const atOnce = pictures.filter((p) => p.atOnce).map((p) => p.src.replace('https://cdn.test/', ''));
if (atOnce.join(' ') !== 'story1.jpg face1.jpg') problems.push(`home: past its hero, it loads at once ${atOnce.join(' ') || 'nothing'}, not the first story's face and the first card's`);
if (!pictures.some((p) => p.src === photo(11).src.src && p.lazy)) problems.push("home: the first card's carousel's second photo is not drawn lazily");
}
// A picture's sizes are its slot's: a lazy one's `auto` first; a grid's tiles', the slot shared among them, a cover's its tiles'.
const slotOf = (p) => (name !== 'layout' ? SLOT : p.src.startsWith('https://cdn.test/c') ? COVER : TILE);
if (pictures.some((p) => p.srcset !== undefined && p.sizes !== (p.first || p.atOnce ? slotOf(p) : `auto, ${slotOf(p)}`).replaceAll('&', '&')))
problems.push(`${name}: a picture with sizes other than its slot's: ${pictures.find((p) => p.srcset !== undefined)?.sizes}`);
if (name === 'layout' && pictures.filter((p) => p.src.startsWith('https://cdn.test/c') && p.srcset).length !== 2) problems.push('layout: its covers are not drawn with their sizes');
if (name === 'layout') {
if (!/<div class="split[^"]*"[^>]*>(<!--[^>]*-->)*<div class="aside\b/.test(body)) problems.push('layout: its Split does not draw its aside first');
if (!/<ul class="list grid[^"]*\bcapped" style="--min: 6rem; --gap: 0.75rem; --columns: 3;"/.test(body)) problems.push('layout: its grid is not drawn capped at three, none under 6rem');
if (!/<ul class="tiles[^"]*sized[^"]*capped[^"]*" style="--min: 6rem; --columns: 3;"/.test(body)) problems.push('layout: its tiles are not drawn capped at three, none under 6rem');
if (!/<div class="stack md[^"]*\bmeasured\b/.test(body)) problems.push('layout: its Stack with measure content is not drawn held to reading width');
if (!/<div class="head[^"]*\balone\b[^"]*"[^>]*>(<!--[^>]*-->)*<div class="row\b/.test(body)) problems.push('layout: its one pane has no row for a wide box to show');
if (!/<span class="word[^"]*"[^>]*>Galleries<\/span>/.test(body)) problems.push("layout: its pane's word is not drawn beside its icon");
}
// A carousel's pictures past its second are not drawn until it is swiped near them.
const carousels = [];
const walk = (v) => (Array.isArray(v) ? v.forEach(walk) : v && typeof v === 'object' && ((v.c === 'Gallery' && v.p?.style === 'carousel' && carousels.push(v)), Object.values(v).forEach(walk)));
walk(ui.root);
const later = new Set(carousels.flatMap((c) => (c.items ?? []).slice(2).map((item) => item.src?.src)));
const early = new Set(carousels.flatMap((c) => (c.items ?? []).slice(0, 2).map((item) => item.src?.src)));
if (pictures.some((p) => later.has(p.src) && !early.has(p.src))) problems.push(`${name}: a carousel draws a picture past its second`);
if (name === 'gallery') {
const photos = carousels[0]?.items ?? [];
if (photos.length < 3 || !photos.every((item) => item.srcset)) problems.push('gallery: its photos are not three or more, each with its sizes');
if (pictures.filter((p) => p.srcset !== undefined).length !== 2) problems.push('gallery: it does not draw its shown photo and the next alone, with their sizes');
// Under its comments, Add a comment… signed in; Sign in to comment signed out where the app signs in; neither where it can't.
const as = (more) => server.render(server.Tree, { props: { ...props(ui), ...more } }).body;
if (!/<button type="button" class="field[^"]*"[^>]*>Add a comment…<\/button>/.test(as({ ontool: async () => ({}) }))) problems.push('gallery: signed in, Add a comment… is not drawn as a field');
if (!/<button type="button" class="signin[^"]*"[^>]*>Sign in to comment<\/button>/.test(as({ onsignin: () => {} }))) problems.push('gallery: signed out, Sign in to comment is not drawn');
if (/Add a comment…|Sign in to comment/.test(body)) problems.push("gallery: where the app can neither send nor sign in, it offers a comment");
}
// A clamped text the server cut is drawn cut, its button the next after it.
for (const { more, shown } of clamped(ui.root)) {
const at = body.indexOf(escaped(shown.at(-1)));
const next = at < 0 ? null : body.slice(at).match(/<button\b[^>]*>([^<]*)<\/button>/);
if (next?.[1] !== more) problems.push(`${name}: a clamped text is not drawn cut with its ${more} button after it: ${shown.at(-1)}`);
}
if (name === 'layout') for (const width of BOXES) drawn.push({ name: `layout in ${width}`, ui, body, links, bar: 'here', width });
else drawn.push({ name, ui, body, links, bar: 'here' });
}
// A screen's Bar where the app draws it, in its own bar: not in the tree, and alone in the bar.
const profile = JSON.parse(readFileSync(join(trees, 'profile.json'), 'utf8'));
const share = { c: 'Link', p: { label: 'Share profile', icon: 'share', share: 'https://grain.test/profile' } };
const barred = { ...profile, root: { c: 'Stack', k: [{ c: 'Bar', p: { title: 'Profile' }, k: [share] }, profile.root] } };
const standing = server.render(server.Tree, { props: props(barred) }).body;
const apart = server.render(server.Tree, { props: props(barred, 'apart') }).body;
const only = server.render(server.Tree, { props: props(barred, 'only') }).body;
const bars = (body) => (body.match(/class="bar here\b/g) ?? []).length;
if (bars(standing) !== 1) problems.push(`bar: drawn where it stands, the profile's Bar is drawn ${bars(standing)} times`);
if (bars(apart) !== 0 || apart.includes('Share profile')) problems.push('bar: apart, the tree still draws its Bar');
if (!/^(<!--.*?-->)*<div class="bar\b/s.test(only) || bars(only) !== 0 || !only.includes('Share profile') || only.includes('<img'))
problems.push(`bar: alone, it draws other than the Bar's buttons: ${only.slice(0, 200)}`);
if (server.barOf(barred.root)?.k?.[0] !== share) problems.push('bar: barOf does not find the Bar at the top of the tree');
drawn.push({ name: 'bar apart', ui: barred, body: apart, links: (apart.match(/<a [^>]*href="\/open\//g) ?? []).length, bar: 'apart' });
drawn.push({ name: 'bar only', ui: barred, body: only, links: 0, bar: 'only' });
// A feed's strip of pinned feeds swaps the screen in place: drawn at the root of the host's stack, not on a screen pushed over it.
const feed = JSON.parse(readFileSync(join(trees, 'feed.json'), 'utf8'));
const pinned = [
{ label: 'Recent', open: { call: { name: 'describe_app', args: { domain: 'grain.social', mode: 'feed' } } }, selected: false },
{ label: 'New York, New York, US', open: { call: { name: 'describe_app', args: { domain: 'grain.social', mode: 'feed', location: 'ny' } } }, selected: true }
];
const stripped = { ...feed, root: { c: 'Stack', k: [{ c: 'Tabs', p: { style: 'strip', items: pinned } }, feed.root] } };
const atRoot = server.render(server.Tree, { props: props(stripped) }).body;
const pushed = server.render(server.Tree, { props: props(stripped, 'here', false) }).body;
if (!/class="tabs[^"]*\bstrip\b/.test(atRoot) || !atRoot.includes('New York, New York, US')) problems.push('strip: at the root, the feeds strip is not drawn');
if (/class="tabs[^"]*\bstrip\b/.test(pushed) || pushed.includes('New York, New York, US')) problems.push('strip: pushed, the feeds strip is still drawn');
drawn.push({ name: 'strip at root', ui: stripped, body: atRoot, links: (atRoot.match(/<a [^>]*href="\/open\//g) ?? []).length, bar: 'here' });
drawn.push({ name: 'strip pushed', ui: stripped, body: pushed, links: (pushed.match(/<a [^>]*href="\/open\//g) ?? []).length, bar: 'here', root: false });
// One's own profile's panes: the server draws them all in their strip, the first shown and the rest folded away, as the browser hydrates them.
const panesBody = server.render(server.Tree, { props: props(PANES) }).body;
const folded = [...panesBody.matchAll(/<div class="pane\b([^"]*)"/g)].map((m) => /\boff\b/.test(m[1]));
if (!/<div class="strip\b/.test(panesBody) || folded.join() !== 'false,true,true') problems.push(`panes: not drawn in a strip, the first shown and the rest folded away: ${folded.join()}`);
if (!panesBody.includes('Galleries here') || !panesBody.includes('Stories here')) problems.push('panes: the server does not draw every pane');
drawn.push({ name: 'panes', ui: PANES, body: panesBody, links: (panesBody.match(/<a [^>]*href="\/open\//g) ?? []).length, bar: 'here' });
// One's own stories with none, opened at Add to your story (the query's `compose`, its Compose `open`): drawn shut on the server, as the browser hydrates it, which then opens it by itself.
const photos = { name: 'photos', kind: 'photos', label: 'Photo', required: true, min: 1, max: 1, maxBytes: 1000000, maxSide: 2000, camera: true };
const add = { key: 'add', label: 'Add to your story', icon: 'plus', style: 'button', form: 'photo', title: 'New story', send: 'Share', fields: [photos], given: {}, writes: [], open: true };
const adding = { v: 1, trusted: true, root: { c: 'Slides', p: { empty: 'No stories right now', name: 'me.test' }, items: [], k: [{ c: 'Stack', p: { gap: 'md' }, k: [{ c: 'Compose', p: add }] }] } };
const writing = (ui) => ({ ...props(ui), ontool: async () => ({}), onupload: async () => ({}) });
const addingBody = server.render(server.Tree, { props: writing(adding) }).body;
if (!addingBody.includes('No stories right now') || !addingBody.includes('Add to your story') || addingBody.includes('<dialog'))
problems.push(`compose: on the server, the empty stories are not drawn with Add to your story shut: ${addingBody.slice(0, 300)}`);
// The browser: happy-dom's document, its globals Node lacks put on Node's.
const { Window } = await import('happy-dom');
const window = new Window({ url: 'https://grain.test/' });
for (const key of Object.getOwnPropertyNames(window)) if (!(key in globalThis)) globalThis[key] = window[key];
Object.assign(globalThis, { window, document: window.document, navigator: window.navigator });
process.env.TZ = 'Pacific/Kiritimati';
const client = await import(pathToFileURL(join(out, 'client', readdirSync(join(out, 'client')).find((f) => /^client\.m?js$/.test(f)))).href);
for (const { name, ui, body, links, bar, width, root } of drawn) {
const target = document.createElement('div');
if (width) target.style.width = width;
document.body.append(target);
target.innerHTML = body;
// Less what Svelte's server adds to a picture to replay its load or error once hydrated, which hydrating takes away.
const before = target.innerHTML.replaceAll(/ on(load|error)="this\.__e=event"/g, '');
const said = [];
const { warn, error } = console;
console.warn = console.error = (...args) => said.push(args.map(String).join(' '));
let app;
try {
app = client.hydrate(client.Tree, { target, props: props(ui, bar, root) });
} catch (e) {
said.push(`threw: ${e.stack}`);
} finally {
console.warn = warn;
console.error = error;
}
const after = target.innerHTML;
// A page's translation leaves the UI's names and identifiers alone, never people's words: Chrome made ALT German's "alt", "OLD".
if (name === 'feed') {
const holding = (text) => [...target.querySelectorAll('*')].filter((e) => e.textContent.trim().startsWith(text));
const kept = (text) => holding(text).some((e) => e.closest('[translate="no"]') !== null);
if (holding('ALT').length === 0 || !kept('ALT')) problems.push('feed: its ALT badge is not kept from translation (translate="no")');
if (holding('@apkussma.bsky.social').length === 0 || !kept('@apkussma.bsky.social')) problems.push('feed: a byline\'s @handle is not kept from translation (translate="no")');
for (const words of ['Primera llegada de Fyne Audio', 'Los primeros palés de altavoces'])
if (holding(words).length === 0 || kept(words)) problems.push(`feed: a gallery's words are kept from translation, or not drawn: ${words}`);
}
// Hydrated, a clamped text the server cut is drawn cut, a button to show more of each.
const cuts = clamped(ui.root);
const words = target.textContent;
for (const { shown, whole } of cuts)
if (!words.includes(shown.join('')) || words.includes(whole.join(''))) problems.push(`${name}: hydrated, a clamped text is not drawn cut: ${shown.at(-1)}`);
const offers = [...target.querySelectorAll('button.more')].filter((b) => cuts.some((c) => c.more === b.textContent)).length;
if (offers !== cuts.length) problems.push(`${name}: ${cuts.length} clamped texts cut, ${offers} buttons to show more`);
if (app) client.unmount(app);
target.remove();
for (const s of said) problems.push(`${name}: hydrating it: ${s}`);
if (after !== before) problems.push(`${name}: hydrated, it changed:\n ${difference(before, after)}`);
say(`${name}: drawn, ${links} links, hydrated`);
}
// Hydrated as drawn, then the form opened by itself: once the tree's effects run, never on the server.
{
const target = document.createElement('div');
document.body.append(target);
target.innerHTML = addingBody;
const before = target.innerHTML;
const said = [];
const { warn, error } = console;
console.warn = console.error = (...args) => said.push(args.map(String).join(' '));
let app;
try {
app = client.hydrate(client.Tree, { target, props: writing(adding) });
if (target.innerHTML !== before) problems.push(`compose: hydrated, it changed:\n ${difference(before, target.innerHTML)}`);
client.flushSync();
} catch (e) {
said.push(`threw: ${e.stack}`);
} finally {
console.warn = warn;
console.error = error;
}
for (const s of said) problems.push(`compose: hydrating it: ${s}`);
if (!target.querySelector('dialog.composer') || !target.textContent.includes('New story')) problems.push('compose: hydrated, Add to your story did not open by itself');
if (app) client.unmount(app);
target.remove();
say('compose: drawn shut, hydrated, opened by itself');
}
// A component the renderer does not know (a tree newer than it): built for production, the server draws its children, else its fallback (an unknown one falling back again), else nothing; in development, server and browser alike draw a box saying so, which hydrates as drawn.
{
const text = (words) => ({ c: 'Text', p: { runs: [{ text: words }], style: 'body' } });
const unknown = {
children: { c: 'Gauge', p: { value: 3 }, k: [text('Gauge child one'), text('Gauge child two')], fallback: text('Not drawn') },
fallback: { c: 'Gauge', fallback: { c: 'Dial', fallback: text('Gauge fallback') } },
nothing: { c: 'Gauge', k: [] }
};
const tree = (node) => ({ v: 1, trusted: true, root: { c: 'Stack', p: { gap: 'md' }, k: [text('Before'), node, text('After')] } });
const draw = (s, node) => s.render(s.Tree, { props: props(tree(node)) }).body;
const plain = (body) => body.replace(/<!--.*?-->/gs, '');
const children = draw(server, unknown.children);
if (!/<div class="stack md[^"]*"><div class="text body[^"]*"><span[^>]*>Gauge child one<\/span> <\/div><div class="text body[^"]*"><span[^>]*>Gauge child two<\/span> <\/div><\/div>/.test(plain(children)) || children.includes('Not drawn'))
problems.push(`unknown: its children are not drawn as a Stack, before its fallback: ${plain(children)}`);
const fallback = draw(server, unknown.fallback);
if (!fallback.includes('Gauge fallback')) problems.push(`unknown: with no children, its fallback's fallback is not drawn: ${plain(fallback)}`);
const nothing = draw(server, unknown.nothing);
const without = server.render(server.Tree, { props: props({ v: 1, trusted: true, root: { c: 'Stack', p: { gap: 'md' }, k: [text('Before'), text('After')] } }) }).body;
if (plain(nothing) !== plain(without)) problems.push(`unknown: with neither, it draws something: ${plain(nothing)}`);
if ([children, fallback, nothing].some((b) => b.includes('not-yet'))) problems.push('unknown: built for production, the server draws the box saying it is not drawn yet');
const dev = await import(pathToFileURL(join(out, 'server-dev/server.mjs')).href);
for (const [name, node] of Object.entries(unknown)) {
const body = dev.render(dev.Tree, { props: props(tree(node)) }).body;
if (!/<span class="not-yet[^"]*" role="note">Gauge isn't drawn on the web yet<\/span>/.test(body)) problems.push(`unknown ${name}: in development, the box saying it is not drawn yet is not drawn: ${plain(body)}`);
const target = document.createElement('div');
document.body.append(target);
target.innerHTML = body;
const before = target.innerHTML;
const said = [];
const { warn, error } = console;
console.warn = console.error = (...args) => said.push(args.map(String).join(' '));
let app;
try {
app = client.hydrate(client.Tree, { target, props: props(tree(node)) });
} catch (e) {
said.push(`threw: ${e.stack}`);
} finally {
console.warn = warn;
console.error = error;
}
for (const s of said) problems.push(`unknown ${name}: hydrating it: ${s}`);
if (target.innerHTML !== before) problems.push(`unknown ${name}: hydrated, it changed:\n ${difference(before, target.innerHTML)}`);
if (app) client.unmount(app);
target.remove();
}
say('unknown: its children, its fallback or nothing in production; in development a box saying so, hydrated');
}
// Stories: the server draws the picture showing alone, as the browser hydrates it; once hydrated, the next two load ahead (a page drawn ahead in a pager, its first alone), and its bar waits for its picture, filling once it loads, or fails for its placeholder. A carousel near the screen loads its next photo ahead, at the width it is drawn.
{
const story = (set, n) => ({ src: { src: `https://cdn.test/${set}${n}.jpg`, fallback: null }, alt: `Story ${n}`, ratio: 1, srcset: `https://cdn.test/${set}${n}-640.jpg 640w, https://cdn.test/${set}${n}.jpg 1440w` });
const slides = (set, p = {}) => ({ v: 1, trusted: true, root: { c: 'Slides', p: { name: 'alice.test', seconds: 1, ...p }, items: [0, 1, 2, 3].map((n) => story(set, n)) } });
const fetched = [];
const { Image, IntersectionObserver } = globalThis;
globalThis.Image = class extends Image {
set src(v) {
fetched.push({ src: v, srcset: this.getAttribute('srcset'), sizes: this.getAttribute('sizes') });
super.src = v;
}
get src() {
return super.src;
}
};
const sources = () => fetched.map((f) => f.src.replace('https://cdn.test/', '')).join(' ');
const pause = (ms) => new Promise((done) => setTimeout(done, ms));
const said = [];
const { warn, error } = console;
console.warn = console.error = (...args) => said.push(args.map(String).join(' '));
try {
const ui = slides('s');
const body = server.render(server.Tree, { props: props(ui) }).body;
const pictures = body.match(/<img\b[^>]*>/g) ?? [];
if (pictures.length !== 1 || !pictures[0].includes('https://cdn.test/s0.jpg')) problems.push(`stories: the server draws other than the picture showing: ${pictures.join(' ')}`);
if (!pictures[0]?.includes(` srcset="${story('s', 0).srcset}"`) || !pictures[0].includes(` sizes="auto, ${SLOT}"`)) problems.push(`stories: the server draws the picture showing without its sizes: ${pictures[0]}`);
const target = document.createElement('div');
document.body.append(target);
target.innerHTML = body;
const before = target.innerHTML.replaceAll(/ on(load|error)="this\.__e=event"/g, '');
const app = client.hydrate(client.Tree, { target, props: props(ui) });
if (target.innerHTML !== before) problems.push(`stories: hydrated, it changed:\n ${difference(before, target.innerHTML)}`);
client.flushSync();
const fill = (i) => target.querySelectorAll('.fill')[i]?.style.width;
if (sources() !== 's1.jpg s2.jpg') problems.push(`stories: hydrated, it loads ahead ${sources() || 'nothing'}, not the next two`);
if (fetched.some((f) => f.srcset !== story('s', Number(f.src.match(/(\d)\.jpg$/)[1])).srcset || !f.sizes)) problems.push(`stories: hydrated, it loads ahead without their sizes: ${JSON.stringify(fetched)}`);
await pause(150);
if (fill(0) !== '0%') problems.push(`stories: its bar ran before its picture loaded (${fill(0)})`);
target.querySelector('.stage img').dispatchEvent(new window.Event('load'));
await pause(150);
if (!(parseFloat(fill(0)) > 0)) problems.push(`stories: its picture loaded, its bar did not fill (${fill(0)})`);
[...target.querySelectorAll('.sr button')].find((b) => b.textContent === 'Next').click();
client.flushSync();
if (sources() !== 's1.jpg s2.jpg s3.jpg') problems.push(`stories: gone on, it loads ahead ${sources()}, not the next two once each`);
await pause(150);
if (fill(1) !== '0%') problems.push(`stories: gone on, its bar ran before its picture loaded (${fill(1)})`);
target.querySelector('.stage img').dispatchEvent(new window.Event('error'));
client.flushSync();
await pause(150);
if (!target.querySelector('.stage .missing') || !(parseFloat(fill(1)) > 0)) problems.push(`stories: its picture failed, its bar did not fill by its placeholder (${fill(1)})`);
client.unmount(app);
target.remove();
fetched.length = 0;
const behind = document.createElement('div');
document.body.append(behind);
const waiting = client.mount(client.Tree, { target: behind, props: { ...props(slides('w', { start: 2 })), active: false } });
client.flushSync();
if (sources() !== 'w2.jpg') problems.push(`stories: drawn ahead in a pager, it loads ahead ${sources() || 'nothing'}, not the one it starts from`);
client.unmount(waiting);
behind.remove();
fetched.length = 0;
globalThis.IntersectionObserver = class {
constructor(seen) {
this.seen = seen;
}
observe(element) {
this.seen([{ target: element, isIntersecting: true }]);
}
unobserve() {}
disconnect() {}
};
const strip = document.createElement('div');
document.body.append(strip);
const carousel = client.mount(client.Tree, { target: strip, props: props({ v: 1, trusted: true, root: { c: 'Gallery', p: { style: 'carousel' }, items: [21, 22, 23].map(photo) } }) });
client.flushSync();
const next = photo(22);
if (fetched.length !== 1 || fetched[0].src !== next.src.src || fetched[0].srcset !== next.srcset || !/^\d+px$/.test(fetched[0].sizes ?? ''))
problems.push(`carousel: near the screen, it loads ahead ${JSON.stringify(fetched)}, not its next photo at its width`);
client.unmount(carousel);
strip.remove();
} catch (e) {
said.push(`threw: ${e.stack}`);
} finally {
console.warn = warn;
console.error = error;
Object.assign(globalThis, { Image, IntersectionObserver });
}
for (const s of said) problems.push(`stories: ${s}`);
say('stories: the next loaded ahead, the bar run once each picture is drawn; a carousel its next');
}
// A feed's card opens on a tap on it, but not on its carousel, nor where the touch moved or its scroller was moving, and a mouse's click opens it as ever; a tap once its scroller came to rest (the browser says so, or it has not moved for a while) opens.
{
const opened = [];
const target = document.createElement('div');
document.body.append(target);
const ui = { v: 1, trusted: true, root: { c: 'List', p: { style: 'rows' }, items: [{ open: opening(1), k: [{ c: 'Text', p: { value: 'A gallery' } }, { c: 'Gallery', p: { style: 'carousel' }, items: [31, 32].map(photo) }] }] } };
const app = client.mount(client.Tree, { target, props: { ...props(ui), oncall: (call) => opened.push(call) } });
client.flushSync();
const card = target.querySelector('a.open');
const scrolled = (type = 'scroll') => document.dispatchEvent(new window.Event(type));
const tap = (at, { type = 'touch', to = 0, scroll = false, glided = false, rested = false, stopped = false } = {}) => {
if (glided) scrolled();
if (rested) scrolled('scrollend');
at.dispatchEvent(new window.PointerEvent('pointerdown', { bubbles: true, isPrimary: true, pointerType: type, clientX: 10, clientY: 10 }));
if (scroll) scrolled();
if (stopped) scrolled('scrollend');
const before = opened.length;
at.dispatchEvent(new window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1, clientX: 10, clientY: 10 + to }));
return opened.length > before;
};
if (!tap(card)) problems.push('taps: a tap on a card does not open it');
if (tap(target.querySelector('[data-swipes]'))) problems.push('taps: a tap on a card\'s carousel opens the card');
if (tap(card, { to: 30 })) problems.push('taps: a touch that moved 30 pixels opens a card');
if (tap(card, { scroll: true })) problems.push('taps: a touch as its page scrolls opens a card');
if (!tap(card, { type: 'mouse', to: 30, scroll: true })) problems.push('taps: a mouse\'s click as its page scrolls does not open a card');
if (tap(card, { glided: true })) problems.push('taps: a touch as its page glides opens a card');
if (tap(card, { glided: true, stopped: true })) problems.push('taps: a touch that stopped its page gliding opens a card');
if (!tap(card, { glided: true, rested: true })) problems.push('taps: a tap as soon as its page came to rest does not open a card');
scrolled();
await new Promise((r) => setTimeout(r, 150));
if (!tap(card)) problems.push('taps: a tap a moment after its page last moved does not open a card');
client.unmount(app);
target.remove();
say('taps: a card opens on a tap, not on its carousel, a touch that moved or one that stopped a scroll, and at once once the scroll rests');
}
// A form opened from a Menu's row (Edit gallery): an @ and what follows it list the accounts `suggest` finds, in a popover (the top layer, so the form's dialog never cuts them off), and one picked by a press takes the @'s place, the menu and its form still open.
{
const asked = [];
const suggest = { method: 'test.actor.search', param: 'q', params: { limit: 8 }, items: 'actors', did: 'did', handle: 'handle', name: 'displayName' };
const edit = { key: 'edit', label: 'Edit gallery', send: 'Save', fields: [{ name: 'description', kind: 'text', max: 1000, facets: true, suggest }], given: {}, writes: [] };
const ui = { v: 1, trusted: true, root: { c: 'Menu', p: {}, k: [{ c: 'Compose', p: edit }] } };
const ontool = async (name, args) => {
asked.push({ name, args });
return { response: { actors: [{ did: 'did:plc:dan', handle: 'danabra.mov', displayName: 'dan' }] } };
};
// happy-dom has no popovers (shown, one says so) and no visual viewport.
const { showPopover } = window.HTMLElement.prototype;
window.HTMLElement.prototype.showPopover = function () {
this.setAttribute('data-shown', '');
};
globalThis.visualViewport = null;
// A browser runs what a handler queued before the next handler (Svelte's flush): so a press's target may be gone before the window hears of it.
const flush = () => client.flushSync();
document.addEventListener('pointerdown', flush);
const target = document.createElement('div');
document.body.append(target);
const app = client.mount(client.Tree, { target, props: { ...props(ui), ontool } });
try {
client.flushSync();
target.querySelector('button.more').click();
client.flushSync();
[...target.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Edit gallery').click();
client.flushSync();
const box = target.querySelector('dialog textarea');
// Typed into while a page translator (Safari's) swaps the text drawn behind the box for its own nodes: what is drawn stays what is written, its mention coloured, however the browser changed the box (a key, an autocorrection, a composition).
const mirror = box.parentElement.querySelector('.mirror');
if (box.closest('[translate="no"]') !== mirror.parentElement) problems.push('mentions: the box and what is drawn behind it are not marked translate="no"');
const typed = (text, inputType) => {
box.value = text;
box.dispatchEvent(new window.InputEvent('input', { bubbles: true, inputType, data: text.at(-1) ?? null }));
client.flushSync();
};
const translate = () => {
for (const node of [...mirror.childNodes]) if (node.nodeType === 3) node.replaceWith(document.createTextNode(node.data));
};
typed('h', 'insertText');
translate();
typed('hd', 'insertText');
typed('hdh', 'insertCompositionText');
translate();
typed('hdhdhdj', 'insertReplacementText');
typed('hdhdhdj @danabra.mov ', 'insertFromPaste');
translate();
const drawn = mirror.textContent.replace('\u200b', '');
if (drawn !== box.value) problems.push(`mentions: translated as it is typed, ${JSON.stringify(box.value)} is drawn ${JSON.stringify(drawn)}`);
if (mirror.querySelector('.mention')?.textContent !== '@danabra.mov') problems.push('mentions: translated as it is typed, the mention is not coloured');
typed('', 'deleteContentBackward');
box.value = 'with @da';
box.setSelectionRange(8, 8);
box.dispatchEvent(new window.Event('input', { bubbles: true }));
await new Promise((r) => setTimeout(r, 300));
client.flushSync();
const list = target.querySelector('[role="listbox"]');
const q = asked[0]?.args?.params?.q;
if (asked.length !== 1 || asked[0].name !== 'query' || asked[0].args.method !== suggest.method || q !== 'da') problems.push(`mentions: @da asked ${JSON.stringify(asked)}, not one query of ${suggest.method} for da`);
if (!list?.hasAttribute('popover') || !list.hasAttribute('data-shown')) problems.push('mentions: the accounts are not shown in a popover');
const option = list?.querySelector('[role="option"]');
if (!option?.textContent.includes('@danabra.mov')) problems.push(`mentions: the accounts list ${JSON.stringify(list?.textContent ?? null)}, not @danabra.mov`);
option?.dispatchEvent(new window.PointerEvent('pointerdown', { bubbles: true, cancelable: true, isPrimary: true, pointerType: 'mouse' }));
client.flushSync();
await new Promise((r) => setTimeout(r, 0));
const after = target.querySelector('dialog textarea');
if (!target.querySelector('.rows') || !after) problems.push('mentions: an account picked by a press closes the menu and its form');
else if (after.value !== 'with @danabra.mov ') problems.push(`mentions: picked, the text is ${JSON.stringify(after.value)}, not "with @danabra.mov "`);
if (target.querySelector('[role="listbox"]')) problems.push('mentions: picked, the accounts are still listed');
} catch (e) {
problems.push(`mentions: ${e.stack}`);
} finally {
client.unmount(app);
target.remove();
document.removeEventListener('pointerdown', flush);
window.HTMLElement.prototype.showPopover = showPopover;
delete globalThis.visualViewport;
}
say("mentions: what is typed is drawn behind the box as it is, translated or not; a menu's form lists @'s accounts in a popover, and one picked by a press takes its place");
}
// A place's header: a Stack with gap none sets its map against what follows, and the map, with pins: false, draws no pin, where without it draws its one.
{
const { fetch } = globalThis;
// Its tiles never come: the test reaches no network.
globalThis.fetch = () => new Promise(() => {});
// Leaflet sets `L` on the window, happy-dom's here, which protomaps-leaflet reads as a global, as a browser's window is.
Object.defineProperty(globalThis, 'L', { get: () => window.L, configurable: true });
const place = { lat: 52.373031, lng: 4.892636, label: 'Amsterdam, Noord-Holland, NL' };
const header = (p) => ({ v: 1, trusted: true, root: { c: 'Stack', p: { gap: 'none' }, k: [{ c: 'Map', p: { height: 'short', bleed: true, zoom: 11, ...p }, items: [place] }, { c: 'Text', p: { runs: [{ text: 'Under it' }], style: 'body' } }] } });
const drawnHeader = server.render(server.Tree, { props: props(header({ pins: false })) }).body;
if (!/class="stack none\b/.test(drawnHeader)) problems.push(`map: a Stack with gap none is not drawn so: ${drawnHeader.slice(0, 200)}`);
const shown = async (p) => {
const target = document.createElement('div');
document.body.append(target);
const app = client.mount(client.Tree, { target, props: props(header(p)) });
client.flushSync();
for (let waited = 0; !target.querySelector('.leaflet-container') && waited < 10000; waited += 20) await new Promise((r) => setTimeout(r, 20));
const seen = { container: !!target.querySelector('.leaflet-container'), pins: target.querySelectorAll('.pin').length };
client.unmount(app);
target.remove();
return seen;
};
try {
const pinned = await shown({});
const plain = await shown({ pins: false });
if (!pinned.container || pinned.pins !== 1) problems.push(`map: with its pins, it draws ${JSON.stringify(pinned)}, not one pin`);
if (!plain.container || plain.pins !== 0) problems.push(`map: with pins false, it draws ${JSON.stringify(plain)}, not a map with no pin`);
} catch (e) {
problems.push(`map: ${e.stack}`);
} finally {
globalThis.fetch = fetch;
}
say('map: gap none against what follows; a pin, or with pins false none');
}
// Mounted, the panes' strip scrolls with every pane opened; an icon clicked chooses its pane, whose Select (none on favorites) is the row's; picking, the icons and the strip hold still.
// At a phone's width, with the build's stylesheet: two picked, the bar (Cancel, 2 selected, Delete 2) is sticky with nothing between it and the screen's scroller that scrolls or hides it, the strip no longer a scroller; else it is held to the strip's bottom, under the screen's foot (next.grain.social's profile). Cancel lets the strip scroll again.
{
const styles = readdirSync(join(out, 'client'))
.filter((f) => f.endsWith('.css'))
.map((f) => Object.assign(document.createElement('style'), { textContent: readFileSync(join(out, 'client', f), 'utf8') }));
document.head.append(...styles);
window.happyDOM.setViewport({ width: 390, height: 844 });
const target = document.createElement('div');
document.body.append(target);
const app = client.mount(client.Tree, { target, props: props(PANES) });
try {
client.flushSync();
const tabs = () => [...target.querySelectorAll('[role="tab"]')];
const chosen = () => tabs().findIndex((t) => t.getAttribute('aria-selected') === 'true');
const end = () => target.querySelector('button.end')?.textContent ?? null;
if (!target.querySelector('.panes.live') || target.querySelector('.pane.off')) problems.push('panes: mounted, the strip does not scroll or a pane is still folded away');
if (end() !== 'Select') problems.push(`panes: the galleries' row ends in ${end()}, not Select`);
tabs()[1].click();
client.flushSync();
if (chosen() !== 1 || end() !== null) problems.push(`panes: favorites clicked, pane ${chosen()} is chosen, its row ending in ${end()}`);
if (!target.querySelectorAll('.pane')[0].inert || target.querySelectorAll('.pane')[1].inert) problems.push('panes: favorites chosen, the galleries are not inert or the favorites are');
tabs()[0].click();
client.flushSync();
target.querySelector('button.end').click();
client.flushSync();
if (!target.querySelector('.panes.held') || tabs().some((t) => !t.disabled)) problems.push('panes: picking, the strip or its icons do not hold still');
for (const cover of [...target.querySelectorAll('button[aria-pressed]')].slice(0, 2)) cover.click();
client.flushSync();
const bar = target.querySelector('[role="toolbar"]');
const said = bar?.textContent.replace(/\s+/g, ' ').trim();
if (said !== 'Cancel 2 selected Delete 2') problems.push(`panes: two picked, the bar says ${said ?? 'nothing'}`);
if (bar && window.getComputedStyle(bar).position !== 'sticky') problems.push(`panes: picking, the bar is ${window.getComputedStyle(bar).position}, not sticky`);
// happy-dom leaves an overflow nothing sets empty, where a browser says visible.
for (let box = bar?.parentElement; box && box !== target; box = box.parentElement) {
const { overflowX, overflowY, display } = window.getComputedStyle(box);
if (![overflowX, overflowY].every((o) => o === '' || o === 'visible' || o === 'clip') || display === 'none')
problems.push(`panes: picking, the bar is in a box that scrolls or hides it (${box.className}: overflow ${overflowX} ${overflowY}, display ${display}), so it is not held at the screen's foot`);
}
bar?.querySelector('button.cancel').click();
client.flushSync();
const strip = target.querySelector('.strip');
if (target.querySelector('[role="toolbar"]') || target.querySelector('.panes.held') || window.getComputedStyle(strip).overflowX !== 'auto') problems.push('panes: cancelled, the bar stays or the strip does not scroll again');
} catch (e) {
problems.push(`panes: ${e.stack}`);
} finally {
client.unmount(app);
target.remove();
for (const style of styles) style.remove();
}
say("panes: mounted they scroll, an icon chooses its pane and its Select, and picking holds them still, its bar held at the screen's foot");
}
// A profile's ⋯ in its Bar, with the build's stylesheet: each row (Links, an Action two Stacks deep, a danger one with a question, a Compose, an Action with an icon, a Toggle) the whole width, its words from the start at the same inset, an icon's words shown, the Stacks no gap between rows, Block in the danger colour. The Bar's rules for its own buttons (icons centred) once reached into the menu: Mute, Block and Report centred on next.grain.social.
{
const styles = readdirSync(join(out, 'client'))
.filter((f) => f.endsWith('.css'))
.map((f) => Object.assign(document.createElement('style'), { textContent: readFileSync(join(out, 'client', f), 'utf8') }));
// The theme's values, plain: happy-dom computes no light-dark().
styles.push(Object.assign(document.createElement('style'), { textContent: ':root { --hud-space-3: 12px; --color-text-primary: #111; --color-text-danger: #a22; }' }));
document.head.append(...styles);
window.happyDOM.setViewport({ width: 390, height: 844 });
const call = (method) => ({ method, service: 'did:web:test', input: {} });
const menu = {
c: 'Menu',
p: { label: 'More' },
k: [
{ c: 'Link', p: { label: 'Share profile', share: 'https://grain.test/profile/alice.test' } },
{ c: 'Link', p: { label: 'Copy handle', copy: '@alice.test' } },
{
c: 'Stack',
p: {},
k: [
{ c: 'Stack', p: {}, k: [{ c: 'Action', p: { label: 'Mute', done: 'Muted', call: call('test.mute') } }] },
{ c: 'Action', p: { label: 'Block', done: 'Unblock', tone: 'danger', confirm: 'Block this account?', create: { collection: 'test.block', record: {} } } },
{ c: 'Compose', p: { key: 'report', label: 'Report', send: 'Report', fields: [{ name: 'why', kind: 'line', label: 'Why' }], given: {}, writes: [] } },
{ c: 'Action', p: { label: 'Pin', icon: 'pin', call: call('test.pin') } },
{ c: 'Toggle', p: { label: 'Notify', on: false, call: call('test.notify') } }
]
}
]
};
const ui = { v: 1, trusted: true, root: { c: 'Stack', k: [{ c: 'Bar', p: { title: 'alice.test' }, k: [menu] }] } };
const target = document.createElement('div');
document.body.append(target);
const app = client.mount(client.Tree, { target, props: { ...props(ui), ontool: async () => ({}) } });
try {
client.flushSync();
target.querySelector('button.more').click();
client.flushSync();
const rows = [...target.querySelectorAll('.rows :is(.button, .toggle)')];
const said = rows.map((row) => row.textContent.trim());
if (said.join('|') !== 'Share profile|Copy handle|Mute|Block|Report|Pin|Notify') problems.push(`menu: its rows are ${JSON.stringify(said)}`);
const looks = rows.map((row) => {
const { display, justifyContent, width, paddingLeft, color } = window.getComputedStyle(row);
return { name: row.textContent.trim(), display, justifyContent, width, paddingLeft, color };
});
const inset = looks[0]?.paddingLeft;
for (const { name, display, justifyContent, width, paddingLeft } of looks)
if (display !== 'flex' || justifyContent !== 'flex-start' || width !== '100%' || paddingLeft !== inset || !/^[1-9]/.test(paddingLeft))
problems.push(`menu: ${name} is drawn ${JSON.stringify({ display, justifyContent, width, paddingLeft })}, not a row the whole width, its words from the start at the menu's inset (${inset})`);
for (const stack of target.querySelectorAll('.rows .stack')) if (!['0', '0px'].includes(window.getComputedStyle(stack).gap)) problems.push(`menu: a Stack in it puts ${window.getComputedStyle(stack).gap} between its rows`);
const spoken = target.querySelector('.rows .pin .spoken');
if (!spoken || window.getComputedStyle(spoken).position === 'absolute') problems.push("menu: Pin's words are hidden, its icon alone");
const mute = looks.find((row) => row.name === 'Mute');
const block = looks.find((row) => row.name === 'Block');
if (!block || !mute || block.color === mute.color) problems.push(`menu: Block is ${block?.color}, as Mute is, not the danger colour`);
if (target.querySelector('.rows [data-bar-form]')) problems.push("menu: Report is marked as the Bar's form");
} catch (e) {
problems.push(`menu: ${e.stack}`);
} finally {
client.unmount(app);
target.remove();
for (const style of styles) style.remove();
}
say("menu: in a Bar, every row the whole width, its words at the same inset, Block in the danger colour");
}
// Each button to show more of a clamped text, clicked, draws it whole: once every tree is hydrated, as a mounted Tree draws dates by the browser's clock.
for (const { name, ui, root } of drawn) {
const cuts = clamped(ui.root);
if (cuts.length === 0) continue;
const target = document.createElement('div');
document.body.append(target);
const app = client.mount(client.Tree, { target, props: props(ui, 'here', root) });
for (const b of target.querySelectorAll('button.more')) if (cuts.some((c) => c.more === b.textContent)) b.click();
client.flushSync();
const opened = target.textContent;
for (const { whole } of cuts) if (!opened.includes(whole.join(''))) problems.push(`${name}: opened, a clamped text is not drawn whole: ${whole.at(-1)}`);
// Opened, a caption's words are translated with the page, and the link showing its address, the line break and the space before the link kept from it: a translation drops a space beside what it keeps, and joins the lines.
if (name === 'feed') {
const said = [...target.querySelectorAll('p')].find((p) => p.textContent.startsWith('I recommend a handlebar bike mirror\n\nmade in the Atmosphere in luminframe.com'));
const spaces = [...(said?.querySelectorAll('span[translate="no"]') ?? [])].map((e) => e.textContent);
if (!said) problems.push('feed: opened, the bike mirror caption is not drawn whole');
else {
if (said.querySelector('a')?.getAttribute('translate') !== 'no') problems.push('feed: a link showing its address (luminframe.com) is not kept from translation');
if (spaces.join('|') !== '\n\n| ') problems.push(`feed: the caption's line break and the space before its link are not kept from translation, only ${JSON.stringify(spaces)}`);
if (said.closest('[translate="no"]')) problems.push("feed: the caption's words are kept from translation");
}
}
if ([...target.querySelectorAll('button.more')].some((b) => cuts.some((c) => c.more === b.textContent))) problems.push(`${name}: opened, a clamped text still offers more`);
client.unmount(app);
target.remove();
say(`${name}: ${cuts.length} clamped texts opened`);
}
} catch (e) {
problems.push(e.stack ?? String(e));
} finally {
rmSync(out, { recursive: true, force: true });
}
for (const p of problems) say(p);
if (problems.length) process.exit(1);
say('every tree drew on the server as the browser hydrated it');