probe.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. (() => {
  2. // Visible-result probe. Evaluate this file's contents in the page once, then for each action:
  3. // The file is one expression: evaluate it as is, or as `() => <file>` / `return (<file>)` where a tool only takes a function.
  4. // await designProbe.watch() before the action (samples the idle page for about 1.2 s)
  5. // (real click / tap / typing, then wait for transitions)
  6. // await designProbe.changes() after; visible:false with no scroll or URL change means the result is not in view.
  7. // hints say what to do next: a missing result, a click that was not real pointer input, an invisible layer that took the pointer,
  8. // a missing transition. Act on them.
  9. // controlChangedOnly: only the pressed control changed: its painted points, or attributes, checked state or the computed style
  10. // of it, its descendants, its label's input and that input's siblings, ::before/::after included (a small switch the point grid
  11. // misses); focus, hover and :active styling alone does not count. Judge whether that is the result.
  12. // It compares what is painted at a grid of viewport points, text boxes in view whose text, attributes or styles were
  13. // mutated, and added nodes that land in the viewport. Points and nodes that change while idle (looping animation,
  14. // tickers), nodes that changed during two earlier idle samples (slow live data) and infinitely running animations are
  15. // ignored; so is the focus or hover styling the previous action left on its control.
  16. // animated: whether the change ran a CSS transition or animation, element.animate(), a view transition or a JS tween (an element's
  17. // style attribute rewritten 3+ times) outside the pressed control (inside it, not the previous control, when only the control changed); a transition on the control
  18. // whose property ends where it was already heading at pointerdown (its hover or focus styling) does not count. hints: what to do; a missing transition is hinted only for the control's own state
  19. // change and for overlays or regions that open, close, expand or collapse, not for content swaps (tabs, filters, data, items leaving a list).
  20. const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  21. const vw = () => document.documentElement.clientWidth;
  22. const inView = (el) => {
  23. const r = el.getBoundingClientRect(), s = getComputedStyle(el);
  24. return r.width > 0 && r.height > 0 && s.visibility !== "hidden" && +s.opacity > 0.1 && r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < vw();
  25. };
  26. const grid = () => {
  27. const w = vw(), h = innerHeight, pts = [];
  28. for (let i = 0; i < 12; i++) for (let j = 0; j < 16; j++) {
  29. const el = document.elementFromPoint(((j + 0.5) * w) / 16, ((i + 0.5) * h) / 12);
  30. if (!el) { pts.push(["", null]); continue; }
  31. const s = getComputedStyle(el), r = el.getBoundingClientRect();
  32. const own = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.data).join("").trim().slice(0, 60);
  33. const clip = [Math.max(0, r.left), Math.max(0, r.top), Math.min(w, r.right), Math.min(h, r.bottom)].map(Math.round);
  34. pts.push([/^(HTML|BODY)$/.test(el.tagName) ? `root|${own}` : [el.tagName, own, s.color, s.backgroundColor, s.opacity, s.transform, ...clip].join("|"), el]);
  35. }
  36. return pts;
  37. };
  38. // Text-owning boxes in view: element -> text, page position, color, opacity.
  39. const textBoxes = () => {
  40. const map = new Map(), walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, { acceptNode: (n) => (n.data.trim() && !n.parentElement.closest("script,style,noscript,template") ? 1 : 2) });
  41. for (let n; (n = walk.nextNode()) && map.size < 4000; ) {
  42. const el = n.parentElement;
  43. if (map.has(el) || !inView(el)) continue;
  44. const r = el.getBoundingClientRect(), s = getComputedStyle(el);
  45. map.set(el, [el.textContent.trim().slice(0, 80), Math.round(r.left), Math.round(r.top + scrollY), Math.round(r.width), Math.round(r.height), s.color, s.opacity, s.visibility].join("|"));
  46. }
  47. return map;
  48. };
  49. const looping = () => document.getAnimations().filter((a) => a.playState === "running" && a.effect?.getTiming().iterations === Infinity).map((a) => a.effect.target).filter(Boolean);
  50. // Pressed control's state, apart from its own box: checked, computed style and ::before/::after of it and its descendants, of the
  51. // input a label holds or names (for/id) and of that input's siblings (label > input:checked + span::after knobs).
  52. const PROPS = ["transform", "translate", "left", "right", "backgroundColor", "color", "opacity", "borderColor", "fill"];
  53. const state = (c) => {
  54. const inputs = [c, ...c.querySelectorAll("input"), c.control, ...(c.labels || [])].filter(Boolean), set = new Set();
  55. for (const e of inputs) for (const n of [e, ...(e.tagName === "INPUT" ? e.parentElement?.children || [] : [])]) for (const d of [n, ...n.querySelectorAll("*")]) set.add(d);
  56. return [...set].slice(0, 80).map((d) => [d.checked, ...["", "::before", "::after"].map((p) => PROPS.map((k) => getComputedStyle(d, p || null)[k]).join())].join()).join("|");
  57. };
  58. // Overlay or expanding region: positioned layer, dialog-like role, or an ancestor of it; aria-expanded / details open on the control.
  59. const overlay = (el) => { for (let e = el; e && e !== document.body; e = e.parentElement) { if (/fixed|absolute|sticky/.test(getComputedStyle(e).position) || e.matches('dialog,details,[role="dialog"],[role="menu"],[role="listbox"],[role="tooltip"],[popover]')) return true; } return false; };
  60. const openState = (c) => { const x = c.closest("[aria-expanded]"); const d = c.closest("details"); return x ? x.getAttribute("aria-expanded") : d ? String(d.open) : undefined; };
  61. // Collection item: el or its nearest ancestor with a sibling of the same tag and class.
  62. const sig = (e) => e.tagName + "." + e.className;
  63. const item = (el) => { for (let e = el; e && e.parentElement && e !== document.body; e = e.parentElement) if ([...e.parentElement.children].some((x) => x !== e && sig(x) === sig(e))) return [e, e.parentElement, sig(e)]; return null; };
  64. const under = (set, el) => { for (const m of set) if (m !== document.body && m !== document.documentElement && m.contains(el)) return true; return false; };
  65. // Motion started after watch(): CSS transitions and animations by event, WAAPI and view transitions by wrapping their entry points.
  66. const motion = (el, prop) => window.designProbe?._rec?.ready && el && window.designProbe._rec.anim.push([el, prop]);
  67. const camel = (p) => p.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
  68. // Values the pressed control's transitions head for at pointerdown (hover and focus included), so its own hover transition is not
  69. // taken for the action's motion: a control transition counts only when its property ends somewhere else.
  70. const goal = (d, p) => { const k = d.getAnimations().find((a) => a.transitionProperty === p)?.effect.getKeyframes().at(-1), cp = camel(p); return k && cp in k ? String(k[cp]) : getComputedStyle(d)[cp]; };
  71. const goals = (c) => {
  72. const m = new Map();
  73. for (const d of [c, ...c.querySelectorAll("*")].slice(0, 80)) {
  74. for (const p of getComputedStyle(d).transitionProperty.split(",").map((x) => x.trim())) if (p !== "all" && p !== "none") m.set(m.size, [d, p, goal(d, p)]);
  75. }
  76. return m;
  77. };
  78. if (!window.designProbe) {
  79. for (const ev of ["transitionrun", "animationstart"]) addEventListener(ev, (e) => motion(e.target, e.propertyName), true);
  80. const animate = Element.prototype.animate;
  81. Element.prototype.animate = function (...a) { motion(this); return animate.apply(this, a); };
  82. const vt = document.startViewTransition;
  83. if (vt) document.startViewTransition = function (...a) { motion(document.documentElement); return vt.apply(this, a); };
  84. }
  85. // An ancestor painted at opacity 0 that still takes the pointer: a closed overlay, scrim or drawer left in the way.
  86. const ghost = (el) => { for (let e = el; e && e.nodeType === 1 && e !== document.body; e = e.parentElement ?? e.getRootNode()?.host) if (+getComputedStyle(e).opacity < 0.05 && getComputedStyle(e).pointerEvents !== "none") return e.tagName.toLowerCase() + (e.id ? "#" + e.id : e.classList[0] ? "." + e.classList[0] : ""); return null; };
  87. window.designProbe = {
  88. async watch() {
  89. this._mo?.disconnect();
  90. const rec = (this._rec = { ready: false, added: [], mutated: new Set(), url: location.href, y: scrollY, target: null, anim: [], styled: new Map(), entered: [] });
  91. this._mo = new MutationObserver((ms) => {
  92. for (const m of ms) {
  93. const el = m.target.nodeType === 1 ? m.target : m.target.parentElement;
  94. if (el) rec.mutated.add(el);
  95. if (rec.ready && m.attributeName === "style") rec.styled.set(el, (rec.styled.get(el) || 0) + 1);
  96. for (const n of m.addedNodes) { rec.added.push(n.nodeType === 1 ? n : n.parentElement); if (rec.ready && n.nodeType === 1 && overlay(n)) rec.entered.push(n); }
  97. }
  98. });
  99. this._mo.observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true });
  100. rec.prev = [document.activeElement, [...document.querySelectorAll(":hover")].pop()].map((e) => e?.closest?.("button,a,input,select,textarea,label,summary")).filter(Boolean);
  101. const gs = [grid()], ts = [textBoxes()];
  102. for (let k = 0; k < 2; k++) { await sleep(600); gs.push(grid()); ts.push(textBoxes()); }
  103. const g2 = gs[2], t2 = ts[2];
  104. rec.unstable = new Set(g2.map((p, i) => gs.some((g) => g[i][0] !== p[0]) && i).filter((i) => i !== false));
  105. rec.idle = new Set([...rec.mutated, ...rec.added.filter(Boolean)]);
  106. for (const [el, k] of t2) if (ts.some((t) => t.get(el) !== k)) rec.idle.add(el);
  107. const seen = (this._seen ||= new Map());
  108. for (const el of rec.idle) seen.set(el, (seen.get(el) || 0) + 1);
  109. for (const [el, n] of seen) if (n >= 2) rec.idle.add(el);
  110. rec.added = []; rec.mutated = new Set(); rec.anim = []; rec.styled = new Map(); rec.entered = [];
  111. rec.view = g2; rec.viewEls = new Set(g2.map(([, el]) => el)); rec.items = new Map([...rec.viewEls].filter(Boolean).map((el) => [el, item(el)])); rec.text = t2; rec.ready = true;
  112. this._down && removeEventListener("pointerdown", this._down, true);
  113. // Shadow DOM retargets e.target to the host; take the real innermost target, or the whole component counts as the control.
  114. addEventListener("pointerdown", (this._down = (e) => { if (rec.target) return; const p = e.composedPath?.() || []; const tg = p[0]?.nodeType === 1 ? p[0] : e.target; rec.target = tg; rec.trusted = e.isTrusted; rec.ghost = ghost(tg); const c = tg.closest?.("button,a,input,select,textarea,label,summary,[role]") || tg; rec.state = state(c); rec.open = openState(c); rec.goals = goals(c); }), true);
  115. return "watching";
  116. },
  117. async changes() {
  118. const rec = this._rec;
  119. if (!rec?.ready) return { error: "call await designProbe.watch() before the action" };
  120. this._mo?.disconnect();
  121. const loops = looping(), ambient = (el) => !!el && (loops.some((t) => t === el || t.contains(el)) || rec.idle.has(el) || under(rec.idle, el));
  122. const t = rec.target?.closest?.("button,a,input,select,textarea,label,summary,[role]") || rec.target, atControl = (el) => !!el && [t, ...rec.prev].some((c) => c && c.contains(el));
  123. const now = grid();
  124. const diff = now.map((p, i) => !rec.unstable.has(i) && p[0] !== rec.view[i][0] && !ambient(p[1]) && !ambient(rec.view[i][1]) && [p[1], rec.view[i][1]]).filter(Boolean);
  125. const ctlState = !!t && t.nodeType === 1 && (rec.state !== state(t) || [...rec.mutated].some((el) => t.contains(el) && !ambient(el)));
  126. const changedPoints = diff.filter(([a, b]) => !atControl(a) && !atControl(b)).length;
  127. let controlOnly = diff.length - changedPoints, ctlChanged = ctlState;
  128. // Focus, hover and :active styling alone is not a result: compare with the control merely focused and hovered.
  129. if ((controlOnly || ctlChanged) && t?.nodeType === 1) {
  130. const f = document.activeElement;
  131. f?.blur?.();
  132. const again = grid();
  133. controlOnly = again.filter((p, i) => !rec.unstable.has(i) && p[0] !== rec.view[i][0] && !ambient(p[1]) && (atControl(p[1]) || atControl(rec.view[i][1]))).length;
  134. ctlChanged = rec.state !== state(t) || [...rec.mutated].some((el) => t.contains(el) && !ambient(el));
  135. f?.focus?.({ preventScroll: true });
  136. }
  137. const mutated = (el) => rec.mutated.has(el) || under(rec.mutated, el);
  138. const textChanged = [...textBoxes()].filter(([el, k]) => rec.text.get(el) !== k && mutated(el) && !ambient(el) && !atControl(el)).map(([el]) => el);
  139. const added = [...new Set(rec.added)].filter((el) => el && el.isConnected && !atControl(el) && !ambient(el) && inView(el));
  140. const name = (el) => `${el.tagName.toLowerCase()} "${(el.textContent || "").trim().slice(0, 30)}"`;
  141. const visible = changedPoints > 0 || textChanged.length > 0 || added.length > 0;
  142. const controlChangedOnly = (controlOnly > 0 || ctlChanged) && !visible, scrolled = Math.round(scrollY - rec.y), urlChanged = location.href !== rec.url;
  143. const same = (el, p) => { if (!p || !rec.goals) return false; for (const [d, q, v] of rec.goals.values()) if (d === el && q === p) return goal(el, p) === v; return false; };
  144. const moved = [...rec.anim.filter(([el, p]) => !same(el, p)).map(([el]) => el), ...[...rec.styled].filter(([, n]) => n >= 3).map(([el]) => el)].filter((el) => el.isConnected !== false && !loops.includes(el));
  145. const animated = visible || controlChangedOnly ? moved.some((el) => (controlChangedOnly ? !!t?.contains?.(el) : el === document.documentElement || !atControl(el))) : null;
  146. const hints = [];
  147. if (!rec.target) hints.push("no pointer input reached the page: if this was a click, use real pointer input at the control's centre (e.g. page.mouse.click); element.click() and dispatched events skip what a user's click goes through");
  148. else if (rec.trusted === false) hints.push("the pointer event was synthetic: click with real pointer input at the control's centre (e.g. page.mouse.click)");
  149. if (rec.ghost) hints.push(`the pointer landed on an invisible layer (${rec.ghost}, opacity 0): a closed overlay, scrim or drawer uses display:none or visibility:hidden plus pointer-events:none, since opacity:0 alone still takes clicks`);
  150. if (!visible && !controlChangedOnly && !scrolled && !urlChanged) hints.push("no result in view: bring it into view or give feedback at the control");
  151. if (controlChangedOnly) hints.push("only the control changed: fine if that is the result (toggle, like, tab), else add feedback");
  152. // A missing transition is hinted only for overlays and regions that enter, leave, expand or collapse; tab, filter and data swaps are not hinted.
  153. const real = (el) => el && !/^(HTML|BODY)$/.test(el.tagName) && !atControl(el) && !ambient(el);
  154. const appeared = now.map(([, el]) => el).filter((el) => real(el) && !rec.viewEls.has(el));
  155. const gone = [...rec.viewEls].filter((el) => real(el) && !(el.isConnected && inView(el)));
  156. const layer = [...new Set(rec.entered)].some((el) => el.isConnected && inView(el)) || [...appeared, ...gone].some(overlay);
  157. const toggled = !!t && t.nodeType === 1 && rec.open !== undefined && rec.open !== openState(t);
  158. // Items leaving a collection whose siblings stay (a filter, a shrinking list) are a content swap.
  159. const removed = gone.length > 0 && !appeared.length && !toggled && gone.every((el) => { const it = rec.items.get(el); return it && !(it[0].isConnected && inView(it[0])) && [...it[1].children].some((x) => x !== it[0] && sig(x) === it[2] && inView(x)); });
  160. const swap = removed || !!t?.closest?.('[role="tab"],[role="tablist"],[role="radio"],[role="option"],select') || (appeared.length > 0 && gone.length > 0 && !layer);
  161. const entered = layer || toggled || appeared.length > 0 !== gone.length > 0;
  162. if (animated === false && controlChangedOnly) hints.push("the control changed state with no transition: a state change in place usually carries motion (references/motion.md)");
  163. else if (animated === false && entered && !swap) hints.push("opened, closed, expanded or collapsed with no transition: something entering or leaving usually carries motion (references/motion.md); if it is instant on purpose, have a reason");
  164. return {
  165. visible, changedPoints, textChanged: textChanged.slice(0, 5).map(name), addedInView: added.slice(0, 5).map(name),
  166. controlChangedOnly, animated, scrolled, urlChanged, hints,
  167. };
  168. },
  169. };
  170. return "designProbe ready";
  171. })()