Public: anyone can read this; the crew can change it.

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

A test proves the served page has exactly one STOP, no layout rule hides it, and it stops on pointerdown #135

Merged opened this

Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.

Merged

smith/arm:smith/129-a-test-proves-the-served-page-has-exactl → main 4 commits fork

  • Merged. smith/129-a-test-proves-the-served-page-has-exactl was merged into main as 97d3f3e.

Review

Sign in to review this change.
1 file changed +112 −0
Software/so101/src/stop-layout.test.ts added +112
@@ -0,0 +1,112 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtempSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { FeetechBus } from "./bus.ts";
6 import { FakeBus } from "./fake-bus.ts";
7 import { startServer, type RunningServer } from "./server.ts";
8
9 // The page has no browser to run in here, so the layout is read, not rendered: the markup gives the STOP button and
10 // the elements that contain it; the stylesheet, flattened out of every @media block, gives the rules that could hide them.
11
12 type El = { tag: string; id: string; classes: string[]; attrs: Record<string, string> };
13
14 /** The button carrying data-stop (every one found) and each one's ancestors, from the markup outside script, style and comments. */
15 function findStops(html: string): El[][] {
16 const markup = html.replace(/<!--[\s\S]*?-->/g, "").replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, "");
17 const VOID = new Set(["meta", "link", "img", "br", "hr", "input", "source", "area", "base", "col", "embed", "wbr"]);
18 const stack: El[] = [];
19 const found: El[][] = [];
20 for (const m of markup.matchAll(/<(\/?)([a-zA-Z][\w-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g)) {
21 const tag = m[2]!.toLowerCase();
22 if (m[1]) {
23 const at = stack.map((e) => e.tag).lastIndexOf(tag);
24 if (at >= 0) stack.length = at;
25 continue;
26 }
27 const attrs: Record<string, string> = {};
28 for (const a of m[3]!.matchAll(/([^\s=/"'>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g)) attrs[a[1]!.toLowerCase()] = a[2] ?? a[3] ?? a[4] ?? "";
29 const el: El = { tag, id: attrs.id ?? "", classes: (attrs.class ?? "").split(/\s+/).filter(Boolean), attrs };
30 if (!VOID.has(tag) && !m[3]!.trimEnd().endsWith("/")) {
31 if ("data-stop" in attrs) found.push([...stack, el]);
32 stack.push(el);
33 } else if ("data-stop" in attrs) found.push([...stack, el]);
34 }
35 return found;
36 }
37
38 /** Every rule of every stylesheet, @media (and other at-rule) blocks flattened into the rules inside them. */
39 function flatRules(css: string): Array<{ selector: string; body: string }> {
40 const rules: Array<{ selector: string; body: string }> = [];
41 const walk = (src: string) => {
42 let i = 0;
43 while (i < src.length) {
44 const open = src.indexOf("{", i);
45 if (open < 0) break;
46 let depth = 1;
47 let j = open + 1;
48 for (; j < src.length && depth; j++) depth += src[j] === "{" ? 1 : src[j] === "}" ? -1 : 0;
49 const head = src.slice(i, open).trim();
50 const inner = src.slice(open + 1, j - 1);
51 if (head.startsWith("@")) walk(inner);
52 else rules.push({ selector: head, body: inner });
53 i = j;
54 }
55 };
56 walk(css.replace(/\/\*[\s\S]*?\*\//g, ""));
57 return rules;
58 }
59
60 /** Whether a selector's last compound (pseudo-classes dropped: the stricter reading) can match the element. */
61 function matches(selector: string, el: El): boolean {
62 const last = selector.trim().split(/[\s>+~]+/).pop()!.replace(/::?[\w-]+(\([^)]*\))?/g, "");
63 if (!last || last === "*") return true;
64 const tag = /^[a-zA-Z][\w-]*/.exec(last)?.[0];
65 if (tag && tag.toLowerCase() !== el.tag) return false;
66 for (const m of last.matchAll(/#([\w-]+)|\.([\w-]+)|\[([\w-]+)(?:[~|^$*]?=["']?([^"'\]]*)["']?)?\]/g)) {
67 if (m[1] && m[1] !== el.id) return false;
68 if (m[2] && !el.classes.includes(m[2])) return false;
69 if (m[3] && !(m[3].toLowerCase() in el.attrs && (m[4] === undefined || el.attrs[m[3].toLowerCase()] === m[4]))) return false;
70 }
71 return true;
72 }
73
74 const hides = (body: string) => /(^|;)\s*display\s*:\s*none\b|(^|;)\s*visibility\s*:\s*(hidden|collapse)\b/i.test(body);
75
76 let server: RunningServer;
77 let html: string;
78
79 beforeAll(async () => {
80 const dataDir = mkdtempSync(join(tmpdir(), "so101-stop-"));
81 server = await startServer(new FeetechBus(new FakeBus([1, 2, 6])), { host: "127.0.0.1", port: 0, ids: [1, 2, 6], posesFile: join(dataDir, "poses.json"), watchdogMs: 60 });
82 html = await (await fetch(`http://127.0.0.1:${server.port}/`)).text();
83 });
84 afterAll(() => Promise.race([server.close(), new Promise((r) => setTimeout(r, 500))]));
85
86 describe("the served page's STOP", () => {
87 test("there is exactly one [data-stop]", () => {
88 expect(findStops(html).length).toBe(1);
89 });
90
91 test("no rule, in any @media block, hides it or an element that contains it", () => {
92 const chain = findStops(html)[0]!;
93 expect(chain.length).toBeGreaterThan(1);
94 const css = [...html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((m) => m[1]!).join("\n");
95 const rules = flatRules(css);
96 expect(rules.length).toBeGreaterThan(20); // the flattening reached the media blocks
97 expect(rules.some((r) => hides(r.body))).toBe(true); // the check can see a hiding rule at all
98 const offenders = rules.filter((r) => hides(r.body)).flatMap((r) => r.selector.split(",").filter((s) => chain.some((el) => matches(s, el))).map((s) => `${s.trim()} { ${r.body.trim()} }`));
99 expect(offenders).toEqual([]);
100 for (const el of chain) expect(el.attrs).not.toHaveProperty("hidden");
101 });
102
103 test("it stops on pointerdown, not click", () => {
104 const button = findStops(html)[0]!.at(-1)!;
105 expect(button.attrs).not.toHaveProperty("onclick");
106 const js = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)].map((m) => m[1]!).join("\n");
107 expect(js).toMatch(/\$\("stop"\)\.addEventListener\("pointerdown",[^\n]*\bstop\(\)/);
108 // the click handler left is the keyboard's (detail 0): a pointer's click has already stopped it on pointerdown
109 const click = /\$\("stop"\)\.addEventListener\("click",[^\n]*/.exec(js)?.[0];
110 if (click) expect(click).toMatch(/e\.detail\s*===\s*0/);
111 });
112 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs