Cotton code
65 lines · 1.9 KB · TypeScriptRaw
/** * The screen as Argent's `describe` answers it, read into elements: what each * is, what it says, where it is. The phone walks (board-walk.ts, * release-walk.ts, update-walk.ts) tap at the centre of a frame read here and * hold no coordinate of their own. */export interface Frame {  x: number;  y: number;  width: number;  height: number;}/** One line of `describe`: what an element is, what it says, where it is. */export interface Element {  role: string;  label: string;  value: string;  id: string;  frame: Frame;}/** * The elements of a `describe` answer, in the order it lists them. A label may * itself hold quotes (`stand-in: heard "walk one"`), so the label is whatever * lies between the first quote after the role and the last quote before * ` value=`, ` id=` or the frame. The `ROOT` line is the screen itself and is * not an element. */export function parseScreen(description: string): Element[] {  const elements: Element[] = [];  for (const raw of description.split("\n")) {    const frame = /\(([\d.]+), ([\d.]+), ([\d.]+), ([\d.]+)\)\s*$/.exec(raw);    const role = /^\s*(AX\w+)/.exec(raw);    if (!frame || !role) continue;    let rest = raw.slice(role[0].length, frame.index).trim();    let id = "";    const idAt = / ?id="([^"]*)"$/.exec(rest);    if (idAt) {      id = idAt[1] ?? "";      rest = rest.slice(0, idAt.index).trim();    }    let value = "";    const valueAt = / ?value="(.*)"$/.exec(rest);    if (valueAt) {      value = valueAt[1] ?? "";      rest = rest.slice(0, valueAt.index).trim();    }    const label = rest.startsWith('"') && rest.endsWith('"') && rest.length >= 2 ? rest.slice(1, -1) : "";    elements.push({      role: role[1] ?? "",      label,      value,      id,      frame: {        x: Number(frame[1]),        y: Number(frame[2]),        width: Number(frame[3]),        height: Number(frame[4]),      },    });  }  return elements;}