224 lines · 12.7 KB · TypeScriptRaw
/** * EVERY TAP ON ANDROID IS READ BY TALKBACK: a control in Cotton's apps on Android (the shared shell and every * flavour under apps/android) has a role and a name, as every control on the iPhone has for VoiceOver. * * It reads every `.kt` under apps/android outside the tests' sources (as the literals guard does) with comments and * strings blanked, and finds each tap: `.clickable(`, `combinedClickable(`, `.selectable(`, `.toggleable(`, * `.tapped(`, `detectTapGestures`, and a hand-rolled tap (`waitForUpOrCancellation`, Podcasts' `awaitRelease()`). Each must sit in a modifier * chain that says what TalkBack reads: * - a NAME: the shell's `.control(name)` / `.named(name)`, a `contentDescription`, an `onClickLabel` (or the same label as * `semantics { onClick(label = …) }`, the action TalkBack offers by that name), the * modifier of a `Text`/`FitText`, whose words name it, or `semantics(mergeDescendants = true)` over words; and * - a ROLE and a click TalkBack can give: `.control`/`.named`, a `clickable(…, role = …)`, `.tapped` (a button by * construction), or a `semantics { … onClick / onLongClick … }` beside the gesture. * A chain that hides itself from TalkBack on purpose (`clearAndSetSemantics`) or a `clickable(enabled = false)` that * only swallows touches is no control. The cheapest honest form of the brief's guard: source-level, so it runs in * guards-main with no emulator; `ControlSemanticsTest` (shell, Robolectric) proves the helpers yield the semantics. * * The allow-list is EMPTY and stays so. */import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";import { dirname, join, relative, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");const APP = join(REPO_ROOT, "apps", "android");const ALLOWED: ReadonlyArray<string> = [];const TAP = /\.clickable\b|\bcombinedClickable\b|\.selectable\b|\.toggleable\b|\.tapped\b|(?<!@)\bdetectTapGestures\b|\bwaitForUpOrCancellation\b|\bawaitRelease\(\)/g;const NAMED_BY_WORDS = new Set(["Text", "FitText", "BasicText"]);/** The source with comments and string contents blanked (newlines kept), so what is scanned is code alone. */export function code(source: string): string { source = source.replace(/^(import|package) .*$/gm, (line) => " ".repeat(line.length)); let out = ""; let i = 0; const n = source.length; const blank = (s: string) => s.replace(/[^\n]/g, " "); while (i < n) { const c = source[i]; if (c === "/" && source[i + 1] === "/") { const end = source.indexOf("\n", i); const stop = end < 0 ? n : end; out += blank(source.slice(i, stop)); i = stop; continue; } if (c === "/" && source[i + 1] === "*") { const end = source.indexOf("*/", i + 2); const stop = end < 0 ? n : end + 2; out += blank(source.slice(i, stop)); i = stop; continue; } if (c === "'") { let j = i + 1; while (j < n && source[j] !== "'") { if (source[j] === "\\") j++; j++; } out += "'" + blank(source.slice(i + 1, j)) + "'"; i = j + 1; continue; } if (c === '"') { const triple = source.startsWith('"""', i); let j = i + (triple ? 3 : 1); let depth = 0; while (j < n) { if (triple && depth === 0 && source.startsWith('"""', j)) { j += 3; break; } if (!triple && depth === 0 && source[j] === '"') { j++; break; } if (!triple && source[j] === "\\") { j += 2; continue; } if (source[j] === "$" && source[j + 1] === "{") { depth++; j += 2; continue; } if (depth > 0 && source[j] === "}") depth--; j++; } // Kept as a one-character string so a template `${…}` never unbalances what follows. const text = source.slice(i, j); out += '"' + blank(text.slice(1, -1)) + '"'; i = j; continue; } out += c; i++; } return out;}type Frame = { open: string; name: string | null; at: number; segment: number };export type Tap = { file: string; line: number; token: string; ok: boolean; why: string };/** Every tap in [source], with whether its chain names it and gives it a role. */export function taps(source: string, file = "<source>"): Tap[] { const text = code(source); const found: Tap[] = []; const marks = new Map<number, string>(); for (const match of text.matchAll(TAP)) marks.set(match.index!, match[0]); const stack: Frame[] = []; const identBefore = (at: number): string | null => { let j = at - 1; while (j >= 0 && /\s/.test(text[j])) j--; const end = j + 1; while (j >= 0 && /[A-Za-z0-9_]/.test(text[j])) j--; const name = text.slice(j + 1, end); return name && /^[A-Za-z_]/.test(name) ? name : null; }; /** Where the argument (or statement) holding [at] ends: the next `,` or close at the holder's depth. */ const segmentEnd = (from: number): number => { let depth = 0; for (let j = from; j < text.length; j++) { const c = text[j]; if (c === "(" || c === "{" || c === "[") depth++; else if (c === ")" || c === "}" || c === "]") { if (depth === 0) return j; depth--; } else if (c === "," && depth === 0) return j; } return text.length; }; const statementStart = (at: number): number => { const before = text.slice(0, at); const fun = Math.max(before.lastIndexOf("\nfun "), before.lastIndexOf("\nprivate fun "), before.lastIndexOf("\ninternal fun ")); return fun < 0 ? 0 : fun; }; for (let i = 0; i < text.length; i++) { const token = marks.get(i); if (token) { const holder = [...stack].reverse().find((frame) => frame.open === "(" && !/^(pointerInput|detectTapGestures|awaitEachGesture|awaitPointerEventScope|then|if)$/.test(frame.name ?? "")); const start = holder ? holder.segment : statementStart(i); const end = holder ? segmentEnd(holder.segment) : text.indexOf("\n}", i) < 0 ? text.length : text.indexOf("\n}", i); const chain = text.slice(start, end); const callsAround = stack.filter((frame) => frame.open === "(").map((frame) => frame.name); // The call's own arguments, where it has any (`clickable(role = …) { }`; `clickable { }` has none). const after = i + token.length + (text.slice(i + token.length).match(/^\s*/)?.[0].length ?? 0); const own = text[after] === "(" ? text.slice(i, segmentEndOfCall(text, after)) : ""; const line = text.slice(0, i).split("\n").length; // A surface whose gesture routes by place to the parts drawn on it (`.readByParts()`): read through its `.part(…)`s. // `detectTapGestures { }` with nothing in it only swallows touches (a stand over the deck): no control. const swallows = token === "detectTapGestures" && /^detectTapGestures\s*(\(\s*\))?\s*\{\s*\}/.test(text.slice(i)); const verdict = swallows ? { ok: true, why: "swallows touches" } : /\.readByParts\(\)/.test(chain) && /\.part\(/.test(text) ? { ok: true, why: "read by its parts" } : judge(token, chain, own, callsAround); found.push({ file, line, token: token.replace(/\s+/g, ""), ...verdict }); } const c = text[i]; if (c === "(" || c === "{" || c === "[") stack.push({ open: c, name: c === "(" ? identBefore(i) : null, at: i, segment: i + 1 }); else if (c === ")" || c === "}" || c === "]") stack.pop(); else if (c === "," && stack.length) stack[stack.length - 1].segment = i + 1; } return found;}function segmentEndOfCall(text: string, open: number): number { let depth = 0; for (let j = open; j < text.length; j++) { if (text[j] === "(") depth++; else if (text[j] === ")") { depth--; if (depth === 0) return j + 1; } } return text.length;}function judge(token: string, chain: string, own: string, callsAround: (string | null)[]): { ok: boolean; why: string } { if (/clearAndSetSemantics/.test(chain)) return { ok: true, why: "hidden on purpose" }; if (/clickable/.test(token) && /enabled\s*=\s*false/.test(own)) return { ok: true, why: "swallows touches" }; const helper = /\.(control|named)\s*\(/.test(chain); const wordsAround = callsAround.some((name) => name !== null && NAMED_BY_WORDS.has(name)); // `mergeDescendants = true`: the element is named by the words it draws inside (a chip's text, a face's line). const named = helper || wordsAround || /contentDescription|onClickLabel|\bonClick\s*\(\s*label\s*=|mergeDescendants\s*=\s*true/.test(chain); const semanticClick = /semantics\s*(\([^)]*\))?\s*\{[^]*?\b(onClick|onLongClick)\b/.test(chain); const role = helper || semanticClick || (/clickable|selectable|toggleable/i.test(token) && (/\brole\s*=/.test(own) || /\brole\s*=\s*Role\./.test(chain))) || token.startsWith(".tapped"); if (!named) return { ok: false, why: "no name: give it .control(name), a contentDescription or an onClickLabel" }; if (!role) return { ok: false, why: "no role or click for TalkBack: .control/.named, clickable(role = …) or semantics { onClick }" }; return { ok: true, why: "" };}function kotlinFiles(folder: string): string[] { return readdirSync(folder).flatMap((name) => { const path = join(folder, name); if (name === "build" || name.startsWith(".")) return []; if (/^(android)?[tT]est([A-Z]\w*)?$/.test(name) && folder.endsWith(`${sep}src`)) return []; if (name === "walker") return []; if (statSync(path).isDirectory()) return kotlinFiles(path); return name.endsWith(".kt") ? [path] : []; });}describe("Android controls are read by TalkBack (apps/android)", () => { const files = existsSync(APP) ? kotlinFiles(APP) : []; const all = files.flatMap((path) => taps(readFileSync(path, "utf8"), relative(REPO_ROOT, path))); it("sees the apps' taps", () => { expect(files.length).toBeGreaterThan(0); expect(all.length).toBeGreaterThan(10); }); it("gives every tap a name and a role", () => { const hits = all.filter((tap) => !tap.ok).map((tap) => `${tap.file}:${tap.line} ${tap.token}: ${tap.why}`); expect(hits.filter((hit) => !ALLOWED.some((allowed) => hit.startsWith(allowed)))).toEqual([]); }); it("keeps its allow-list empty", () => { expect(ALLOWED).toEqual([]); });});describe("the tap reader", () => { const judged = (source: string) => taps(source).map((tap) => tap.ok); it("passes a named control and a worded clickable with a role", () => { expect(judged('Box(Modifier.size(44.dp).control(lines.line("words", "close")) { close() })')).toEqual([]); expect(judged('Text(words, modifier = Modifier.clickable(role = Role.Button) { go() })')).toEqual([true]); expect(judged('Box(Modifier.semantics { contentDescription = label }.tapped { go() })')).toEqual([true]); expect(judged('Box(Modifier.named(name) { open() }.pointerInput(card) { detectTapGestures { open() } })')).toEqual([true]); // A double tap with its action named for TalkBack (Words' whole size, files.whole). expect(judged('Box(Modifier.pointerInput(Unit) { detectTapGestures(onDoubleTap = { fit() }) }.semantics { onClick(label = words.whole) { fit(); true } })')).toEqual([true]); }); it("fails a tap with no name or no role", () => { expect(judged("Box(Modifier.size(44.dp).clickable { close() })")).toEqual([false]); expect(judged('Text(words, modifier = Modifier.clickable { go() })')).toEqual([false]); expect(judged("Box(Modifier.pointerInput(Unit) { detectTapGestures { go() } })")).toEqual([false]); expect(judged("Box(Modifier.pointerInput(Unit) { detectTapGestures { go() } }.semantics { onClick { go(); true } })")).toEqual([false]); expect(judged("Box(Modifier.size(44.dp).tapped { close() })")).toEqual([false]); expect(judged("Box(Modifier.pointerInput(s) { awaitEachGesture { awaitFirstDown(); waitForUpOrCancellation() } })")).toEqual([false]); }); it("reads past comments and strings", () => { expect(judged('// Modifier.clickable { }\nval s = "detectTapGestures"')).toEqual([]); expect(judged("Box(Modifier.named(n) { }.pointerInput(Unit) { detectTapGestures { return@detectTapGestures } })")).toEqual([true]); expect(judged('Box(Modifier.semantics { contentDescription = "${a}" }.tapped { go() })')).toEqual([true]); }); it("lets a chain hidden on purpose or a touch-swallower be", () => { expect(judged("Box(Modifier.clickable(enabled = false) {})")).toEqual([true]); expect(judged("Box(Modifier.pointerInput(Unit) { detectTapGestures { } })")).toEqual([true]); expect(judged("Box(Modifier.clearAndSetSemantics { }.pointerInput(Unit) { detectTapGestures { } })")).toEqual([true]); }); it("reads a surface routed by place through its parts, and only where it has parts", () => { const surface = "Box(Modifier.readByParts().pointerInput(s) { awaitEachGesture { waitForUpOrCancellation() } }) {\n"; expect(judged(surface + ' Box(Modifier.part(lines.line("faces", "hifi.next"), play.next))\n}')).toEqual([true]); expect(judged(surface + "}")).toEqual([false]); });});