File size: 13,299 Bytes
1e6582e
 
 
 
 
 
 
 
10d623c
1e6582e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10d623c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e6582e
10d623c
1e6582e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// Widened control collector. Returns raw facts per control; classes (icon / text control / input) are derived later.
// Differences from e1/collect.js, each tied to a control the old script missed:
//  - transparent native inputs that still receive the click are kept (Wikipedia's menu, language and radio inputs)
//  - a visible <label> stands in for a checkbox/radio/file input that is hidden some other way
//  - minimum size 6x8 px instead of 12x12 (Hacker News vote arrows are 10x10)
//  - controls cut by the screen edge are kept when at least half is visible, clipped to the viewport
//  - open shadow roots and same-origin iframes are walked; pointer-cursor elements are added as weak candidates
//  - a link that wraps over several lines gives one box per line
// Also returns `statics`: blocks of plain text and standalone pictures, which are not controls.
() => {
  const W = innerWidth, H = innerHeight;
  const NATIVE = 'a[href],button,input:not([type=hidden]),select,textarea,summary';
  const ROLES = ['button', 'link', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'checkbox', 'radio', 'switch', 'combobox',
    'textbox', 'searchbox', 'option', 'slider', 'spinbutton', 'treeitem'];
  const ROLE_SEL = ROLES.map(r => `[role=${r}]`).join(',');
  const WEAK = '[onclick],[tabindex]:not([tabindex="-1"]),[contenteditable=""],[contenteditable=true]';
  const out = [], frames = [], seen = new Set();

  function* walk(root, off) {
    for (const el of root.querySelectorAll('*')) {
      yield [el, off];
      if (el.shadowRoot) yield* walk(el.shadowRoot, off);
      if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
        const r = el.getBoundingClientRect();
        let doc = null;
        try { doc = el.contentDocument; } catch (e) {}
        if (r.width > 20 && r.height > 20 && r.right > 0 && r.bottom > 0 && r.left < W && r.top < H)
          frames.push({ kind: doc ? 'same-origin frame' : 'cross-origin frame', rect: [r.left + off[0], r.top + off[1], r.right + off[0], r.bottom + off[1]].map(Math.round) });
        if (doc && doc.documentElement) yield* walk(doc, [off[0] + r.left, off[1] + r.top]);
      }
      if (el.tagName === 'CANVAS') {
        const r = el.getBoundingClientRect();
        if (r.width > 100 && r.height > 100 && r.right > 0 && r.bottom > 0 && r.left < W && r.top < H)
          frames.push({ kind: 'canvas', rect: [r.left + off[0], r.top + off[1], r.right + off[0], r.bottom + off[1]].map(Math.round) });
      }
    }
  }
  const style = el => el.ownerDocument.defaultView.getComputedStyle(el);
  // contains() and parent that cross shadow boundaries
  const up = el => el.parentElement || (el.getRootNode() instanceof ShadowRoot ? el.getRootNode().host : null);
  function inside(inner, outer) { for (let n = inner; n; n = up(n)) if (n === outer) return true; return false; }
  // Is the point (in the element's own document coordinates) on this element or something inside it?
  // An ancestor does not count (that let invisible links under other content through), except a <label> around its input.
  function hit(el, x, y) {
    const root = el.getRootNode();
    let top = (root.elementFromPoint ? root : el.ownerDocument).elementFromPoint(x, y);
    while (top && top.shadowRoot && top.shadowRoot.elementFromPoint) {            // descend into nested shadow roots
      const deeper = top.shadowRoot.elementFromPoint(x, y);
      if (!deeper || deeper === top) break;
      top = deeper;
    }
    if (!top) return false;
    if (top === el || inside(top, el)) return true;
    return top.tagName === 'LABEL' && top.control === el;
  }
  function consider(el, off, why, rect) {
    const cs = style(el);
    if (cs.visibility === 'hidden' || cs.display === 'none' || cs.pointerEvents === 'none') return false;
    if (el.closest('[inert]') || (el.checkVisibility && !el.checkVisibility({ contentVisibilityAuto: true }))) return false;
    const r = rect || box(el);
    const x0 = Math.max(r.left + off[0], 0), y0 = Math.max(r.top + off[1], 0), x1 = Math.min(r.right + off[0], W), y1 = Math.min(r.bottom + off[1], H);
    const w = x1 - x0, h = y1 - y0;
    if (w <= 0 || h <= 0 || Math.min(w, h) < 6 || Math.max(w, h) < 8) return false;
    if (w * h < 0.5 * r.width * r.height) return false;                       // less than half of it is on screen
    const transparent = +cs.opacity < 0.1;
    const native = el.matches(NATIVE);
    if (transparent && !(native && w <= 400 && h <= 120)) return false;       // invisible overlays other than small native controls
    if (!hit(el, (x0 + x1) / 2 - off[0], (y0 + y1) / 2 - off[1])) return false;
    const key = [x0, y0, x1, y1].map(v => Math.round(v / 2)).join(',');
    if (seen.has(key)) return true;                                           // same box already recorded (label + input)
    seen.add(key);
    const img = el.querySelector && el.querySelector('img[alt]'), svgTitle = el.querySelector && el.querySelector('svg title');
    out.push({
      i: out.length, why, tag: el.tagName.toLowerCase(), type: el.getAttribute('type') || '', role: el.getAttribute('role') || '',
      text: (el.innerText || el.value || '').trim().replace(/\s+/g, ' ').slice(0, 80),
      aria: (el.getAttribute('aria-label') || el.getAttribute('title') || (img && img.alt) || (svgTitle && svgTitle.textContent) || '').trim().slice(0, 80),
      placeholder: el.getAttribute('placeholder') || '', disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true',
      transparent, cursor: cs.cursor, rect: [x0, y0, x1, y1].map(Math.round), _el: el,
    });
    return true;
  }

  // The box of a control. An inline link around an image reports only its text line, so take in the media it wraps.
  function box(el) {
    let r = el.getBoundingClientRect();
    if (el.tagName === 'A' && style(el).display.startsWith('inline')) {
      for (const m of el.querySelectorAll('img,svg,picture,video')) {
        const q = m.getBoundingClientRect();
        if (q.width < 4 || q.height < 4) continue;
        r = new DOMRect(Math.min(r.left, q.left), Math.min(r.top, q.top), Math.max(r.right, q.right) - Math.min(r.left, q.left), Math.max(r.bottom, q.bottom) - Math.min(r.top, q.top));
      }
    }
    return r;
  }
  // One box per line for a link that wraps; fragments on the same line are merged.
  function lines(el) {
    if (el.tagName !== 'A' || style(el).display !== 'inline' || el.querySelector('img,svg,picture,video')) return [];
    const rows = [];
    for (const r of el.getClientRects()) {
      if (r.width < 1 || r.height < 1) continue;
      const row = rows.find(q => Math.abs((q.top + q.bottom) / 2 - (r.top + r.bottom) / 2) < r.height / 2);
      if (row) { row.left = Math.min(row.left, r.left); row.right = Math.max(row.right, r.right); row.top = Math.min(row.top, r.top); row.bottom = Math.max(row.bottom, r.bottom); }
      else rows.push({ left: r.left, right: r.right, top: r.top, bottom: r.bottom });
    }
    return rows.length > 1 ? rows.map(q => new DOMRect(q.left, q.top, q.right - q.left, q.bottom - q.top)) : [];
  }
  const all = [...walk(document, [0, 0])];
  // 1. native controls and ARIA roles. Wrapped inline links get one box per line.
  for (const [el, off] of all) {
    if (!(el.matches(NATIVE) || el.matches(ROLE_SEL))) continue;
    const rs = lines(el);
    if (rs.length > 1) rs.forEach(r => consider(el, off, 'native', r));
    else consider(el, off, el.matches(NATIVE) ? 'native' : 'role');
  }
  // 2. a visible label standing in for a checkbox / radio / file input that was not recorded itself
  const recorded = () => new Set(out.map(o => o._el));
  let rec = recorded();
  for (const [el, off] of all) {
    if (el.tagName !== 'LABEL' || !el.control || rec.has(el.control)) continue;
    if (['checkbox', 'radio', 'file'].includes(el.control.type)) consider(el, off, 'label-for-hidden-input');
  }
  // 3. weak candidates: click handlers, focusable elements, and the outermost element of each pointer-cursor region
  rec = recorded();
  const weak = [];
  for (const [el, off] of all) {
    if (rec.has(el) || el.matches(NATIVE) || el.matches(ROLE_SEL)) continue;
    if (el.matches(WEAK)) { weak.push([el, off, 'handler-or-focusable']); continue; }
    const cs = style(el);
    const parent = up(el);
    if (cs.cursor === 'pointer' && !(parent && style(parent).cursor === 'pointer')) weak.push([el, off, 'pointer-cursor']);
  }
  for (const [el, off, why] of weak) {
    const r = el.getBoundingClientRect();
    if (r.width > 600 || r.height > 200) continue;                            // whole cards, rows and panels
    if ([...rec].some(o => inside(o, el) || inside(el, o))) continue;         // wraps, or sits inside, a recorded control
    if (el.tagName === 'LABEL' && el.control && rec.has(el.control)) continue;
    consider(el, off, why);
  }
  // 4. things that are not controls: blocks of plain text and standalone pictures. Returned separately as `statics`.
  const ctrl = new Set(out.map(o => o._el)), statics = [];
  // inside a recorded control, or inside something that is a control by tag or role but was not recorded (then it stays unlabelled)
  const inControl = el => { for (let n = el; n; n = up(n)) if (ctrl.has(n) || n.matches(NATIVE) || n.matches(ROLE_SEL)) return true; return false; };
  const shownCache = new Map();
  function shown(el) {                                   // visible, and no ancestor is hidden or transparent
    if (shownCache.has(el)) return shownCache.get(el);
    const cs = style(el), p = up(el);
    const ok = cs.display !== 'none' && cs.visibility !== 'hidden' && +cs.opacity >= 0.1 && (!p || shown(p));
    shownCache.set(el, ok);
    return ok;
  }
  function topAt(el, x, y) {                             // the element drawn on top at a point, looking into shadow roots
    const root = el.getRootNode();
    let top = (root.elementFromPoint ? root : el.ownerDocument).elementFromPoint(x, y);
    while (top && top.shadowRoot && top.shadowRoot.elementFromPoint) {
      const deeper = top.shadowRoot.elementFromPoint(x, y);
      if (!deeper || deeper === top) break;
      top = deeper;
    }
    return top;
  }
  const clip = (r, off) => [Math.max(r.left + off[0], 0), Math.max(r.top + off[1], 0), Math.min(r.right + off[0], W), Math.min(r.bottom + off[1], H)];
  // 4a. text blocks: the text an element holds directly, grouped under its nearest block-level ancestor
  const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'OPTION', 'TITLE', 'TEMPLATE']);
  const blocks = new Map();
  for (const [el, off] of all) {
    if (SKIP.has(el.tagName) || el.namespaceURI !== 'http://www.w3.org/1999/xhtml') continue;
    let checked = false, ok = false;
    for (const n of el.childNodes) {
      if (n.nodeType !== 3 || n.nodeValue.trim().length < 2) continue;
      if (!checked) { checked = true; ok = !inControl(el) && shown(el) && !(el.checkVisibility && !el.checkVisibility({ contentVisibilityAuto: true })); }
      if (!ok) break;
      const range = el.ownerDocument.createRange();
      range.selectNodeContents(n);
      const rs = [...range.getClientRects()].filter(r => r.width >= 1 && r.height >= 1 && r.bottom > 0 && r.top < H - off[1] && r.right > 0 && r.left < W - off[0]);
      if (!rs.length) continue;
      let box = el;
      while (up(box) && ['inline', 'contents'].includes(style(box).display)) box = up(box);
      const onTop = r => { const t = topAt(el, (r.left + r.right) / 2, (r.top + r.bottom) / 2); return t && inside(t, box); };
      if (!onTop(rs[0]) || !onTop(rs[rs.length - 1])) continue;   // covered by something else, or clipped away
      const b = blocks.get(box) || { x0: 1e9, y0: 1e9, x1: -1e9, y1: -1e9, text: '', tag: box.tagName.toLowerCase() };
      for (const r of rs) { const q = clip(r, off); b.x0 = Math.min(b.x0, q[0]); b.y0 = Math.min(b.y0, q[1]); b.x1 = Math.max(b.x1, q[2]); b.y1 = Math.max(b.y1, q[3]); }
      if (b.text.length < 80) b.text = (b.text + ' ' + n.nodeValue.trim().replace(/\s+/g, ' ')).trim().slice(0, 80);
      blocks.set(box, b);
    }
  }
  for (const b of blocks.values())
    if (b.x1 - b.x0 >= 8 && b.y1 - b.y0 >= 8) statics.push({ kind: 'text', tag: b.tag, text: b.text, rect: [b.x0, b.y0, b.x1, b.y1].map(Math.round) });
  // 4b. pictures that are not part of a control
  const seenPic = new Set();
  for (const [el, off] of all) {
    const t = el.tagName;
    if (!(t === 'IMG' || t === 'VIDEO' || (t.toLowerCase() === 'svg' && !el.ownerSVGElement))) continue;
    if (inControl(el) || !shown(el)) continue;
    const r = el.getBoundingClientRect(), q = clip(r, off), w = q[2] - q[0], h = q[3] - q[1];
    if (w < 12 || h < 12 || w * h < 0.5 * r.width * r.height) continue;
    const top = topAt(el, (q[0] + q[2]) / 2 - off[0], (q[1] + q[3]) / 2 - off[1]);
    if (!top || !(top === el || inside(top, el))) continue;
    const key = q.map(v => Math.round(v / 2)).join(',');
    if (seenPic.has(key)) continue;
    seenPic.add(key);
    statics.push({ kind: 'image', tag: t.toLowerCase(), text: (el.getAttribute('alt') || el.getAttribute('aria-label') || '').slice(0, 80), rect: q.map(Math.round) });
  }
  for (const o of out) delete o._el;
  return { url: location.href, title: document.title, W, H, dpr: devicePixelRatio, n: out.length, els: out, statics, frames };
}