GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/presentations/template

Test Show and 3 more files

A test in the presentations folder of Cosmic that checks Show, using Louvain. It makes site (`make_site`), sets up (`setUp`) and sets up class (`setUpClass`).

648 lines of Python and JavaScript and CSS from cosmic, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1125 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Presentations — Template Page render · cosmic / tools/explore/presentations/template/index.html lines 1–38
  2. Show render · cosmic / tools/explore/presentations/template/show.css lines 1–58
  3. Show interaction · cosmic / tools/explore/presentations/template/show.js lines 1–196
  4. Test Show test · cosmic / tools/explore/presentations/test_show.py lines 1–356

Presentations — Template Page

A web page in the explore folder of Cosmic. Published at https://ventusltd.github.io/cosmic/tools/explore/presentations/template/.

rendercosmic / tools/explore/presentations/template/index.html · lines 1–38 of 38 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
README: "`build_graph.json` (see `GRAPH-CONTRACT.md`) feeds `visualise.py`, which writes `visual/index.html`: pipeline (Ingest / Transform / Output), estate map and topic flow, coloured by role, topic, stage or pattern, with a reachability overlay."
Inputs & outputs
Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/cosmic/tools/explore/presentations/template/.
What it achieves
Short guided stories about the code estate for newcomers: one picture and one or two plain sentences per card, each with its evidence and a link to go deeper.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cosmic · tools/explore/presentations/template · page
Uses
Show (stylesheet), Show (script src)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/presentations/template/index.html:1-38 · blob a92e7a0aaf84d31b6f3cbea85bdcae1c86775036 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Stories — Explore Code</title>
<meta name="description" content="Short guided stories about the code estate for newcomers: one picture and one or two plain sentences per card, each with its evidence and a link to go deeper.">
<meta name="generator" content="{{GENERATOR}}">
<link rel="stylesheet" href="show.css">
</head>
<body>
<a class="skip" href="#main">Skip to the stories</a>
<header>
  <p class="brand"><a href="../index.html">EXPLORE CODE</a> · STORIES</p>
  <h1 id="title">Stories</h1>
  <p class="lead" id="lead">The most promising experiments, told in a few cards each. Swipe, use the arrow keys, or tap Next.</p>
</header>
<main id="main">
  <ul id="list" class="list" aria-label="Stories"></ul>
  <section id="player" class="player" hidden aria-roledescription="carousel" aria-labelledby="title">
    <div class="bar">
      <a class="btn ghost" id="back" href="#">All stories</a>
      <p class="count" id="count" aria-live="polite"></p>
    </div>
    <div class="dots" id="dots" aria-hidden="true"></div>
    <article class="card" id="card" aria-roledescription="slide" tabindex="-1"></article>
    <div class="nav">
      <button type="button" class="btn" id="prev" aria-label="Previous card">Back</button>
      <button type="button" class="btn primary" id="next" aria-label="Next card">Next</button>
    </div>
  </section>
  <p id="status" class="k" role="status"></p>
  <!--NOSCRIPT-->
</main>
<footer><p class="k">Built by {{GENERATOR}} from build graph cut {{CUT}}. Every card names its evidence keys; nothing here copies code.</p></footer>
<script src="show.js"></script>
</body>
</html>

Show

A style sheet in the template folder of Cosmic. Served with the page at https://ventusltd.github.io/cosmic/tools/explore/presentations/template/.

