Skip to content

176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.

106 KB
Raw Blame
// Static checks for the guided-steps demo pages, their READMEs, the home page and the shared stylesheet.
// Run from the repo root: node --test "tests/*.test.js"
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { sections, table } = require('./helpers/markdown.js');
const vm = require('node:vm');
const { execFileSync } = require('node:child_process');

const ROOT = path.resolve(__dirname, '..');
const ANIM = path.join(ROOT, 'animations');
const read = f => fs.readFileSync(f, 'utf8');
const count = (s, sub) => s.split(sub).length - 1;
const words = s => s.trim().split(/\s+/).length;
const isDemoDir = dir => fs.existsSync(path.join(dir, 'index.html'));
// The part of s from the first `from` up to the next `to` after it ('' when `from` is missing).
const between = (s, from, to) => {
  const start = s.indexOf(from);
  if (start < 0) return '';
  const end = s.indexOf(to, start + from.length);
  return s.slice(start, end < 0 ? undefined : end);
};
// The text inside the braces of the first block that starts with `header` (which ends with the block's opening brace), the braces
// matched, so a rule after the block's closing brace is not part of it ('' when there is no such block).
const blockOf = (s, header) => {
  const start = s.indexOf(header);
  if (start < 0) return '';
  for (let i = start + header.length, depth = 1; i < s.length; i++) {
    if (s[i] === '{') depth++;
    else if (s[i] === '}' && --depth === 0) return s.slice(start + header.length, i);
  }
  return '';
};
const decode = s => s.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
// The rules of a stylesheet as { selector, body }: comments removed, rules inside @media and @supports included.
const cssRules = css => [...css.replace(/\/\*[\s\S]*?\*\//g, '').matchAll(/([^{}]+)\{([^{}]*)\}/g)]
  .map(m => ({ selector: m[1].trim(), body: m[2] }));
// [ids, classes + attributes + pseudo-classes, elements] of a selector that has no functional pseudo-class.
const specificity = selector => [
  (selector.match(/#[\w-]+/g) || []).length,
  (selector.match(/\.[\w-]+|\[[^\]]*\]|(?<!:):(?!:)[\w-]+/g) || []).length,
  (selector.replace(/\.[\w-]+|#[\w-]+|\[[^\]]*\]|::?[\w-]+/g, ' ').match(/[a-zA-Z][\w-]*/g) || []).length
];
const outranks = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]; return false; };

const demos = fs.readdirSync(ANIM, { withFileTypes: true }).filter(c => c.isDirectory()).flatMap(c =>
  fs.readdirSync(path.join(ANIM, c.name), { withFileTypes: true }).filter(d => d.isDirectory())
    .map(d => ({ cat: c.name, slug: d.name, dir: path.join(ANIM, c.name, d.name) })));
const pageOf = d => read(path.join(d.dir, 'index.html'));
const steps = demos.filter(d => pageOf(d).includes('<main class="hb-page">'));
const HOME = read(path.join(ROOT, 'index.html'));
const tryItOf = html => between(html, '<section class="hb-step hb-try"', '<section class="hb-step hb-prompt-step"');
// The raw first column of the README's Key parameters table.
const keyParameters = d => sections(read(path.join(d.dir, 'README.md')))['Key parameters'].split('\n')
  .filter(l => /^\s*\|/.test(l)).slice(2).map(row => (row.split('|')[1] || '').trim()).filter(Boolean);

const ENTRANCE_EXIT = '02-entrance-and-exit';
// Categories whose demos have all moved to the guided-steps page. A demo here that lost <main class="hb-page">
// would otherwise drop out of every check below without any failure. Add a category when its last demo is converted.
const CONVERTED = [ENTRANCE_EXIT, '05-text-typography', '07-ambient-background', '06-3d-advanced', '04-micro-interactions', '01-scroll-based', '03-page-transitions'];

// The Pause button of a loop page, exactly as in the template; {MODE} is '' (the page pauses itself) or '="css"'.
const PAUSE = '<button class="hb-play" type="button" id="btn-pause" data-hb-pause{MODE} data-state="playing"><svg class="hb-ic hb-i-pause" viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg><svg class="hb-ic hb-i-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3l14 9-14 9z"/></svg><span class="hb-pause-label">Pause</span></button>';

// The Show me and Reset buttons of a do-it page, exactly as in the template (Reset only where the demo has a state to reset).
const SHOW_ME = '<button class="hb-play" type="button" id="btn-demo" data-hb-demo><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"/></svg>Show me</button>';
const RESET = '<button class="hb-play" type="button" id="btn-reset" data-hb-reset><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>Reset</button>';

// The Play and Back to top buttons of a scroll page, exactly as in the template.
const PLAY = '<button class="hb-play" type="button" id="btn-scroll" data-hb-autoscroll><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M19 12l-7 7-7-7"/></svg>Play</button>';
const TOP = '<button class="hb-play" type="button" id="btn-top" data-hb-top><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>Back to top</button>';

// Show me belongs to do-it pages and Reset to do-it and loop pages, each exactly as in the template: the shared script picks
// what to press on arrival by the button it finds, and Reset brings back what the visitor changed. `html` is the whole page
// and `player` its player bar.
function assertShowMeAndReset(kind, html, player) {
  const bar = player.replace(/>\s+</g, '><'); // the player bar without the white space between its elements
  if (kind === 'do') {
    assert.equal(count(html, 'data-hb-demo'), 1, 'one Show me control');
    assert.ok(bar.includes(SHOW_ME), 'the Show me button is in the player bar exactly as in the template');
  } else {
    assert.equal(count(html, 'data-hb-demo'), 0, 'only a do-it page has data-hb-demo');
  }
  if (!html.includes('data-hb-reset')) return;
  assert.ok(kind === 'do' || kind === 'loop', 'only a do-it or loop page has data-hb-reset');
  assert.equal(count(html, 'data-hb-reset'), 1, 'at most one Reset');
  assert.ok(bar.includes(RESET), 'the Reset button is in the player bar exactly as in the template');
  // On a do-it page Reset comes right after Show me: on phones two buttons that sit next to each other share one row.
  if (kind === 'do') assert.ok(bar.includes(SHOW_ME + RESET), 'on a do-it page the Reset button comes right after Show me');
}

// Play and Back to top, each exactly as in the template, and the scroller belong to scroll pages, and only to them: the shared
// script presses Play before anything else on arrival, so a stray one on another kind of page would quietly replace that page's
// own arrival. `html` is the whole page, `player` its player bar and `autoplay` whether the body asks for the run on arrival.
function assertScrollControls(kind, html, player, autoplay) {
  if (kind !== 'scroll') {
    for (const marker of ['data-hb-autoscroll', 'data-hb-top', 'data-hb-scroller']) {
      assert.equal(count(html, marker), 0, `only a scroll page has ${marker}`);
    }
    return;
  }
  // A scroll page shows itself once on arrival: the shared script presses Play when the body asks for autoplay.
  assert.ok(autoplay, 'a scroll page scrolls once on arrival (data-hb-autoplay on the body)');
  assert.equal(count(html, 'data-hb-autoscroll'), 1, 'one Play control');
  assert.equal(count(html, 'data-hb-top'), 1, 'one Back to top control');
  const bar = player.replace(/>\s+</g, '><'); // the player bar without the white space between its elements
  assert.ok(bar.includes(PLAY) && bar.includes(TOP), 'Play and Back to top are in the player bar exactly as in the template');
  // Back to top comes right after Play: on phones two buttons that sit next to each other share one row.
  assert.ok(bar.includes(PLAY + TOP), 'the Back to top button comes right after Play');
  assert.ok(count(html, 'data-hb-scroller') <= 1, 'at most one scroller');
  // A scroll page has none of the other player controls; Slow motion is one of them (Play's speed is fixed).
  for (const other of ['data-hb-replay', 'data-hb-loop', 'data-hb-pause', 'data-hb-demo', 'data-hb-slowmo']) {
    assert.equal(count(html, other), 0, `a scroll page has no ${other}`);
  }
}

for (const cat of CONVERTED) {
  test(`every ${cat} demo uses the guided-steps page`, () => {
    const inCategory = demos.filter(d => d.cat === cat);
    assert.ok(inCategory.length > 0, `${cat} has demos`);
    assert.deepEqual(inCategory.filter(d => !steps.includes(d)).map(d => d.slug), []);
  });
}

test('Rotate In uses the guided-steps page', () => {
  assert.ok(steps.some(d => d.cat === ENTRANCE_EXIT && d.slug === 'rotate-in'));
});

for (const d of steps) {
  test(`${d.cat}/${d.slug} uses the guided-steps page correctly`, () => {
    const html = pageOf(d);
    // The shared files carry a version so visitors do not get a cached older copy after publishing.
    assert.match(html, /<link rel="stylesheet" href="\.\.\/\.\.\/\.\.\/assets\/css\/demo-page\.css\?v=\d+">/, 'page stylesheet');
    assert.match(html, /<script src="\.\.\/\.\.\/\.\.\/assets\/js\/demo-page\.js\?v=\d+" defer><\/script>/, 'page script');
    const body = html.match(/<body class="hb" data-hb-kind="(once|loop|scroll|do)"( data-hb-autoplay)?(?: data-hb-motion-note="([^"]*)")?>/);
    assert.ok(body, 'the body declares the page kind');
    const kind = body[1];
    // A scroll page where reduced motion turns an effect off says so in its own words; the shared script ends the note with
    // " because your device is set to reduce motion.", so the sentence starts with a capital letter and has no full stop.
    if (body[3] !== undefined) {
      assert.equal(kind, 'scroll', 'only a scroll page has data-hb-motion-note');
      assert.match(body[3], /^[A-Z][^.]*[^.\s]$/, 'data-hb-motion-note is one sentence with no full stop');
    }
    for (const old of ['handbook.css', 'handbook.js', 'hb-view', 'hb-side', 'hb-take', 'ah-bar', 'Copy source', 'Read more',
      'class="note"', 'class="kv"', 'class="lbl"', 'class="btn-row"', 'Bricolage', 'PlexMono']) {
      assert.ok(!html.includes(old), `old markup left: ${old}`);
    }
    for (const part of ['<nav class="hb-bar"', '<main class="hb-page">', '<header class="hb-head">',
      '<section class="hb-step hb-watch"', '<div class="hb-player">',
      '<section class="hb-step hb-prompt-step"', '<p class="hb-prompt">', '<ul class="hb-chips">',
      '<button class="hb-copy" type="button">', '<section class="hb-about"', '<ul class="hb-tags hb-good">',
      '<ul class="hb-tags hb-avoid">', '<section class="hb-related"', '<footer class="hb-foot">']) {
      assert.equal(count(html, part), 1, `exactly one ${part}`);
    }
    // Try it is optional: a demo with no settings leaves the whole step out.
    assert.ok(count(html, '<section class="hb-step hb-try"') <= 1, 'at most one Try it step');
    const hasTry = html.includes('<section class="hb-step hb-try"');
    assert.match(html, /<p class="hb-cat">\d{2}\.\d{2} · [^<]+<\/p>/);
    const prompt = html.match(/<p class="hb-prompt">([^<]*)<\/p>/)[1];
    assert.ok(words(prompt) >= 60 && words(prompt) <= 130, `prompt has ${words(prompt)} words`);
    if (hasTry) assert.ok(prompt.trim().endsWith('Match the settings listed below.'), 'prompt ending');
    else assert.ok(!prompt.includes('Match the settings listed below.'), 'a page without settings does not point to them');
    if (!hasTry) {
      // Nothing of a Try it step is left behind (a mistyped Try it tag would otherwise skip every settings check).
      assert.ok(!/hb-try|hb-setting|hb-options/.test(html), 'a page without Try it has no settings markup');
      assert.ok(!html.includes('Your settings are added at the end.'), 'a page without settings does not promise them under Copy prompt');
    }
    const nums = [...html.matchAll(/<span class="hb-num" aria-hidden="true">(\d+)<\/span>/g)].map(m => Number(m[1]));
    assert.deepEqual(nums, hasTry ? [1, 2, 3] : [1, 2], 'steps are numbered in order');
    assert.ok(!prompt.includes('`'), 'prompt contains no code');
    const player = between(html, '<div class="hb-player">', '</div>');
    if (kind === 'once') {
      assert.equal(count(html, 'data-hb-replay'), 1, 'one Replay control');
      assert.ok(player.includes('data-hb-replay'), 'Replay is in the player bar');
      assert.ok(body[2], 'a plays-once page plays on arrival (data-hb-autoplay on the body)');
    }
    if (kind === 'loop') {
      assert.equal(count(html, 'data-hb-pause'), 1, 'one Pause control');
      assert.ok(['', '="css"'].some(mode => player.includes(PAUSE.replace('{MODE}', mode))),
        'the Pause button is in the player bar exactly as in the template, starting in the playing state');
      assert.equal(count(html, 'data-hb-replay') + count(html, 'data-hb-loop') + count(html, 'data-hb-autoplay'), 0,
        'a loop has no Replay, Loop or autoplay');
    }
    if (kind === 'do') {
      // A do-it page shows itself once on arrival: the shared script presses Show me when the body asks for autoplay.
      assert.ok(body[2], 'a do-it page runs Show me once on arrival (data-hb-autoplay on the body)');
      for (const other of ['data-hb-replay', 'data-hb-loop', 'data-hb-pause', 'data-hb-autoscroll', 'data-hb-top']) {
        assert.equal(count(html, other), 0, `a do-it page has no ${other}`);
      }
    }
    assertScrollControls(kind, html, player, !!body[2]);
    assertShowMeAndReset(kind, html, player);
    for (const marker of ['data-hb-loop', 'data-hb-slowmo', 'data-hb-pause', 'data-hb-demo', 'data-hb-reset', 'data-hb-autoscroll', 'data-hb-top']) {
      assert.ok(count(html, marker) <= 1, `at most one ${marker}`);
      assert.equal(count(player, marker), count(html, marker), `${marker} is in the player bar`);
      const input = (html.match(new RegExp(`<input[^>]*${marker}[^>]*>`)) || [''])[0];
      assert.ok(!/\schecked\b/.test(input), `${marker} switch starts unchecked`);
    }
    if (hasTry) {
      const tryIt = tryItOf(html);
      const main = between(tryIt, '<div class="hb-settings">', '<details class="hb-options">');
      const mainCount = count(main, 'class="hb-setting"');
      assert.ok(mainCount >= 1 && mainCount <= 3, `${mainCount} main settings`);
      assert.equal(count(tryIt, 'class="hb-hint"'), count(tryIt, 'class="hb-setting"'), 'every setting has one hint');
    }
    const good = count(between(html, '<ul class="hb-tags hb-good">', '</ul>'), '<li>');
    const avoid = count(between(html, '<ul class="hb-tags hb-avoid">', '</ul>'), '<li>');
    assert.ok(good >= 3 && good <= 5, `${good} Good for tags`);
    assert.ok(avoid >= 1 && avoid <= 3, `${avoid} Avoid on tags`);
    for (const [, href] of html.matchAll(/<a href="([^"]+)" rel="(?:prev|next)"/g)) {
      assert.ok(isDemoDir(path.resolve(d.dir, href)), `pager link ${href}`);
    }
  });

  test(`${d.slug}: every setting has a label and every choice group has one choice made`, () => {
    if (!pageOf(d).includes('<section class="hb-step hb-try"')) return; // no settings, no Try it step
    const tryIt = tryItOf(pageOf(d));
    // A choice group is a div whose class list includes seg or swatches, wherever the class attribute sits.
    const groups = [...tryIt.matchAll(/<div\b(?=[^>]*\sclass="(?:[^"]*\s)?(seg|swatches)(?:\s[^"]*)?")([^>]*)>([\s\S]*?)<\/div>/g)];
    assert.equal(groups.length, count(tryIt, 'role="group"'), 'every group in Try it is a choice group that is checked here');
    for (const [, cls, attrs, inner] of groups) {
      const labelledBy = (attrs.match(/aria-labelledby="([^"]+)"/) || [])[1];
      assert.ok(/role="group"/.test(attrs), `a ${cls} group has role="group"`);
      assert.ok(labelledBy && tryIt.includes(`id="${labelledBy}"`), `a ${cls} group is labelled`);
      assert.equal(count(inner, 'aria-pressed="true"'), 1, `${labelledBy} has exactly one choice made`);
    }
    for (const [, name, attrs] of tryIt.matchAll(/<(input|select|textarea)\b([^>]*)>/g)) {
      if (/type="checkbox"/.test(attrs)) continue;
      const id = (attrs.match(/\sid="([^"]+)"/) || [])[1];
      assert.ok(id && new RegExp(`<label[^>]*\\sfor="${id}"`).test(tryIt), `${name} ${id || '(no id)'} has a label`);
    }
    assert.equal(count(tryIt, 'type="checkbox"'), count(tryIt, 'class="hb-switch-row"'), 'every switch sits in a labelled switch row');
  });

  test(`${d.slug}: README is ready for the site`, () => {
    const s = sections(read(path.join(d.dir, 'README.md')));
    for (const h of ['What it is', 'When to use it', 'Key parameters', 'See also']) assert.ok(s[h], `section ${h}`);
    assert.ok(!s['What it is'].includes('`'), 'What it is has no code');
    assert.ok(!s['Key parameters'].includes('`'), 'Key parameters has no code');
    assert.ok(table(s['Key parameters']).length > 0, 'Key parameters has rows');
    const links = [...s['See also'].matchAll(/^\s*[-*]\s+\[[^\]]+\]\(([^)\s]+)\)(.*)$/gm)];
    assert.ok(links.length > 0, 'See also has links');
    for (const [, href, rest] of links) {
      assert.ok(isDemoDir(path.resolve(d.dir, href)), `See also link ${href}`);
      assert.match(rest, /^\s*[—–-]\s*\S/, `See also ${href} has a short description`);
    }
  });

  test(`${d.slug}: Try it and the README Key parameters name the same settings`, () => {
    if (!pageOf(d).includes('<section class="hb-step hb-try"')) return; // no settings, no Try it step
    const tryIt = tryItOf(pageOf(d));
    const names = [...tryIt.matchAll(/<(p|label) class="hb-setting-name"[^>]*>([^<]*)<\/\1>|<label class="hb-switch-row"><span>([^<]*)<\/span>/g)]
      .map(m => decode((m[2] ?? m[3]).trim()));
    const keys = keyParameters(d);
    assert.ok(names.length > 0, 'Try it has settings');
    for (const name of names) assert.ok(keys.includes(name), `Try it setting "${name}" is in Key parameters`);
    for (const key of keys) assert.ok(names.includes(key), `Key parameter "${key}" is a setting in Try it`);
  });

  test(`${d.slug}: See also links use the titles of the pages they open`, () => {
    const seeAlso = sections(read(path.join(d.dir, 'README.md')))['See also'];
    for (const [, name, href] of seeAlso.matchAll(/^\s*[-*]\s+\[([^\]]+)\]\(([^)\s]+)\)/gm)) {
      const h1 = read(path.join(path.resolve(d.dir, href), 'index.html')).match(/<h1>([^<]*)<\/h1>/);
      assert.ok(h1, `${href} has a title`);
      assert.equal(name, decode(h1[1]), `See also ${href}`);
    }
  });

  test(`${d.slug}: the meta, Open Graph, Twitter and JSON-LD descriptions match the lede`, () => {
    const html = pageOf(d);
    const lede = decode(html.match(/<p class="hb-lede">([^<]*)<\/p>/)[1]);
    for (const tag of ['name="description"', 'property="og:description"', 'name="twitter:description"']) {
      const meta = html.match(new RegExp(`<meta ${tag} content="([^"]*)">`));
      assert.ok(meta, `<meta ${tag}> is there`);
      assert.equal(decode(meta[1]), lede, tag);
    }
    const ld = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
    assert.ok(ld, 'JSON-LD is there');
    assert.equal(JSON.parse(ld[1]).description, lede, 'JSON-LD description');
  });

  test(`${d.slug}: the player switches and every Try it field have autocomplete="off"`, () => {
    const html = pageOf(d);
    const player = between(html, '<div class="hb-player">', '</div>');
    const fields = [...player.matchAll(/<input\b[^>]*>/g), ...tryItOf(html).matchAll(/<(?:input|select|textarea)\b[^>]*>/g)].map(m => m[0]);
    // A Try it made only of choice buttons, on a scroll or do-it page whose player bar has no switch, has no form field at all;
    // any page that does hold a field must have it found here, or the check below would pass without checking anything.
    if (html.includes('<section class="hb-step hb-try"') && /<(?:input|select|textarea)/.test(html)) assert.ok(fields.length > 0, 'the page has fields');
    for (const field of fields) assert.match(field, /\sautocomplete="off"/, field);
  });

  test(`${d.slug}: the home page card uses the page's title, or the shorter name an owner ruling keeps`, () => {
    // Four 3D & Advanced cards keep a shorter name than their page title, by an owner ruling.
    const SHORTER = { 'fluid-simulation': 'Fluid Simulation', 'ray-marching-sdf': 'Ray Marching / SDF', 'cloth-simulation': 'Cloth Simulation', 'volumetric-smoke': 'Volumetric Smoke' };
    const h1 = decode(pageOf(d).match(/<h1>([^<]*)<\/h1>/)[1]);
    const entry = HOME.match(new RegExp(`\\['${d.slug}','((?:[^'\\\\]|\\\\.)*)',`));
    assert.ok(entry, 'home page entry');
    assert.equal(entry[1].replace(/\\'/g, "'"), SHORTER[d.slug] || h1);
  });

  test(`${d.slug}: the home page card uses the page's description`, () => {
    const lede = decode(pageOf(d).match(/<p class="hb-lede">([^<]*)<\/p>/)[1]);
    const entry = HOME.match(new RegExp(`\\['${d.slug}','(?:[^'\\\\]|\\\\.)*','((?:[^'\\\\]|\\\\.)*)'\\]`));
    assert.ok(entry, 'home page entry');
    assert.equal(entry[1].replace(/\\'/g, "'"), lede);
  });
}

// The pages the switch tests cover. FINAL GATE: while the rollout runs these are the pages that have the switch; at integration
// this line becomes `const SWITCHED = steps;`, so an animation page without the switch fails
// (docs/superpowers/specs/2026-10-13-see-inside-compare-rollout-design.md, section 4, item 5).
const SWITCHED = steps.filter(d => pageOf(d).includes('data-hb-modes'));
// The mode switch (See inside and Compare), exactly as in the template, between the Watch step's heading and its stage, with
// a note for See inside and one for Compare after the player bar, both hidden until their mode is pressed.
const MODES = '<div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes><button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button><button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button><button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button></div>';
// The notes box exactly: the See inside note, then the Compare note, each a direct child of the box and hidden at first.
const NOTES_BOX = /<div class="hb-mode-notes" aria-live="polite"><p data-hb-for="inside" hidden>((?:(?!<\/p>)[\s\S])*)<\/p><p data-hb-for="compare" hidden>((?:(?!<\/p>)[\s\S])*)<\/p><\/div>/;
const sentencesIn = html => decode(html.replace(/<[^>]+>/g, '')).split(/[.!?](?:\s|$)/).filter(s => s.trim()).length;
// The index of the bracket that closes the one at `at` in a script (round, square and curly brackets counted together),
// stepping over strings, template text (its ${…} parts are read as code), comments and regular expressions; -1 when it is
// never closed.
function closingOf(src, at) {
  let depth = 0;
  for (let i = at; i < src.length; i++) {
    const c = src[i];
    if (c === '"' || c === "'") {
      for (i++; i < src.length && src[i] !== c; i++) if (src[i] === '\\') i++;
    } else if (c === '`') {
      for (i++; i < src.length && src[i] !== '`'; i++) {
        if (src[i] === '\\') i++;
        else if (src[i] === '$' && src[i + 1] === '{') { i = closingOf(src, i + 1); if (i < 0) return -1; }
      }
    } else if (c === '/' && src[i + 1] === '/') {
      i = src.indexOf('\n', i);
      if (i < 0) return -1;
    } else if (c === '/' && src[i + 1] === '*') {
      i = src.indexOf('*/', i + 2) + 1;
      if (i < 1) return -1;
    } else if (c === '/' && /(?:^|[(,=:[!&|?{};])\s*$/.test(src.slice(Math.max(0, i - 80), i))) {
      // a regular expression: up to its closing slash, past escapes and character classes
      for (i++; i < src.length && src[i] !== '/'; i++) {
        if (src[i] === '\\') i++;
        else if (src[i] === '[') while (++i < src.length && src[i] !== ']') if (src[i] === '\\') i++;
      }
    } else if ('([{'.includes(c)) depth++;
    else if (')]}'.includes(c) && --depth === 0) return i;
  }
  return -1;
}
for (const d of SWITCHED) {
  test(`${d.slug}: the mode switch is as in the template, before the stage, with a note for See inside and Compare`, () => {
    const html = pageOf(d), flat = html.replace(/>\s+</g, '><');
    assert.equal(count(html, 'data-hb-modes'), 1, 'one mode switch');
    assert.ok(flat.includes(MODES), 'the mode switch is exactly as in the template');
    const watch = between(flat, '<section class="hb-step hb-watch"', '</section>');
    const at = watch.indexOf(MODES);
    const stageAt = watch.search(/<div class="stage[\s"]/);
    assert.ok(stageAt > -1 && at > watch.indexOf('<div class="hb-step-head">') && at < stageAt, 'between the heading and the stage');
    const notes = between(watch, '<div class="hb-mode-notes" aria-live="polite">', '</div>');
    assert.ok(notes && watch.indexOf(notes) > watch.indexOf('<div class="hb-player">'), 'the notes come after the player bar');
    for (const mode of ['inside', 'compare']) assert.equal(count(notes, `<p data-hb-for="${mode}" hidden>`), 1, `one ${mode} note, hidden at first`);
    for (const [, href] of notes.matchAll(/<a href="([^"]+)"/g)) assert.ok(isDemoDir(path.resolve(d.dir, href)), `note link ${href}`);
  });

  test(`${d.slug}: exactly two notes, See inside then Compare, each one or two sentences`, () => {
    const flat = pageOf(d).replace(/>\s+</g, '><');
    const box = between(flat, '<section class="hb-step hb-watch"', '</section>').match(NOTES_BOX);
    assert.ok(box, 'the notes box holds the See inside note and then the Compare note, each a direct child, and nothing else');
    for (const [i, name] of [[1, 'See inside'], [2, 'Compare']]) {
      const n = sentencesIn(box[i]);
      assert.ok(n >= 1 && n <= 2, `the ${name} note has ${n} sentences`);
    }
  });

  test(`${d.slug}: the page's script listens for hb:mode, and its styles mark modes on the stage only`, () => {
    const html = pageOf(d);
    const script = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m => m[1]).join('\n');
    assert.match(script, /document\.addEventListener\(\s*['"]hb:mode['"]/, 'the page script listens for hb:mode on document');
    // The listener is in place once the script has run: no load or DOMContentLoaded handler holds it, whether written in the call
    // or as a named function (a load listener for something else, such as Scrollspy Navigation's remeasure, is fine)
    const listen = script.search(/document\.addEventListener\(\s*['"]hb:mode['"]/);
    for (const m of script.matchAll(/addEventListener\(\s*['"](?:DOMContentLoaded|load)['"]\s*,\s*([A-Za-z_$][\w$]*)?\s*(\(|=>)?/g)) {
      const name = m[1] && !m[2] && !/^(?:function|async)$/.test(m[1]) ? m[1].replace(/\$/g, '\\$') : '';
      const def = name ? script.search(new RegExp(`function\\s+${name}\\s*\\(|\\b(?:const|let|var)\\s+${name}\\s*=`)) : -1;
      const from = name ? (def > -1 ? script.indexOf('{', def) : -1) : m.index + m[0].indexOf('(');
      if (from < 0) continue;
      const to = closingOf(script, from);
      assert.ok(!(listen > from && listen < (to < 0 ? script.length : to)),
        `the hb:mode listener is not in place at the top level: it waits for the page to load (${m[0].trim()}…)`);
    }
    const style = [...html.matchAll(/<style>([\s\S]*?)<\/style>/g)].map(m => m[1]).join('\n');
    const marked = cssRules(style).flatMap(r => r.selector.split(',').map(s => s.trim())).filter(s => s.includes('data-hb-mode'));
    for (const sel of marked) {
      assert.ok(!/data-hb-mode=["']?normal/.test(sel), `no rule for Normal: ${sel}`);
      assert.match(sel, /\.stage\[data-hb-mode="(?:inside|compare)"\]/, `a mode rule names the stage: ${sel}`);
    }
  });
}

test("on phones the mode switch's own rule outranks the rule for choice buttons, so its three buttons share the row equally", () => {
  const bare = read(path.join(ROOT, 'assets', 'css', 'demo-page.css')).replace(/\/\*[\s\S]*?\*\//g, '');
  const modes = cssRules(blockOf(bare, '@media(max-width:760px){')).find(r => r.selector === '.hb-page .seg.hb-modes button');
  const seg = cssRules(blockOf(bare, '@media(max-width:600px){')).find(r => r.selector === '.hb-page .seg button');
  assert.ok(modes && /(^|;)\s*flex:\s*1 1 0\s*(;|$)/.test(modes.body), 'up to 760px the mode buttons share their row equally (flex: 1 1 0)');
  assert.ok(seg && /(^|;)\s*flex:/.test(seg.body), 'the phone rule for choice buttons sets flex too');
  assert.ok(outranks(specificity(modes.selector), specificity(seg.selector)), `${modes.selector} must outrank ${seg.selector}`);
});

// The do-it pages played with the pointer, where Show me was once the only thing a keyboard could do, can be played from the
// keyboard too: the stage holds something that takes keyboard focus (a button, a link or an element with tabindex="0"), and
// the page answers keys (its own script listens for keydown, or its own style has a :focus-visible rule). Every page that
// misses one is listed at once.
const KEYBOARD_PAGES = {
  '04-micro-interactions': ['cursor-follower', 'hover-state', 'image-trail', 'spotlight-hover', 'magnetic-button', 'click-ripple', 'before-after-slider', 'magnifier-lens', 'card-deck-swipe'],
  '05-text-typography': ['text-particles'],
  '06-3d-advanced': ['2-5d-pseudo-3d', 'depth-map-photo', 'holographic-card', 'image-distortion-hover', 'parallax-3d-tilt', 'water-ripple']
};
test('the do-it pages played with the pointer can be played from the keyboard', () => {
  const problems = [];
  for (const [cat, slugs] of Object.entries(KEYBOARD_PAGES)) {
    for (const slug of slugs) {
      const html = read(path.join(ANIM, cat, slug, 'index.html'));
      const stage = between(html, '<div class="stage', '<div class="hb-player">');
      const style = [...html.matchAll(/<style>([\s\S]*?)<\/style>/g)].map(m => m[1]).join('\n');
      const script = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m => m[1]).join('\n');
      if (!stage) problems.push(`${cat}/${slug}: no stage found`);
      else if (!/<button\b|<a\b[^>]*\shref=|\stabindex="0"/.test(stage)) problems.push(`${cat}/${slug}: nothing in the stage takes keyboard focus`);
      // The keyboard does what the pointer does in one of three ways: the arrow keys move a pretend pointer (a keydown
      // listener that names an arrow key), keyboard focus shows what Show me shows (a :focus-visible selector in a rule
      // with .is-demo), or a click with no pointer (detail 0: Enter, Space or assistive technology) starts the effect.
      // A :focus-visible rule that only recolors the focus ring is none of these.
      const arrows = /['"]keydown['"]/.test(script) && /\bArrow(Left|Right|Up|Down)\b/.test(script);
      const focusShows = cssRules(style).some(rule => rule.selector.includes(':focus-visible') && rule.selector.includes('.is-demo'));
      const keyClick = /\.detail\s*[!=]==?\s*0\b/.test(script);
      if (!arrows && !focusShows && !keyClick) problems.push(`${cat}/${slug}: no keyboard path (arrow keys, focus styled with .is-demo, or a click with detail 0)`);
    }
  }
  assert.deepEqual(problems, []);
});

// The Show me and Reset rules run on the player bar of every page above. These cases run them on made-up player bars, so
// each kind is covered before a page of that kind exists.
test('Show me belongs to do-it pages and Reset to do-it and loop pages, each exactly as in the template', () => {
  const PAUSE_BUTTON = PAUSE.replace('{MODE}', '');
  const REPLAY = '<button class="hb-play" type="button" id="btn-play" data-hb-replay>Replay</button>';
  const SLOW = '<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>';
  const barOf = (...items) => `<div class="hb-player">\n      ${items.join('\n      ')}\n    </div>`;
  const check = (kind, html) => assertShowMeAndReset(kind, html, between(html, '<div class="hb-player">', '</div>'));
  const ok = (kind, ...items) => assert.doesNotThrow(() => check(kind, barOf(...items)), `a ${kind} page with ${items.length} controls passes`);
  const notOk = (message, kind, html) => assert.throws(() => check(kind, html), err => err.message.startsWith(message), `${kind}: ${message}`);

  ok('do', SHOW_ME);
  ok('do', SHOW_ME, RESET);
  ok('do', SHOW_ME, RESET, SLOW);
  ok('loop', PAUSE_BUTTON, RESET, SLOW); // a loop may have a Reset too: Pause, Reset, Slow motion
  ok('loop', PAUSE_BUTTON, SLOW);
  ok('once', REPLAY, SLOW);
  ok('scroll', PLAY, TOP);

  for (const kind of ['once', 'loop', 'scroll']) notOk('only a do-it page has data-hb-demo', kind, barOf(SHOW_ME, REPLAY));
  for (const kind of ['once', 'scroll']) notOk('only a do-it or loop page has data-hb-reset', kind, barOf(REPLAY, RESET));

  notOk('one Show me control', 'do', barOf(RESET));
  notOk('one Show me control', 'do', barOf(SHOW_ME, SHOW_ME.replace('id="btn-demo"', 'id="btn-demo-2"')));
  notOk('the Show me button is in the player bar exactly as in the template', 'do', barOf(SHOW_ME.replace('Show me</button>', 'Play</button>')));
  notOk('on a do-it page the Reset button comes right after Show me', 'do', barOf(SHOW_ME, SLOW, RESET));
  notOk('on a do-it page the Reset button comes right after Show me', 'do', barOf(RESET, SHOW_ME));
  for (const [kind, first] of [['do', SHOW_ME], ['loop', PAUSE_BUTTON]]) {
    notOk('the Reset button is in the player bar exactly as in the template', kind, barOf(first, RESET.replace('class="hb-play"', 'class="hb-reset"')));
    notOk('the Reset button is in the player bar exactly as in the template', kind, barOf(first, RESET.replace('id="btn-reset"', 'id="reset"')));
    notOk('the Reset button is in the player bar exactly as in the template', kind, `<div class="stage">${RESET}</div>${barOf(first)}`);
    notOk('at most one Reset', kind, barOf(first, RESET, RESET.replace('id="btn-reset"', 'id="btn-reset-2"')));
  }
});

// The Play, Back to top and scroller rules run on every page above. These cases run them on made-up pages, so the scroll
// kind is covered before a scroll page exists.
test('Play, Back to top and the scroller belong to scroll pages, and a scroll page runs once on arrival with no other player control', () => {
  const noIcon = button => button.replace(/<svg[\s\S]*?<\/svg>/, '');
  const REPLAY = '<button class="hb-play" type="button" id="btn-play" data-hb-replay>Replay</button>';
  const LOOP = '<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="loop-tog" data-hb-loop autocomplete="off"><span>Loop</span></label>';
  const SLOW = '<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>';
  const pageOf = (bar, stage = '') => `<div class="stage">${stage}</div>\n    <div class="hb-player">\n      ${bar.join('\n      ')}\n    </div>`;
  const run = (kind, html, autoplay = true) => assertScrollControls(kind, html, between(html, '<div class="hb-player">', '</div>'), autoplay);
  const ok = (kind, html) => assert.doesNotThrow(() => run(kind, html), `a ${kind} page passes`);
  const notOk = (message, kind, html, autoplay) => assert.throws(() => run(kind, html, autoplay), err => err.message.startsWith(message), `${kind}: ${message}`);

  const scrollPage = pageOf([PLAY, TOP]);
  ok('scroll', scrollPage);
  ok('scroll', pageOf([PLAY, TOP], '<div data-hb-scroller></div>')); // the stage holds its own scroller

  notOk('a scroll page scrolls once on arrival (data-hb-autoplay on the body)', 'scroll', scrollPage, false);
  notOk('one Play control', 'scroll', pageOf([TOP]));
  notOk('one Play control', 'scroll', pageOf([PLAY, PLAY.replace('btn-scroll', 'btn-scroll-2'), TOP]));
  notOk('one Back to top control', 'scroll', pageOf([PLAY]));
  // Each button in the player bar exactly as in the template (one in the stage, relabelled, without its icon, with another id
  // or class fails), and Back to top right after Play.
  const EXACT = 'Play and Back to top are in the player bar exactly as in the template';
  notOk(EXACT, 'scroll', `<div class="stage">${PLAY}</div>\n<div class="hb-player">\n${TOP}\n</div>`);
  notOk(EXACT, 'scroll', pageOf([PLAY.replace('Play</button>', 'Scroll</button>'), TOP]));
  notOk(EXACT, 'scroll', pageOf([PLAY, TOP.replace('Back to top</button>', 'Top</button>')]));
  notOk(EXACT, 'scroll', pageOf([noIcon(PLAY), TOP]));
  notOk(EXACT, 'scroll', pageOf([PLAY, noIcon(TOP)]));
  notOk(EXACT, 'scroll', pageOf([PLAY.replace('id="btn-scroll"', 'id="btn-play"'), TOP]));
  notOk(EXACT, 'scroll', pageOf([PLAY, TOP.replace('id="btn-top"', 'id="top"')]));
  notOk(EXACT, 'scroll', pageOf([PLAY.replace('class="hb-play"', 'class="hb-scroll"'), TOP]));
  notOk('the Back to top button comes right after Play', 'scroll', pageOf([TOP, PLAY]));
  notOk('the Back to top button comes right after Play', 'scroll', pageOf([PLAY, '<span class="hb-hint">6 seconds</span>', TOP]));
  notOk('at most one scroller', 'scroll', pageOf([PLAY, TOP], '<div data-hb-scroller></div><div data-hb-scroller></div>'));
  // A scroll page has none of the other player controls; Slow motion is one of them (Play's speed is fixed).
  for (const [marker, control] of [['data-hb-replay', REPLAY], ['data-hb-loop', LOOP], ['data-hb-pause', PAUSE.replace('{MODE}', '')],
    ['data-hb-demo', SHOW_ME], ['data-hb-slowmo', SLOW]]) {
    notOk(`a scroll page has no ${marker}`, 'scroll', pageOf([PLAY, TOP, control]));
  }

  // Only scroll pages have these markers: the shared script presses Play before anything else on arrival, so a stray one on
  // another kind of page would quietly replace that page's own arrival.
  for (const kind of ['once', 'loop', 'do']) {
    ok(kind, pageOf([REPLAY]));
    notOk('only a scroll page has data-hb-autoscroll', kind, pageOf([REPLAY, PLAY]));
    notOk('only a scroll page has data-hb-top', kind, pageOf([REPLAY, TOP]));
    notOk('only a scroll page has data-hb-scroller', kind, pageOf([REPLAY], '<div data-hb-scroller></div>'));
  }
});

test('every guided-steps page and the home page link the same version of the shared files', () => {
  const versions = new Set([...steps.map(pageOf), HOME].flatMap(html => [...html.matchAll(/demo-page\.(?:css|js)\?v=(\d+)/g)].map(m => m[1])));
  assert.equal(versions.size, 1, `versions in use: ${[...versions].join(', ')}`);
  assert.match(HOME, /<script src="assets\/js\/demo-page\.js\?v=\d+" defer><\/script>/, 'the home page links the page script, for Copy prompt');
});

// A page that starts a setting lower on phones marks that choice data-hb-phone, and its own script takes the phone default from
// the mark and presses it there. The home page reads the page without running it, and on a phone the shared script counts the
// marked choice instead of the pressed one, so a card's Copy prompt copies what the page copies on the same screen.
test('a setting that starts lower on phones marks that choice data-hb-phone, and the page script starts there from the mark', () => {
  const PHONE_DEFAULTS = { 'gpgpu-particle-system': ['count-seg', '16,000'], 'cloth-simulation': ['detail-seg', 'Low'], 'audio-visualizer': ['bars-seg', 'Some'] };
  for (const slug of Object.keys(PHONE_DEFAULTS)) assert.ok(steps.some(d => d.slug === slug), `${slug} is a guided-steps page`);
  for (const d of steps) {
    const html = pageOf(d), where = `${d.cat}/${d.slug}`;
    const scripts = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/g)].map(m => m[1]).join('\n');
    const markup = html.replace(/<script\b[\s\S]*?<\/script>/g, '');
    // Every mark is on a choice button of a choice group in Try it, one at most in each group, and never on the pressed choice:
    // the markup presses the default of larger screens.
    const marked = {};
    for (const [, attrs, inner] of tryItOf(markup).matchAll(/<div\b(?=[^>]*\sclass="(?:[^"]*\s)?(?:seg|swatches)(?:\s[^"]*)?")([^>]*)>([\s\S]*?)<\/div>/g)) {
      const id = (attrs.match(/\sid="([^"]+)"/) || [])[1];
      const phone = [...inner.matchAll(/<button\b([^>]*)>([^<]*)<\/button>/g)].filter(([, a]) => /\sdata-hb-phone(?=[\s=]|$)/.test(a));
      assert.ok(phone.length <= 1, `${where}: ${id} marks one phone default at most`);
      for (const [, a, label] of phone) {
        assert.ok(!/aria-pressed="true"/.test(a), `${where}: the phone default of ${id} is not the choice pressed in the markup`);
        marked[id] = decode(label.trim());
      }
    }
    assert.equal(Object.keys(marked).length, count(markup, 'data-hb-phone'), `${where}: every data-hb-phone is on a choice button in Try it`);
    for (const id of Object.keys(marked)) assert.ok(scripts.includes(`#${id} [data-hb-phone]`), `${where}: the page script reads the phone default of ${id} from its mark`);
    const known = PHONE_DEFAULTS[d.slug];
    if (known) assert.deepEqual(marked, { [known[0]]: known[1] }, `${where}: phones start with ${known[1]}`);
  }
});

// The footer of every page: the site's name, a link to the source on GitHub (in a new tab) and Back to top.
test('every guided-steps page has the same footer, with a link to the source on GitHub', () => {
  const FOOTER = '<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>';
  assert.ok(steps.length > 0, 'there are guided-steps pages');
  assert.deepEqual(steps.filter(d => count(pageOf(d), FOOTER) !== 1 || count(pageOf(d), '<footer') !== 1).map(d => `${d.cat}/${d.slug}`), [],
    'pages without exactly this footer');
});

// The Star link at the end of every page's top bar and the star row under its prompt card, the same on every page
// (docs/superpowers/specs/2026-10-12-star-button-design.md).
const STAR_ICON = '<svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>';
const STAR_HREF = 'href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"';
const BAR_STAR = `<a class="hb-star" ${STAR_HREF} aria-label="Star on GitHub">${STAR_ICON}<span>Star on GitHub</span></a>`;
const STAR_ROW = `<div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" ${STAR_HREF}>${STAR_ICON}Star on GitHub</a></div>`;
test('every guided-steps page asks for a star at the end of its top bar and under its prompt card', () => {
  const lastAfter = (part, piece, before) => part.trimEnd().endsWith(piece) &&
    part.slice(0, part.lastIndexOf(piece)).trimEnd().endsWith(before);
  // The star row comes after the card has closed: every div opened from the card's start is closed again before it.
  const afterCard = promptStep => {
    const before = promptStep.slice(promptStep.indexOf('<div class="hb-card">'), promptStep.lastIndexOf(STAR_ROW));
    return before.startsWith('<div class="hb-card">') && count(before, '<div') === count(before, '</div>');
  };
  const wrong = steps.filter(d => {
    const html = pageOf(d);
    const bar = between(html, '<nav class="hb-bar"', '</nav>');
    const promptStep = between(html, '<section class="hb-step hb-prompt-step"', '</section>');
    return count(html, BAR_STAR) !== 1 || !lastAfter(bar, BAR_STAR, '</span>') ||
      count(html, STAR_ROW) !== 1 || !lastAfter(promptStep, STAR_ROW, '</div>') || !afterCard(promptStep);
  }).map(d => `${d.cat}/${d.slug}`);
  assert.deepEqual(wrong, [], 'pages without the Star link right after the pager, or without the star row right after the prompt card');
});

test('the shared stylesheet makes the Star link a round star from 820px to 1060px and leaves it to the star row below 820px', () => {
  const css = read(path.join(ROOT, 'assets/css/demo-page.css')).replace(/\/\*[\s\S]*?\*\//g, '');
  const sets = (rules, selector, declaration) => rules.some(rule => rule.selector.split(',').some(part => part.trim() === selector) &&
    rule.body.split(';').some(d => d.replace(/\s+/g, '') === declaration));
  const within = media => cssRules(between(css, `@media(${media}){`, '\n}'));
  assert.ok(sets(cssRules(css), '.hb-bar .hb-pager', 'margin-left:auto'), 'the pager sits beside the Star link, at the right end');
  assert.ok(sets(cssRules(css), '.hb-bar .hb-star', 'box-sizing:border-box'), 'the Star link is 44px high whatever the demo sets');
  assert.ok(sets(within('max-width:1060px'), '.hb-bar .hb-star', 'width:44px'), 'from 820px to 1060px the Star link is a 44px round star');
  assert.ok(sets(within('max-width:1060px'), '.hb-bar .hb-star>span', 'display:none'), 'with no words');
  const hiding = cssRules(css).filter(rule => rule.selector.split(',').some(part => part.trim() === '.hb-bar .hb-star') &&
    rule.body.split(';').some(d => d.replace(/\s+/g, '') === 'display:none'));
  assert.equal(hiding.length, 1, 'one rule takes the Star link out of the top bar');
  assert.ok(sets(within('max-width:819px'), '.hb-bar .hb-star', 'display:none'), 'and it is for screens under 820px, where the star row asks instead');
});

const sharedRules = cssRules(read(path.join(ROOT, 'assets/css/demo-page.css')));
const rulesFor = selector => sharedRules.filter(rule => rule.selector.split(',').some(part => part.trim() === selector));

test('the shared stylesheet draws the focus ring inward inside the stage, beating the site ring', () => {
  // The stage clips what sticks out of it, so the site ring (drawn 3px outside) is cut off on anything focusable inside it.
  const site = sharedRules.filter(rule => /^body\.hb[^,]*:focus-visible$/.test(rule.selector));
  assert.equal(site.length, 1, 'the site focus ring rule (body.hb :focus-visible) is in the stylesheet');
  const inward = '.hb-page .stage :focus-visible';
  assert.ok(rulesFor(inward).some(rule => /(^|;)\s*outline-offset:\s*-3px\s*(;|$)/.test(rule.body)), 'a focus ring inside the stage is drawn 3px inward');
  assert.ok(outranks(specificity(inward), specificity(site[0].selector)),
    `${inward} (${specificity(inward)}) must outrank ${site[0].selector} (${specificity(site[0].selector)})`);
});

test('the shared stylesheet turns CSS scroll snapping off on a box that Play is scrolling', () => {
  // While Play scrolls a box the shared script marks it data-hb-autoscrolling; with snapping on, every step would snap to the
  // nearest snap point and the box would jump from card to card. !important, so that a snap type the page sets on the box
  // itself (inline, or in its own style) does not win, and nothing has to be remembered and written back afterwards.
  assert.ok(rulesFor('[data-hb-autoscrolling]').some(rule => /(^|;)\s*scroll-snap-type:\s*none\s*!important\s*(;|$)/.test(rule.body)),
    'a box marked data-hb-autoscrolling has scroll-snap-type: none !important');
});

test('the shared stylesheet gives a stage that grows with its text the same 260px short-window minimum as the other stages', () => {
  // On a short laptop window a tighter header lets a stage be 260px tall. A stage that grows with its text needs the same
  // minimum, or it stays at 300px and pushes the player bar off the first screen.
  for (const unit of ['vh', 'svh']) {
    const minimum = `clamp(260px,calc(100${unit} - 330px),440px)`;
    assert.ok(rulesFor('.hb-page .stage').some(rule => rule.body.includes(`height:var(--hb-stage-h,${minimum})`)), `a stage is ${minimum} tall on a short window`);
    assert.ok(rulesFor('.hb-page .stage.hb-grow').some(rule => rule.body.includes(`min-height:${minimum}`)), `a growing stage is at least ${minimum} tall on a short window`);
  }
});

test('the shared stylesheet keeps choice buttons at least 44px wide', () => {
  assert.ok(rulesFor('.hb-page .seg button').some(rule => /(^|;)\s*min-width:\s*44px\s*(;|$)/.test(rule.body)), 'a choice button is at least 44px wide');
});

test('the shared stylesheet draws the mode switch beside the Watch heading and the note beside a short player bar from 761px, and hides an empty notes box', () => {
  const css = read(path.join(ROOT, 'assets', 'css', 'demo-page.css'));
  const rules = cssRules(css);
  const has = sel => rules.some(r => r.selector.split(',').map(s => s.trim()).includes(sel));
  for (const sel of ['.hb-page .seg.hb-modes', '.hb-mode-notes p']) assert.ok(has(sel), sel);
  // The empty box is the aria-live region that makes a screen reader read each note out, so it must stay rendered: display:none
  // would take it out of the accessibility tree, and the first note shown might not be announced. It is hidden to the eye and taken
  // out of the flow instead, which takes no room and adds no gap. The box counts as empty until a note is un-hidden, and a note is
  // whatever element has data-hb-for (the script un-hides those), wherever it sits in the box.
  const emptyNotes = rules.filter(r => r.selector === '.hb-mode-notes:not(:has([data-hb-for]:not([hidden])))');
  assert.ok(emptyNotes.some(r => /(^|;)\s*position:\s*absolute\s*(;|$)/.test(r.body) && /(^|;)\s*clip-path:\s*inset\(50%\)\s*(;|$)/.test(r.body)),
    'an empty notes box takes no room: it is taken out of the flow and clipped away');
  assert.ok(!emptyNotes.some(r => /(^|;)\s*display:\s*none\s*(;|$)/.test(r.body)),
    'an empty notes box stays rendered, so the first note shown is announced by the live region');
  assert.ok(rules.some(r => r.selector === '.hb-mode-notes a' && /(^|;)\s*text-decoration:\s*underline\s*(;|$)/.test(r.body)),
    'a link in a note is underlined');
  // The switch is also a .seg, and the .seg rules (the gap, and the phone rule for .seg buttons) come later in the file: the
  // switch's own rules name .seg.hb-modes so that they outrank them and the three buttons are equal on phones.
  assert.ok(rules.some(r => r.selector === '.hb-page .seg.hb-modes button' && /(^|;)\s*flex:\s*1 1 0\s*(;|$)/.test(r.body)),
    'up to 760px the three mode buttons share their row equally, outranking the phone rule for .seg buttons');
  assert.match(css, /@media\(min-width:761px\)\{\s*\.hb-watch:has\(> \.hb-modes\)\{display:grid/, 'from 761px the switch shares the heading row');
  // From 761px a player bar with one or two controls leaves room beside it, so the note for the mode in view sits next to the bar,
  // under the switch, and is on a laptop's first screen: three columns (the player bar's own width, the room left over, the switch's
  // width); the heading spans the first two, the player bar keeps the start of its row (a note taller than the bar grows the row,
  // not the bar, so the bar does not move) and the note spans the other two. A bar with a third control, or with the note that
  // reduced motion adds (looked for itself: a bar with one control and that note has only two children), keeps the two columns,
  // the full row and the note under it. Up to 760px the note stays under the player bar: no other rule places it. The blocks
  // are taken with their braces matched, so a rule after a block's closing brace is not counted as inside it.
  const bare = css.replace(/\/\*[\s\S]*?\*\//g, '');
  const wide = blockOf(bare, '@media(min-width:761px){');
  const phones = blockOf(bare, '@media(max-width:760px){');
  const SHORT = '.hb-watch:has(> .hb-modes):not(:has(> .hb-player > :nth-child(3), > .hb-player > .hb-player-note))';
  for (const [what, text] of [
    ['three columns: the player bar, the room left over, the switch', `${SHORT}{grid-template-columns:auto minmax(0,1fr) auto}`],
    ['the heading runs up to the switch\'s column (the first two of three)', '.hb-watch:has(> .hb-modes) > .hb-step-head > div > h2{grid-row:1;grid-column:1/-2;'],
    ['the switch is in the third column', `${SHORT} > .hb-modes{grid-column:3}`],
    ['the player bar starts its row and stays at the start of it when the row grows', `${SHORT} > .hb-player{grid-column:1;align-self:start}`],
    ['the note spans the other two columns', `${SHORT} > .hb-mode-notes{grid-column:2/-1;`],
    ['a bar with a third control keeps the two columns (the switch beside the heading, the rest on the full row)', '.hb-watch:has(> .hb-modes){display:grid;grid-template-columns:minmax(0,1fr) auto;']
  ]) assert.ok(wide.includes(text), `from 761px: ${what}`);
  assert.ok(wide.includes('.hb-watch:has(> .hb-modes) > .hb-modes{grid-row:1;grid-column:2;flex-wrap:nowrap;'), 'the 761px block is the one that has the switch beside the heading');
  assert.equal(count(wide, '> .hb-mode-notes{'), 1, 'one rule places the note beside the player bar, and it is in the 761px block');
  assert.equal(count(css, '> .hb-mode-notes{'), 1, 'no other rule places the note, so phones keep it under the player bar');
  assert.ok(phones.includes('.hb-page .seg.hb-modes button{flex:1 1 0'), 'the block up to 760px is found (it holds the equal mode buttons)');
  assert.ok(!/\.hb-watch|\.hb-mode-notes|\.hb-player/.test(phones), 'up to 760px nothing makes the Watch step a grid or places the note or the player bar');
});

test('from 761px the help line runs under the heading and the switch, as wide as without the switch, and the heading row is no taller than the heading line', () => {
  // The Watch step's heading box and the box around its heading and help line give way (display: contents), so the number, the
  // heading and the help line take places on the step's grid: the heading in the first row up to the switch's column, the help line
  // in the second row across every column, as wide as on a page without the switch, both as far in as the number and the heading
  // box's gap put them there. Only those two plain boxes give way: no heading, paragraph or section loses its box, so nothing loses
  // its meaning for screen readers. The heading row is no taller than the heading line, so the stage and the player bar stay where
  // they are on a page without the switch: the switch is stretched to that line (from 761px its buttons drop the 44px minimum they
  // keep up to 760px), the number spans both rows (it reaches into the help line's row there too), and the help line is pulled up
  // by the gap between the step's rows less its own 4px. That gap is set in one place, the custom property --hb-watch-gap (12px on
  // short laptop screens), and the pull reads it, so the two cannot drift apart. With a coarse pointer (a phone held sideways, a
  // tablet) each mode button's tap area reaches 10px above and below it, an empty ::after that moves nothing, so even with the
  // smallest heading line a finger gets 44px. The values are read from the rules they follow, so a change to one of those fails
  // here. Every rule from 761px is for a Watch step that has the switch, so a page without it is drawn as before.
  const bare = read(path.join(ROOT, 'assets', 'css', 'demo-page.css')).replace(/\/\*[\s\S]*?\*\//g, '');
  const wide = blockOf(bare, '@media(min-width:761px){');
  const coarse = blockOf(bare, '@media(min-width:761px) and (pointer:coarse){');
  const shortLaptop = blockOf(bare, '@media(min-width:601px) and (max-height:760px){');
  const outside = bare.replace(/@media[^{]*\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}/g, ''); // the rules outside every @media block
  // The first px value of a property in the one rule written for exactly this selector
  const px = (css, selector, prop) => {
    const found = cssRules(css).filter(r => r.selector === selector && new RegExp(`(^|;)\\s*${prop}:`).test(r.body));
    assert.equal(found.length, 1, `one ${selector} rule sets ${prop}`);
    return Number(found[0].body.match(new RegExp(`(?:^|;)\\s*${prop}:\\s*(-?[\\d.]+)px`))[1]);
  };
  // The selectors of a selector list (commas inside brackets, as in :has(a, b), do not split it)
  const selectorsOf = list => {
    const out = [];
    let depth = 0, from = 0;
    for (let i = 0; i < list.length; i++) {
      if (list[i] === '(') depth++;
      else if (list[i] === ')') depth--;
      else if (list[i] === ',' && depth === 0) { out.push(list.slice(from, i).trim()); from = i + 1; }
    }
    return [...out, list.slice(from).trim()];
  };
  const indent = px(outside, '.hb-num', 'width') + px(outside, '.hb-step-head', 'gap');
  const own = px(outside, '.hb-step-head p', 'margin');
  const W = '.hb-watch:has(> .hb-modes)';
  assert.ok(outside.includes('.hb-watch{--hb-watch-gap:16px;gap:var(--hb-watch-gap)}'), 'the Watch step\'s gap is --hb-watch-gap, 16px');
  assert.ok(shortLaptop.includes('.hb-watch{--hb-watch-gap:12px}'), 'on a short laptop screen --hb-watch-gap is 12px');
  for (const rule of cssRules(bare).filter(r => selectorsOf(r.selector).includes('.hb-watch'))) {
    assert.ok(!/(^|;)\s*(row-)?gap:\s*(?!var\(--hb-watch-gap\))/.test(rule.body), `the Watch step's gap is set only through --hb-watch-gap: .hb-watch{${rule.body}}`);
  }
  for (const [what, text] of [
    ['the heading box and the box inside it give way', `${W} > .hb-step-head,${W} > .hb-step-head > div{display:contents}`],
    ['the number is in the first column over the heading row and the help line row, at the top', `${W} > .hb-step-head > .hb-num{grid-row:1/span 2;grid-column:1;align-self:start}`],
    [`the heading is in the first row up to the switch's column, ${indent}px in`, `${W} > .hb-step-head > div > h2{grid-row:1;grid-column:1/-2;margin-left:${indent}px}`],
    [`the help line is in the second row across every column, ${indent}px in, pulled up by the step's gap less its own ${own}px`,
      `${W} > .hb-step-head > div > p{grid-row:2;grid-column:1/-1;margin:calc(${own}px - var(--hb-watch-gap)) 0 0 ${indent}px}`],
    ['the switch is in the heading row, stretched to the heading line', `${W} > .hb-modes{grid-row:1;grid-column:2;flex-wrap:nowrap;align-self:stretch}`],
    ['its buttons drop the 44px minimum', `${W} > .hb-modes button{min-height:0}`]
  ]) assert.ok(wide.includes(text), `from 761px: ${what}`);
  assert.ok(!bare.includes('@media(min-width:761px) and (max-height:760px)'), 'short laptop screens need no pull of their own: --hb-watch-gap carries their gap');
  for (const [what, text] of [
    ['a mode button holds its tap area', `${W} > .hb-modes button{position:relative}`],
    ['the tap area reaches 10px above and below the button, and no wider', `${W} > .hb-modes button::after{content:"";position:absolute;inset:-10px 0}`]
  ]) assert.ok(coarse.includes(text), `from 761px with a coarse pointer: ${what}`);
  // The tap area counts from inside the button's border: the smallest heading line (the heading's smallest font size, everywhere or
  // on a short laptop screen, times its line height) less the two borders, plus 10px above and 10px below.
  const [, least, lineHeight] = cssRules(outside).find(r => r.selector === '.hb-step-head h2').body.match(/font:\s*\d+\s+clamp\(([\d.]+)px,[^)]*\)\/([\d.]+)/);
  const line = Math.min(Number(least), px(shortLaptop, '.hb-step-head h2', 'font-size')) * Number(lineHeight);
  const tap = line - 2 * px(outside, '.hb-page .seg button', 'border') + 2 * 10;
  assert.ok(tap >= 44, `with the smallest heading line (${line}px) a mode button's tap area is ${tap}px, under 44px`);
  const contents = cssRules(bare).filter(r => /(^|;)\s*display:\s*contents\s*(;|$)/.test(r.body)).flatMap(r => selectorsOf(r.selector));
  assert.deepEqual(contents, [`${W} > .hb-step-head`, `${W} > .hb-step-head > div`], 'only the two plain boxes give way');
  assert.equal(count(bare, '.hb-modes button{min-height:0}'), 1, 'only from 761px do the mode buttons drop the 44px minimum');
  assert.equal(px(outside, '.hb-page .seg button', 'min-height'), 44, 'up to 760px the mode buttons keep the 44px minimum of choice buttons');
  for (const css of [wide, coarse]) {
    for (const rule of cssRules(css)) for (const sel of selectorsOf(rule.selector)) assert.ok(sel.startsWith(W), `for a Watch step with the switch: ${sel}`);
  }
});

// The learning path and the idea lessons wait on feat/learn-pilot (docs/superpowers/specs/2026-10-13-see-inside-compare-rollout-design.md,
// section 5): no tracked page links into learn/ and the shared stylesheet keeps none of their rules. Delete this test when the
// learning path resumes (its first step reverts the clean-up commit, which takes this test away too).
test('while the learning path waits, no tracked page links into learn/ and the shared stylesheet has none of its rules', () => {
  let pages;
  try {
    pages = execFileSync('git', ['ls-files', '--', '*.html'], { cwd: ROOT, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).split(/\r?\n/).filter(Boolean);
  } catch {
    // No git here (a copy from a source zip): every page in the folder, outside git's, the agents' and the packages' folders
    const walk = dir => fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true }).flatMap(e => e.isDirectory()
      ? (['.git', '.claude', '.superpowers', 'node_modules'].includes(e.name) ? [] : walk(path.join(dir, e.name)))
      : e.name.endsWith('.html') ? [path.join(dir, e.name)] : []);
    pages = walk('');
  }
  assert.ok(pages.length > 100, `the tracked pages are found (${pages.length})`);
  const linking = pages.filter(f => /href="(?:(?:\.\.\/)+|\/animation-handbook\/)?learn\//.test(read(path.join(ROOT, f))));
  assert.deepEqual(linking, [], 'pages that link into learn/');
  assert.ok(!fs.existsSync(path.join(ROOT, 'learn')), 'the learn/ folder is gone');
  const css = read(path.join(ROOT, 'assets', 'css', 'demo-page.css')).replace(/\/\*[\s\S]*?\*\//g, '');
  for (const name of ['hb-lesson', 'hb-why', 'hb-seen', 'hb-learn', 'hb-path']) assert.ok(!css.includes(name), `no ${name} rule`);
});

test('the home page uses Schibsted Grotesk and asks what to animate', () => {
  assert.ok(HOME.includes("url('assets/fonts/schibsted-latin.woff2')"), 'Latin font file');
  assert.ok(HOME.includes("url('assets/fonts/schibsted-latin-ext.woff2')"), 'Latin Extended font file');
  for (const old of ['Bricolage', 'PlexMono', 'var(--mono)', '--mono:']) assert.ok(!HOME.includes(old), `still uses ${old}`);
  assert.ok(HOME.includes('<h1 class="h1" id="hero-title">What do you want to animate?</h1>'), 'heading');
  assert.ok(HOME.includes('Pick a place, or describe it in your own words. Every animation plays live, and each one comes with a ready-made prompt for your AI assistant.'), 'intro line');
});

// Every place the number of animations is written is compared with the cards in CATS: the home page (its head too), the root
// README, the issue template, the 404 page and the sitemap. Each sentence named below must still be found, so rewording one fails here
// instead of leaving its number unchecked.
const totalCards = () => homeConst('CATS').reduce((n, cat) => n + cat.entries.length, 0);
// The number in the first match of `pattern` (its first group) in `text`, or NaN when nothing matches.
const numberIn = (text, pattern) => { const m = String(text).match(pattern); return m ? Number(m[1]) : NaN; };

test('the counts written on the home page match its cards', () => {
  const cards = totalCards();
  assert.ok(HOME.includes(`${cards} free animations · no coding needed`), 'hero pill');
  assert.ok(HOME.includes(`<span id="more-label">Browse all ${cards} animations</span>`), 'Browse all button');
  assert.ok(HOME.includes(`<p class="foot-t">${cards} web animations with live demos and copyable prompts.</p>`), 'footer');
  assert.ok(between(HOME, '<noscript>', '</noscript>').includes(`All ${cards} are still easy to reach`), 'no-JavaScript note');
  // The head: what search engines and social sites show.
  const head = between(HOME, '<head>', '</head>');
  const meta = attr => (head.match(new RegExp(`<meta ${attr} content="([^"]*)">`)) || [])[1];
  const ld = between(head, '<script type="application/ld+json">', '</script>').replace('<script type="application/ld+json">', '');
  const texts = {
    '<title>': (head.match(/<title>([^<]*)<\/title>/) || [])[1],
    'meta description': meta('name="description"'),
    'og:title': meta('property="og:title"'),
    'og:description': meta('property="og:description"'),
    'twitter:title': meta('name="twitter:title"'),
    'twitter:description': meta('name="twitter:description"'),
    'JSON-LD description': ld && JSON.parse(ld).description
  };
  for (const [where, text] of Object.entries(texts)) {
    assert.ok(text, `the home page has its ${where}`);
    assert.equal(numberIn(text, /(\d+) web animation techniques/i), cards, `${where}: ${text}`);
  }
});

// The Full catalog of the root README lists every card of the home page once, in the order of CATS and under its category's
// heading, each as "- **[Name](its page on the live site)** — description": Name and description are the card's, word for
// word, and the folder the link names holds the page. Every problem is listed at once, so one run shows them all.
test('the Full catalog in the root README lists every card once, in home order, linked to its live page', () => {
  const LIVE = 'https://matinmonshizadeh.github.io/animation-handbook/';
  const ENTRY = /^- \*\*\[([^\]]+)\]\(https:\/\/matinmonshizadeh\.github\.io\/animation-handbook\/(animations\/([^/()\s]+)\/([^/()\s]+)\/)\)\*\* — (.+)$/;
  const cats = homeConst('CATS');
  // Each card by the path of its page, "animations/<category folder>/<slug>/", in the order of CATS.
  const cards = new Map(cats.flatMap(cat => cat.entries.map(([slug, name, desc]) => [`${cat.folder}/${slug}/`, { cat, name, desc }])));
  const problems = [], listed = [];
  let heading = null; // the category whose "### NN · Name · N techniques" heading the line is under
  for (const line of sections(read(path.join(ROOT, 'README.md')))['Full catalog'].split('\n')) {
    const h = line.match(/^### (\d{2}) · /);
    if (h) { heading = cats.find(cat => cat.n === h[1]); continue; }
    if (!line.startsWith('- ')) continue;
    const m = line.match(ENTRY);
    if (!m) { problems.push(`not "- **[Name](${LIVE}animations/<category>/<slug>/)** — description": ${line}`); continue; }
    const [, name, page, folder, slug, desc] = m;
    listed.push(page);
    if (!isDemoDir(path.join(ANIM, folder, slug))) problems.push(`${page}: there is no index.html in that folder`);
    const card = cards.get(page);
    if (!card) { problems.push(`${page}: no card on the home page opens it`); continue; }
    if (card.cat !== heading) problems.push(`${page}: listed under ${heading ? `${heading.n} ${heading.name}` : 'no category heading'}, its card is in ${card.cat.n} ${card.cat.name}`);
    if (name !== card.name) problems.push(`${page}: named "${name}", its card "${card.name}"`);
    if (desc !== card.desc) problems.push(`${page}: described "${desc}", its card "${card.desc}"`);
  }
  for (const page of cards.keys()) if (!listed.includes(page)) problems.push(`${page}: not in the Full catalog`);
  for (const page of new Set(listed)) if (listed.indexOf(page) !== listed.lastIndexOf(page)) problems.push(`${page}: listed more than once`);
  // The order: the cards that are listed, each at its first line, against the same cards in the order of CATS.
  const order = listed.filter((page, i) => cards.has(page) && listed.indexOf(page) === i);
  const want = [...cards.keys()].filter(page => order.includes(page));
  const misplaced = order.findIndex((page, i) => page !== want[i]);
  if (misplaced >= 0) problems.push(`${order[misplaced]}: out of the order of CATS, where ${want[misplaced]} comes here`);
  assert.deepEqual(problems, []);
});

test('the counts written in the root README match the cards', () => {
  const cats = homeConst('CATS'), cards = totalCards();
  const readme = read(path.join(ROOT, 'README.md'));
  assert.equal(numberIn(readme, /<img src="docs\/hero\.webp" alt="[^"]*?(\d+) web animation techniques/), cards, "README: the picture's alt text");
  // Every picture the README shows (img src and source srcset) is in the repository.
  for (const [, file] of readme.matchAll(/\s(?:src|srcset)="(docs\/[^"]+)"/g)) assert.ok(fs.existsSync(path.join(ROOT, file)), `README: ${file} is in the repository`);
  assert.equal(numberIn(readme, /^\*\*A visual reference of (\d+) web animation techniques/m), cards, 'README: the intro line');
  assert.equal(numberIn(readme, /badge\/techniques-(\d+)-/), cards, 'README: the techniques badge');
  assert.equal(numberIn(readme, /^All (\d+) techniques, each linked to its live demo\.$/m), cards, 'README: the Full catalog line');
  for (const [said] of readme.matchAll(/\d+ web animation techniques/gi)) assert.equal(numberIn(said, /(\d+)/), cards, `README: "${said}"`);
  // Each category's count, in the Categories table, in its heading in the Full catalog and in the summary that opens its list.
  const rows = table(sections(readme)['Categories']);
  const headings = [...readme.matchAll(/^### (\d{2}) · (.+?) · (\d+) techniques$/gm)];
  const summaries = [...readme.matchAll(/^<details><summary>Browse all (\d+) techniques in (.+?)<\/summary>$/gm)];
  assert.equal(rows.length, cats.length, 'README: one Categories row per category');
  assert.equal(headings.length, cats.length, 'README: one Full catalog heading per category');
  assert.equal(summaries.length, cats.length, 'README: one "Browse all N techniques in …" summary per category');
  for (const cat of cats) {
    const row = rows.find(r => r[0] === cat.n), heading = headings.find(h => h[1] === cat.n);
    const summary = summaries.find(s => decode(s[2]) === cat.name);
    assert.ok(row && row[1].startsWith(`[${cat.name}]`), `README: a Categories row for ${cat.n} ${cat.name}`);
    assert.equal(Number(row[2]), cat.entries.length, `README: the Categories count of ${cat.n} ${cat.name}`);
    assert.ok(heading && heading[2] === cat.name, `README: a Full catalog heading for ${cat.n} ${cat.name}`);
    assert.equal(Number(heading[3]), cat.entries.length, `README: the heading "${heading[0]}"`);
    assert.ok(summary, `README: a "Browse all N techniques in ${cat.name}" summary`);
    assert.equal(Number(summary[1]), cat.entries.length, `README: the summary "${summary[0]}"`);
    // The line under each heading is the category's description on the home page.
    const line = between(readme, heading[0], '<details>').match(/<sub>([^<]*)<\/sub>/);
    assert.ok(line && decode(line[1]) === cat.desc, `README: the line under "${heading[0]}" is the home page's description of ${cat.name}`);
  }
});

// Without JavaScript the home page draws no cards, so every animation is also there as a plain link, for visitors and for
// crawlers that run no script. tools/update-sitemap.mjs writes the list from the cards, between two comment lines.
test('the no-JavaScript list links every animation once, in home order, under its group and with its line', () => {
  const START = '<!-- plain-links: written by tools/update-sitemap.mjs from the cards; not by hand -->', END = '<!-- /plain-links -->';
  const noscript = between(HOME, '<noscript>', '</noscript>');
  assert.ok(noscript.includes(START) && noscript.includes(END), 'the list sits inside the noscript block, between its two comment lines');
  const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  const expected = homeConst('CATS').map(cat => `<h3>${esc(cat.name)}</h3>\n<ul>\n` +
    cat.entries.map(([slug, name, desc]) => `<li><a href="${cat.folder}/${slug}/">${esc(name)}</a>: ${esc(desc)}</li>`).join('\n') + '\n</ul>').join('\n');
  assert.equal(between(HOME, START, END).slice(START.length).replace(/\r\n/g, '\n').trim(), expected);
});

// llms.txt: the handbook as one plain list, for AI tools that read a site without running its scripts.
// tools/update-sitemap.mjs writes it from the cards and the Famous effects page.
test('llms.txt lists every card once, in the order of CATS under its group, with its live address and its line, then the Famous effects page', () => {
  const LIVE = 'https://matinmonshizadeh.github.io/animation-handbook/';
  const text = read(path.join(ROOT, 'llms.txt')).replace(/\r\n/g, '\n');
  const cats = homeConst('CATS'), cards = cats.flatMap(cat => cat.entries.map(([slug, name, desc]) => ({ name, address: `${LIVE}${cat.folder}/${slug}/`, desc })));
  assert.ok(text.startsWith('# Animation Handbook\n'), 'llms.txt starts with the title');
  assert.match(text, new RegExp(`^> .*\\b${cards.length}\\b`, 'm'), 'the summary under the title gives the count');
  const lines = text.split('\n').filter(line => line.startsWith('- [') && line.includes(`](${LIVE}animations/`));
  assert.equal(lines.length, cards.length, 'one line per card');
  cards.forEach((card, i) => assert.equal(lines[i], `- [${card.name}](${card.address}): ${card.desc}`, `line ${i + 1}`));
  const headings = text.split('\n').filter(line => line.startsWith('## '));
  assert.deepEqual(headings, [...cats.map(cat => `## ${cat.name}`), '## Famous effects', '## Optional'], 'the groups in home order, then Famous effects and Optional');
  // The Famous effects page with its own description (white space squeezed), after the last card.
  const lede = decode(read(path.join(ROOT, 'famous', 'index.html')).match(/<meta name="description" content="([^"]+)">/)[1]).replace(/\s+/g, ' ').trim();
  assert.ok(text.includes(`## Famous effects\n\n- [Famous effects](${LIVE}famous/): ${lede}\n`), 'the Famous effects line under its own heading');
  assert.doesNotMatch(text, /skill/i, 'llms.txt says nothing of the AI skill, which is gone');
});

test('the AI skill is gone: no skill folder, plugin file, tool or install line is left', () => {
  for (const gone of ['skills', '.claude-plugin', 'tools/make-skill.mjs', 'tests/skill.test.js']) assert.ok(!fs.existsSync(path.join(ROOT, gone)), `${gone} is removed`);
  for (const file of ['README.md', 'CONTRIBUTING.md', 'CLAUDE.md']) assert.doesNotMatch(read(path.join(ROOT, file)), /npx skills add|make-skill|Agent Skill|AI skill/i, `${file} does not mention the skill`);
});

test('the counts written in the issue template, the 404 page and the sitemap match the cards', () => {
  const cards = totalCards();
  const template = read(path.join(ROOT, '.github/ISSUE_TEMPLATE/config.yml'));
  assert.equal(numberIn(template, /See all (\d+) techniques/), cards, 'config.yml: the link to the live handbook');
  assert.equal(numberIn(read(path.join(ROOT, '404.html')), />Browse all (\d+) animations</), cards, '404.html: the Browse all link');
  // The sitemap lists two URLs more than the total: the home page and the Famous effects page, first and in that order, each
  // address once.
  const sitemap = read(path.join(ROOT, 'sitemap.xml'));
  assert.equal(count(sitemap, '<url>'), cards + 2, 'sitemap.xml lists the home page, the Famous effects page and every animation');
  const LIVE = 'https://matinmonshizadeh.github.io/animation-handbook/';
  const locs = [...sitemap.matchAll(/<loc>([^<]*)<\/loc>/g)].map(m => m[1]);
  assert.deepEqual(locs.slice(0, 2), [LIVE, `${LIVE}famous/`], 'the home page, then Famous effects');
  assert.equal(new Set(locs).size, locs.length, 'each address once');
  const famousLine = sitemap.split('\n').find(line => line.includes(`<loc>${LIVE}famous/</loc>`)) || '';
  assert.match(famousLine, /<\/loc><lastmod>\d{4}-\d{2}-\d{2}<\/lastmod><changefreq>monthly<\/changefreq><priority>0\.8<\/priority><\/url>\s*$/, 'Famous effects: monthly, priority 0.8');
});

// GitHub Pages serves 404.html at every address it has no file for, at any depth, so a relative address in it would
// point somewhere else from every one: each link, icon, font and the search form use an absolute one.
test('the 404 page stays out of search results and every address in it works at any depth', () => {
  const file = path.join(ROOT, '404.html');
  assert.ok(fs.existsSync(file), '404.html is at the root');
  const html = read(file);
  assert.ok(html.includes('<meta name="robots" content="noindex">'), 'noindex');
  const addresses = [...html.matchAll(/\s(?:href|src|action)="([^"]*)"/g), ...html.matchAll(/url\(\s*['"]?([^'")\s]+)/g)].map(m => m[1]);
  assert.ok(addresses.length > 0, 'the page has addresses to check');
  for (const address of addresses) assert.match(address, /^(?:\/animation-handbook\/|https:\/\/|#)/, address);
  // Each file the page loads or links on the site is in the repository (a folder address stands for its index.html).
  for (const address of addresses.filter(a => a.startsWith('/animation-handbook/'))) {
    const file = address.replace(/^\/animation-handbook\//, '').replace(/[?#].*$/, '');
    assert.ok(fs.existsSync(path.join(ROOT, file === '' || file.endsWith('/') ? file + 'index.html' : file)), `${address} is in the repository`);
  }
});

test('the 404 page sends a mistyped address where it belongs and never off the site', () => {
  const html = read(path.join(ROOT, '404.html'));
  const start = html.indexOf('function whereTo(');
  assert.ok(start >= 0, 'whereTo in 404.html');
  let depth = 0, end = html.indexOf('{', start);
  for (; end < html.length; end++) { if (html[end] === '{') depth++; else if (html[end] === '}' && --depth === 0) break; }
  const whereTo = vm.runInNewContext('(' + html.slice(start, end + 1) + ')');
  const cases = [
    ['/animation-handbook/animations/02-entrance-and-exit/Rotate-In/', '?x=1#y', { go: '/animation-handbook/animations/02-entrance-and-exit/rotate-in/?x=1#y' }],
    ['/animation-handbook/animations/', '', { go: '/animation-handbook/?view=all#results' }],
    ['/animation-handbook/animations/02-entrance-and-exit/', '', { go: '/animation-handbook/?view=all#results' }],
    ['/animation-handbook/animations/02-entrance-and-exit/rotate-inn/', '', { words: 'rotate inn' }],
    ['/animation-handbook/animations%2F02-entrance-and-exit%2Frotate-in/', '', { words: 'rotate in' }],
    ['/animation-handbook/12345', '', { words: '' }],
    ['/FOO/Bar', '', { words: 'Bar' }],
    ['//evil.example/X', '', { words: 'X' }]
  ];
  for (const [where, rest, want] of cases) assert.deepEqual({ ...whereTo(where, rest) }, want, where + rest);
});

test('the 404 page sends /finder and /find to the finder, keeping only its answers, and offers it as a way back', () => {
  const html = read(path.join(ROOT, '404.html'));
  const start = html.indexOf('function whereTo(');
  assert.ok(start >= 0, 'whereTo in 404.html');
  let depth = 0, end = html.indexOf('{', start);
  for (; end < html.length; end++) { if (html[end] === '{') depth++; else if (html[end] === '}' && --depth === 0) break; }
  const whereTo = vm.runInNewContext('(' + html.slice(start, end + 1) + ')');
  const cases = [
    ['/animation-handbook/finder', '', { go: '/animation-handbook/?view=find' }],
    ['/animation-handbook/find/', '', { go: '/animation-handbook/?view=find' }],
    ['/animation-handbook/Finder/', '?what=text&when=scroll&how=draw#top', { go: '/animation-handbook/?view=find&what=text&when=scroll&how=draw' }],
    ['/animation-handbook/FIND', '?q=fade&how=fade&utm_source=x', { go: '/animation-handbook/?view=find&how=fade' }],
    ['/animation-handbook/finder', '?what=%3Cb%3E', { go: '/animation-handbook/?view=find' }],
    ['/animation-handbook/finder', '?view=find&all=1&xwhat=a&what=a%2Fb&how=fade', { go: '/animation-handbook/?view=find&how=fade' }],
    ['/animation-handbook/finders', '', { words: 'finders' }],
    ['/animation-handbook/animations/finder/', '', { words: 'finder' }]
  ];
  for (const [where, rest, want] of cases) assert.deepEqual({ ...whereTo(where, rest) }, want, where + rest);
  assert.ok(html.includes('<a class="way" href="/animation-handbook/?view=find">Find an animation by what you saw</a>'), 'the third way back');
});

// Where the bracket that opens at HOME[from] ('[' or '{') is closed. It steps over strings and // comments, so a quote or bracket
// inside either does not count.
function blockEnd(from) {
  const open = HOME[from], close = open === '[' ? ']' : '}';
  let depth = 0, i = from, quote = null;
  for (; i < HOME.length; i++) {
    const ch = HOME[i];
    if (quote) { if (ch === '\\') i++; else if (ch === quote) quote = null; continue; }
    if (ch === '/' && HOME[i + 1] === '/') { while (i < HOME.length && HOME[i] !== '\n') i++; continue; }
    if (ch === "'" || ch === '"' || ch === '`') quote = ch;
    else if (ch === open) depth++;
    else if (ch === close && --depth === 0) break;
  }
  return i;
}
// The value of `const NAME=` in the home page's script: an array or object literal of plain data, read with vm.
function homeConst(name) {
  const start = HOME.indexOf(`const ${name}=`);
  assert.ok(start >= 0, `const ${name} in index.html`);
  const from = start + `const ${name}=`.length;
  // vm builds the value in its own realm; the JSON copy is made of ordinary arrays and objects that deepEqual accepts.
  return JSON.parse(JSON.stringify(vm.runInNewContext('(' + HOME.slice(from, blockEnd(from) + 1) + ')')));
}
// A function of the home page's script, `function NAME(…){…}`, read with vm so a test can call it.
function homeFunction(name) {
  const start = HOME.indexOf(`function ${name}(`);
  assert.ok(start >= 0, `function ${name} in index.html`);
  return vm.runInNewContext('(' + HOME.slice(start, blockEnd(HOME.indexOf('{', start)) + 1) + ')');
}
const PLACE_KEYS = ['btn', 'text', 'imgcard', 'bg', 'menu', 'load', 'intro', 'scroll', 'page'];

test('every animation on the home page has one or more places, all of them known', () => {
  const places = homeConst('PLACES');
  const slugs = homeConst('CATS').flatMap(cat => cat.entries.map(e => e[0]));
  assert.deepEqual(Object.keys(places), slugs, 'PLACES lists every card once, in home order');
  for (const slug of slugs) {
    assert.ok(places[slug].length >= 1, `${slug} has a place`);
    for (const key of places[slug]) assert.ok(PLACE_KEYS.includes(key), `${slug}: unknown place ${key}`);
    assert.equal(new Set(places[slug]).size, places[slug].length, `${slug} lists a place twice`);
  }
});

test('every place holds at least one animation', () => {
  const used = new Set(Object.values(homeConst('PLACES')).flat());
  for (const key of PLACE_KEYS) assert.ok(used.has(key), `${key} holds no animation`);
});

test('the eight Start cards are on the home page', () => {
  const picks = homeConst('PICKS'), slugs = new Set(Object.keys(homeConst('PLACES')));
  assert.equal(picks.length, 8);
  assert.equal(new Set(picks).size, 8, 'the eight Start cards are all different');
  for (const slug of picks) assert.ok(slugs.has(slug), slug);
});

test('a typed word loses its ending by the rule in the spec', () => {
  const stem = homeFunction('stem');
  // "ring", "string" and "spring" keep "ing" (what is left is too short or has no vowel) and "ss" keeps its s; after "ing" or
  // "ed" a doubled last letter goes too while three letters stay, but not l, s, f or z ("scrolling", and "added" keeps three).
  // A short word in "eed" keeps its "ed" ("speed" cut to "spe" would find "spectrum"); a longer one loses it as before, so
  // "succeed" still finds "success".
  const want = { ring: 'ring', string: 'string', spring: 'spring', uses: 'use', galleries: 'galler', press: 'press', glass: 'glass',
    snapping: 'snap', blurred: 'blur', dragging: 'drag', scrolling: 'scroll', added: 'add', flipping: 'flip', tapping: 'tap',
    pinned: 'pin', clipping: 'clip', scrubbing: 'scrub', fades: 'fad', cards: 'card', boxes: 'box',
    speed: 'speed', need: 'need', agreed: 'agreed', speeds: 'speed', succeed: 'succe' };
  assert.deepEqual(Object.fromEntries(Object.keys(want).map(word => [word, stem(word)])), want);
});

// The home page's search as the page runs it: the cards and their word lists built by the page's own code (from PLACE_LIST
// up to BY_SLUG), then its search functions, in one context with the page's CATS, PLACES, WORDS and SAME. `cards` is the page's
// own list of cards (ALL), each with its word lists.
function homeSearch() {
  const at = marker => { const i = HOME.indexOf(marker); assert.ok(i >= 0, `${marker} in index.html`); return i; };
  const context = vm.createContext({ CATS: homeConst('CATS'), PLACES: homeConst('PLACES'), WORDS: homeConst('WORDS'), SAME: homeConst('SAME') });
  vm.runInContext(HOME.slice(at('const PLACE_LIST=['), at('const BY_SLUG=')), context);
  context.cards = vm.runInContext('ALL', context);
  for (const name of ['stem', 'queryWords', 'score', 'search', 'askURL']) {
    const start = at(`function ${name}(`);
    vm.runInContext(HOME.slice(start, blockEnd(HOME.indexOf('{', start)) + 1), context);
  }
  return context;
}

test('the search finds what a visitor describes, and each Popular suggestion keeps its first result', () => {
  const page = homeSearch(), names = text => page.search(text).map(e => e.name);
  const shown = Number(HOME.match(/const PAGE=(\d+);/)[1]);
  // The search box's own example: a button that springs back as it is pressed comes first, and Bounce In is on the first page.
  const example = HOME.match(/<input id="q"[^>]* placeholder="For example: ([^"]+)">/)[1];
  const found = names(example);
  assert.equal(found[0], 'Button Press Scale', `"${example}": ${found.slice(0, shown).join(', ')}`);
  assert.ok(found.slice(0, shown).includes('Bounce In'), `"${example}" shows Bounce In on the first page: ${found.slice(0, shown).join(', ')}`);
  const first = { 'text that types itself': 'Typewriter Effect', 'loading spinner': 'Loading Spinner', 'background with moving stars': 'Starfield / Space Particles',
    'confetti when done': 'Success Confetti', 'menu that slides in': 'Drawer / Panel Slide', fade: 'Fade In / Fade Out' };
  for (const [text, name] of Object.entries(first)) assert.equal(names(text)[0], name, `"${text}": ${names(text).slice(0, 5).join(', ')}`);
  // A Parallax card first, and the two cards that fake depth without the word parallax come too.
  const parallax = names('parallax');
  assert.match(parallax[0], /Parallax/, `"parallax": ${parallax.join(', ')}`);
  for (const name of ['2.5D / Pseudo-3D', 'Depth-Map Photo']) assert.ok(parallax.includes(name), `"parallax" finds ${name}: ${parallax.join(', ')}`);
  const change = page.search('page change animation')[0];
  assert.equal(change.cat.name, 'Page Transitions', `"page change animation": ${change.name} first`);
  // The Popular suggestions, in the hero and in the Nothing-found panel, each with the first result it had before the groups.
  const popular = { 'fade in': 'Fade In / Fade Out', 'typing text': 'Kinetic Typography', 'loading spinner': 'Loading Spinner', parallax: 'Parallax Depth-of-Field',
    confetti: 'Success Confetti' };
  for (const panel of [between(HOME, '<p class="pop"><span>Popular:</span>', '</p>'), between(HOME, '<div class="empty" id="empty"', '</div>')]) {
    assert.deepEqual([...panel.matchAll(/data-q="([^"]*)"/g)].map(m => m[1]), Object.keys(popular), 'the Popular suggestions');
  }
  for (const [text, name] of Object.entries(popular)) assert.equal(names(text)[0], name, `"${text}": ${names(text).slice(0, 5).join(', ')}`);
});

test('a typed word also finds the cards that use another word of its group, after every card that has the word itself', () => {
  const page = homeSearch(), names = text => page.search(text).map(e => e.name);
  // Words a visitor may type that no card uses.
  for (const [text, name] of [['wobble', 'Error Shake'], ['popup', 'Modal Expand'], ['mouse', 'Cursor Follower'], ['loader', 'Loading Spinner'],
    ['scrolltrigger', 'Scroll-Triggered Animation'], ['gsap scrolltrigger', 'Scroll-Triggered Animation']]) {
    assert.ok(names(text).includes(name), `"${text}" finds ${name}: ${names(text).join(', ')}`);
  }
  // Each word of every group, typed alone: the cards with the typed word itself come first, then the ones found through the group.
  for (const text of homeConst('SAME').flat()) {
    const [word] = page.queryWords(text), has = e => [...e.nameW, ...e.placeW, ...e.moreW, ...e.descW].some(x => x.startsWith(word));
    const found = page.search(text), others = found.findIndex(e => !has(e));
    assert.ok(others < 0 || found.slice(others).every(e => !has(e)), `"${text}": ${found.map(e => e.name + (has(e) ? '' : ' (group)')).join(', ')}`);
  }
  for (const [text, name] of [['tap', 'Click / Tap Ripple'], ['click', 'Click / Tap Ripple'], ['elastic', 'Elastic Transition'], ['springy', 'Bounce In']]) {
    assert.equal(names(text)[0], name, `"${text}": ${names(text).join(', ')}`);
  }
});

// WORDS: everyday words a visitor may type for a card that the card's own texts do not say (another name for the effect, the
// part of a page it is, a common misspelling). They count 2, between a place name and the description.
test('every extra search word belongs to a card, in home order, and says something the card does not say already', () => {
  const words = homeConst('WORDS'), page = homeSearch();
  const slugs = homeConst('CATS').flatMap(cat => cat.entries.map(entry => entry[0]));
  for (const slug of Object.keys(words)) assert.ok(slugs.includes(slug), `${slug} is not a card`);
  assert.deepEqual(Object.keys(words), slugs.filter(slug => slug in words), 'WORDS is in the same order as CATS');
  const stop = new Set(vm.runInContext('[...STOP]', page));
  for (const e of page.cards) {
    const list = (words[e.slug] || '').split(' ').filter(Boolean);
    assert.deepEqual([...e.moreW], list, `${e.slug}: the card's extra words are the ones in WORDS`);
    if (e.slug in words) assert.ok(list.length, `${e.slug} has no words: leave it out`);
    assert.equal(new Set(list).size, list.length, `${e.slug} names a word twice`);
    for (const word of list) {
      assert.match(word, /^[a-z0-9]+$/, `${e.slug}: "${word}" is one lowercase word`);
      assert.ok(!stop.has(word), `${e.slug}: "${word}" is a word the search leaves out`);
      const typed = page.stem(word);
      assert.ok(![...e.nameW, ...e.placeW, ...e.descW].some(x => x.startsWith(typed)), `${e.slug}: "${word}" already finds this card`);
    }
  }
});

test('everyday words that no card says find the card a visitor means', () => {
  const page = homeSearch(), names = text => page.search(text).map(e => e.name);
  const first = { shine: 'Shimmer Effect', aos: 'Reveal on Scroll', sidebar: 'Drawer / Panel Slide', lightbox: 'Modal Expand',
    snackbar: 'Toast Notification', alert: 'Toast Notification', mask: 'Clip-Path Reveal', thinking: 'Typing Indicator',
    stepper: 'Progress Animation', filter: 'FLIP Technique', tabs: 'Segmented Control', accordian: 'Accordion Open/Close',
    skelton: 'Skeleton Loader', countup: 'Counter Animation', kenburns: 'Ken Burns Effect', darkmode: 'Theme Toggle Morph',
    offcanvas: 'Drawer / Panel Slide', colour: 'Scroll-Driven Background Color', 'shiny card': 'Holographic Card', hint: 'Tooltip Reveal' };
  for (const [text, name] of Object.entries(first)) assert.equal(names(text)[0], name, `"${text}": ${names(text).slice(0, 5).join(', ')}`);
  const among = { sparkle: ['Shimmer Effect', 'Holographic Card'], navbar: ['Hide-on-Scroll Header', 'Hamburger Menu Toggle', 'Scrollspy Navigation'],
    carousel: ['3D Carousel', 'Snap Scrolling', 'Rotate Word Carousel'], gallery: ['3D Carousel', 'Horizontal Scroll'], grey: ['Skeleton Loader'] };
  for (const [text, wanted] of Object.entries(among)) for (const name of wanted) assert.ok(names(text).includes(name), `"${text}" finds ${name}: ${names(text).join(', ')}`);
  // A misspelled "parallax" finds the Parallax cards.
  for (const text of ['paralax', 'parallex']) assert.match(names(text)[0] || '', /Parallax/, `"${text}": ${names(text).slice(0, 5).join(', ')}`);
  // "speed" keeps its ending, so it does not find the Audio Visualizer's "spectrum".
  assert.ok(!names('speed').includes('Audio Visualizer'), `"speed": ${names('speed').slice(0, 5).join(', ')}`);
});

// The handbook has no card for these yet, and an honest empty result offers Ask for it. When one of them gets its card, take it
// out of this list.
test('a word for something the handbook does not have finds nothing', () => {
  const page = homeSearch();
  for (const text of ['dock', 'chart', 'checkbox']) assert.equal(page.search(text).map(e => e.name).join(', '), '', `"${text}"`);
});

// A typed word finds a card's own words by their start ("scroll" finds "scrolling"). An extra word is another name, so it counts
// only when all of it is typed, or all but its ending: otherwise "page" would find Page Curl's "pageturn" in every search for a
// page transition, and "bar" the View Transitions API's "barba".
test('an extra word counts only when all of it, or all but its ending, is typed', () => {
  const page = homeSearch(), names = text => page.search(text).map(e => e.name);
  for (const text of ['page transition', 'page transitions', 'transition between pages']) {
    assert.equal(names(text)[0], 'View Transitions API', `"${text}": ${names(text).slice(0, 5).join(', ')}`);
  }
  for (const text of ['bar', 'progress bar', 'search bar', 'tab bar']) {
    assert.ok(!names(text).includes('View Transitions API'), `"${text}" finds the View Transitions API: ${names(text).slice(0, 5).join(', ')}`);
  }
  assert.ok(!names('water').includes('Ink Spread Reveal'), `"water" is not "watercolor": ${names('water').slice(0, 5).join(', ')}`);
  // The whole word, or the word without its ending, still finds its card.
  for (const [text, name] of [['pageturn', 'Page Curl'], ['barba', 'View Transitions API'], ['tabs', 'Segmented Control'],
    ['celebrating', 'Success Confetti'], ['snowflake', 'Snow / Rain'], ['watercolor', 'Ink Spread Reveal']]) {
    assert.equal(names(text)[0], name, `"${text}": ${names(text).slice(0, 5).join(', ')}`);
  }
});

// First results that an extra word must not take away from the card that has the typed word in its own name.
test('the extra words leave these first results as they were', () => {
  const page = homeSearch(), names = text => page.search(text).map(e => e.name);
  const first = { succeed: 'Success Confetti', 'text highlight': 'Highlighter Sweep', 'lava lamp': 'Morphing Blob', drop: 'Ink Spread Reveal',
    'card flip': '3D Flip Card', 'image zoom': 'Zoom Into Image', 'button hover': 'Hover State Animation', stroke: 'Handwriting Draw' };
  for (const [text, name] of Object.entries(first)) assert.equal(names(text)[0], name, `"${text}": ${names(text).slice(0, 5).join(', ')}`);
});

test('of two cards with the same score, the one that has more of the typed words comes first', () => {
  const page = homeSearch(), names = text => page.search(text).map(e => e.name);
  // Zoom Into Image has "zoom" and "scroll"; Parallax Scrolling says "scroll" three times and comes earlier on the home page.
  assert.equal(names('zoom on scroll')[0], 'Zoom Into Image', names('zoom on scroll').slice(0, 5).join(', '));
});

test('Nothing matches offers Ask for it: a link to the GitHub form with the typed words filled in', () => {
  const panel = between(HOME, '<div class="empty" id="empty" hidden>', '</div>');
  assert.ok(panel.includes('<p class="empty-ask">Not in the handbook yet? <a class="pillbtn" id="empty-gh" href="https://github.com/matinmonshizadeh/animation-handbook/issues/new?template=animation_not_here.yml" target="_blank" rel="noopener">Ask for it on GitHub</a></p>'), panel);
  const url = new URL(homeSearch().askURL('dock that grows & shrinks #1'));
  assert.equal(url.origin + url.pathname, 'https://github.com/matinmonshizadeh/animation-handbook/issues/new');
  assert.deepEqual([...url.searchParams.keys()], ['template', 'title', 'answers']);
  assert.equal(url.searchParams.get('template'), 'animation_not_here.yml');
  assert.equal(url.searchParams.get('title'), '[not here] dock that grows & shrinks #1');
  assert.equal(url.searchParams.get('answers'), 'Searched for “dock that grows & shrinks #1” — https://matinmonshizadeh.github.io/animation-handbook/?q=dock%20that%20grows%20%26%20shrinks%20%231');
  // Only fields the form has are filled.
  const form = read(path.join(ROOT, '.github', 'ISSUE_TEMPLATE', 'animation_not_here.yml'));
  assert.match(form, /^\s+id: answers\r?$/m);
});

test('the star ask: a marked star row turns its button gold and pulses it once, with transform only and only where motion is welcome', () => {
  const bare = read(path.join(ROOT, 'assets', 'css', 'demo-page.css')).replace(/\/\*[\s\S]*?\*\//g, '');
  const body = selector => cssRules(bare).filter(r => r.selector === selector).map(r => r.body).join(';');
  assert.match(body('.hb-star-row.is-asked .hb-star-btn'), /(^|;)\s*border-color:\s*#f2c14e/, 'a gold edge');
  assert.match(body('.hb-star-row.is-asked .hb-star-btn .hb-ic'), /(^|;)\s*fill:\s*#f2c14e/, 'a gold star');
  const welcome = cssRules(blockOf(bare, '@media(prefers-reduced-motion:no-preference){'));
  const pulse = welcome.filter(r => r.selector === '.hb-star-row.is-asked .hb-star-btn' && /animation/.test(r.body));
  assert.equal(pulse.length, 1, 'the pulse is declared where motion is welcome');
  assert.match(pulse[0].body, /^\s*animation:\s*hb-ask\s+[\d.]+s\s+[\w-]+(\s+1)?\s*;?\s*$/, `it runs once: ${pulse[0].body}`);
  assert.equal(cssRules(bare).filter(r => r.selector.includes('.is-asked') && /animation/.test(r.body)).length, 1, 'nothing else animates a marked row');
  const frames = cssRules(blockOf(bare, '@keyframes hb-ask{'));
  assert.ok(frames.length > 1 && frames.every(f => /^\s*transform:[^;]*;?\s*$/.test(f.body)), 'the pulse moves with transform only');
});

test('the home page head gives search engines and social sites one title, one description and the author', () => {
  const head = between(HOME, '<head>', '</head>');
  const meta = attr => { const m = head.match(new RegExp(`<meta ${attr} content="([^"]*)">`)); return m && decode(m[1]); };
  const ld = JSON.parse(between(head, '<script type="application/ld+json">', '</script>').replace('<script type="application/ld+json">', ''));
  const title = decode((head.match(/<title>([^<]*)<\/title>/) || [])[1] || '');
  assert.ok(title, 'the home page has a title');
  for (const attr of ['property="og:title"', 'name="twitter:title"']) assert.equal(meta(attr), title, attr);
  const description = meta('name="description"');
  assert.ok(description && description.length <= 160, `the description has at most 160 characters (${description && description.length}): ${description}`);
  assert.match(description, /ready-made prompt for your AI assistant/, 'the description names the prompt');
  for (const attr of ['property="og:description"', 'name="twitter:description"']) assert.equal(meta(attr), description, attr);
  assert.equal(ld.description, description, 'JSON-LD description');
  const holder = read(path.join(ROOT, 'LICENSE')).match(/^Copyright \(c\) \d{4} (.+)$/m)[1].trim();
  assert.equal(meta('name="author"'), holder, 'meta author: the name in the LICENSE');
  assert.equal(ld.author && ld.author.name, holder, 'JSON-LD author: the name in the LICENSE');
  assert.match(head, /<link rel="canonical" href="[^"]*">\r?\n<link rel="sitemap" type="application\/xml" title="Sitemap" href="sitemap\.xml">\r?\n/, 'the sitemap link, right after the canonical link');
});

// The opening tags of the home page's markup: scripts, styles and comments left out.
const homeTags = () => HOME.replace(/<script\b[\s\S]*?<\/script>|<style\b[\s\S]*?<\/style>|<!--[\s\S]*?-->/g, '').match(/<[a-z][^>]*>/g);
const tagAttr = (tag, name) => (tag.match(new RegExp(`\\s${name}="([^"]*)"`)) || [])[1];
const tagHasClass = (tag, name) => (tagAttr(tag, 'class') || '').split(/\s+/).includes(name);

test('every place has one tile, one phone-bar chip and one count, and the markup names no other place', () => {
  const tags = homeTags();
  const placed = tags.filter(tag => tagAttr(tag, 'data-place') !== undefined), counted = tags.filter(tag => tagAttr(tag, 'data-count') !== undefined);
  for (const tag of placed) assert.ok(PLACE_KEYS.includes(tagAttr(tag, 'data-place')), `unknown place: ${tag}`);
  for (const tag of counted) assert.ok(PLACE_KEYS.includes(tagAttr(tag, 'data-count')), `unknown place: ${tag}`);
  for (const key of PLACE_KEYS) {
    assert.equal(placed.filter(tag => tagAttr(tag, 'data-place') === key && tagHasClass(tag, 'place')).length, 1, `one ${key} tile`);
    assert.equal(placed.filter(tag => tagAttr(tag, 'data-place') === key && tagHasClass(tag, 'pchip')).length, 1, `one ${key} chip in the phone bar`);
    assert.equal(placed.filter(tag => tagAttr(tag, 'data-place') === key).length, 2, `${key}: its tile and its phone-bar chip, nothing else`);
    assert.equal(counted.filter(tag => tagAttr(tag, 'data-count') === key).length, 1, `one ${key} count`);
  }
});

// A group's key, in its chip and in the address (?cat=): its name in small letters, every run of other characters a hyphen.
const groupKey = name => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');

test('the chips under the results heading are All and the seven groups in home order, each with its group color', () => {
  const cats = homeConst('CATS');
  const row = between(HOME, '<div class="spots" id="spots"', '</div>');
  assert.match(row, /^<div class="spots" id="spots" role="group" aria-label="Groups">/, 'the row is a group named Groups');
  assert.equal(count(row, '<button'), cats.length + 1, 'All and one chip for each group, nothing else');
  const chips = [...row.matchAll(/<button type="button" class="spot" data-cat="([^"]*)" aria-pressed="(true|false)">(?:<i class="(c\d)" aria-hidden="true"><\/i>)?([^<]*)<\/button>/g)]
    .map(m => ({ key: m[1], pressed: m[2], dot: m[3] || '', name: decode(m[4]) }));
  // All, the first chip, names no group and starts pressed: it is Start.
  assert.deepEqual(chips, [{ key: '', pressed: 'true', dot: '', name: 'All' },
    ...cats.map(cat => ({ key: groupKey(cat.name), pressed: 'false', dot: cat.cat.replace('-cat', ''), name: cat.name }))]);
  const tags = homeTags();
  assert.equal(tags.filter(tag => tagAttr(tag, 'data-cat') !== undefined).length, cats.length + 1, 'no other button names a group');
  assert.equal(tags.filter(tag => tagHasClass(tag, 'spot') && tagAttr(tag, 'data-place') !== undefined).length, 0, 'no chip under the results heading names a place');
  // The dot takes the deep end of its group's gradient, the color of that group's cards.
  const css = [...HOME.matchAll(/<style>([\s\S]*?)<\/style>/g)].map(m => m[1]).join('\n');
  assert.ok(cssRules(css).some(rule => rule.selector === '.spot i' && /(^|;)\s*background:\s*var\(--g2\)/.test(rule.body)), 'the dot is drawn in the group color (--g2)');
});

// The address of a view, as the page reads it: the page's own slugify, CAT and fromURL() run with the page's CATS and places.
function homeAddress(search) {
  const line = marker => { const at = HOME.indexOf(marker); assert.ok(at >= 0, `${marker} in index.html`); return HOME.slice(at, HOME.indexOf('\n', at)); };
  const start = HOME.indexOf('function fromURL(');
  assert.ok(start >= 0, 'function fromURL in index.html');
  const code = `${line('const slugify=')}\n${line('const CAT=')}\n${HOME.slice(start, blockEnd(HOME.indexOf('{', start)) + 1)}\nfromURL()`;
  const next = vm.runInNewContext(code, { CATS: homeConst('CATS'), PLACE_LIST: homeConst('PLACE_LIST'), FIND_Q: [], URLSearchParams, location: { search } });
  return JSON.parse(JSON.stringify(next));
}

test('an address with ?cat= opens that group; a search or a place wins over it, and a name that is no group opens All animations', () => {
  const cats = homeConst('CATS');
  for (const cat of cats) {
    const key = groupKey(cat.name), next = homeAddress('?cat=' + key);
    assert.deepEqual({ cat: next.cat, view: next.view, place: next.place, q: next.q, all: next.all }, { cat: key, view: '', place: '', q: '', all: false }, `?cat=${key}`);
  }
  assert.equal(homeAddress('?cat=micro-interactions&all=1').all, true, 'all=1 shows the whole group');
  assert.equal(homeAddress('').cat, '', 'Start names no group');
  let next = homeAddress('?q=fade&cat=micro-interactions');
  assert.deepEqual([next.q, next.cat, next.view], ['fade', '', ''], 'a search wins');
  next = homeAddress('?place=buttons&cat=micro-interactions');
  assert.deepEqual([next.place, next.cat, next.view], ['btn', '', ''], 'a place wins');
  // An old link with a name that is no group (and names every object has, such as constructor) opens All animations, as before.
  for (const name of ['nothing', 'constructor', 'toString']) {
    next = homeAddress('?cat=' + name);
    assert.deepEqual([next.cat, next.view], ['', 'all'], `?cat=${name}`);
  }
});

test('the home page shows a group by the same paging, heading and address rules as a place', () => {
  const script = HOME.slice(HOME.indexOf('const state={'), HOME.indexOf('// ---------- The finder (?view=find) ----------'));
  assert.ok(script.includes("const state={q:'',place:'',cat:'',view:'',all:false,what:'',when:'',how:''};"), 'the view names its group (cat)');
  assert.ok(script.includes('const isFiltered=()=>!!(state.q||state.place||state.cat||state.view);'), 'a group counts as a picked view (Clear shows, the first eight cards)');
  assert.ok(script.includes("list=ALL.filter(e=>e.cat===CAT[state.cat]);title=CAT[state.cat].name;sub=list.length+' animations';"), 'its cards, its name as the heading, its count');
  assert.ok(script.includes('spotsEl.hidden=!!(state.q||state.place||state.view);'), 'the chips show at Start and on a group only');
  assert.ok(script.includes("else if(state.cat)p.push('cat='+state.cat);"), 'the address names the group');
  assert.ok(script.includes("if(state.all&&(state.q||state.place||state.cat||state.view==='find'))p.push('all=1');"), 'and Show all adds all=1');
  // Every place that sets the whole view names cat, so a view never keeps the group of the one before it.
  assert.equal(count(script, "place:'',cat:'',view:''"), 4, 'the view at boot, from the address, in go() and while typing');
  assert.equal(count(script, "place:'',view:''"), 0, 'no view is written without its group');
});

test('the home page keeps its GitHub button on phones as a round star, and leaves it out only below 360px', () => {
  assert.equal(count(HOME, '</svg><span class="gh-t">GitHub</span> <span class="gh-c" id="gh-star-count"></span></a>'), 1,
    'the word GitHub has a span of its own, so small screens can hide it from sight and still read it out');
  const css = [...HOME.matchAll(/<style>([\s\S]*?)<\/style>/g)].map(m => m[1]).join('\n');
  const hiding = cssRules(css).filter(rule => rule.selector.split(',').some(part => part.trim() === '.gh') &&
    /(^|;)\s*display:\s*none/.test(rule.body));
  assert.equal(hiding.length, 1, 'one rule hides the GitHub button');
  assert.equal(count(HOME, '@media(max-width:359px){.gh{display:none}}'), 1, 'and it is for screens under 360px');
  const round = cssRules(between(css, '@media(max-width:879px){', '}}') + '}');
  const has = (selector, declarations) => round.some(rule => rule.selector === selector &&
    declarations.every(want => rule.body.split(';').some(d => d.replace(/\s+/g, '') === want)));
  assert.ok(has('.gh', ['width:44px', 'padding:0']), 'from 879px down the GitHub button is a 44px round star');
  assert.ok(has('.gh-t', ['position:absolute', 'width:1px', 'height:1px', 'overflow:hidden']), 'its word is hidden from sight and still read out');
  assert.ok(has('.gh-c', ['display:none']), 'and the star count goes');
  assert.ok(cssRules(between(css, '@media(min-width:601px) and (max-width:620px){', '}}') + '}').some(rule => rule.selector === '.top .nav .lnk'),
    'from 601px to 620px the two text links make room for it');
});

// The Famous effects page (famous/) is reached from the home page's footer until the tab pass adds it to the top bar
// (docs/superpowers/specs/2026-10-13-famous-effects-design.md); opened from disk, the link names famous/index.html, as the
// cards name their pages' index.html. With three links the footer's row wraps on the narrowest phones.
test('the home page footer links the Famous effects page', () => {
  const footer = between(HOME, '<footer class="wrap foot">', '</footer>');
  assert.equal(count(footer, '<a class="lnk" href="famous/">Famous effects</a>'), 1, 'one Famous effects link in the footer');
  assert.ok(HOME.includes(`if(FROM_DISK)document.querySelectorAll('a[href="famous/"]').forEach(a=>a.setAttribute('href','famous/index.html'));`),
    'opened from disk, the link opens famous/index.html');
  assert.ok(cssRules(between(HOME, '<style>', '</style>')).some(rule => rule.selector === '.foot .nav' && /(^|;)\s*flex-wrap:\s*wrap/.test(rule.body)),
    'the footer links wrap on the narrowest phones');
});