chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.3.1 Latest 5 packages
0
0
// Whether the shell draws an app's frame on a server as a browser hydrates
// it, at every width: `Shell` (server.ts) drawn with Svelte's `render` in
// Node, with no browser's globals, for a sample app with every part of a
// frame (an action, the account's picture and items, links, an aside),
// signed out and in, its screen a tree of the renderer's server test
// (Grain's feed) and a wide one (Grain's profile); then hydrated
// (client.ts, Svelte's development build) in happy-dom's document at a
// phone's width (390), a tablet's (900) and a desktop's (1440), each with
// the same props.
//
// cd web && npm run ssr `just check` runs it, and CI's web job
//
// It fails where drawing throws or draws otherwise for a width (the band
// is the stylesheet's to say, never code's); where hydrating warns,
// throws, or changes what the server drew, the head's frame stylesheet
// too; where the frame's stylesheet (frame.ts's `frameCss`) puts a width
// in another band than its bar (under 600), its rail (600 to 1199) and
// its sidebar (1200 on), or shows the aside where the navigation, the
// column and the aside do not fit (900) or hides it where they do (1440);
// where the column is not drawn at the top screen's measure before any
// code runs (`data-measure`); and where the page made as the first history
// entry is not the tab's own URL. Signed in, a screen whose Bar has a +
// for the action's form and a gear: it fails where the + is not shown at
// 390 or is shown at 900 and 1440 (the navigation's action is it there),
// or the gear is not shown at every width, as the head's stylesheet says
// in happy-dom. Then, signed in, in the browser alone,
// with a fake server: it fails where Create does more than draw the
// action's form over the screen on show (a screen pushed, a history entry
// made), where a form opens again once cancelled (the page loaded again;
// a screen a link opened at a form gone back from and forward to, or
// loaded again; an entry an older shell kept with `compose` in it), where
// a history entry holds `compose`, or where the action's form sent does
// not open the screen of the record it made; and, a screen of pictures
// pushed from a link and gone back from (and forward to, and back), where
// focus does not move into it and back to the link, where the screen under
// it is not inert or is aria-hidden, or where its pictures loading after it
// is let go warn (Svelte's derived_inert); and a long feed, its foot shown
// to a fake IntersectionObserver: where it does not load its next page
// once, loads one under a screen over it (inert), or loads again after a
// page failed until Try again is pressed. Both builds go to a
// directory of their own in the system's temporary directory, taken away
// after. In the same world, a strip of stories opening a pager: it fails
// where another's story tapped opens one's own page's form (read ahead
// beside it, or swiped to), where one's own page with no pictures does not
// stay shown, or where Your story's form opens other than once. A feed's
// own pin, read again in place: it fails where a feed pushed over a tab
// loses its back or title pinned or unpinned, or where one in Home's root
// place by its strip (chosen there, or loaded at its URL) unpinned is not
// pushed over Home's root at its URL. And the
// app's own pages (`pages`): it fails where a page's path is not its
// `describe_app` over Home, where the server does not draw its text and
// its head (title, description, canonical URL, indexed), where a footer
// link to it does not open it in the app with its URL, or where a link in
// its text to another page on the app's site does not open that. And the
// app's own sign-in screen (`signIn`), drawn at three widths and hydrated
// as the pages are: it fails where its URL's `back` is not kept to the
// app's origin, where the server does not draw its heading, links, form
// (the handle, where it comes back to, Create one) and why it was sent
// back, or its head (out of search); where it makes a history entry; or,
// in the browser against a fake typeahead, where typing does not ask the
// typeahead's own host, the arrows and Enter do not pick an account and
// send the form with its handle, a picture does not fall back, or Escape
// does not close the list.
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(web, 'renderer/test/trees');
const out = mkdtempSync(join(tmpdir(), 'hud-shell-ssr-'));
const say = (line) => console.log(`==> ${line}`);
const problems = [];
const NOW = Date.parse('2026-11-18T12:00:00.000Z');
const query = (method, params = {}) => ({ name: 'query', args: { method, params } });
const FEED = query('test.feed.getFeed', { feed: 'home' });
const PROFILE = { name: 'describe_app', args: { domain: 'app.test', actor: 'me' } };
const FOLLOWING = query('test.feed.getFeed', { feed: 'following' });
const PINNED = query('test.feed.getFeed', { feed: 'camera', camera: 'X100V' });
const UNPINNED = query('test.feed.getFeed', { feed: 'camera', camera: 'GR' });
/** The account's preferences, whose pinned feeds' paths choose Home's root (its `first`). */
const PREFS = query('test.actor.getPreferences');
/** Each tab's root, signed in, Home's `home`. */
const rootsWith = (home) => [home, query('test.explore'), query('test.notifications'), PROFILE];
/** An app with every part of a frame. */
const APP = {
domain: 'app.test',
name: 'Test',
head: { siteName: 'Test', title: 'Test', description: 'A test app.', image: 'https://app.test/og.jpg' },
search: { typeahead: query('test.actor.typeahead'), results: '/search?q={q}', person: '/profile/{actor}' },
tabs: [
{ label: 'Home', wordmark: 'test', path: '/', icon: 'feed', call: FEED, guest: 'call', first: { call: PREFS, at: 'preferences.@pinnedFeedsPref.items', path: 'path', after: 'test.actor.setPreference' } },
{ label: 'Explore', icon: 'search', call: query('test.explore'), guest: 'call' },
{ label: 'Notifications', icon: 'notification', call: query('test.notifications'), badge: { call: query('test.unread'), count: 'count' } },
{ label: 'Profile', icon: 'people', call: PROFILE }
],
routes: [
{ path: '/explore', call: query('test.explore') },
{ path: '/notifications', call: query('test.notifications') },
{ path: '/settings', call: query('test.settings') },
{ path: '/stories', call: query('test.stories') },
{ path: '/profile/{actor}/post/{rkey}', call: query('test.getPost', { post: 'at://{actor}/test.post/{rkey}' }) },
{ path: '/profile/{actor}/gallery/{rkey}', call: query('test.getGallery', { gallery: 'at://{actor}/test.gallery/{rkey}' }) },
{ path: '/feeds/following', call: FOLLOWING },
{ path: '/camera/{name}', tab: 'Explore', call: query('test.feed.getFeed', { feed: 'camera', camera: '{name}' }) },
{ path: '/profile/{actor}', call: { name: 'describe_app', args: { domain: 'app.test', actor: '{actor}' } } }
],
pages: [
{ path: '/terms', title: 'Terms', description: 'The terms.', markdown: 'pages/terms.md' },
{ path: '/privacy', title: 'Privacy', markdown: 'pages/privacy.md' }
],
frame: {
destinations: 'tabs',
action: { label: 'Create', icon: 'imagePlus', call: { ...FEED, args: { ...FEED.args, compose: 'New' } } },
account: {
picture: { tab: 'Profile', call: query('test.actor.getProfile', { actor: 'me' }), at: 'avatar' },
items: [
{ label: 'Settings', icon: 'settings', call: query('test.settings') },
{ host: 'signOut', label: 'Log out', icon: 'logOut' },
{ host: 'signIn', label: 'Sign in', icon: 'logIn', about: 'Share your photography' }
]
},
links: [
{ label: 'Terms', href: '/terms' },
{ label: 'AT Protocol', href: 'https://atproto.com' }
],
aside: { call: query('test.aside') }
},
signIn: {
title: 'Log in with your atmosphere account',
text: '[What is an atmosphere account?](https://atmosphereaccount.com/)',
placeholder: 'e.g. user.bsky.social',
legal: 'By signing in you agree to our [Terms](/terms).',
create: { text: "Don't have an account?", label: 'Create one' },
typeahead: { url: 'https://typeahead.test', method: 'test.typeahead.searchActors', param: 'q', params: { limit: 5 }, items: 'actors', did: 'did', handle: 'handle', name: 'displayName', avatar: 'avatar', avatarFallback: 'avatarFallback' }
}
};
/** The sign-in screen as the server reads it from its URL (`signInScreen`): back to the account's profile, a handle refused. */
const SIGN_IN = { back: '/profile/me', handle: 'nobody.test', error: 'nobody.test does not resolve to an account' };
const tree = (name) => JSON.parse(readFileSync(join(trees, `${name}.json`), 'utf8'));
const ASIDE = { v: 1, trusted: true, root: { c: 'Text', p: { runs: [{ text: 'Beside the column' }], style: 'body' } } };
/** A form of the action's (its `compose`, New), drawn as a Bar's +. */
const FORM = { c: 'Compose', p: { key: 'new', label: 'New', icon: 'plus', send: 'Post', fields: [{ name: 'title', kind: 'line', label: 'Title', max: 100 }], writes: { create: 'test.post' } } };
/** A screen whose Bar has a + for the action's form and a gear that opens a screen. */
const BARRED = {
v: 1,
trusted: true,
root: {
c: 'Stack',
k: [
{ c: 'Bar', k: [FORM, { c: 'Link', p: { label: 'My feeds', icon: 'settings', open: { call: query('test.settings') } } }] },
{ c: 'Text', p: { runs: [{ text: 'A feed' }], style: 'body' } }
]
}
};
/** A feed with Home's strip, as Grain's feeds have it: Home's root, Following and a pinned camera, the one drawn `selected` (none, a camera not pinned). */
const STRIPPED = (selected, words) => ({
v: 1,
trusted: true,
root: {
c: 'Stack',
k: [
{
c: 'Tabs',
p: {
style: 'strip',
items: [
{ label: 'For You', open: { call: FEED }, selected: selected === FEED },
{ label: 'Following', open: { call: FOLLOWING }, selected: selected === FOLLOWING },
{ label: 'X100V', open: { call: PINNED }, selected: selected === PINNED }
]
}
},
{ c: 'Text', p: { runs: [{ text: words }], style: 'body' } }
]
}
});
/** One of the app's own pages, as HUD's `describe_app` of it draws it: its title in a Bar over its Markdown's blocks, its head its own, a link to another page on the app's site. */
const pageCall = (path) => ({ name: 'describe_app', args: { domain: 'app.test', page: path } });
const pageTree = (title, words) => ({
v: 1,
trusted: true,
title,
head: { title: `${title} - Test`, description: `The ${title.toLowerCase()}.`, canonical: `/${title.toLowerCase()}` },
root: {
c: 'Stack',
p: { gap: 'md' },
k: [
{ c: 'Bar', p: { title } },
{
c: 'RichText',
p: {
blocks: [
{ kind: 'heading', level: 2, runs: [{ text: 'Overview' }] },
{ kind: 'paragraph', runs: [{ text: `${words} See the ` }, { text: 'privacy policy', link: 'https://app.test/privacy' }, { text: '.' }] }
]
}
}
]
}
});
const TERMS = pageCall('/terms');
const answered = (ui) => ({ result: { _meta: { ui } } });
const HOST = { endpoints: { mcp: '/api/mcp', upload: '/api/upload' }, signIn: '/auth/signin', signOut: '/auth/signout' };
/** A history that makes its entries in a list, and runs `entered` where `browser` says it hydrates. */
function history(browser) {
const made = [];
return {
made,
navigation: { here: undefined, go: async (url, state, replace) => void made.push({ url, tab: state.tab, replace }), entered: (run) => browser && queueMicrotask(run) }
};
}
/** The pages drawn: signed out and in, the feed (content), a wide profile, a screen with a Bar whose + is the action's form (`twin`), and the sign-in screen. */
const PAGES = [
{ name: 'feed signed out', signedIn: false, path: '/', ui: tree('feed'), measure: 'content' },
{ name: 'feed signed in', signedIn: true, path: '/', ui: tree('feed'), measure: 'content' },
{ name: 'profile wide', signedIn: true, path: '/profile/me', ui: { ...tree('profile'), measure: 'wide' }, measure: 'wide', tab: 3 },
{ name: 'a Bar with the action signed in', signedIn: true, path: '/', ui: BARRED, measure: 'content', twin: true },
{ name: 'Following, a swap of Home', signedIn: true, path: '/feeds/following', ui: STRIPPED(FOLLOWING, 'The following feed'), measure: 'content', calls: [FOLLOWING], strip: true },
{ name: "a wide pinned camera in Home's root place", signedIn: true, path: '/camera/X100V', ui: { ...STRIPPED(PINNED, 'The following feed'), measure: 'wide' }, measure: 'content', calls: [PINNED], strip: true, rootMeasure: 'content' },
{ name: "the app's own page, its terms, over Home", signedIn: false, path: '/terms', ui: pageTree('Terms', 'The terms of using Test.'), measure: 'content', calls: [FEED, TERMS], page: true },
{ name: 'Home at the first feed pinned, Following', signedIn: true, path: '/', ui: STRIPPED(FOLLOWING, 'The following feed'), measure: 'content', calls: [FOLLOWING], roots: rootsWith(FOLLOWING), strip: true },
{ name: 'the sign-in screen', signedIn: false, path: '/auth/signin?back=%2Fprofile%2Fme', measure: 'content', signIn: SIGN_IN }
];
const props = (page, navigation) => ({
app: APP,
host: HOST,
navigation,
screen: page.signIn
? { tab: -1, calls: [], top: null, aside: answered(ASIDE), names: [], missing: false, signIn: page.signIn }
: { tab: page.tab ?? 0, calls: page.calls ?? [page.tab === 3 ? PROFILE : FEED], top: answered(page.ui), aside: answered(ASIDE), names: [], missing: false, ...(page.roots ? { roots: page.roots } : {}), ...(page.rootMeasure ? { measure: page.rootMeasure } : {}) },
under: null,
signedIn: page.signedIn,
origin: 'https://app.test',
path: page.path,
now: NOW,
counts: page.signedIn ? Promise.resolve({ 2: 3 }) : null,
picture: page.signedIn ? 'https://cdn.test/me.jpg' : 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)}…`;
}
/** The value a custom property has at the window's width, by the frame stylesheet's media rules that match (the last that sets it), on `selector`. */
function valueAt(css, property, selector, matches) {
let found = null;
for (const [, media, body] of css.matchAll(/@media ([^{]+)\{((?:[^{}]*\{[^{}]*\})*)\}/g)) {
if (!matches(media)) continue;
for (const [, on, rule] of body.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
if (on.trim() !== selector) continue;
const set = new RegExp(`${property}:([^;}]+)`).exec(rule);
if (set) found = set[1];
}
}
return found;
}
/** Whether a width matches a media query of min-width and max-width alone. */
const matchesAt = (width) => (media) =>
[...media.matchAll(/\((min|max)-width: ([\d.]+)px\)/g)].every(([, side, px]) => (side === 'min' ? width >= Number(px) : width <= Number(px)));
/** Each width, the band it is drawn in (the navigation's width) and whether the feed's aside shows. */
const WIDTHS = [
{ width: 390, nav: '0px', aside: null },
{ width: 900, nav: '72px', aside: null },
{ width: 1440, nav: '245px', aside: '320px' }
];
try {
// 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' } } }
});
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' } }
});
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);
// The frame's bands and its aside, by the stylesheet's media rules at each width.
const css = server.frameCss(server.layoutOf(APP.frame));
for (const { width, nav, aside } of WIDTHS) {
const at = matchesAt(width);
const drawn = valueAt(css, '--hud-frame-nav', ':root', at);
if (drawn !== nav) problems.push(`at ${width}: the navigation is ${drawn}, not ${nav}`);
const shown = valueAt(css, '--hud-frame-aside-shown', '.hud-frame[data-measure="content"]', at);
if (shown !== aside) problems.push(`at ${width}: the aside beside the column is ${shown ?? 'not shown'}, not ${aside ?? 'not shown'}`);
if (valueAt(css, '--hud-frame-aside-shown', '.hud-frame[data-measure="wide"]', at) !== null) problems.push(`at ${width}: the aside is shown beside a wide screen, where it never fits`);
}
say('the frame is a bar at 390, a rail at 900 and a sidebar at 1440, the aside beside the column at 1440 alone');
// The account's own profile by its handle is the Profile tab at its root, not a profile pushed over Home; another's is pushed over Home.
const caller = {
call: async (name, args) => ({ _meta: { ui: ASIDE, viewer: { did: 'did:plc:me', handle: 'me.test' } }, structuredContent: { name, args } }),
resolve: async (actor) => actor
};
const own = (await server.screenAt(APP, new URL('https://app.test/profile/me.test'), caller, true)).screen;
if (own.tab !== 3 || JSON.stringify(own.calls) !== JSON.stringify([PROFILE])) problems.push(`the account's own profile is drawn on tab ${own.tab} as ${JSON.stringify(own.calls)}, not the Profile tab's root`);
const other = (await server.screenAt(APP, new URL('https://app.test/profile/bob.test'), caller, true)).screen;
if (other.tab !== 0 || other.calls.length !== 2) problems.push(`another's profile is drawn on tab ${other.tab} as ${JSON.stringify(other.calls)}, not over Home`);
say("the account's own profile, loaded, is the Profile tab at its root; another's is over Home");
// A feed Home's strip offers, and selects, is Home's root level in its root's place (no back, its strip shown), whatever its route's tab; one the strip does not select is pushed over its route's tab.
const feeds = (ui) => ({ call: async () => ({ _meta: { ui } }), resolve: async (actor) => actor });
const swaps = [
['/feeds/following', STRIPPED(FOLLOWING, 'Following'), 0, [FOLLOWING]],
['/camera/X100V', STRIPPED(PINNED, 'X100V'), 0, [PINNED]],
['/camera/GR', STRIPPED(null, 'GR'), 1, [query('test.explore'), UNPINNED]]
];
for (const [path, ui, tab, calls] of swaps) {
const at = (await server.screenAt(APP, new URL(`https://app.test${path}`), feeds(ui), true)).screen;
if (at.tab !== tab || JSON.stringify(at.calls) !== JSON.stringify(calls)) problems.push(`${path} is drawn on tab ${at.tab} as ${JSON.stringify(at.calls)}, not on tab ${tab} as ${JSON.stringify(calls)}`);
}
say("a feed Home's strip selects is Home's root level, pinned or not by its route; one it does not is pushed");
// In a tab's root's place, a screen is as wide as that root, whatever its own view asks: a wide camera feed under Home's strip at Home's reading width; pushed, at its own.
const wide = { ...STRIPPED(PINNED, 'X100V'), measure: 'wide' };
const byFeed = { call: async (name, args) => ({ _meta: { ui: args.params?.feed === 'home' ? STRIPPED(FEED, 'Home') : args.params?.camera === 'GR' ? { ...STRIPPED(null, 'GR'), measure: 'wide' } : wide } }), resolve: async (actor) => actor };
const kept = (await server.screenAt(APP, new URL('https://app.test/camera/X100V'), byFeed, true)).screen;
if (kept.measure !== 'content') problems.push(`a wide camera feed in Home's root place keeps ${kept.measure}, not Home's content`);
const pushed = (await server.screenAt(APP, new URL('https://app.test/camera/GR'), byFeed, true)).screen;
if (pushed.measure !== undefined) problems.push(`a camera feed pushed over Explore keeps ${pushed.measure}, not its own`);
say("a screen in a tab's root's place keeps the root's measure; one pushed has its own");
// Signed in, Home's root is the first pinned path with a screen (its `first`), at `/` from the first paint: Following first, then reordered, Home's own path first; a camera first, its feed, at `/` as Home's root. Signed out, or the preferences failing, Home's call.
const methods = [];
const pinning = (paths, failing = false) => ({
call: async (name, args) => {
methods.push(args.method);
if (args.method === PREFS.args.method) {
if (failing) throw new Error('refused');
return { structuredContent: { response: { preferences: [{ $type: 'test.actor.defs#themePref' }, { $type: 'test.actor.defs#pinnedFeedsPref', items: paths.map((path) => ({ path })) }] } } };
}
const feed = query(args.method, args.params);
return { _meta: { ui: feed.args.params.camera ? { ...STRIPPED(feed.args.params.camera === 'X100V' ? PINNED : null, 'A camera'), measure: 'wide' } : STRIPPED(feed.args.params.feed === 'following' ? FOLLOWING : FEED, 'A feed') } };
},
resolve: async (actor) => actor
});
const homes = [
['/', ['/groups', '/feeds/following', '/'], true, false, 0, [FOLLOWING], FOLLOWING],
['/', ['/', '/feeds/following'], true, false, 0, [FEED], FEED],
['/', ['/camera/X100V', '/feeds/following'], true, false, 0, [PINNED], PINNED],
['/', ['/feeds/following'], false, false, 0, [FEED], FEED],
['/', ['/feeds/following'], true, true, 0, [FEED], FEED],
['/camera/X100V', ['/feeds/following'], true, false, 0, [PINNED], FOLLOWING],
['/camera/X100V', ['/camera/X100V'], true, false, 0, [PINNED], PINNED],
['/feeds/following', ['/feeds/following'], true, false, 0, [FOLLOWING], FOLLOWING]
];
for (const [path, paths, signedIn, failing, tab, calls, root] of homes) {
methods.length = 0;
const { screen, status } = await server.screenAt(APP, new URL(`https://app.test${path}`), pinning(paths, failing), signedIn);
const named = `${path} with ${JSON.stringify(paths)} pinned${signedIn ? '' : ', signed out'}${failing ? ', the preferences failing' : ''}`;
if (status !== 200 || screen.tab !== tab || JSON.stringify(screen.calls) !== JSON.stringify(calls)) problems.push(`${named} is drawn on tab ${screen.tab} as ${JSON.stringify(screen.calls)}, not on tab ${tab} as ${JSON.stringify(calls)}`);
if (JSON.stringify(screen.roots) !== JSON.stringify(signedIn ? rootsWith(root) : APP.tabs.map((t) => (t.guest === 'call' ? t.call : (t.guest ?? null))))) problems.push(`${named} carries the roots ${JSON.stringify(screen.roots)}`);
if (methods.includes(PREFS.args.method) !== signedIn) problems.push(`${named}: the preferences were ${signedIn ? 'not ' : ''}asked`);
}
const under = (await server.screenAt(APP, new URL('https://app.test/camera/X100V'), pinning(['/feeds/following']), true)).screen;
if (under.measure !== 'content') problems.push(`a wide camera feed in the place of Home's chosen root, Following, keeps ${under.measure}, not Following's content`);
const camera = (await server.screenAt(APP, new URL('https://app.test/'), pinning(['/camera/X100V']), true)).screen;
if (camera.measure !== undefined) problems.push(`a camera feed chosen as Home's root keeps ${camera.measure}, not its own`);
say("Home's root is the first pinned path with a screen, at / from the first paint, and the strip's feeds are in its place");
// What a tab's first chooses of what is listed: a path of the app's own alone, its own URL its call, any other by its routes.
const firstOf = (paths, tab = APP.tabs[0]) => server.chosenRoot(APP, tab, { preferences: [{ $type: 'pinnedFeedsPref', items: paths.map((path) => ({ path })) }] }, async (actor) => actor);
const chosen = [
[['//evil.test/feeds/following', '/\\evil.test/feeds/following', 'https://evil.test/feeds/following', 'feeds/following', 5], null],
[['/?utm_source=x'], FEED],
[['/camera/Fuji%20X100V'], query('test.feed.getFeed', { feed: 'camera', camera: 'Fuji X100V' })],
[['/camera/Fuji X100V'], query('test.feed.getFeed', { feed: 'camera', camera: 'Fuji X100V' })],
[[], null]
];
for (const [paths, want] of chosen) {
const got = await firstOf(paths);
if (JSON.stringify(got) !== JSON.stringify(want)) problems.push(`${JSON.stringify(paths)} pinned chooses ${JSON.stringify(got)}, not ${JSON.stringify(want)}`);
}
if ((await firstOf(['/feeds/following'], APP.tabs[1])) !== null) problems.push('a tab with no first chose a root');
say("a tab's first chooses only the app's own paths, its own URL its call");
// An app's own page, by its path: its describe_app over Home's root, as a screen of any route is; a path no page or route has, nothing.
const terms = await server.screenAt(APP, new URL('https://app.test/terms'), feeds(pageTree('Terms', 'Terms')), false);
if (terms.status !== 200 || terms.screen.tab !== 0 || JSON.stringify(terms.screen.calls) !== JSON.stringify([FEED, TERMS])) problems.push(`/terms is drawn on tab ${terms.screen.tab} as ${JSON.stringify(terms.screen.calls)}, not the page's describe_app over Home`);
const none = await server.screenAt(APP, new URL('https://app.test/cookies'), feeds(ASIDE), false);
if (none.status !== 404) problems.push(`/cookies, no page's or route's, answers ${none.status}, not 404`);
say("an app's own page, loaded, is its describe_app over Home; a path nothing has is not found");
// The sign-in screen, by its URL: where it comes back to (a path of this origin, else home), the handle and why it was sent back with.
const asked = server.signInScreen(new URL('https://app.test/auth/signin?back=%2Fprofile%2Fme&handle=nobody.test&error=Nope'));
if (JSON.stringify(asked.signIn) !== JSON.stringify({ back: '/profile/me', handle: 'nobody.test', error: 'Nope' }) || asked.tab !== -1 || asked.calls.length) problems.push(`the sign-in screen is read as ${JSON.stringify(asked)}`);
const evil = server.signInScreen(new URL('https://app.test/auth/signin?back=javascript:alert(1)'), { handle: 'a.test', error: 'Refused' }).signIn;
if (JSON.stringify(evil) !== JSON.stringify({ back: '/', handle: 'a.test', error: 'Refused' })) problems.push(`the sign-in screen, off the origin and posted, is read as ${JSON.stringify(evil)}`);
say('the sign-in screen comes back to a path of its own origin, saying what it was sent back with');
const drawn = [];
for (const page of PAGES) {
let result;
try {
result = server.render(server.Shell, { props: props(page, history(false).navigation) });
} catch (e) {
problems.push(`${page.name}: drawing it threw: ${e.stack}`);
continue;
}
if (!result.body.includes(`data-measure="${page.measure}"`)) problems.push(`${page.name}: the frame is not drawn at its screen's measure, ${page.measure}`);
if (!result.head.includes('--hud-frame-nav:245px')) problems.push(`${page.name}: the head has no frame stylesheet`);
if (result.body.includes('>Create</span>') !== page.signedIn) problems.push(`${page.name}: the action is ${page.signedIn ? 'not drawn signed in' : 'drawn signed out'}`);
if (result.body.includes('Share your photography') === page.signedIn) problems.push(`${page.name}: signing in is ${page.signedIn ? 'offered signed in' : 'not offered signed out'}`);
if (!result.body.includes('Beside the column')) problems.push(`${page.name}: the aside the server answered is not drawn`);
if (page.signedIn && !result.body.includes('src="https://cdn.test/me.jpg"')) problems.push(`${page.name}: the account's picture is not drawn by the server`);
if (page.strip && (result.body.includes('aria-label="Back"') || !result.body.includes('The following feed') || !result.body.includes('X100V'))) problems.push(`${page.name}: not drawn as Home's root with its strip and no back`);
if (page.page) {
if (!result.body.includes('<h2') || !result.body.includes('The terms of using Test.') || !result.body.includes('href="https://app.test/privacy"')) problems.push(`${page.name}: its Markdown is not drawn by the server`);
for (const tag of ['<title>Terms - Test</title>', 'name="description" content="The terms."', 'rel="canonical" href="https://app.test/terms"', 'name="robots" content="max-image-preview:large"'])
if (!result.head.includes(tag)) problems.push(`${page.name}: its head has no ${tag}`);
}
if (page.signIn) {
for (const part of [
/Log in with your atmosphere account/,
/href="https:\/\/atmosphereaccount\.com\/" target="_blank"/,
/method="post" action="\/auth\/signin"/,
/name="back" value="\/profile\/me"/,
/name="handle"/,
/value="nobody\.test"/,
/placeholder="e\.g\. user\.bsky\.social"/,
/role="alert">nobody\.test does not resolve to an account/,
/<a href="\/terms"[^>]*>Terms<\/a>/,
/class="cancel[^"]*" href="\/profile\/me"/,
/name="create" value="1"/
])
if (!part.test(result.body)) problems.push(`${page.name}: the server did not draw ${part}`);
if (!result.body.includes('href="/auth/signin?back=%2Fprofile%2Fme"')) problems.push(`${page.name}: its navigation's Sign in does not come back where the screen does`);
for (const tag of ['<title>Sign in · Test</title>', 'name="robots" content="noindex"'])
if (!result.head.includes(tag)) problems.push(`${page.name}: its head has no ${tag}`);
}
drawn.push({ page, head: result.head, body: result.body });
say(`${page.name}: drawn`);
}
const { Window } = await import('happy-dom');
const window = new Window({ url: 'https://app.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, location: window.location });
const built = pathToFileURL(join(out, 'client', readdirSync(join(out, 'client')).find((f) => /^client\.m?js$/.test(f)))).href;
let loads = 0;
for (const { page, head, body } of drawn) {
for (const { width } of WIDTHS) {
// Each a page loaded afresh: its own modules, whose clock no tree mounted before has settled.
const client = await import(`${built}?load=${loads++}`);
window.happyDOM.setViewport({ width, height: 900 });
const name = `${page.name} at ${width}`;
document.head.innerHTML = head;
const target = document.createElement('div');
document.body.replaceChildren(target);
target.innerHTML = body;
const before = target.innerHTML.replaceAll(/ on(load|error)="this\.__e=event"/g, '');
const headBefore = document.head.innerHTML;
const said = [];
const { warn, error } = console;
console.warn = console.error = (...args) => said.push(args.map(String).join(' '));
const { made, navigation } = history(true);
let app;
try {
app = client.hydrate(client.Shell, { target, props: props(page, navigation) });
} catch (e) {
said.push(`threw: ${e.stack}`);
} finally {
console.warn = warn;
console.error = error;
}
const after = target.innerHTML;
const headAfter = document.head.innerHTML;
await new Promise((done) => setTimeout(done, 0));
// A screen over its tab's root is entered as two entries, the root's and its own, so its back goes to the root.
const first = (page.calls?.length ?? 1) > 1 ? '/' : page.path;
// The sign-in screen makes no entry: its form and links load pages anew.
if (page.signIn && made.length) problems.push(`${name}: it made history entries, ${JSON.stringify(made)}`);
if (!page.signIn && (made[0]?.url !== first || made[0]?.replace !== true)) problems.push(`${name}: its first history entry is ${JSON.stringify(made[0])}, not ${first}`);
if (first !== page.path) {
await new Promise((done) => setTimeout(done, 20));
if (made.at(-1)?.url !== page.path) problems.push(`${name}: its last history entry is ${JSON.stringify(made.at(-1))}, not the page's own, ${page.path}`);
}
if (page.twin) {
const shown = (element) => element !== null && window.getComputedStyle(element).display !== 'none';
const bar = target.querySelector('.stack:not([hidden]) .tools');
const plus = bar?.querySelector('button[data-bar-form="New"]') ?? null;
const gear = bar?.querySelector('[aria-label="My feeds"], [title="My feeds"]') ?? null;
if (!plus) problems.push(`${name}: the Bar's + is not drawn`);
else if (shown(plus) !== (width < 600)) problems.push(`${name}: the Bar's + is ${shown(plus) ? 'shown beside the action' : 'hidden with no action beside it'}`);
if (!shown(gear)) problems.push(`${name}: the Bar's gear is not shown`);
else say(`${name}: the gear shown, the + ${width < 600 ? 'shown' : 'hidden, the action beside it'}`);
}
if (app) client.unmount(app);
for (const s of said) problems.push(`${name}: hydrating it: ${s}`);
if (after !== before) problems.push(`${name}: hydrated, it changed:\n ${difference(before, after)}`);
if (!headAfter.includes(headBefore.match(/<style>[^<]*<\/style>/)?.[0] ?? '')) problems.push(`${name}: hydrated, the head's frame stylesheet changed`);
say(`${name}: hydrated as drawn`);
}
}
// The sign-in screen in the browser, its typeahead a fake: what is
// typed is asked of it at its own host; the arrows choose an account
// and Enter picks it, filling in the handle and sending the form; a
// picture that fails falls back, then goes; Escape closes the list.
{
const client = await import(`${built}?load=${loads++}`);
const fetched = [];
const fetchWas = globalThis.fetch;
globalThis.fetch = async (url) => {
fetched.push(String(url));
return Response.json({ actors: [{ did: 'did:plc:chad', handle: 'chadtmiller.com', displayName: 'Chad', avatar: 'https://cdn.test/chad.jpg', avatarFallback: 'https://pds.test/chad.jpg' }, { did: 'did:plc:zds', handle: 'zds.chadtmiller.com' }] });
};
const target = document.createElement('div');
document.body.replaceChildren(target);
const page = { ...PAGES.at(-1), signIn: { back: '/', handle: '', error: null } };
const app = client.mount(client.Shell, { target, props: props(page, history(true).navigation) });
const until = async (ok, what) => {
for (let i = 0; i < 100 && !ok(); i++) await new Promise((done) => setTimeout(done, 10));
if (!ok()) throw new Error(`never: ${what}`);
};
const options = () => [...target.querySelectorAll('[role="option"]')];
const key = (input, name) => input.dispatchEvent(new window.KeyboardEvent('keydown', { key: name, bubbles: true, cancelable: true }));
try {
const input = target.querySelector('input[name="handle"]');
const form = input.form;
const sent = [];
form.addEventListener('submit', (event) => {
event.preventDefault();
sent.push(new window.FormData(form).get('handle'));
});
input.focus();
input.value = 'chadtm';
input.dispatchEvent(new window.Event('input', { bubbles: true }));
await until(() => options().length === 2, 'two accounts suggested');
if (fetched[0] !== 'https://typeahead.test/xrpc/test.typeahead.searchActors?limit=5&q=chadtm') problems.push(`the sign-in screen asked ${fetched[0]}`);
const picture = () => options()[0].querySelector('img');
if (picture()?.getAttribute('src') !== 'https://cdn.test/chad.jpg' || !options()[0].textContent.includes('@chadtmiller.com') || !options()[0].textContent.includes('Chad')) problems.push(`the first suggestion is drawn as ${options()[0].outerHTML}`);
picture().dispatchEvent(new window.Event('error'));
await until(() => picture()?.getAttribute('src') === 'https://pds.test/chad.jpg', 'the fallback picture');
picture().dispatchEvent(new window.Event('error'));
await until(() => !picture(), 'no picture once both failed');
key(input, 'ArrowDown');
key(input, 'ArrowDown');
key(input, 'ArrowUp');
await until(() => options()[0]?.getAttribute('aria-selected') === 'true', 'the first chosen');
key(input, 'Enter');
await until(() => sent.length === 1, 'the form sent');
if (sent[0] !== 'chadtmiller.com' || input.value !== 'chadtmiller.com' || options().length) problems.push(`picked, the form sent ${sent[0]} with ${input.value} in the field and ${options().length} suggestions left`);
input.value = 'zds';
input.dispatchEvent(new window.Event('input', { bubbles: true }));
await until(() => options().length === 2, 'suggested again');
key(input, 'Escape');
await until(() => options().length === 0, 'Escape closed the list');
if (sent.length !== 1) problems.push(`Escape sent the form`);
say('the sign-in screen suggests accounts as a handle is typed, picked by the arrows and Enter, a picture falling back');
} catch (e) {
problems.push(`the sign-in screen: ${e.message}`);
} finally {
client.unmount(app);
globalThis.fetch = fetchWas;
}
}
// Signed in, against a fake server: the action's form, and a screen
// opened at a form, open it once.
const client = await import(`${built}?load=${loads++}`);
const WRITE = { name: 'query', args: { method: 'test.stories', params: {}, compose: true } };
const POST = 'at://did:plc:me/test.post/1';
// Another account's post, its handle unknown until its answer says it.
const THEIR_POST = { name: 'query', args: { method: 'test.getPost', params: { post: 'at://did:plc:them/test.post/2' } } };
// Another's gallery: a screen with pictures, as a profile's or a gallery's.
const THEIR_GALLERY = { name: 'query', args: { method: 'test.getGallery', params: { gallery: 'at://did:plc:them/test.gallery/3' } } };
const picture = (n) => ({ src: { src: `https://cdn.test/${n}.jpg`, fallback: null }, alt: '', ratio: 1, srcset: `https://cdn.test/${n}-600.jpg 600w, https://cdn.test/${n}.jpg 1200w` });
// Who has stories, as a strip whose items open a pager: one's own, none yet, opened at its form (Your story's `compose`), then another's.
const YOURS = { name: 'query', args: { method: 'test.story.get', params: { actor: 'did:plc:me' }, compose: true } };
const THEIRS = { name: 'query', args: { method: 'test.story.get', params: { actor: 'did:plc:gabriel' } } };
const ADD = { c: 'Compose', p: { key: 'add', label: 'Add to your story', icon: 'plus', send: 'Share', fields: [{ name: 'title', kind: 'line', label: 'Title', max: 100 }], writes: { create: 'test.story' } } };
const STRIP = {
c: 'List',
p: { style: 'strip', pages: true },
items: [
{ open: { call: YOURS }, k: [{ c: 'Text', p: { runs: [{ text: 'Your story' }], style: 'body' } }] },
{ open: { call: THEIRS }, k: [{ c: 'Text', p: { runs: [{ text: "Gabriel's story" }], style: 'body' } }] }
]
};
/** Whether one has stories of one's own: none at first, so Your story opens at its form. */
let mine = false;
const storiesOf = ({ params, compose }) =>
params.actor !== 'did:plc:me'
? { v: 1, trusted: true, root: { c: 'Text', p: { runs: [{ text: 'Gabriel at the lake' }], style: 'body' } } }
: mine
? { v: 1, trusted: true, root: { c: 'Text', p: { runs: [{ text: 'My story at the beach' }], style: 'body' } } }
: { v: 1, trusted: true, root: { c: 'Slides', p: { empty: 'No stories right now' }, items: [], k: [compose ? { ...ADD, p: { ...ADD.p, open: true } } : ADD] } };
const screenOf = (words, opened) => ({
v: 1,
trusted: true,
root: {
c: 'Stack',
k: [
{ c: 'Bar', k: [opened ? { ...FORM, p: { ...FORM.p, open: true } } : FORM] },
{ c: 'Text', p: { runs: [{ text: words }], style: 'body' } },
{ c: 'Link', p: { label: 'Write one', open: { call: WRITE } } },
{ c: 'Link', p: { label: 'My profile', open: { call: { name: 'describe_app', args: { domain: 'app.test', actor: 'did:plc:me' } } } } },
{ c: 'Link', p: { label: 'Their post', open: { call: THEIR_POST } } },
{ c: 'Link', p: { label: 'Their gallery', open: { call: THEIR_GALLERY } } },
{ c: 'Link', p: { label: 'A long feed', open: { call: PAGED } } },
STRIP
]
}
});
// A feed of three pages, five items each, its foot a "Load more" that pages as it comes into view; a link on it opens a screen over it.
const PAGED = query('test.paged');
/** Whether the feed's pages fail, as a server down does. */
let pagesFail = false;
const pagedOf = (cursor) => ({
v: 1,
trusted: true,
root: {
c: 'Stack',
k: [
{ c: 'Link', p: { label: 'Their post', open: { call: THEIR_POST } } },
{ c: 'List', p: { page: true }, items: Array.from({ length: 5 }, (_, i) => ({ k: [{ c: 'Text', p: { runs: [{ text: `Item ${cursor}.${i}` }], style: 'body' } }] })) }
]
},
...(cursor < 2 ? { next: query('test.paged', { cursor: cursor + 1 }) } : {})
});
const calls = [];
const answer = ({ name, args }) => {
if (name === 'apply_writes') return { structuredContent: { results: [{ uri: POST, cid: 'c' }] } };
if (args.method === 'test.getPost') {
const author = args.params.post.startsWith('at://did:plc:them/') ? { author: { did: 'did:plc:them', handle: 'them.test' } } : {};
return { structuredContent: author, _meta: { ui: { v: 1, trusted: true, root: { c: 'Text', p: { runs: [{ text: `The post ${args.params.post}` }], style: 'body' } } } } };
}
if (args.method === 'test.paged') {
const cursor = args.params.cursor ?? 0;
if (cursor > 0 && pagesFail) return { isError: true, content: [{ type: 'text', text: 'The feed is down.' }] };
return { _meta: { ui: pagedOf(cursor) } };
}
if (args.method === 'test.getGallery')
return { _meta: { ui: { v: 1, trusted: true, root: { c: 'Stack', k: [{ c: 'Bar', p: { title: 'Their gallery' } }, { c: 'Gallery', p: { style: 'stack' }, items: [picture(1), picture(2)] }] } } } };
if (args.method === 'test.story.get') return { _meta: { ui: storiesOf(args), viewer: { did: 'did:plc:me', handle: 'me.test' } } };
if (args.method === 'test.feed.getFeed' || args.method === 'test.stories') return { _meta: { ui: screenOf(args.method, args.compose !== undefined), viewer: { did: 'did:plc:me', handle: 'me.test' } } };
if (name === 'describe_app' && args.page) return { _meta: { ui: pageTree(args.page === '/terms' ? 'Terms' : 'Privacy', `The page ${args.page}.`) } };
if (name === 'describe_app') return { _meta: { ui: { v: 1, trusted: true, root: { c: 'Text', p: { runs: [{ text: `Profile of ${args.actor}` }], style: 'body' } } } } };
return { structuredContent: {} };
};
globalThis.fetch = async (_, init) => {
const made = JSON.parse(init.body);
calls.push(made);
return new Response(JSON.stringify(answer(made)), { status: 200, headers: { 'Content-Type': 'application/json' } });
};
const target = document.createElement('div');
document.body.replaceChildren(target);
const page = PAGES[1];
const start = (history) => {
const base = props(page, history.navigation);
return client.mount(client.Shell, { target, props: { ...base, screen: { ...base.screen, top: answered(screenOf('test.feed.getFeed', false)) } } });
};
const settle = () => new Promise((done) => setTimeout(done, 60));
const until = async (ok, what) => {
for (let i = 0; i < 100 && !ok(); i++) await new Promise((done) => setTimeout(done, 20));
if (!ok()) throw new Error(`never: ${what}`);
};
const form = () => target.querySelector('dialog.composer');
const levels = () => target.querySelectorAll('.stack:not([hidden]) > section.level').length;
const cancel = async () => {
[...form().querySelectorAll('button')].find((button) => button.textContent.trim() === 'Cancel').click();
await until(() => !form(), 'Cancel closed the form');
};
const opening = () => calls.filter((call) => call.args.compose !== undefined).length;
let app;
try {
let history = new client.History();
app = start(history);
await until(() => history.entries.length === 1 && levels() === 1, 'the page made its first history entry');
target.querySelector('.side .action').click();
await until(form, "Create opened the action's form");
if (levels() !== 1) problems.push(`Create pushed a screen: ${levels()} levels`);
if (history.entries.length !== 1) problems.push(`Create made a history entry: ${JSON.stringify(history.entries.map((e) => e.url))}`);
if (!target.querySelector('.stack:not([hidden]) > section.level').textContent.includes('test.feed.getFeed')) problems.push("Create's form is not over the screen it was on");
await cancel();
say("Create drew the action's form over the screen on show, and Cancel closed it");
// A link read ahead (pressed, as a phone's are as they show) whose answer teaches a handle opens at once, at that handle's URL, though
// the router sets its state only once its move settles: the answer lands first, and the entry the shell made stays.
const theirs = () => [...target.querySelectorAll('.stack:not([hidden]) a')].find((link) => link.textContent.includes('Their post'));
theirs().dispatchEvent(new window.PointerEvent('pointerdown', { bubbles: true, isPrimary: true, pointerType: 'touch' }));
await until(() => calls.some((call) => call.args.params?.post === THEIR_POST.args.params.post), 'their post read ahead');
await settle();
theirs().click();
await until(() => levels() === 2 && target.textContent.includes(`The post ${THEIR_POST.args.params.post}`), 'their post, read ahead, opened on the first click');
await settle();
const urls = history.entries.map((entry) => entry.url);
if (urls.join() !== '/,/profile/them.test/post/2' || history.at !== 1) problems.push(`their post, read ahead, left the entries ${JSON.stringify(urls)} at ${history.at}, not / and /profile/them.test/post/2 at 1`);
if (levels() !== 2) problems.push(`their post, read ahead, is not on screen: ${levels()} levels`);
history.go(-1);
await until(() => levels() === 1, 'back from their post, Home');
say('a link read ahead whose answer teaches a handle opens on the first click, at its handle\'s URL');
// A screen pushed and gone back from, as a link tapped opens it: focus moves into it (at its title) and comes back to the link; the
// screen under it is inert, never aria-hidden (which a browser refuses over the focused link); and a picture of the screen let go that
// loads after (an <img> keeps loading once taken out) reads nothing of it (Svelte's derived_inert).
const warned = [];
const { warn } = console;
console.warn = (...args) => void warned.push(args.map(String).join(' '));
try {
const link = [...target.querySelectorAll('.stack:not([hidden]) a')].find((each) => each.textContent.includes('Their gallery'));
link.focus();
link.click();
await until(() => levels() === 2 && target.querySelector('.stack:not([hidden]) > section.level:last-child img'), 'their gallery opened');
await settle();
const [under, top] = target.querySelectorAll('.stack:not([hidden]) > section.level');
if (!under.hasAttribute('inert') || under.hasAttribute('aria-hidden')) problems.push(`pushed, the screen under is drawn ${under.outerHTML.slice(0, 120)}, not inert alone`);
if (!top.contains(document.activeElement)) problems.push(`pushed, focus is on ${document.activeElement?.outerHTML.slice(0, 80)}, not in the screen on top`);
const pictures = [...top.querySelectorAll('img')];
history.go(-1);
await until(() => levels() === 1, 'back from their gallery, Home');
await settle();
if (document.activeElement !== link) problems.push(`gone back, focus is on ${document.activeElement?.outerHTML.slice(0, 80)}, not the link that opened the screen`);
// Gone forward to, it is drawn as it last was while its call is made again, then the answer in its place; gone back from once
// more, its pictures loading late read nothing of it either.
const asked = () => calls.filter((call) => call.args.method === 'test.getGallery').length;
const before = asked();
history.go(1);
await until(() => levels() === 2 && asked() > before && !target.querySelector('.stack:not([hidden]) > section.level[aria-busy="true"]'), 'forward, their gallery made again');
await settle();
pictures.push(...target.querySelectorAll('.stack:not([hidden]) > section.level:last-child img'));
history.go(-1);
await until(() => levels() === 1, 'back from their gallery again, Home');
for (const img of pictures) for (const type of ['load', 'error']) img.dispatchEvent(new window.Event(type));
await settle();
} finally {
console.warn = warn;
}
for (const said of warned) problems.push(`a screen pushed and gone back from: ${said}`);
say('a screen pushed and gone back from: focus moved into it and back, the screen under was inert, its pictures loading late warned nothing');
// A long feed pages itself as its foot comes within a screen of view, once a page, and never while a screen is over it or after a
// page failed, until Try again is pressed. The browser's IntersectionObserver a fake here, its foot shown when the test says.
{
const watching = new Set();
const Observer = globalThis.IntersectionObserver;
globalThis.IntersectionObserver = class {
constructor(seen, options) {
Object.assign(this, { seen, options, watched: new Set() });
}
observe(element) {
this.watched.add(element);
watching.add(this);
}
unobserve(element) {
this.watched.delete(element);
}
disconnect() {
this.watched.clear();
watching.delete(this);
}
takeRecords() {
return [];
}
};
/** The feed's foot, scrolled within a screen of view: each observer watching it told so. */
const footShown = () => {
for (const observer of [...watching])
for (const element of [...observer.watched]) if (element.classList.contains('more')) observer.seen([{ target: element, isIntersecting: true }], observer);
};
const pages = (cursor) => calls.filter((call) => call.args.method === 'test.paged' && (call.args.params.cursor ?? 0) === cursor).length;
const foot = () => target.querySelector('.stack:not([hidden]) > section.level:last-child .more');
const drawn = (text) => target.querySelector('.stack:not([hidden]) > section.level:last-child')?.textContent.includes(text);
try {
[...target.querySelectorAll('.stack:not([hidden]) :is(a, button)')].find((each) => each.textContent.includes('A long feed')).click();
await until(() => levels() === 2 && drawn('Item 0.4') && foot(), 'the long feed opened');
await settle();
if (pages(1)) problems.push('the long feed asked for its second page before its foot was in view');
const watcher = [...watching].find((observer) => [...observer.watched].includes(foot()));
if (!watcher || !/100%/.test(watcher.options.rootMargin)) problems.push(`the long feed's foot is watched ${watcher ? `with the margin ${watcher.options.rootMargin}` : 'by nothing'}, not a screen ahead`);
footShown();
footShown();
await until(() => drawn('Item 1.4'), 'its second page, as its foot came into view');
await settle();
if (pages(1) !== 1) problems.push(`its foot shown twice, the long feed asked for its second page ${pages(1)} times, not once`);
[...target.querySelectorAll('.stack:not([hidden]) > section.level:last-child a')].find((each) => each.textContent.includes('Their post')).click();
await until(() => levels() === 3, 'their post opened over the long feed');
await settle();
footShown();
await settle();
if (pages(2)) problems.push('under their post, inert, the long feed asked for its third page');
history.go(-1);
await until(() => levels() === 2 && !target.querySelector('.stack:not([hidden]) > section.level[aria-busy="true"]'), 'back at the long feed');
await settle();
pagesFail = true;
footShown();
await until(() => foot()?.querySelector('[role="alert"]'), 'its third page failed');
await settle();
footShown();
await settle();
const button = foot().querySelector('button');
if (pages(2) !== 1 || !foot().textContent.includes('The feed is down.') || button.textContent.trim() !== 'Try again') problems.push(`a page failed, the long feed asked for it ${pages(2)} times and drew ${foot().textContent.trim()}`);
pagesFail = false;
button.click();
await until(() => drawn('Item 2.4') && !foot(), 'its third page, Try again pressed, and no foot after the last');
history.go(-1);
await until(() => levels() === 1, 'back from the long feed, Home');
} finally {
globalThis.IntersectionObserver = Observer;
}
say('a long feed paged as its foot came into view, once a page, never under a screen or after a page failed until Try again');
}
// Another's story tapped: its pager has no page of one's own, which opens at a form (Your story's `compose`), a page only of the pager it opens itself.
const pager = () => target.querySelector('.pager');
const tap = (words) => [...target.querySelectorAll('.stack:not([hidden]) li.item')].find((el) => el.textContent.includes(words)).querySelector('.open').click();
const turn = async (way) => {
target.querySelector(`.pager .arrow.${way}`).click();
await new Promise((done) => setTimeout(done, 400));
};
// Closed as its ✕ does, the browser's back (the test's history standing in for it).
const shut = async () => {
history.go(-1);
await until(() => !pager(), 'the pager closed');
};
const readOwn = () => calls.filter((call) => call.args.method === 'test.story.get' && call.args.params.actor === 'did:plc:me').length;
tap("Gabriel's story");
await until(() => pager()?.textContent.includes('Gabriel at the lake'), "Gabriel's story shown in the pager");
await settle();
if (readOwn() !== 0) problems.push("another's story tapped, one's own page was read beside it");
if (target.querySelector('.pager .arrow.previous')) problems.push("another's story tapped, its pager has a page before it");
if (form()) problems.push("another's story tapped, a form opened");
await shut();
say("another's story tapped: its pager has no page of one's own, which opens at a form");
// Your story tapped, with none: its form alone, over Home, and no stories under it; closed, sent or not, the step it made is gone back from
// (the browser's back, the test's history standing in for it).
const home = history.at;
const realBack = globalThis.history.back;
globalThis.history.back = () => history.go(-1);
try {
tap('Your story');
await until(form, 'Your story tapped, with none, opened its form');
if (!form().textContent.includes('Add to your story')) problems.push(`Your story opened another form: ${form().textContent.slice(0, 80)}`);
if (pager()) problems.push('Your story tapped, with none, drew the stories under its form');
if (!target.querySelector('.stack:not([hidden]) > section.level')?.textContent.includes('test.feed.getFeed')) problems.push("Your story's form is not over Home");
await cancel();
await until(() => history.at === home && !pager(), "Your story's form cancelled, back at Home");
say('Your story tapped, with none: its form alone over Home, and Cancel went back to Home');
const writes = () => calls.filter((call) => call.name === 'apply_writes').length;
const wrote = writes();
tap('Your story');
await until(form, 'Your story tapped again, with none, opened its form');
form().querySelector('form').requestSubmit();
await until(() => !form() && history.at === home && !pager(), "Your story's form sent, back at Home");
if (writes() !== wrote + 1) problems.push(`Your story's form sent ${writes() - wrote} writes, not 1`);
say('Your story tapped, with none: its form sent, back at Home');
} finally {
globalThis.history.back = realBack;
}
// Your story tapped, with stories: its pager, one's own page first and the others' after it.
mine = true;
tap('Your story');
await until(() => pager()?.textContent.includes('My story at the beach'), 'Your story tapped, with stories, shown in the pager');
if (form()) problems.push('Your story tapped, with stories, opened its form');
await turn('next');
if (!pager()?.querySelector('section.page:not([inert])')?.textContent.includes('Gabriel at the lake')) problems.push('Your story tapped, with stories, has no page of the others after it');
await shut();
say('Your story tapped, with stories: its pager, the others after it');
const reload = async (why) => {
client.unmount(app);
app = null;
const before = opening();
history = new client.History(history.entries.map((entry) => ({ ...entry })), history.at);
app = start(history);
await settle();
await until(() => !target.querySelector('[aria-busy="true"]'), `${why}: the page settled`);
if (form()) problems.push(`${why}: a form opened again`);
if (opening() !== before) problems.push(`${why}: a call was made with compose again`);
};
await reload('loaded again after Create');
say('loaded again, no form opened');
[...target.querySelectorAll('.stack:not([hidden]) a')].find((link) => link.textContent.includes('Write one')).click();
await until(form, 'a screen opened at a form opened it');
if (levels() !== 2) problems.push(`a screen opened at a form is not pushed: ${levels()} levels`);
if (history.entries.at(-1)?.url !== '/stories') problems.push(`a screen opened at a form has the URL ${history.entries.at(-1)?.url}, not /stories`);
await cancel();
history.go(-1);
await until(() => levels() === 1, 'back, the screen under it');
history.go(1);
await until(() => levels() === 2, 'forward, the screen opened at a form');
await settle();
if (form()) problems.push('gone back from and forward to, a screen opened at a form opened it again');
await reload('a screen opened at a form, loaded again');
say('a screen opened at a form opened it once: back, forward and loaded again, no form');
if (JSON.stringify(history.entries).includes('compose')) problems.push(`a history entry holds compose: ${JSON.stringify(history.entries)}`);
history.entries.at(-1).state.calls[1] = WRITE;
await reload("an older shell's entry with compose, loaded again");
say("an older shell's entry with compose, loaded again, opened no form");
target.querySelector('.side .action').click();
await until(form, "Create opened the action's form again");
form().querySelector('form').requestSubmit();
await until(() => !form() && history.entries.at(-1)?.url === '/profile/me.test/post/1', 'the form sent, the screen of the record it made');
if (!calls.some((call) => call.name === 'apply_writes')) problems.push("the action's form sent nothing");
await until(() => target.textContent.includes(`The post ${POST}`), 'the record made drawn');
say("the action's form sent, the screen of the record it made opened");
const on = () => [...target.querySelectorAll('.side .item.on')].map((item) => item.textContent.trim()).join();
const choose = (label) => [...target.querySelectorAll('.side .items a.item')].find((item) => item.textContent.trim() === label).click();
choose('Explore');
await until(() => on() === 'Explore', 'Explore chosen');
choose('Home');
await until(() => on() === 'Home' && levels() === 1 && history.entries.at(-1)?.url === '/', 'Home chosen again, at its root, as its link says');
say('a tab chosen shows its root, as its link says, in one click');
[...target.querySelectorAll('.stack:not([hidden]) a')].find((link) => link.textContent.includes('My profile')).click();
await until(() => on() === 'Profile' && levels() === 1 && history.entries.at(-1)?.url === '/profile/me.test', "a link to the account's own profile chooses the Profile tab");
say("a link to the account's own profile is the Profile tab, at its root");
// A footer link to one of the app's own pages opens it in the app, over the tab on show, its URL the page's; a link in its text to another page on the app's site opens that one too; back, the one before.
[...target.querySelectorAll('.side .links a')].find((link) => link.textContent.trim() === 'Terms').click();
await until(() => history.entries.at(-1)?.url === '/terms' && target.textContent.includes('The page /terms.'), 'the footer link opened the terms in the app');
if (levels() !== 2 || on() !== 'Profile') problems.push(`the terms opened as ${levels()} levels on ${on()}, not over the tab on show`);
[...target.querySelectorAll('.stack:not([hidden]) a')].find((link) => link.textContent === 'privacy policy').click();
await until(() => history.entries.at(-1)?.url === '/privacy' && target.textContent.includes('The page /privacy.'), "the terms' link opened the privacy policy in the app");
history.go(-1);
await until(() => levels() === 2 && target.querySelector('.stack:not([hidden]) > section.level:last-of-type')?.textContent.includes('The page /terms.'), 'back, the terms');
say("a footer link opens the app's own page in the app, and a link in it another, back the one before");
// The pager closed returns to the screen it was opened over, one history entry back, however many times it is asked to close at once
// (✕, ✕ again and Escape before the first lands, as a story running out under a tap on ✕ does): Home's root, a screen pushed over it,
// that screen loaded again (the server's two levels), and the browser's back from the pager.
const browserBack = globalThis.history.back;
globalThis.history.back = () => history.go(-1);
const closeAll = async () => {
const box = pager();
box.querySelector('button.close').click();
box.querySelector('button.close').click();
box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
await until(() => !pager(), 'the pager closed');
await settle();
};
const over = async (why, url, depth) => {
const at = history.at;
tap("Gabriel's story");
await until(() => pager()?.textContent.includes('Gabriel at the lake'), `${why}: the pager opened`);
if (history.at !== at + 1) problems.push(`${why}: the pager made no history entry of its own`);
await closeAll();
if (history.at !== at || history.entries[history.at].url !== url || levels() !== depth) problems.push(`${why}: closed, it is at ${history.entries[history.at]?.url} with ${levels()} levels (entry ${history.at}), not back at ${url} with ${depth} (entry ${at})`);
// Forward to the pager's entry, the same entry stepped back from before: closing it steps back again.
history.go(1);
await until(() => pager(), `${why}: forward, the pager again`);
await closeAll();
if (history.at !== at || levels() !== depth) problems.push(`${why}: back, forward and closed again, it is at entry ${history.at} with ${levels()} levels, not ${at} with ${depth}`);
tap("Gabriel's story");
await until(() => pager(), `${why}: the pager opened again`);
history.go(-1);
await until(() => !pager(), `${why}: the browser's back closed the pager`);
await settle();
if (history.at !== at || levels() !== depth) problems.push(`${why}: the browser's back from the pager left ${levels()} levels at entry ${history.at}, not ${depth} at ${at}`);
};
try {
choose('Home');
await until(() => on() === 'Home' && levels() === 1, 'Home chosen');
await over("Home's root", '/', 1);
[...target.querySelectorAll('.stack:not([hidden]) a')].find((link) => link.textContent.includes('Write one')).click();
await until(() => levels() === 2 && form(), 'a screen pushed over Home');
await cancel();
await over('a screen pushed over Home', '/stories', 2);
history.go(-1);
await until(() => levels() === 1, "back from the pushed screen, Home's root");
history.go(1);
await until(() => levels() === 2, 'forward to the pushed screen');
await reload('the pushed screen, loaded again');
await until(() => levels() === 2, 'loaded again, the pushed screen over Home');
await over('a screen loaded with Home under it', '/stories', 2);
} finally {
globalThis.history.back = browserBack;
}
say('the pager, closed however many times at once or by the browser, returns to the screen it was opened over, one entry back');
} catch (e) {
problems.push(`signed in: ${e.message}`);
} finally {
if (app) client.unmount(app);
}
// Signed in, Home's root as the server chose it: Following, its URL `/`, Home's own. A preference
// set (its first's `after`) chooses it again: Home on show keeps what it draws, and takes the new
// root (Home's own call, pinned as `/`) as Home is chosen again, its URL `/` still. A page loaded
// again at `/` with an entry of the old root draws the root chosen now.
{
const client = await import(`${built}?load=${loads++}`);
const fetchWas = globalThis.fetch;
let pins = ['/feeds/following'];
const asked = [];
const MOVE = { c: 'Action', p: { label: 'Move up', done: 'Moved', key: 'move', call: { method: 'test.actor.setPreference', service: 'did:web:app.test#app', input: {} } } };
const feedOf = (call) => ({ v: 1, trusted: true, root: { c: 'Stack', k: [{ c: 'Text', p: { runs: [{ text: `The ${call.args.params.feed} feed` }], style: 'body' } }, MOVE] } });
globalThis.fetch = async (_, init) => {
const made = JSON.parse(init.body);
asked.push(made);
const prefs = { preferences: [{ $type: 'test.actor.defs#pinnedFeedsPref', items: pins.map((path) => ({ path })) }] };
const answer = made.name === 'call_procedure' ? { structuredContent: { output: {} } } : made.args.method === PREFS.args.method ? { structuredContent: prefs } : { _meta: { ui: feedOf(made), viewer: { did: 'did:plc:me', handle: 'me.test' } } };
return Response.json(answer);
};
const target = document.createElement('div');
document.body.replaceChildren(target);
const page = PAGES.find((p) => p.roots);
const start = (history, home) => {
const base = props(page, history.navigation);
return client.mount(client.Shell, { target, props: { ...base, screen: { ...base.screen, calls: [home], roots: rootsWith(home), top: answered(feedOf(home)) } } });
};
const until = async (ok, what) => {
for (let i = 0; i < 100 && !ok(); i++) await new Promise((done) => setTimeout(done, 20));
if (!ok()) throw new Error(`never: ${what}`);
};
const shown = () => target.querySelector('.stack:not([hidden]) > section.level')?.textContent ?? '';
const preferred = () => asked.filter((made) => made.args?.method === PREFS.args.method).length;
let app;
try {
const history = new client.History();
app = start(history, FOLLOWING);
await until(() => history.entries.length === 1, 'the first history entry');
if (history.entries[0].url !== '/') problems.push(`Home at its chosen root, Following, made its first entry at ${history.entries[0].url}, not /`);
pins = ['/', '/feeds/following'];
[...target.querySelectorAll('.stack:not([hidden]) button')].find((button) => button.textContent.includes('Move up')).click();
await until(() => preferred() === 1, 'the preferences read again once set');
await new Promise((done) => setTimeout(done, 60));
if (!shown().includes('The following feed')) problems.push(`a preference set took Home's root from under it, on show: ${shown().slice(0, 60)}`);
[...target.querySelectorAll('.side .items a.item')].find((item) => item.textContent.trim() === 'Home').click();
const entry = () => history.entries[history.at];
await until(() => shown().includes('The home feed') && entry()?.url === '/' && JSON.stringify(entry().state.calls) === JSON.stringify([FEED]), 'Home chosen again: its new root, at /');
say("a preference set chooses Home's root again, taken as Home is chosen again, its URL / still");
client.unmount(app);
app = null;
const old = new client.History([{ url: '/', state: { tab: 0, calls: [FOLLOWING], pager: null, up: false }, replace: true }], 0);
app = start(old, FEED);
await new Promise((done) => setTimeout(done, 60));
if (!shown().includes('The home feed')) problems.push(`loaded again at / with an entry of the old root, Home draws ${shown().slice(0, 60)}, not the root chosen now`);
say('loaded again at / with an entry of the old root, Home draws the root chosen now');
} catch (e) {
problems.push(`Home's chosen root: ${e.message}`);
} finally {
if (app) client.unmount(app);
globalThis.fetch = fetchWas;
}
}
// A feed's own pin, as Grain's camera feeds have one: its write read
// again in place (`reload`). A feed pushed over a tab keeps its back
// and its title, pinned and unpinned. One in Home's root place by
// Home's strip, chosen there or loaded at its URL, that its unpin takes
// out of the strip is a feed pushed over Home's root: its back and
// title drawn, at its URL still, back going to Home's root.
{
const client = await import(`${built}?load=${loads++}`);
const fetchWas = globalThis.fetch;
let pinned = false;
const pin = (on) => ({ c: 'Action', p: { label: on ? 'Pin' : 'Unpin', reload: true, call: { method: 'test.actor.setPreference', service: 'did:web:app.test#app', input: { pinned: on } } } });
const strip = (selected) => ({
c: 'Tabs',
p: {
style: 'strip',
items: [
{ label: 'For You', open: { call: FEED }, selected: selected === FEED },
{ label: 'Following', open: { call: FOLLOWING }, selected: false },
...(pinned ? [{ label: 'X100V', open: { call: PINNED }, selected: selected === PINNED }] : [])
]
}
});
const homeOf = () => ({ v: 1, trusted: true, root: { c: 'Stack', k: [strip(FEED), { c: 'Text', p: { runs: [{ text: 'The home feed' }], style: 'body' } }, { c: 'Link', p: { label: 'The camera', open: { call: PINNED } } }] } });
const cameraOf = () => ({ v: 1, trusted: true, root: { c: 'Stack', k: [{ c: 'Bar', p: { title: 'X100V' }, k: [pin(!pinned)] }, strip(PINNED), { c: 'Text', p: { runs: [{ text: 'The camera feed' }], style: 'body' } }] } });
globalThis.fetch = async (_, init) => {
const made = JSON.parse(init.body);
if (made.name === 'call_procedure') {
pinned = made.args.input.pinned;
return Response.json({ structuredContent: { output: {} } });
}
if (made.args?.method === PREFS.args.method) return Response.json({ structuredContent: { preferences: [] } });
const ui = made.args?.params?.feed === 'camera' ? cameraOf() : homeOf();
return Response.json({ _meta: { ui, viewer: { did: 'did:plc:me', handle: 'me.test' } } });
};
const target = document.createElement('div');
document.body.replaceChildren(target);
const page = PAGES[1];
const start = (history, calls, top, path) => {
const base = props(page, history.navigation);
return client.mount(client.Shell, { target, props: { ...base, path, screen: { ...base.screen, calls, top: answered(top) } } });
};
const until = async (ok, what) => {
for (let i = 0; i < 100 && !ok(); i++) await new Promise((done) => setTimeout(done, 20));
if (!ok()) throw new Error(`never: ${what}`);
};
const stack = () => target.querySelector('.stack:not([hidden])');
const top = () => [...(stack()?.querySelectorAll(':scope > section.level') ?? [])].at(-1);
/** The screen on show: how many levels its stack has, its bar's back and title, its wordmark, its words. */
const shown = () => {
const level = top();
const bar = level?.querySelector(':scope > .screen-bar');
return { levels: stack()?.querySelectorAll(':scope > section.level').length ?? 0, back: Boolean(bar?.querySelector('.back')), title: bar?.querySelector('h1.screen')?.textContent.trim() ?? null, wordmark: Boolean(bar?.querySelector('h1.wordmark')), words: level?.querySelector('.body')?.textContent ?? '' };
};
const button = (name) => [...(top()?.querySelectorAll('button') ?? [])].find((b) => b.getAttribute('aria-label') === name || b.textContent.trim() === name);
const press = async (name, then) => {
await until(() => button(name), `${name} shown`);
button(name).click();
await until(() => button(then), `${name} pressed: ${then} shown`);
await new Promise((done) => setTimeout(done, 60));
};
const pushed = (what) => {
const now = shown();
if (!now.back || now.title !== 'X100V' || now.wordmark || !now.words.includes('The camera feed')) problems.push(`${what}: not the camera feed pushed, with its back and title: ${JSON.stringify(now)}`);
};
const entry = (history) => history.entries[history.at];
let app;
try {
// Pushed from a link (its route's tab, Explore), pinned, unpinned and pinned again: pushed throughout.
let history = new client.History();
app = start(history, [FEED], homeOf(), '/');
await until(() => history.entries.length === 1, 'the first history entry');
[...target.querySelectorAll('.stack:not([hidden]) a, .stack:not([hidden]) button')].find((a) => a.textContent.trim() === 'The camera').click();
await until(() => shown().words.includes('The camera feed'), 'the camera feed pushed');
pushed('opened');
await press('Pin', 'Unpin');
pushed('pushed, then pinned');
await press('Unpin', 'Pin');
pushed('pushed, pinned, then unpinned');
await press('Pin', 'Unpin');
pushed('pushed, unpinned, then pinned again');
if (entry(history).url !== '/camera/X100V') problems.push(`the pushed feed pinned is at ${entry(history).url}, not /camera/X100V`);
say('a feed pushed over a tab keeps its back and title, pinned, unpinned and pinned again');
client.unmount(app);
app = null;
// Pinned, chosen in Home's strip: Home's root level; unpinned, pushed over Home's root.
pinned = true;
history = new client.History();
app = start(history, [FEED], homeOf(), '/');
await until(() => history.entries.length === 1, 'the first history entry');
[...target.querySelectorAll('.stack:not([hidden]) .tabs.strip > *')].find((tab) => tab.textContent.trim() === 'X100V').click();
await until(() => shown().words.includes('The camera feed'), "the strip's camera in Home's root place");
const rooted = shown();
if (rooted.levels !== 1 || rooted.back || !rooted.wordmark) problems.push(`the strip's camera is not Home's root level: ${JSON.stringify(rooted)}`);
await press('Unpin', 'Pin');
await until(() => shown().levels === 2, "unpinned, Home's root under it");
pushed("in Home's root place by its strip, then unpinned");
if (entry(history).url !== '/camera/X100V' || entry(history).state.tab !== 0) problems.push(`the strip's camera unpinned is at ${entry(history).url} on tab ${entry(history).state.tab}, not /camera/X100V on Home`);
top().querySelector('.back').click();
await until(() => shown().levels === 1 && shown().words.includes('The home feed'), "back to Home's root");
say("a feed chosen in Home's strip and unpinned there is pushed over Home's root, back going to it");
client.unmount(app);
app = null;
// Pinned, loaded at its URL: Home's root level, as the server draws it; unpinned, pushed over Home's root.
pinned = true;
history = new client.History();
app = start(history, [PINNED], cameraOf(), '/camera/X100V');
await until(() => history.entries.length >= 1 && shown().words.includes('The camera feed'), 'the pinned camera loaded');
if (shown().back || !shown().wordmark) problems.push(`the pinned camera loaded is not Home's root level: ${JSON.stringify(shown())}`);
await press('Unpin', 'Pin');
await until(() => shown().levels === 2, "unpinned, Home's root under it");
pushed("loaded at its URL in Home's root place, then unpinned");
if (entry(history).url !== '/camera/X100V') problems.push(`the loaded camera unpinned is at ${entry(history).url}, not /camera/X100V`);
await press('Pin', 'Unpin');
pushed("loaded in Home's root place, unpinned, then pinned again");
say("a feed loaded at its URL in Home's root place and unpinned is pushed over Home's root, and stays pushed pinned again");
} catch (e) {
problems.push(`a feed's own pin: ${e.message}`);
} finally {
if (app) client.unmount(app);
globalThis.fetch = fetchWas;
}
}
// A story's URL. Its route (`pager`) opens its screen in the story
// viewer, from a link as from a strip, and the URL follows the story
// shown, in place (a story on, or another account's page), so the
// browser's back leaves the viewer. Loaded, the server draws the viewer
// over its account's profile (`under`), its head the story's, and the
// browser hydrates it as drawn: three history entries, so closing it
// goes to the profile, which the browser reads.
{
const client = await import(`${built}?load=${loads++}`);
const fetchWas = globalThis.fetch;
const CAROL = 'did:plc:carol';
const story = (n) => `at://${CAROL}/test.story/${n}`;
const ARCHIVE = (at) => ({ name: 'query', args: { method: 'test.story.archive', params: { actor: CAROL }, ...(at ? { at } : {}) } });
const LIVE = query('test.story.live', { actor: CAROL });
const STORY_APP = {
...APP,
routes: [{ path: '/profile/{actor}/story/{rkey}', pager: true, under: '/profile/{actor}', call: { name: 'query', args: { method: 'test.story.archive', params: { actor: '{actor:did}' }, at: 'at://{actor:did}/test.story/{rkey}' } } }, ...APP.routes]
};
const slides = (start) => ({
v: 1,
trusted: true,
head: { title: 'A story by @carol.test' },
root: { c: 'Slides', p: { name: 'Carol', ...(start ? { start } : {}) }, items: [1, 2].map((n) => ({ src: null, alt: `Carol's story ${n}`, ratio: null, open: { call: ARCHIVE(story(n)) } })) }
});
const home = {
v: 1,
trusted: true,
root: {
c: 'Stack',
k: [
{ c: 'List', p: { style: 'strip', pages: true }, items: [{ open: { call: LIVE }, k: [{ c: 'Text', p: { runs: [{ text: "Carol's stories" }], style: 'body' } }] }] },
{ c: 'Link', p: { label: "Carol's archive", open: { call: ARCHIVE(story(2)) } } }
]
}
};
const carol = { response: { stories: [{ creator: { did: CAROL, handle: 'carol.test' } }] } };
const answerOf = ({ name, args }) => {
const viewer = { did: 'did:plc:me', handle: 'me.test' };
if (args.method === 'test.story.archive') return { _meta: { ui: slides(args.at === story(2) ? 1 : 0), viewer }, structuredContent: carol };
if (args.method === 'test.story.live') return { _meta: { ui: slides(0), viewer }, structuredContent: carol };
if (name === 'describe_app') return { _meta: { ui: { v: 1, trusted: true, root: { c: 'Text', p: { runs: [{ text: `Profile of ${args.actor}` }], style: 'body' } } }, viewer } };
return { _meta: { ui: home, viewer } };
};
globalThis.fetch = async (_, init) => Response.json(answerOf(JSON.parse(init.body)));
const until = async (ok, what) => {
for (let i = 0; i < 100 && !ok(); i++) await new Promise((done) => setTimeout(done, 20));
if (!ok()) throw new Error(`never: ${what}`);
};
const target = document.createElement('div');
document.body.replaceChildren(target);
const pager = () => target.querySelector('.pager');
const shows = () => pager()?.querySelector('section.page:not(.side) .stage')?.getAttribute('aria-label') ?? '';
const levels = () => target.querySelectorAll('.stack:not([hidden]) > section.level').length;
const next = () => [...pager().querySelectorAll('section.page:not(.side) .sr button')].find((b) => b.textContent === 'Next').click();
let app;
try {
let history = new client.History();
const base = props(PAGES[1], history.navigation);
app = client.mount(client.Shell, { target, props: { ...base, app: STORY_APP, screen: { ...base.screen, top: answered(home) } } });
await until(() => history.entries.length === 1, 'the first history entry');
const url = () => history.entries[history.at]?.url;
[...target.querySelectorAll('.stack:not([hidden]) li.item')].find((el) => el.textContent.includes("Carol's stories")).querySelector('.open').click();
await until(() => shows() === "Carol's story 1" && url() === '/profile/carol.test/story/1', 'the strip opened the viewer, its URL the story shown');
if (history.entries.length !== 2) problems.push(`the viewer opened as ${history.entries.length} entries, not one over the screen`);
next();
await until(() => shows() === "Carol's story 2" && url() === '/profile/carol.test/story/2', 'the next story, its URL');
if (history.entries.length !== 2) problems.push(`a story on made an entry of its own: ${JSON.stringify(history.entries.map((e) => e.url))}`);
history.go(-1);
await until(() => !pager() && url() === '/', "the browser's back left the viewer");
say('the viewer opened from a strip follows the story shown in place, and back leaves it');
[...target.querySelectorAll('.stack:not([hidden]) a')].find((link) => link.textContent.includes("Carol's archive")).click();
await until(() => shows() === "Carol's story 2" && url() === '/profile/carol.test/story/2', "a story's link opened it in the viewer, at the story");
if (levels() !== 1) problems.push(`a story's link pushed a screen: ${levels()} levels`);
history.go(-1);
await until(() => !pager() && url() === '/', 'back from the story linked');
say("a link to a story's screen opens it in the viewer, at that story, not pushed");
client.unmount(app);
app = null;
const caller = { call: async (name, args) => answerOf({ name, args }), resolve: async (actor) => (actor === 'carol.test' ? CAROL : actor) };
const loaded = await server.screenAt(STORY_APP, new URL('https://app.test/profile/carol.test/story/2'), caller, true);
const want = [FEED, { name: 'describe_app', args: { domain: 'app.test', actor: 'carol.test' } }];
if (JSON.stringify(loaded.screen.pager?.calls) !== JSON.stringify([ARCHIVE(story(2))]) || JSON.stringify(loaded.screen.calls) !== JSON.stringify(want) || loaded.screen.tab !== 0)
problems.push(`a story's URL is read as ${JSON.stringify({ tab: loaded.screen.tab, calls: loaded.screen.calls, pager: loaded.screen.pager })}`);
history = new client.History();
const drawnProps = (navigation) => ({ ...props(PAGES[1], navigation), app: STORY_APP, screen: loaded.screen, under: loaded.under, path: '/profile/carol.test/story/2' });
// The server's own navigation, as on the server: it makes no entries.
const result = server.render(server.Shell, { props: drawnProps({ here: undefined, go: async () => undefined, entered: () => undefined }) });
if (!result.body.includes('class="pager') || !result.body.includes('aria-label="Carol\'s story 2"')) problems.push("a story's URL: the server did not draw the story in the viewer");
if (!result.head.includes('<title>A story by @carol.test</title>')) problems.push("a story's URL: its head is not the story's");
target.innerHTML = result.body;
const said = [];
const { warn, error } = console;
console.warn = console.error = (...args) => said.push(args.map(String).join(' '));
try {
app = client.hydrate(client.Shell, { target, props: drawnProps(history.navigation) });
} finally {
console.warn = warn;
console.error = error;
}
for (const s of said) problems.push(`a story's URL, hydrating it: ${s}`);
await until(() => history.entries.length === 3, "a story's URL entered as three entries");
const urls = history.entries.map((e) => e.url).join(' ');
if (urls !== '/ /profile/carol.test /profile/carol.test/story/2') problems.push(`a story's URL entered as ${urls}`);
if (shows() !== "Carol's story 2") problems.push(`a story's URL, hydrated, shows ${shows()}`);
const browserBack = globalThis.history.back;
globalThis.history.back = () => history.go(-1);
try {
pager().querySelector('button.close').click();
await until(() => !pager() && url() === '/profile/carol.test', "closed, the story's account's profile");
} finally {
globalThis.history.back = browserBack;
}
await until(() => target.querySelector('.stack:not([hidden]) > section.level:last-of-type')?.textContent.includes('Profile of carol.test'), 'the profile under it read');
say("a story's URL: drawn in the viewer over its account's profile, hydrated as drawn, closing to the profile");
} catch (e) {
problems.push(`a story's URL: ${e.message}`);
} finally {
if (app) client.unmount(app);
globalThis.fetch = fetchWas;
}
}
} finally {
rmSync(out, { recursive: true, force: true });
}
if (problems.length) {
for (const p of problems) console.log(`FAIL ${p}`);
process.exit(1);
}
say('the shell drew on the server as the browser hydrated it, at every width');
process.exit(0);