rendercosmic / tools/explore/presentations/template/show.css · lines 1–58 of 58 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Presentations — Template Page (cosmic, https://ventusltd.github.io/cosmic/tools/explore/presentations/template/). It is itself an entry point, published at https://ventusltd.github.io/cosmic/tools/explore/presentations/template/.
What it achieves
Explore Code stories player (show-1). Site palette from `explore.css`; no web fonts, no CDN.
Why it matters
Loaded by the Template page at https://ventusltd.github.io/cosmic/tools/explore/presentations/template/.
Application
cosmic · tools/explore/presentations/template · style sheet
Uses
none found
Used by
loaded by Presentations — Template Page (stylesheet)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/presentations/template/show.css:1-58 · blob c444a48e016365c77d880b3aaa2f001226d21157 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* Explore Code stories player (show-1). Site palette from explore.css; no web fonts, no CDN. */
*{box-sizing:border-box}
[hidden]{display:none!important}
html{-webkit-text-size-adjust:100%}
body{background:#000;color:#fff;font:16px/1.55 ui-monospace,Menlo,Consolas,monospace;margin:0;overflow-x:hidden}
header,main,footer{max-width:720px;margin:0 auto;padding:0 16px}
a{color:#66ccff}
a:focus-visible,button:focus-visible,summary:focus-visible,.card:focus-visible{outline:2px solid #00ffff;outline-offset:2px}
.skip{position:absolute;left:-999px;top:0;background:#000;padding:10px}
.skip:focus{left:8px;z-index:9}
.brand{color:#00ffff;margin:18px 0 2px;font-size:13px;letter-spacing:.06em}
.brand a{color:#00ffff;text-decoration:none;display:inline-block;min-height:44px;line-height:44px}
h1{font-size:22px;margin:0 0 6px;overflow-wrap:anywhere}
h2{font-size:17px;margin:0 0 4px;overflow-wrap:anywhere}
.lead{color:#cfd5df;margin:0 0 14px}
.k{color:#a6adbb;font-size:13px;overflow-wrap:anywhere}
.list{list-style:none;padding:0;margin:0 0 20px;display:grid;gap:12px}
.list a{display:grid;grid-template-columns:96px 1fr;gap:12px;align-items:center;min-height:88px;padding:10px;
  border:1px solid #2f343d;border-radius:8px;background:#0b0e14;color:#fff;text-decoration:none}
.list a:hover{border-color:#66ccff}
.list svg{width:96px;height:64px;display:block}
.list .t{font-weight:bold;color:#00ffff}
.list .b{color:#cfd5df;font-size:14px}
.list .n{color:#a6adbb;font-size:12px}
.bar{display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap}
.count{margin:0;color:#a6adbb;font-size:14px}
.dots{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0}
.dots i{width:8px;height:8px;border-radius:50%;background:#2f343d;display:block}
.dots i.on{background:#00ffff}
.card{overflow-wrap:anywhere;border:1px solid #2f343d;border-radius:10px;background:#0b0e14;padding:14px;min-height:300px;touch-action:pan-y;
  user-select:none;-webkit-user-select:none;transition:transform .22s ease,opacity .22s ease}
.card.out-l{transform:translateX(-24px);opacity:0}
.card.out-r{transform:translateX(24px);opacity:0}
.card figure{margin:0 0 10px}
.card svg{width:100%;height:auto;display:block;max-height:46vh;max-width:460px;margin:0 auto}
.card .say{font-size:17px;margin:8px 0;max-width:none;user-select:text;-webkit-user-select:text}
.card .say+.say{color:#cfd5df;font-size:16px}
.legend{list-style:none;padding:0;margin:6px 0 0;display:flex;flex-wrap:wrap;gap:4px 14px;font-size:13px;color:#cfd5df}
.legend i{display:inline-block;width:10px;height:10px;margin-right:6px;vertical-align:middle}
details{margin:10px 0 0;border-top:1px solid #2f343d}
summary{cursor:pointer;min-height:44px;line-height:44px;color:#a6adbb;font-size:14px}
details ul{padding-left:18px;margin:0 0 6px}
details li{font-size:12px;margin:6px 0;overflow-wrap:anywhere;user-select:text;-webkit-user-select:text}
details li a{display:inline-block;min-height:44px;line-height:1.5;padding:12px 0}
.btn{display:inline-flex;align-items:center;justify-content:center;min-height:44px;min-width:44px;padding:8px 16px;
  border:1px solid #2f343d;border-radius:8px;background:#0b0e14;color:#fff;font:inherit;text-decoration:none;cursor:pointer}
.btn:hover{border-color:#66ccff}
.btn.primary{background:#003a4a;border-color:#00ffff}
.btn.ghost{border-color:transparent;padding-left:0;color:#66ccff}
.btn[disabled]{opacity:.4;cursor:default}
.deeper{display:flex;margin-top:12px;width:100%;color:#000;background:#00ffff;border-color:#00ffff;font-weight:bold}
.nav{display:flex;justify-content:space-between;gap:12px;margin:12px 0 24px}
.nav .btn{flex:1}
.plain{overflow-wrap:anywhere}
.plain ol{padding-left:20px}
.plain li{margin:0 0 12px}
footer{border-top:1px solid #2f343d;margin-top:20px;padding-bottom:20px}
@media (prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important;scroll-behavior:auto!important}}

Show

A JavaScript file in the template folder of Cosmic that draws stories. Served with the page at https://ventusltd.github.io/cosmic/tools/explore/presentations/template/. It gets JSON (`getJSON`), shows list (`showList`) and renders list (`renderList`).

interactioncosmic / tools/explore/presentations/template/show.js · lines 1–196 of 196 · Entry point · pattern renderCard (shared by 3 files)

What it does
It draws stories. Defines 18 functions or classes, including $, esc, fmt, svg, wrap2. Side effects: changes the web page (DOM); makes network requests.
Inputs & outputs
In: JSON file stories.json. Out: SVG drawing.
Downstream impact
Used directly by 1 file: Presentations — Template Page (cosmic, https://ventusltd.github.io/cosmic/tools/explore/presentations/template/). It is itself an entry point, published at https://ventusltd.github.io/cosmic/tools/explore/presentations/template/.
What it achieves
Explore Code stories player (show-1): one shared page for every story. It responds to hashchange, click and keydown events.
Why it matters
Loaded by the Template page at https://ventusltd.github.io/cosmic/tools/explore/presentations/template/.
Application
cosmic · tools/explore/presentations/template · script
Uses
none found
Used by
loaded by Presentations — Template Page (script src)
Produces
$, esc, fmt, svg, wrap2, clip, P, picture, legend, getJSON, story, showList
Defines here
$, esc, fmt, svg, wrap2, clip, P, picture, legend, getJSON, story, showList, renderList, renderCard, swap, route, go, bind
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/presentations/template/show.js:1-196 · blob 630713854dfffb00aadc2fb42f5bf0089437740a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* Explore Code stories player (show-1): one shared page for every story.
   Hash routes: "" = list, "#<story>/<n>" = card n (1-based). Swipe, arrow keys, Home/End, Escape. */
(function () {
  'use strict';
  var $ = function (id) { return document.getElementById(id); };
  var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  var INDEX = null, CACHE = {}, cur = { id: null, i: 0, story: null };
  var NS = 'http://www.w3.org/2000/svg';

  function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]; }); }
  function fmt(v) { return typeof v === 'number' ? (Math.abs(v) < 1 && v !== 0 ? v.toFixed(2) : v.toLocaleString('en-GB')) : esc(v); }
  function svg(w, h, body, label) {
    return '<svg xmlns="' + NS + '" viewBox="0 0 ' + w + ' ' + h + '" role="img" aria-label="' + esc(label) + '">' + body + '</svg>';
  }
  function wrap2(s, n) {
    var w = String(s == null ? '' : s).split(/\s+/), l = ['', ''], k = 0;
    w.forEach(function (x) { if (k < 2 && l[k] && (l[k] + ' ' + x).length > n) k++; if (k < 2) l[k] = l[k] ? l[k] + ' ' + x : x; else l[1] += ' ' + x; });
    return l.filter(Boolean).map(function (x) { return clip(x, n); });
  }
  function clip(s, n) { s = String(s == null ? '' : s); return s.length > n ? s.slice(0, n - 1) + '…' : s; }

  // ---------------------------------------------------------------- pictures (pure functions of the card's pic spec)
  var PIC = {
    bars: function (p, a, small) {
      var it = p.items || [], max = p.max || Math.max.apply(null, it.map(function (x) { return x.v; }).concat([1e-9]));
      var rh = small ? 14 : 34, w = 320, b = '';
      it.forEach(function (x, k) {
        var y = k * rh, bw = Math.max(2, (w - (small ? 0 : 60)) * x.v / max);
        if (small) { b += '<rect x="0" y="' + (y + 2) + '" width="' + Math.max(2, 96 * x.v / max) + '" height="' + (rh - 5) + '" fill="' + x.c + '"/>'; return; }
        b += '<text x="0" y="' + (y + 12) + '" fill="#cfd5df" font-size="12">' + esc(clip(x.l, 44)) + '</text>' +
             '<rect x="0" y="' + (y + 16) + '" width="' + bw + '" height="12" rx="2" fill="' + x.c + '"/>' +
             '<text x="' + (bw + 6) + '" y="' + (y + 27) + '" fill="#fff" font-size="12">' + fmt(x.v) + '</text>';
      });
      return svg(small ? 96 : w, Math.max(rh * it.length, 10), b, a);
    },
    waffle: function (p, a, small) {
      var parts = p.parts || [], tot = p.total || parts.reduce(function (s, x) { return s + x.v; }, 0) || 1, b = '', cells = [], acc = 0;
      parts.forEach(function (x) { var c = Math.round(100 * (acc + x.v) / tot) - Math.round(100 * acc / tot); acc += x.v; for (var i = 0; i < c; i++) cells.push(x.c); });
      var s = small ? 6 : 26, g = small ? 0.5 : 3, cols = small ? 16 : 10;
      cells.forEach(function (c, i) { b += '<rect x="' + (i % cols) * s + '" y="' + Math.floor(i / cols) * s + '" width="' + (s - g) + '" height="' + (s - g) + '" fill="' + c + '"/>'; });
      return svg(cols * s, Math.ceil(cells.length / cols) * s, b, a);
    },
    number: function (p, a, small) {
      if (small) return svg(96, 64, '<text x="48" y="44" text-anchor="middle" fill="' + p.c + '" font-size="30" font-weight="bold">' + fmt(p.v) + '</text>', a);
      return svg(320, 130, '<text x="160" y="70" text-anchor="middle" fill="' + p.c + '" font-size="60" font-weight="bold">' + fmt(p.v) + '</text>' +
        '<text x="160" y="98" text-anchor="middle" fill="#fff" font-size="14">' + esc(clip(p.l, 44)) + '</text>' +
        '<text x="160" y="120" text-anchor="middle" fill="#a6adbb" font-size="12">' + esc(clip(p.sub, 50)) + '</text>', a);
    },
    tiles: function (p, a, small) {
      var it = (p.items || []).slice(0, 6), cols = small ? 3 : Math.min(3, it.length), W = 100, H = 104, b = '';
      it.forEach(function (x, k) {
        var X = (k % cols) * (W + 6), Y = Math.floor(k / cols) * (H + 6);
        b += '<rect x="' + X + '" y="' + Y + '" width="' + W + '" height="' + H + '" rx="6" fill="#000" stroke="' + x.c + '" stroke-width="2"/>' +
             '<text x="' + (X + 8) + '" y="' + (Y + 18) + '" fill="#a6adbb" font-size="12">' + fmt(x.n) + '</text>' +
             '<text x="' + (X + W / 2) + '" y="' + (Y + 62) + '" text-anchor="middle" fill="' + x.c + '" font-size="34" font-weight="bold">' + esc(clip(x.s, 5)) + '</text>' +
             (small ? '' : wrap2(x.l, 15).map(function (ln, j) { return '<text x="' + (X + W / 2) + '" y="' + (Y + 84 + j * 13) + '" text-anchor="middle" fill="#fff" font-size="11">' + esc(ln) + '</text>'; }).join(''));
      });
      var rows = Math.ceil(it.length / cols) || 1;
      return svg(cols * (W + 6) - 6, rows * (H + 6) - 6, b, a);
    },
    steps: function (p, a, small) {
      var it = p.items || [], done = p.done || [], b = '', h = small ? 64 : Math.max(60, it.length * 46), gap = it.length > 1 ? (h - 30) / (it.length - 1) : 0;
      if (small) { it.forEach(function (x, k) { var X = 12 + k * (72 / Math.max(1, it.length - 1)); b += (k ? '<line x1="' + (X - 72 / Math.max(1, it.length - 1)) + '" y1="32" x2="' + X + '" y2="32" stroke="#2f343d" stroke-width="3"/>' : '') + '<circle cx="' + X + '" cy="32" r="8" fill="' + (done[k] === false ? '#2f343d' : '#00ffff') + '"/>'; }); return svg(96, 64, b, a); }
      it.forEach(function (x, k) {
        var y = 15 + k * gap;
        if (k) b += '<line x1="16" y1="' + (y - gap + 10) + '" x2="16" y2="' + (y - 10) + '" stroke="#2f343d" stroke-width="3"/>';
        b += '<circle cx="16" cy="' + y + '" r="10" fill="' + (done[k] === false ? '#2f343d' : '#00ffff') + '"/>' +
             '<text x="36" y="' + (y + 5) + '" fill="#fff" font-size="14">' + esc(clip(x, 34)) + '</text>';
      });
      return svg(320, h, b, a);
    },
    scatter: function (p, a, small) {
      var bx = p.box, W = small ? 96 : 320, H = small ? 64 : 360, mid = (bx[1] + bx[3]) / 2 * Math.PI / 180;
      var sx = (bx[2] - bx[0]) * Math.cos(mid), sy = bx[3] - bx[1], k = Math.min(W / sx, H / sy), ox = (W - sx * k) / 2, b = '';
      function P(lon, lat) { return [ox + (lon - bx[0]) * Math.cos(mid) * k, H - (lat - bx[1]) * k]; }
      (p.pts || []).forEach(function (q) { var xy = P(q[0], q[1]); b += '<circle cx="' + xy[0].toFixed(1) + '" cy="' + xy[1].toFixed(1) + '" r="' + (small ? 1.2 : 3) + '" fill="' + p.c + '" opacity=".8"/>'; });
      if (p.hi && p.hi[0] != null) { var h = P(p.hi[0], p.hi[1]); b += '<circle cx="' + h[0] + '" cy="' + h[1] + '" r="' + (small ? 3 : 8) + '" fill="none" stroke="#ffae00" stroke-width="2"/>' + (small ? '' : '<text x="' + Math.min(h[0] + 12, W - 80) + '" y="' + (h[1] + 4) + '" fill="#ffae00" font-size="13">' + esc(p.hi[2]) + '</text>'); }
      return svg(W, H, '<rect width="' + W + '" height="' + H + '" fill="#05070b"/>' + b, a);
    },
    ptable: function (p, a, small) {
      var s = small ? 5 : 17.5, b = '';
      (p.cells || []).forEach(function (c) {
        var X = (c.c - 1) * s, Y = (c.r - 1) * s;
        b += '<rect x="' + X + '" y="' + Y + '" width="' + (s - 1) + '" height="' + (s - 1) + '" fill="' + c.k + '"/>';
        if (!small) b += '<text x="' + (X + s / 2 - 0.5) + '" y="' + (Y + s * 0.66) + '" text-anchor="middle" fill="#000" font-size="7">' + esc(c.s) + '</text>';
      });
      var rows = Math.max.apply(null, (p.cells || []).map(function (c) { return c.r; }).concat([1]));
      return svg(18 * s, rows * s, b, a);
    }
  };
  function picture(p, alt, small) {
    var f = PIC[p && p.type];
    try { return f ? f(p, alt, small) : ''; } catch (e) { return ''; }
  }
  function legend(p) {
    var it = p.type === 'waffle' ? p.parts : p.type === 'ptable' ? p.legend : null;
    if (!it) return '';
    return '<ul class="legend">' + it.map(function (x) { return '<li><i style="background:' + x.c + '"></i>' + esc(x.l) + ' (' + fmt(x.v) + ')</li>'; }).join('') + '</ul>';
  }

  // ---------------------------------------------------------------- data
  function getJSON(url) {
    return fetch(url, { cache: 'no-cache' }).then(function (r) { if (!r.ok) throw new Error(url + ': HTTP ' + r.status); return r.json(); });
  }
  function story(id) {
    if (CACHE[id]) return Promise.resolve(CACHE[id]);
    var s = (INDEX.stories || []).filter(function (x) { return x.id === id; })[0];
    if (!s) return Promise.reject(new Error('no story ' + id));
    return getJSON(s.url).then(function (d) { CACHE[id] = d; return d; });
  }

  // ---------------------------------------------------------------- views
  function showList() {
    cur.id = null;
    $('player').hidden = true; $('list').hidden = false;
    $('title').textContent = 'Stories';
    $('lead').hidden = false;
    document.title = 'Stories — Explore Code';
  }
  function renderList() {
    $('list').innerHTML = (INDEX.stories || []).map(function (s) {
      return '<li><a href="#' + esc(s.id) + '/1">' + picture(s.pic, s.title, true) +
        '<span><span class="t">' + esc(s.title) + '</span><br><span class="b">' + esc(s.blurb) + '</span><br><span class="n">' + s.cards + ' cards</span></span></a></li>';
    }).join('');
  }
  function renderCard(dir) {
    var s = cur.story, c = s.cards[cur.i], N = s.cards.length, el = $('card');
    var keys = (c.keys || []).map(function (k) {
      return '<li>' + (k.href ? '<a href="' + esc(k.href) + '">' + esc(k.k) + '</a>' : esc(k.k)) + '</li>';
    }).join('');
    var htm = '<figure>' + picture(c.pic, c.alt) + legend(c.pic) + '</figure>' +
      c.say.map(function (t) { return '<p class="say">' + esc(t) + '</p>'; }).join('') +
      '<a class="btn deeper" href="' + esc(c.deeper.href) + '">Go deeper: ' + esc(c.deeper.label) + '</a>' +
      (keys ? '<details><summary>Evidence (' + c.keys.length + ' key' + (c.keys.length > 1 ? 's' : '') + ')</summary><ul>' + keys + '</ul></details>' : '');
    var swap = function () {
      el.innerHTML = htm;
      el.setAttribute('aria-label', 'Card ' + (cur.i + 1) + ' of ' + N);
      el.className = 'card';
    };
    if (dir && !reduce) { el.className = 'card ' + (dir > 0 ? 'out-l' : 'out-r'); setTimeout(swap, 160); } else swap();
    $('count').textContent = s.title + ' · ' + (cur.i + 1) + ' of ' + N;
    $('dots').innerHTML = s.cards.map(function (_, k) { return '<i' + (k === cur.i ? ' class="on"' : '') + '></i>'; }).join('');
    $('prev').disabled = cur.i === 0;
    $('next').textContent = cur.i === N - 1 ? 'All stories' : 'Next';
  }
  function route() {
    var m = location.hash.replace(/^#/, '').match(/^([\w-]+)(?:\/(\d+))?$/);
    if (!m || !INDEX) { showList(); return; }
    story(m[1]).then(function (s) {
      var i = Math.max(0, Math.min(s.cards.length - 1, (+m[2] || 1) - 1));
      var dir = cur.id === s.id ? i - cur.i : 0;
      cur.id = s.id; cur.story = s; cur.i = i;
      $('list').hidden = true; $('player').hidden = false; $('lead').hidden = true;
      $('title').textContent = s.title;
      document.title = s.title + ' — Stories — Explore Code';
      renderCard(dir);
    }).catch(function (e) { $('status').textContent = 'Could not load that story (' + e.message + ').'; showList(); });
  }
  function go(d) {
    if (!cur.story) return;
    var i = cur.i + d;
    if (i < 0) return;
    if (i >= cur.story.cards.length) { location.hash = ''; return; }
    history.replaceState(null, '', '#' + cur.id + '/' + (i + 1));
    route();
  }

  // ---------------------------------------------------------------- input
  function bind() {
    window.addEventListener('hashchange', route);
    $('prev').addEventListener('click', function () { go(-1); });
    $('next').addEventListener('click', function () { go(1); });
    document.addEventListener('keydown', function (e) {
      if (!cur.story || e.altKey || e.ctrlKey || e.metaKey) return;
      var t = e.target && e.target.tagName;
      if (t === 'INPUT' || t === 'TEXTAREA') return;
      if (e.key === 'ArrowRight') { go(1); e.preventDefault(); }
      else if (e.key === 'ArrowLeft') { go(-1); e.preventDefault(); }
      else if (e.key === 'Home') { go(-cur.i); e.preventDefault(); }
      else if (e.key === 'End') { go(cur.story.cards.length - 1 - cur.i); e.preventDefault(); }
      else if (e.key === 'Escape') { location.hash = ''; }
    });
    var x0 = null, y0 = null, card = $('card');
    card.addEventListener('pointerdown', function (e) { if (e.pointerType !== 'mouse') { x0 = e.clientX; y0 = e.clientY; } });
    card.addEventListener('pointerup', function (e) {
      if (x0 === null) return;
      var dx = e.clientX - x0, dy = e.clientY - y0; x0 = null;
      if (Math.abs(dx) > 50 && Math.abs(dx) > 1.5 * Math.abs(dy)) go(dx < 0 ? 1 : -1);
    });
    card.addEventListener('pointercancel', function () { x0 = null; });
  }

  bind();
  getJSON('stories.json').then(function (d) { INDEX = d; renderList(); route(); })
    .catch(function (e) { $('status').textContent = 'The story list could not be loaded (' + e.message + '). Open this page through a web server.'; });
})();

Test Show

A test in the presentations folder of Cosmic that checks Show, using Louvain. It makes site (`make_site`), sets up (`setUp`) and sets up class (`setUpClass`).

testcosmic / tools/explore/presentations/test_show.py · lines 1–356 of 356 · Entry point · pattern test_parse_key (shared by 2 files)

What it does
It tests its inputs. Defines 29 functions or classes, including fixture_graph, key, make_site, run, TestStories. Uses libraries functools, http.server, json, os, re. Side effects: changes the web page (DOM); reads or writes files.
Inputs & outputs
In: JSON file build_graph.json; JSON file clarity.json; JSON file clean-manifest.json; JSON file communities.json; JSON file communities.metrics.json; JSON file periodic.json; JSON file receipts.json; JSON file laws.json. Out: JSON file communities.json; JSON file keys.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `show.py` (story mode).
Why it matters
Guards the behaviour of Show.
Application
cosmic · tools/explore/presentations · test
Uses
Show (import), functools, http.server, json, os, re, shutil, sys, tempfile
Used by
none found
Produces
fixture_graph, key, make_site, run, TestStories, Quiet, serve, TestPlayer
Defines here
fixture_graph, key, make_site, run, TestStories, setUp, tearDown, stories, test_all_six_stories, test_numbers_come_from_inputs, test_keys_link_to_real_section_pages, test_deeper_links_only_to_existing_pages, test_massless_no_code_text, test_noscript_has_every_card, test_missing_inputs_skip_with_warning, test_bad_input_is_fail_safe, test_no_graph_fails, test_only_and_cross_cut_key_resolution, test_parse_key, Quiet, log_message, serve, TestPlayer, setUpClass, tearDownClass, page, test_viewports, test_swipe_keys_and_back, test_reduced_motion_and_noscript
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/presentations/test_show.py:1-356 · blob 640b3eb6625dd3efbf84178fbd43320e843af0a0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Tests for show.py (story mode). Run: python3 -m pytest -q tools/explore/presentations/test_show.py

Unit tests build a small fixture site (no CPU-heavy inputs). The browser test (Playwright, Chromium) serves the
fixture site and checks the player at 390x844, 820x1180, 1366x768 and 1920x1080: zero console errors, no
sideways scroll, every visible tap target at least 44x44 px, swipe + arrow keys, and the <noscript> copy.
Set SHOW_SITE=<explore-code folder that already has show/> to run the same browser checks on a real build.
"""
import functools
import http.server
import json
import os
import re
import shutil
import sys
import tempfile
import threading
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import show  # noqa: E402

C1 = 'a' * 40
C2 = 'b' * 40
CODE_RE = re.compile(r'(function\s*\w*\s*\(|=>|\bdef \w+\(|\bimport \w|;\s*\}|\{\s*return\b|const \w+ =)')


def fixture_graph():
    files = []
    for i in range(12):
        repo = 'alpha' if i < 8 else 'beta'
        files.append({'id': i, 'repo': repo, 'path': 'src/f%d.js' % i, 'section': 1 + i // 4, 'block': 1 + i % 4,
                      'title': 'File %d' % i, 'role': ['render', 'geodesy'][i % 2], 'dependents': list(range(i % 3))})
    return {'schema': 'explore-build-graph-v1', 'cut': '2026-12-05T00:00:00+00:00',
            'roles': [{'id': 'render', 'title': 'Render (DOM, canvas, maps, HTML)', 'colour': '#ff6666'},
                      {'id': 'geodesy', 'title': 'Geodesy and coordinates', 'colour': '#00ffff'}],
            'repos': [{'repo': 'alpha', 'commit': C1, 'core': True, 'descriptor': 'Alpha draws maps. It also does more.'},
                      {'repo': 'beta', 'commit': C2, 'core': True, 'readme_summary': 'Beta measures distance.'},
                      {'repo': 'gamma', 'commit': C2, 'core': False}],
            'sections': [{'section': k, 'url': 's/%04d.html' % k} for k in (1, 2, 3)],
            'files': files,
            'journeys': [{'id': 'a', 'title': 'Journey A: Map to Site', 'url': 'journeys/a.html',
                          'steps': [{'label': 'Alpha', 'found': True, 'key_files': [0]},
                                    {'label': 'Beta', 'found': False, 'key_files': []}]}]}


def key(i, g):
    f = g['files'][i]
    return '%s@%s %s:1-10 %s' % (f['repo'], C1 if f['repo'] == 'alpha' else C2, f['path'], 'c' * 40)


def make_site(root, with_inputs=True):
    g = fixture_graph()
    site = os.path.join(root, 'explore-code')
    for d in ('s', 'repos', 'journeys', 'visual', 'clarity', 'lab', 'periodic/furnace', 'seethrough', 'pilot', 'laws'):
        os.makedirs(os.path.join(site, d), exist_ok=True)
    w = lambda rel, obj: open(os.path.join(site, rel), 'w').write(obj if isinstance(obj, str) else json.dumps(obj))
    w('build_graph.json', g)
    for p in ('index.html', 's/0001.html', 's/0002.html', 's/0003.html', 'repos/alpha.html', 'repos/beta.html',
              'journeys/a.html', 'visual/index.html', 'clarity/index.html', 'periodic/index.html', 'periodic/Al.html',
              'periodic/furnace/index.html', 'pilot/index.html'):
        w(p, '<!DOCTYPE html><title>x</title><p>page</p>')
    if not with_inputs:
        return site, g
    w('clarity/clarity.json', {'schema': 'clarity-v1', 'cut': g['cut'], 'categories': ['core', 'copy', 'via', 'unreached'],
                               'counts': {'core': 7, 'copy': 2, 'via': 1, 'unreached': 2},
                               'titles': {'core': 'Unique and in use', 'copy': 'Copies of other code',
                                          'via': 'Reachable only through copies', 'unreached': 'Not reached'}})
    w('clean-manifest.json', {'schema': 'clean-manifest-v1', 'graph_cut': g['cut'],
                              'summary': 'Of 12 files ... Nothing was deleted or edited in any repository.',
                              'main_view': [{'file_id': i} for i in range(10)],
                              'set_aside': [{'file_id': 10, 'key': key(10, g), 'target': key(2, g), 'category': 'near-copy-of',
                                             'confidence': 0.99, 'reason': '99% of its lines are the same as src/f2.js (alpha), which stays.'},
                                            {'file_id': 11, 'key': key(11, g), 'category': 'noise-generated', 'confidence': 0.7}],
                              'counts': {'by_category': {'near-copy-of': 1, 'noise-generated': 1},
                                         'by_repo': {'alpha': {'main_view': 8, 'set_aside': 0}, 'beta': {'main_view': 2, 'set_aside': 2}}}})
    w('lab/communities.json', {'schema': 'explore-lab-overlay-v1', 'cut': g['cut'], 'n': 12,
                               'legend': {'c': ['id', 'label', 'size', 'top_repo', 'top_repo_share', 'repos', 'hub_file'],
                                          'rows': [[0, 'maps tiles draw', 7, 'alpha', 0.8, 2, 3], [1, 'distance sums', 4, 'beta', 1.0, 1, 9]]}})
    w('lab/communities.metrics.json', {'metrics': {'modularity': {'louvain': 0.8, 'repo_partition': 0.4, 'topic_partition': 0.3},
                                                   'louvain_communities': 2}})
    w('periodic/periodic.json', {'schema': 'explore-periodic-v1', 'cut': g['cut'], 'counts': {'files': 12, 'elements': 3},
                                 'axes': {'groups': [{'id': 'render', 'colour': '#ff6666'}]},
                                 'elements': [{'key': 'block:Al', 'symbol': 'Al', 'title': 'Alpha maps', 'file_count': 8, 'group': 'render',
                                               'analogue': {'symbol': 'H', 'rule': 'hydrogen'}, 'tiny_helpers': 30,
                                               'evidence': [key(0, g).rsplit(' ', 1)[0]]},
                                              {'key': 'block:Ux', 'symbol': 'Ux', 'title': 'Unsettled thing', 'file_count': 0,
                                               'state': 'UNSETTLED', 'competing_values': [{'files': 1, 'value': 'x'}, {'files': 2, 'value': 'y'}],
                                               'analogue': {'symbol': 'F', 'rule': 'halogen'}, 'evidence': []},
                                              {'key': 'candidate:B', 'proposed_symbol': '*B', 'title': 'Beta (candidate)', 'file_count': 4}]})
    w('periodic/furnace/receipts.json', {'schema': 'periodic-furnace-receipts-v1', 'graph_cut': g['cut'],
                                         'counts': {'elements': 3, 'agree': 1, 'annihilate': 0, 'not_yet_built': 2,
                                                    'electron_files': 3, 'positron_files': 1},
                                         'elements': [{'Z': 1, 'symbol': 'H', 'row': 1, 'col': 1, 'status': 'agree'},
                                                      {'Z': 2, 'symbol': 'He', 'row': 1, 'col': 18, 'status': 'not yet built'},
                                                      {'Z': 3, 'symbol': 'Li', 'row': 2, 'col': 1, 'status': 'not yet built'}]})
    w('laws/laws.json', {'schema': 'estate-laws-v1', 'graph_cut': g['cut'],
                         'laws': {'gravity': {'id': 'G1', 'name': 'Gravity', 'law': 'Use concentrates: a few files carry most uses.',
                                              'means': 'A small number of files account for most uses.', 'verdict': 'HOLDS',
                                              'evidence': [key(3, g)]},
                                  'entropy': {'id': 'S1', 'name': 'Entropy', 'law': 'Copies spread.', 'means': 'More copies over time.',
                                              'verdict': 'PARTLY', 'evidence': []}}})
    w('seethrough/index.json', {'schema': 'explore-seethrough-v1', 'cut': g['cut'], 'names': 40, 'linked_files': 2,
                                'files': {'1': {'s': 1, 'b': 2, 'k': 'alpha/src/f1.js', 'n': 3, 'm': [['Cowley Substation', 4, 'exact', 'e']]},
                                          '5': {'s': 2, 'b': 2, 'k': 'alpha/src/f5.js', 'n': 1, 'm': [['Iron Acton', 2, 'exact', 'e']]}}})
    w('pilot/places.json', {'schema': 'explore-pilot-places-v1', 'cut': g['cut'],
                            'places': [{'i': 0, 'name': 'London', 'lat': 51.5, 'lon': -0.12,
                                        'files': [{'id': 1, 'key': key(1, g), 'url': 's/0001.html#f2'}, {'id': 2, 'key': key(2, g)}]},
                                       {'i': 1, 'name': 'Leeds', 'lat': 53.8, 'lon': -1.55, 'files': [{'id': 3, 'key': key(3, g)}]}]})
    return site, g


def run(site, *extra):
    return show.main(['--site', site, '--clean', os.path.join(site, 'clean-manifest.json')] + list(extra))


class TestStories(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.mkdtemp()
        self.site, self.g = make_site(self.tmp)

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def stories(self):
        idx = json.load(open(os.path.join(self.site, 'show', 'stories.json')))
        return idx, {s['id']: json.load(open(os.path.join(self.site, 'show', s['url']))) for s in idx['stories']}

    def test_all_six_stories(self):
        self.assertEqual(run(self.site), 0)
        idx, S = self.stories()
        self.assertEqual(idx['schema'], show.INDEX_SCHEMA)
        self.assertEqual([s['id'] for s in idx['stories']], show.ORDER)
        for s in S.values():
            self.assertEqual(s['schema'], show.STORY_SCHEMA)
            self.assertTrue(s['cards'])
            for c in s['cards']:
                self.assertIn(c['pic']['type'], ('bars', 'waffle', 'number', 'tiles', 'steps', 'scatter', 'ptable'))
                self.assertTrue(1 <= len(c['say']) <= 2, c['say'])
                self.assertTrue(c['alt'])
                self.assertTrue(c['deeper']['href'] and c['deeper']['label'])
                self.assertTrue(c['keys'], 'every card names evidence: %s' % c['say'])

    def test_numbers_come_from_inputs(self):
        run(self.site)
        _, S = self.stories()
        self.assertIn('Of 12 files, 10 stay in the cleaned view and 2 are set aside.', S['clean']['cards'][0]['say'])
        self.assertIn('2 core engines', S['engines']['cards'][0]['say'][0])
        self.assertIn('Alpha draws maps.', S['engines']['cards'][1]['say'][0])
        self.assertIn('1 of 2 steps', S['engines']['cards'][-1]['say'][1])
        self.assertIn('0.80 against 0.40', S['communities']['cards'][0]['say'][1])
        self.assertIn('2 physical-style laws', S['laws']['cards'][0]['say'][0])
        self.assertIn('1 agree', S['periodic']['cards'][-1]['say'][1])
        self.assertIn('London appears in the most files (2)', S['seethrough']['cards'][-1]['say'][1])

    def test_keys_link_to_real_section_pages(self):
        run(self.site)
        _, S = self.stories()
        hrefs = [k['href'] for s in S.values() for c in s['cards'] for k in c['keys'] if k['href']]
        self.assertTrue(hrefs)
        for h in hrefs:
            self.assertTrue(os.path.exists(os.path.join(self.site, 'show', h.split('#')[0])), h)
        near = S['clean']['cards'][1]['keys']
        self.assertEqual(near[0]['href'], '../s/0003.html#f3')  # file 10 -> section 3 block 3

    def test_deeper_links_only_to_existing_pages(self):
        run(self.site)
        _, S = self.stories()
        for s in S.values():
            for c in s['cards']:
                p = c['deeper']['href'].split('#')[0].split('?')[0]
                self.assertTrue(os.path.exists(os.path.normpath(os.path.join(self.site, 'show', p))), p)
        # chess is not in the fixture site: falls back to the visualiser community colouring
        self.assertEqual(S['communities']['cards'][-1]['deeper']['href'], '../visual/index.html#colour=community')

    def test_massless_no_code_text(self):
        run(self.site)
        for dp, _, fns in os.walk(os.path.join(self.site, 'show', 'stories')):
            for f in fns:
                t = open(os.path.join(dp, f)).read()
                self.assertIsNone(CODE_RE.search(t), f)
                self.assertLess(len(t), 40000, 'a story stays small')

    def test_noscript_has_every_card(self):
        run(self.site)
        page = open(os.path.join(self.site, 'show', 'index.html')).read()
        ns = page[page.index('<noscript>'):page.index('</noscript>')]
        _, S = self.stories()
        self.assertEqual(ns.count('<li>'), sum(len(s['cards']) for s in S.values()))
        self.assertIn('Of 12 files, 10 stay in the cleaned view', ns)
        self.assertNotIn('http://', page.replace('http://www.w3.org', ''))
        self.assertNotRegex(page, r'<(script|link)[^>]+(src|href)="(https?:)?//')

    def test_missing_inputs_skip_with_warning(self):
        site, _ = make_site(tempfile.mkdtemp(dir=self.tmp), with_inputs=False)
        self.assertEqual(show.main(['--site', site]), 0)
        idx = json.load(open(os.path.join(site, 'show', 'stories.json')))
        self.assertEqual([s['id'] for s in idx['stories']], ['engines'])
        self.assertEqual(show.main(['--site', site, '--strict']), 1)

    def test_bad_input_is_fail_safe(self):
        open(os.path.join(self.site, 'laws', 'laws.json'), 'w').write('{not json')
        self.assertEqual(run(self.site), 0)
        idx, _ = self.stories()
        self.assertNotIn('laws', [s['id'] for s in idx['stories']])

    def test_no_graph_fails(self):
        os.remove(os.path.join(self.site, 'build_graph.json'))
        self.assertEqual(show.main(['--site', self.site]), 1)

    def test_only_and_cross_cut_key_resolution(self):
        # lab from another cut: hub ids resolve through keys.json by repo/path, not by id
        lab = os.path.join(self.site, 'lab')
        d = json.load(open(os.path.join(lab, 'communities.json')))
        d['cut'] = 'older'
        d['legend']['rows'][0][6] = 0
        json.dump(d, open(os.path.join(lab, 'communities.json'), 'w'))
        json.dump({'k': ['beta@%s:src/f9.js' % C2[:12]]}, open(os.path.join(lab, 'keys.json'), 'w'))
        self.assertEqual(run(self.site, '--only', 'communities'), 0)
        idx, S = self.stories()
        self.assertEqual([s['id'] for s in idx['stories']], ['communities'])
        hubkeys = [k for c in S['communities']['cards'] for k in c['keys'] if k['k'].startswith('beta@')]
        self.assertTrue(hubkeys)
        self.assertEqual(hubkeys[0]['href'], '../s/0003.html#f2')  # file 9 by repo/path in this cut

    def test_parse_key(self):
        self.assertEqual(show.parse_key('r@%s a/b.js:1-9 %s' % (C1, C2)), ('r', 'a/b.js'))
        self.assertEqual(show.parse_key('r@abcdef123456:a/b.js'), ('r', 'a/b.js'))
        self.assertIsNone(show.parse_key('block:Al'))


class Quiet(http.server.SimpleHTTPRequestHandler):
    def log_message(self, *a):
        pass


def serve(root):
    h = functools.partial(Quiet, directory=root)
    srv = http.server.ThreadingHTTPServer(('127.0.0.1', 0), h)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    return srv


VIEWS = [(390, 844), (820, 1180), (1366, 768), (1920, 1080)]
TAPS = """() => { const out = []; document.querySelectorAll('a, button, summary').forEach(e => {
  const r = e.getBoundingClientRect(), cs = getComputedStyle(e);
  if (!r.width || !r.height || cs.visibility === 'hidden' || r.right < 0 || r.bottom < 0 || r.left > innerWidth) return;
  if (r.width < 44 || r.height < 44) out.push(e.tagName + ' ' + (e.textContent || '').trim().slice(0, 40) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height)); });
  return out; }"""
SIDEWAYS = '() => document.documentElement.scrollWidth - innerWidth'


@unittest.skipIf(os.environ.get('SHOW_NO_BROWSER'), 'browser tests disabled')
class TestPlayer(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        try:
            from playwright.sync_api import sync_playwright
        except ImportError:
            raise unittest.SkipTest('playwright not installed')
        cls.tmp = tempfile.mkdtemp()
        real = os.environ.get('SHOW_SITE')
        if real:
            cls.site = real
        else:
            cls.site, _ = make_site(cls.tmp)
            run(cls.site)
        cls.srv = serve(cls.site)
        cls.base = 'http://127.0.0.1:%d/show/' % cls.srv.server_address[1]
        cls.pw = sync_playwright().start()
        try:
            cls.browser = cls.pw.chromium.launch()
        except Exception as ex:  # no browser on this machine
            cls.pw.stop()
            raise unittest.SkipTest('chromium unavailable: %s' % ex)
        cls.ids = [s['id'] for s in json.load(open(os.path.join(cls.site, 'show', 'stories.json')))['stories']]

    @classmethod
    def tearDownClass(cls):
        cls.browser.close()
        cls.pw.stop()
        cls.srv.shutdown()
        shutil.rmtree(cls.tmp, ignore_errors=True)

    def page(self, w, h, **kw):
        ctx = self.browser.new_context(viewport={'width': w, 'height': h}, **kw)
        pg = ctx.new_page()
        errs = []
        pg.on('console', lambda m: errs.append(m.text) if m.type == 'error' else None)
        pg.on('pageerror', lambda e: errs.append(str(e)))
        return ctx, pg, errs

    def test_viewports(self):
        for w, h in VIEWS:
            with self.subTest(view='%dx%d' % (w, h)):
                ctx, pg, errs = self.page(w, h, has_touch=w < 1000)
                pg.goto(self.base + 'index.html')
                pg.wait_for_selector('#list a')
                self.assertEqual(pg.locator('#list a').count(), len(self.ids))
                self.assertLessEqual(pg.evaluate(SIDEWAYS), 0, 'list sideways scroll')
                self.assertEqual(pg.evaluate(TAPS), [], 'list taps')
                for sid in self.ids:
                    pg.goto(self.base + 'index.html#%s/1' % sid)
                    pg.wait_for_selector('#card figure svg')
                    n = json.load(open(os.path.join(self.site, 'show', 'stories', sid + '.json')))['cards']
                    for i in range(len(n)):
                        pg.wait_for_function('document.querySelector("#count").textContent.indexOf("%d of %d") >= 0' % (i + 1, len(n)))
                        pg.wait_for_timeout(200)
                        pg.evaluate('() => { const d = document.querySelector("#card details"); if (d) d.open = true; }')
                        self.assertLessEqual(pg.evaluate(SIDEWAYS), 0, '%s card %d sideways scroll' % (sid, i + 1))
                        self.assertEqual(pg.evaluate(TAPS), [], '%s card %d taps' % (sid, i + 1))
                        if i < len(n) - 1:
                            pg.keyboard.press('ArrowRight')
                self.assertEqual(errs, [])
                ctx.close()

    def test_swipe_keys_and_back(self):
        ctx, pg, errs = self.page(390, 844, has_touch=True)
        sid = self.ids[0]
        pg.goto(self.base + 'index.html#%s/1' % sid)
        pg.wait_for_selector('#card figure svg')
        box = pg.locator('#card').bounding_box()
        y = box['y'] + 60
        pg.evaluate("""([x0, x1, y]) => { const c = document.getElementById('card');
          const ev = (t, x) => c.dispatchEvent(new PointerEvent(t, {clientX: x, clientY: y, pointerType: 'touch', bubbles: true}));
          ev('pointerdown', x0); ev('pointerup', x1); }""", [box['x'] + 300, box['x'] + 40, y])
        pg.wait_for_function('location.hash.endsWith("/2")')
        self.assertFalse(pg.locator('#list').is_visible(), 'story list hidden while a story plays')
        pg.keyboard.press('ArrowLeft')
        pg.wait_for_function('location.hash.endsWith("/1")')
        self.assertTrue(pg.locator('#prev').is_disabled())
        pg.keyboard.press('Escape')
        pg.wait_for_selector('#list a')
        self.assertEqual(errs, [])
        ctx.close()

    def test_reduced_motion_and_noscript(self):
        ctx, pg, errs = self.page(390, 844, reduced_motion='reduce')
        pg.goto(self.base + 'index.html#%s/1' % self.ids[0])
        pg.wait_for_selector('#card figure svg')
        pg.locator('#next').click()
        # with reduced motion the next card is drawn at once, without the slide class
        self.assertEqual(pg.evaluate('document.getElementById("card").className'), 'card')
        ctx.close()
        ctx, pg, errs = self.page(390, 844, java_script_enabled=False)
        pg.goto(self.base + 'index.html')
        txt = pg.inner_text('main')
        self.assertIn('plain text', txt)
        self.assertGreater(pg.locator('.plain li').count(), 3)
        self.assertLessEqual(pg.evaluate(SIDEWAYS), 0)
        ctx.close()


if __name__ == '__main__':
    unittest.main()