The best way to control Claude Code, Codex and more from any computer or phone

main
mjs 102 lines 3.85 KB
Raw
1 #!/usr/bin/env node
2 // Finds elements in a frozen beat to target from a story: prints a selector, the box (in beat
3 // pixels) and the text of the smallest elements containing `text`, and of their clickable or
4 // labelled ancestors. Usage: find.mjs <beats/name.html> <text> [--all]
5 import * as NodeHttp from "node:http";
6 import * as NodeFS from "node:fs";
7 import * as NodeModule from "node:module";
8 import * as NodePath from "node:path";
9
10 import { findChrome } from "./chrome.mjs";
11
12 const [file, text] = process.argv.slice(2);
13 if (!file || !text) {
14 console.error("usage: find.mjs <beats/name.html> <text>");
15 process.exit(2);
16 }
17 const REPO = NodePath.resolve(import.meta.dirname, "../../../..");
18 const { chromium } = NodeModule.createRequire(NodePath.join(REPO, "scripts/package.json"))(
19 "playwright-core",
20 );
21 const root = NodePath.dirname(NodePath.resolve(file));
22 const server = NodeHttp.createServer((req, res) => {
23 NodeFS.readFile(
24 NodePath.join(root, decodeURIComponent(new URL(req.url, "http://x").pathname)),
25 (error, body) =>
26 error
27 ? res.writeHead(404).end()
28 : res
29 .writeHead(200, req.url.endsWith(".html") ? { "content-type": "text/html" } : {})
30 .end(body),
31 );
32 }).listen(0, "127.0.0.1");
33 await new Promise((resolve) => server.once("listening", resolve));
34 const browser = await chromium.launch({
35 executablePath: findChrome(chromium),
36 args: ["--no-sandbox"],
37 });
38 try {
39 const [width, height] = (
40 /name="kit-viewport" content="(\d+)x(\d+)"/.exec(NodeFS.readFileSync(file, "utf8")) ?? [
41 0, 1440, 720,
42 ]
43 )
44 .slice(1)
45 .map(Number);
46 const page = await browser.newPage({ viewport: { width, height } });
47 await page.goto(`http://127.0.0.1:${server.address().port}/${NodePath.basename(file)}`);
48 const found = await page.evaluate((needle) => {
49 // Short, stable selectors: data attributes and aria labels over generated classes.
50 const describe = (el) => {
51 const parts = [];
52 for (
53 let node = el;
54 node && node !== document.body && parts.length < 4;
55 node = node.parentElement
56 ) {
57 const data = [...node.attributes].find(
58 (a) => a.name.startsWith("data-") && !/^data-(base-ui|state|kit)/.test(a.name),
59 );
60 const label = node.getAttribute("aria-label");
61 const part =
62 node.tagName.toLowerCase() +
63 (node.id && !node.id.startsWith("base-ui") ? `#${CSS.escape(node.id)}` : "") +
64 (data ? `[${data.name}${data.value ? `="${data.value.slice(0, 40)}"` : ""}]` : "") +
65 (label ? `[aria-label="${label.slice(0, 50)}"]` : "");
66 parts.unshift(part);
67 if (data || label || node.id) {
68 const selector = parts.join(" > ");
69 try {
70 if (document.querySelectorAll(selector).length === 1) return selector;
71 } catch {}
72 }
73 }
74 return parts.join(" > ");
75 };
76 const matches = [...document.querySelectorAll("body *")].filter(
77 (el) =>
78 el.textContent.includes(needle) &&
79 ![...el.children].some((c) => c.textContent.includes(needle)),
80 );
81 return matches.slice(0, 6).map((el) => {
82 const chain = [];
83 for (let node = el; node && node !== document.body; node = node.parentElement) {
84 if (
85 node === el ||
86 node.matches("button, a, [role], [aria-label], li, section, aside, form, [data-slot]")
87 ) {
88 const r = node.getBoundingClientRect();
89 chain.push(
90 `${describe(node)} @ ${Math.round(r.left)},${Math.round(r.top)} ${Math.round(r.width)}×${Math.round(r.height)} "${node.textContent.trim().slice(0, 50)}"`,
91 );
92 }
93 if (chain.length >= 5) break;
94 }
95 return chain.join("\n ↑ ");
96 });
97 }, text);
98 console.log(found.length ? found.join("\n\n") : `no element contains "${text}"`);
99 } finally {
100 await browser.close();
101 server.close();
102 }