@botiverse/porthole 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,14 +7,16 @@
7
7
  * The host drives it (`porthole/annotate.start|stop|show|focus|clear`) and it reports
8
8
  * (`porthole/annotate.selected|unselected|cancelled|anchored|activated`):
9
9
  * - picking an element: the element under the pointer (or finger) is outlined with its name; a
10
- * click or tap picks it, and the content's own handlers never see that click; Escape cancels;
10
+ * click or tap picks it, and the content's own handlers never see that click (unless the content
11
+ * patched the DOM's built-ins, P105); Escape cancels;
11
12
  * - selecting text: each selection that settles is reported, with where it is, and its clearing;
12
13
  * - marks: each anchor is found in the content as it is now (its CSS selector, its text where it
13
14
  * was, its text anywhere, its words with any spacing) and drawn over it, in a layer of the
14
15
  * shell's own (a closed shadow root), again whenever the content changes; what can't be found
15
16
  * is reported `orphaned`;
16
- * - markers (P104): a mark with a count gets a small bubble with the number at its anchor's end;
17
- * a click on it is reported (`activated`), and the content's own handlers never see it;
17
+ * - markers (P104): a mark with a count gets a small bubble with the number beside its anchor's
18
+ * last line (P105: in the line's gutter); a click on it is reported (`activated`), and the
19
+ * content's own handlers never see it;
18
20
  * - following: while a mark has a marker, once a scroll, a resize or a change of the content
19
21
  * settles, the marks that moved since the host was last told are reported, at most once a
20
22
  * second, so the host's own UI beside a mark can follow.
@@ -50,9 +52,12 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
50
52
  const rangeRects = Range.prototype.getClientRects;
51
53
  const attachShadow = Element.prototype.attachShadow;
52
54
  const getAttribute = Element.prototype.getAttribute;
55
+ const listenOn = EventTarget.prototype.addEventListener;
53
56
  const post = window.parent.postMessage.bind(window.parent);
57
+ // Read once: content can replace window.parent (it is [Replaceable]), never what was read.
58
+ const framed = window.parent !== window;
54
59
  const tell = (method, params) => {
55
- if (window.parent !== window) {
60
+ if (framed) {
56
61
  post({ jsonrpc: "2.0", method, params }, "*");
57
62
  }
58
63
  };
@@ -360,7 +365,7 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
360
365
  // An element's mark with a marker is quieter (a thin line): the marker says what it is.
361
366
  // A marker is a small bubble with a number, drawn in its own colors and font (only what the
362
367
  // layer inherits from the page could reach it, so each of those is set here).
363
- const STYLE = ".mark{position:absolute;border-radius:2px;background:rgba(250,204,21,.18);box-shadow:inset 0 -2px 0 rgba(234,179,8,.95)}.mark.element{background:rgba(250,204,21,.07);box-shadow:none;outline:2px solid rgba(234,179,8,.9);outline-offset:1px}.mark.active{background:rgba(250,204,21,.26);box-shadow:inset 0 -3px 0 rgb(234,179,8),0 0 0 2px rgba(234,179,8,.45)}.mark.element.active{background:rgba(250,204,21,.12);box-shadow:none;outline-width:3px}.mark.element.quiet{background:rgba(250,204,21,.05);outline:1px solid rgba(234,179,8,.6);outline-offset:2px}.mark.element.quiet.active{background:rgba(250,204,21,.1);outline:2px solid rgba(234,179,8,.9)}.marker{position:absolute;box-sizing:border-box;height:18px;min-width:18px;display:flex;align-items:center;justify-content:center;gap:3px;margin:0;padding:0 5px;border:1px solid rgba(161,98,7,.6);border-radius:9px 9px 9px 2px;background:#fde68a;color:#422006;box-shadow:0 1px 2px rgba(0,0,0,.3);font:600 11px/16px system-ui,-apple-system,Segoe UI,Roboto,sans-serif;font-style:normal;letter-spacing:0;word-spacing:0;text-transform:none;text-indent:0;text-shadow:none;direction:ltr;writing-mode:horizontal-tb;white-space:nowrap;user-select:none;-webkit-user-select:none;cursor:pointer;pointer-events:auto}.marker:hover{background:#fcd34d}.marker.active{background:#facc15;box-shadow:0 0 0 2px rgba(234,179,8,.55),0 1px 2px rgba(0,0,0,.3)}.marker.inert{pointer-events:none}.marker svg{display:block;width:11px;height:11px;flex:none}.mark.flash{animation:flash 1.8s ease-out}@keyframes flash{from{box-shadow:inset 0 -3px 0 rgb(234,179,8),0 0 0 6px rgba(250,204,21,.6)}}.hover{position:absolute;outline:2px solid #2563eb;outline-offset:1px;background:rgba(37,99,235,.12)}.tag{position:absolute;max-width:70vw;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:12px/18px ui-monospace,SFMono-Regular,Menlo,monospace;padding:0 6px;border-radius:4px;background:#1e293b;color:#fff}";
368
+ const STYLE = ".mark{position:absolute;border-radius:2px;background:rgba(250,204,21,.18);box-shadow:inset 0 -2px 0 rgba(234,179,8,.95)}.mark.element{background:rgba(250,204,21,.07);box-shadow:none;outline:2px solid rgba(234,179,8,.9);outline-offset:1px}.mark.active{background:rgba(250,204,21,.26);box-shadow:inset 0 -3px 0 rgb(234,179,8),0 0 0 2px rgba(234,179,8,.45)}.mark.element.active{background:rgba(250,204,21,.12);box-shadow:none;outline-width:3px}.mark.element.quiet{background:rgba(250,204,21,.05);outline:1px solid rgba(234,179,8,.6);outline-offset:2px}.mark.element.quiet.active{background:rgba(250,204,21,.1);outline:2px solid rgba(234,179,8,.9)}.marker{position:absolute;box-sizing:border-box;height:18px;min-width:18px;display:flex;align-items:center;justify-content:center;gap:3px;margin:0;padding:0 5px;border:1px solid rgba(161,98,7,.6);border-radius:9px 9px 9px 2px;background:#fde68a;color:#422006;box-shadow:0 1px 2px rgba(0,0,0,.3);font:600 11px/16px system-ui,-apple-system,Segoe UI,Roboto,sans-serif;font-style:normal;letter-spacing:0;word-spacing:0;text-transform:none;text-indent:0;text-shadow:none;direction:ltr;writing-mode:horizontal-tb;white-space:nowrap;user-select:none;-webkit-user-select:none;cursor:pointer;pointer-events:auto}.marker:hover{background:#fcd34d}.marker.active{background:#facc15;box-shadow:0 0 0 2px rgba(234,179,8,.55),0 1px 2px rgba(0,0,0,.3)}.marker.compact{padding:0 4px}.marker.inert{pointer-events:none}.marker svg{display:block;width:11px;height:11px;flex:none}.mark.flash{animation:flash 1.8s ease-out}@keyframes flash{from{box-shadow:inset 0 -3px 0 rgb(234,179,8),0 0 0 6px rgba(250,204,21,.6)}}.hover{position:absolute;outline:2px solid #2563eb;outline-offset:1px;background:rgba(37,99,235,.12)}.tag{position:absolute;max-width:70vw;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:12px/18px ui-monospace,SFMono-Regular,Menlo,monospace;padding:0 6px;border-radius:4px;background:#1e293b;color:#fff}";
364
369
  // Inline and important: the content's own style sheets can't hide, shrink or move it by
365
370
  // accident. Set again at each draw, since its scripts can rewrite it (narrowing only: the
366
371
  // content can still cover the layer, or move it with its ancestors, P104).
@@ -390,55 +395,275 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
390
395
  const markerNodes = new Map();
391
396
  const MARKER_HEIGHT = 18;
392
397
  const SVG = "http://www.w3.org/2000/svg";
393
- const markerOf = (mark, rects, overlaps) => {
394
- let at = null;
395
- for (let i = rects.length - 1; i >= 0 && at === null; i -= 1) {
396
- if (rects[i].width !== 0 || rects[i].height !== 0) {
397
- at = rects[i];
398
+ const labelOf = (count) => (count === 0 ? "" : count > 99 ? "99+" : String(count));
399
+ // Its size, near enough to place it: the padding and the glyph, then the number.
400
+ const markerWidth = (label) => Math.max(MARKER_HEIGHT, 23 + (label === "" ? 0 : 3 + label.length * 7));
401
+ // Compact (P105): the number alone, or the glyph alone for none, with less padding.
402
+ const compactWidth = (label) => (label === "" ? 21 : Math.max(MARKER_HEIGHT, 10 + label.length * 7));
403
+ // A rect's last line with words on it: its last box with a width, else any with a size.
404
+ const lastBox = (rects) => {
405
+ let any = null;
406
+ for (let i = rects.length - 1; i >= 0; i -= 1) {
407
+ if (rects[i].width > 0) {
408
+ return rects[i];
398
409
  }
410
+ if (any === null && rects[i].height > 0) {
411
+ any = rects[i];
412
+ }
413
+ }
414
+ return any;
415
+ };
416
+ // Where a text anchor's marker goes (P105, #36). At its words' end, raised (0.9), it lay over
417
+ // the first letters of the next word, or between two lines. Now it sits beside the anchor's
418
+ // last line, centred on it, clear of that line's words, and over nothing of the content's but
419
+ // the background of a box holding the anchor, with nothing else between it and the words:
420
+ // in the line's gutter, just past the right edge of the anchor's block (its content box);
421
+ // where the frame is too narrow for that (text that runs to the frame's edges), at the
422
+ // frame's right edge; where something else is beside the block (a table's next cell, a card
423
+ // in a row of them), just past the line's last word. Markers on one line of one block go
424
+ // together, in the order their words end. Where the bubble with its glyph fits in none of
425
+ // these, the number alone does (compact); where that fits in none either (a full line on a
426
+ // narrow screen), it goes as far right as it can, over the line's end.
427
+ const computedOf = window.getComputedStyle;
428
+ const elementsAt = Document.prototype.elementsFromPoint;
429
+ const containsOf = Node.prototype.contains;
430
+ const INLINE = /^(inline|contents|none|ruby|table-(row|column|header|footer))/;
431
+ const blockOf = (range) => {
432
+ let node = range.endContainer;
433
+ if (node.nodeType !== 1) {
434
+ node = node.parentElement;
435
+ }
436
+ while (node !== null && node !== document.body && node !== document.documentElement && INLINE.test(computedOf.call(window, node).display)) {
437
+ node = node.parentElement;
438
+ }
439
+ return node === null || node === document.documentElement ? document.body : node;
440
+ };
441
+ // The right edge of its content box: past it is the block's padding, then what is beside it.
442
+ const contentRight = (block) => {
443
+ const style = computedOf.call(window, block);
444
+ return elementRect.call(block).right - (parseFloat(style.borderRightWidth) || 0) - (parseFloat(style.paddingRight) || 0);
445
+ };
446
+ // How far the words reach on the anchor's last line (at), in its block: at least its own.
447
+ // Read forward from the anchor's end, 64 characters at a time, only until the text leaves
448
+ // that line (P105: the whole rest of a long block, for each marker, cost 100 ms and more).
449
+ const lineEnd = (range, block, at) => {
450
+ let end = at.right;
451
+ let node = range.endContainer;
452
+ if (node.nodeType !== 3) {
453
+ return end;
454
+ }
455
+ const middle = at.top + at.height / 2;
456
+ const walker = createTreeWalker.call(document, block, NodeFilter.SHOW_TEXT);
457
+ walker.currentNode = node;
458
+ const piece = createRange.call(document);
459
+ let from = range.endOffset;
460
+ for (let pieces = 0; node !== null && pieces < 64; pieces += 1) {
461
+ const length = node.nodeValue.length;
462
+ if (from >= length) {
463
+ node = walker.nextNode();
464
+ from = 0;
465
+ continue;
466
+ }
467
+ const to = Math.min(length, from + 64);
468
+ try {
469
+ piece.setStart(node, from);
470
+ piece.setEnd(node, to);
471
+ } catch (_) {
472
+ return end;
473
+ }
474
+ for (const rect of Array.from(rangeRects.call(piece))) {
475
+ if (rect.top > middle) {
476
+ return end;
477
+ }
478
+ if (rect.width > 0 && rect.bottom >= middle && rect.right > end) {
479
+ end = rect.right;
480
+ }
481
+ }
482
+ from = to;
483
+ }
484
+ return end;
485
+ };
486
+ // Nothing of the content's at a point but a box that holds the block (its background); a
487
+ // point out of view hides nothing.
488
+ const clearAt = (x, y, block) => {
489
+ if (x < 0 || y < 0 || x >= document.documentElement.clientWidth || y >= document.documentElement.clientHeight) {
490
+ return true;
399
491
  }
400
- if (at === null) {
492
+ const hits = elementsAt.call(document, x, y);
493
+ const first = hits[0] === layer ? hits[1] : hits[0];
494
+ return first === undefined || containsOf.call(first, block);
495
+ };
496
+ // Its box: two opposite corners and its middle (the line's middle, up to it, is the path's).
497
+ const clearOver = (left, top, width, block) =>
498
+ clearAt(left + width / 2, top + MARKER_HEIGHT / 2, block) && clearAt(left + 1, top + 1, block) && clearAt(left + width - 1, top + MARKER_HEIGHT - 1, block);
499
+ const GAP = 6;
500
+ const NEAR = 3;
501
+ const BETWEEN = 3;
502
+ const EDGE = 2;
503
+ const STEP = 8;
504
+ const overlapping = (placed, left, top, width) => placed.filter((other) => Math.abs(other.top - top) < MARKER_HEIGHT && left < other.left + other.width + BETWEEN && other.left < left + width + BETWEEN)[0];
505
+ // The first place, of those above, where a line's markers fit, or null.
506
+ const placeLine = (line, compact, gap, placed, room) => {
507
+ const block = line.block;
508
+ let width = -BETWEEN;
509
+ for (const each of line.items) {
510
+ width += (compact ? each.small : each.width) + BETWEEN;
511
+ }
512
+ const most = room - EDGE - width;
513
+ const right = Math.max(contentRight(block), line.words);
514
+ // Along the line's middle, past the block, how far nothing stands in the way.
515
+ const reach = (to) => {
516
+ for (let x = right + 1; x < to; x += STEP) {
517
+ if (!clearAt(x, line.middle, block)) {
518
+ return x;
519
+ }
520
+ }
521
+ return to;
522
+ };
523
+ // A place, moved past the markers already there (rightwards; at the frame's edge, leftwards).
524
+ const fits = (left, leftwards) => {
525
+ for (let tries = 0; tries < 20; tries += 1) {
526
+ if (left < line.words + gap || left > most || reach(left + width) < left + width) {
527
+ return null;
528
+ }
529
+ const hit = overlapping(placed, left, line.top, width);
530
+ if (!hit) {
531
+ return clearOver(left, line.top, width, block) ? left : null;
532
+ }
533
+ left = leftwards ? hit.left - BETWEEN - width : hit.left + hit.width + BETWEEN;
534
+ }
401
535
  return null;
536
+ };
537
+ const gutter = right + gap;
538
+ let left = fits(gutter, false);
539
+ if (left === null && gutter > most) {
540
+ left = fits(most, true);
402
541
  }
403
- const label = mark.count === 0 ? "" : mark.count > 99 ? "99+" : String(mark.count);
404
- // Its size, near enough to place it: the padding and the glyph, then the number.
405
- const width = Math.max(MARKER_HEIGHT, 23 + (label === "" ? 0 : 3 + label.length * 7));
406
- const room = document.documentElement.clientWidth || window.innerWidth;
407
- // At the end of a text anchor's last line, raised; on an element's top right corner.
408
- let left = mark.found.range ? at.right + 2 : at.right - width / 2;
409
- let top = at.top - MARKER_HEIGHT / 2 - (mark.found.range ? 3 : 0);
410
- // Not cut off at the frame's top while its anchor is in view; with its anchor as it goes.
542
+ if (left === null) {
543
+ left = fits(line.words + gap, false);
544
+ }
545
+ return left === null ? null : { left, width };
546
+ };
547
+ const placeLines = (wanted, placed, room) => {
548
+ // One line of one block: markers whose last lines share a middle.
549
+ const lines = [];
550
+ wanted.sort((a, b) => a.at.top - b.at.top || a.at.right - b.at.right);
551
+ for (const each of wanted) {
552
+ const middle = each.at.top + each.at.height / 2;
553
+ let line = null;
554
+ for (const one of lines) {
555
+ if (line === null && one.block === each.block && Math.abs(one.middle - middle) < Math.min(one.height, each.at.height) / 2) {
556
+ line = one;
557
+ }
558
+ }
559
+ if (line === null) {
560
+ line = { block: each.block, middle, height: each.at.height, bottom: each.at.bottom, range: each.range, at: each.at, items: [] };
561
+ lines.push(line);
562
+ }
563
+ line.items.push(each);
564
+ if (each.at.right > line.at.right) {
565
+ line.at = each.at;
566
+ line.range = each.range;
567
+ }
568
+ }
569
+ const seen = document.documentElement.clientHeight || window.innerHeight;
570
+ for (const line of lines) {
571
+ line.top = line.middle - MARKER_HEIGHT / 2;
572
+ // Not cut off at the frame's top while its anchor is in view; with its anchor as it goes.
573
+ if (line.top < 2) {
574
+ line.top = Math.min(2, line.bottom - MARKER_HEIGHT);
575
+ }
576
+ let compact = false;
577
+ let found = null;
578
+ let left;
579
+ if (line.top + MARKER_HEIGHT < 0 || line.top > seen) {
580
+ // Out of view, nothing is measured: it is placed again as it comes into view.
581
+ found = { left: Math.max(EDGE, Math.min(contentRight(line.block) + GAP, room - EDGE - line.items.length * MARKER_HEIGHT)) };
582
+ } else {
583
+ line.words = lineEnd(line.range, line.block, line.at);
584
+ found = placeLine(line, false, GAP, placed, room);
585
+ if (found === null) {
586
+ compact = true;
587
+ found = placeLine(line, true, NEAR, placed, room);
588
+ }
589
+ }
590
+ if (found !== null) {
591
+ left = found.left;
592
+ } else {
593
+ // Over the line's end, as far right as nothing else stands in the way.
594
+ let width = -BETWEEN;
595
+ for (const each of line.items) {
596
+ width += each.small + BETWEEN;
597
+ }
598
+ let limit = room - EDGE;
599
+ const right = Math.max(contentRight(line.block), line.words);
600
+ for (let x = right + 1; x < limit; x += STEP) {
601
+ if (!clearAt(x, line.middle, line.block)) {
602
+ limit = x - NEAR;
603
+ }
604
+ }
605
+ left = Math.max(EDGE, Math.min(room - EDGE, limit) - width);
606
+ }
607
+ for (const each of line.items) {
608
+ each.compact = compact;
609
+ each.left = left;
610
+ each.top = line.top;
611
+ const width = compact ? each.small : each.width;
612
+ placed.push({ left, top: line.top, width });
613
+ left += width + BETWEEN;
614
+ }
615
+ }
616
+ };
617
+ // An element's marker: on its top right corner, inside the frame's width, beside another.
618
+ const placeCorner = (each, placed, room) => {
619
+ let left = each.at.right - each.width / 2;
620
+ let top = each.at.top - MARKER_HEIGHT / 2;
411
621
  if (top < 2) {
412
- top = Math.min(2, at.bottom - MARKER_HEIGHT);
622
+ top = Math.min(2, each.at.bottom - MARKER_HEIGHT);
413
623
  }
414
- // Two marks ending in one place: the later marker goes beside the earlier one.
415
624
  for (let tries = 0; tries < 20; tries += 1) {
416
- const hit = overlaps.filter((other) => Math.abs(other.top - top) < MARKER_HEIGHT && left < other.left + other.width + 2 && other.left < left + width + 2)[0];
625
+ const hit = overlapping(placed, left, top, each.width);
417
626
  if (!hit) {
418
627
  break;
419
628
  }
420
- left = hit.left + hit.width + 2;
629
+ left = hit.left + hit.width + BETWEEN;
421
630
  }
422
- left = Math.max(2, Math.min(left, room - width - 2));
423
- overlaps.push({ left, top, width });
631
+ each.left = Math.max(EDGE, Math.min(left, room - each.width - EDGE));
632
+ each.top = top;
633
+ placed.push({ left: each.left, top, width: each.width });
634
+ };
635
+ // The marker's node, kept across draws for its mark, where it was placed.
636
+ const markerOf = (each) => {
637
+ const mark = each.mark;
638
+ const label = each.label;
424
639
  const kept = markerNodes.get(mark.id);
425
- const marker = kept ? kept.element : createElement.call(document, "div");
426
- marker.className = "marker" + (mark.id === active ? " active" : "") + (mode.elements ? " inert" : "");
427
- marker.style.cssText = "left:" + left + "px;top:" + top + "px";
640
+ let marker = kept ? kept.element : null;
641
+ if (marker === null) {
642
+ marker = createElement.call(document, "div");
643
+ // A listener of its own makes it a thing to tap: WebKit makes a tap a click only on such
644
+ // an element (P105, measured: the window's listener isn't enough). It never runs (the
645
+ // window's first listener stops every click on the layer); the click is told there.
646
+ callOf(listenOn, marker, ["click", tapTarget]);
647
+ }
648
+ marker.className = "marker" + (each.compact ? " compact" : "") + (mark.id === active ? " active" : "") + (mode.elements ? " inert" : "");
649
+ marker.style.cssText = "left:" + each.left + "px;top:" + each.top + "px";
428
650
  markers.push({ id: mark.id, element: marker });
429
- if (kept && kept.label === label) {
651
+ const form = (each.compact ? "compact:" : "full:") + label;
652
+ if (kept && kept.form === form) {
430
653
  return marker;
431
654
  }
432
- markerNodes.set(mark.id, { element: marker, label });
655
+ markerNodes.set(mark.id, { element: marker, form });
433
656
  marker.replaceChildren();
434
- const glyph = createElementNS.call(document, SVG, "svg");
435
- glyph.setAttribute("viewBox", "0 0 16 16");
436
- glyph.setAttribute("aria-hidden", "true");
437
- const path = createElementNS.call(document, SVG, "path");
438
- path.setAttribute("fill", "currentColor");
439
- path.setAttribute("d", "M3 2h10a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H8l-4 3v-3H3a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z");
440
- glyph.appendChild(path);
441
- marker.appendChild(glyph);
657
+ if (!each.compact || label === "") {
658
+ const glyph = createElementNS.call(document, SVG, "svg");
659
+ glyph.setAttribute("viewBox", "0 0 16 16");
660
+ glyph.setAttribute("aria-hidden", "true");
661
+ const path = createElementNS.call(document, SVG, "path");
662
+ path.setAttribute("fill", "currentColor");
663
+ path.setAttribute("d", "M3 2h10a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H8l-4 3v-3H3a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z");
664
+ glyph.appendChild(path);
665
+ marker.appendChild(glyph);
666
+ }
442
667
  if (label !== "") {
443
668
  const number = createElement.call(document, "span");
444
669
  number.textContent = label;
@@ -446,25 +671,43 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
446
671
  }
447
672
  return marker;
448
673
  };
674
+ const tapTarget = () => {};
449
675
  let active = null;
676
+ // The mark whose marker the pointer is over: its words are lit as the active mark's are, so
677
+ // a marker in the gutter shows which words it is for (P105).
678
+ let hot = null;
450
679
  let flashing = null;
451
680
  let flashUntil = 0;
681
+ // The layer's parts: its style, the marks, the markers, the outline while picking. A draw
682
+ // replaces the marks and the outline, and leaves each marker that stays where it is (P105): a
683
+ // marker taken out of the page and put back mid-press loses its click (WebKit, measured once
684
+ // the pointer's arrival on a marker lit its mark and redrew).
685
+ let boxes = null;
686
+ const boxesOf = (root) => {
687
+ if (boxes === null || boxes.style.parentNode !== root || boxes.marks.parentNode !== root || boxes.markers.parentNode !== root || boxes.hover.parentNode !== root) {
688
+ const style = createElement.call(document, "style");
689
+ if (nonce !== "") {
690
+ style.nonce = nonce;
691
+ }
692
+ boxes = { style, marks: createElement.call(document, "div"), markers: createElement.call(document, "div"), hover: createElement.call(document, "div") };
693
+ root.replaceChildren(boxes.style, boxes.marks, boxes.markers, boxes.hover);
694
+ }
695
+ if (boxes.style.textContent !== STYLE) {
696
+ boxes.style.textContent = STYLE;
697
+ }
698
+ return boxes;
699
+ };
452
700
  const draw = () => {
453
701
  if (marks.length === 0 && hover === null && layer === null) {
454
702
  return;
455
703
  }
456
704
  const root = ensureLayer();
705
+ const into = boxesOf(root);
457
706
  const parts = [];
458
- const style = createElement.call(document, "style");
459
- if (nonce !== "") {
460
- style.nonce = nonce;
461
- }
462
- style.textContent = STYLE;
463
- parts.push(style);
464
707
  const flashOn = Date.now() < flashUntil;
465
- // Markers go over every mark, in the order of the marks.
466
- const badges = [];
467
- const overlaps = [];
708
+ // What is measured first, then drawn: no node of the layer changes while the page is read.
709
+ const corners = [];
710
+ const wanted = [];
468
711
  markers = [];
469
712
  for (const mark of marks) {
470
713
  if (mark.found === null) {
@@ -476,25 +719,57 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
476
719
  continue;
477
720
  }
478
721
  const each = createElement.call(document, "div");
479
- each.className = "mark " + (mark.found.range ? "text" : "element") + (mark.count === null ? "" : " quiet") + (mark.id === active ? " active" : "") + (flashOn && mark.id === flashing ? " flash" : "");
722
+ each.className = "mark " + (mark.found.range ? "text" : "element") + (mark.count === null ? "" : " quiet") + (mark.id === active || mark.id === hot ? " active" : "") + (flashOn && mark.id === flashing ? " flash" : "");
480
723
  each.style.cssText = "left:" + rect.left + "px;top:" + rect.top + "px;width:" + rect.width + "px;height:" + rect.height + "px";
481
724
  parts.push(each);
482
725
  }
483
726
  if (mark.count !== null) {
484
- const marker = markerOf(mark, rects, overlaps);
485
- if (marker !== null) {
486
- badges.push(marker);
727
+ const at = lastBox(rects);
728
+ if (at !== null) {
729
+ const label = labelOf(mark.count);
730
+ const each = { mark, order: corners.length + wanted.length, label, width: markerWidth(label), small: compactWidth(label), compact: false, at, left: 0, top: 0 };
731
+ if (mark.found.range) {
732
+ // Kept while it still holds the words (P105): a change elsewhere doesn't move them.
733
+ if (mark.block === undefined || !mark.block.isConnected || !containsOf.call(mark.block, mark.found.range.endContainer)) {
734
+ mark.block = blockOf(mark.found.range);
735
+ }
736
+ each.range = mark.found.range;
737
+ each.block = mark.block;
738
+ wanted.push(each);
739
+ } else {
740
+ corners.push(each);
741
+ }
487
742
  }
488
743
  }
489
744
  }
490
- for (const marker of badges) {
491
- parts.push(marker);
745
+ // Markers go over every mark: elements' on their corners first, then the lines'.
746
+ const room = document.documentElement.clientWidth || window.innerWidth;
747
+ const placed = [];
748
+ for (const each of corners) {
749
+ placeCorner(each, placed, room);
750
+ }
751
+ // The layer's own boxes out of the way while places are hit-tested (P105): each test
752
+ // otherwise walks every mark and marker the last draw left (0.13 ms each, 300 of them).
753
+ if (wanted.length > 0) {
754
+ into.marks.style.display = "none";
755
+ into.markers.style.display = "none";
756
+ try {
757
+ placeLines(wanted, placed, room);
758
+ } finally {
759
+ into.marks.style.display = "";
760
+ into.markers.style.display = "";
761
+ }
762
+ }
763
+ const badges = [];
764
+ for (const each of corners.concat(wanted).sort((a, b) => a.order - b.order)) {
765
+ badges.push(markerOf(each));
492
766
  }
493
767
  for (const id of Array.from(markerNodes.keys())) {
494
768
  if (!markers.some((each) => each.id === id)) {
495
769
  markerNodes.delete(id);
496
770
  }
497
771
  }
772
+ const outlines = [];
498
773
  if (hover !== null && hover.isConnected) {
499
774
  const rect = elementRect.call(hover);
500
775
  const outline = createElement.call(document, "div");
@@ -504,9 +779,20 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
504
779
  tag.className = "tag";
505
780
  tag.textContent = describe(hover).slice(0, 80);
506
781
  tag.style.cssText = "left:" + Math.max(4, rect.left) + "px;top:" + (rect.top >= 24 ? rect.top - 22 : Math.max(4, rect.bottom + 4)) + "px";
507
- parts.push(outline, tag);
782
+ outlines.push(outline, tag);
783
+ }
784
+ into.marks.replaceChildren(...parts);
785
+ for (const child of Array.from(into.markers.childNodes)) {
786
+ if (badges.indexOf(child) === -1) {
787
+ into.markers.removeChild(child);
788
+ }
789
+ }
790
+ for (const badge of badges) {
791
+ if (badge.parentNode !== into.markers) {
792
+ into.markers.appendChild(badge);
793
+ }
508
794
  }
509
- root.replaceChildren(...parts);
795
+ into.hover.replaceChildren(...outlines);
510
796
  };
511
797
  let drawing = false;
512
798
  const redraw = () => {
@@ -520,18 +806,15 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
520
806
  };
521
807
 
522
808
  const resultOf = (mark) => (mark.found === null ? { id: mark.id, state: "orphaned" } : { id: mark.id, state: "attached", rect: box(rectOf(mark.found)) });
809
+ // Two boxes more than 0.5 px apart on any side (or one of them unknown).
810
+ const apart = (a, b) => !a || !b || Math.abs(a.x - b.x) > 0.5 || Math.abs(a.y - b.y) > 0.5 || Math.abs(a.width - b.width) > 0.5 || Math.abs(a.height - b.height) > 0.5;
523
811
  // What the host was last told of each mark (mark.told), so a settle tells only what moved.
524
812
  const moved = (mark, result) => {
525
813
  const told = mark.told;
526
814
  if (!told || told.state !== result.state) {
527
815
  return true;
528
816
  }
529
- if (result.state !== "attached") {
530
- return false;
531
- }
532
- const a = told.rect;
533
- const b = result.rect;
534
- return Math.abs(a.x - b.x) > 0.5 || Math.abs(a.y - b.y) > 0.5 || Math.abs(a.width - b.width) > 0.5 || Math.abs(a.height - b.height) > 0.5;
817
+ return result.state === "attached" && apart(told.rect, result.rect);
535
818
  };
536
819
  const report = (pairs) => {
537
820
  if (pairs.length > 0) {
@@ -630,27 +913,42 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
630
913
  }).observe(document, { childList: true, subtree: true, characterData: true });
631
914
  window.addEventListener("resize", redraw);
632
915
  window.addEventListener("scroll", redraw, true);
633
- // Once a scroll, a resize or a run of changes has settled, the marks that moved since the host
634
- // was last told, in one report (P104), while any mark has a marker (a host without markers
635
- // hears what it heard before), and at most one a second, the latest: the reports share the
636
- // bridge's 120 a minute with the person's selections and clicks. While marks are being
637
- // found again, that run tells it instead.
916
+ // Follow-ups. Once a scroll, a resize or a run of changes has settled: the marks that moved
917
+ // since the host was last told, in one report (P104), while any mark has a marker (a host
918
+ // without markers hears the reports it heard before); and once a scroll has settled, the
919
+ // person's selection, if its box moved since it was told (P105). Each only what moved more
920
+ // than 0.5 px, and all of them on one clock, at most one report a second (the latest): they
921
+ // share the bridge's 120 a minute with the person's own selections and clicks. While marks
922
+ // are being found again, that run tells them instead.
638
923
  const FOLLOW_EVERY = 1000;
639
924
  let settleTimer = 0;
640
925
  let followTimer = 0;
641
926
  let followed = 0;
927
+ // A scroll moved the page since the selection was last told: it is followed only then.
928
+ let selectionScrolled = false;
929
+ const counted = () => marks.some((mark) => mark.count !== null);
642
930
  const sendFollow = () => {
643
- if (marks.length === 0 || settling()) {
644
- return;
931
+ let sent = 0;
932
+ if (marks.length > 0 && !settling() && counted()) {
933
+ const pairs = resultsOf(true);
934
+ if (pairs.length > 0) {
935
+ report(pairs);
936
+ sent += 1;
937
+ }
645
938
  }
646
- const pairs = resultsOf(true);
647
- if (pairs.length > 0) {
648
- followed = Date.now();
649
- report(pairs);
939
+ if (selectionScrolled) {
940
+ selectionScrolled = false;
941
+ if (reportSelection(true)) {
942
+ sent += 1;
943
+ }
944
+ }
945
+ if (sent > 0) {
946
+ // Each report takes its own second of the clock: two at once leave the next one empty.
947
+ followed = Date.now() + (sent - 1) * FOLLOW_EVERY;
650
948
  }
651
949
  };
652
950
  const follow = () => {
653
- if (followTimer !== 0 || !marks.some((mark) => mark.count !== null)) {
951
+ if (followTimer !== 0 || !(selectionScrolled || counted())) {
654
952
  return;
655
953
  }
656
954
  const wait = followed + FOLLOW_EVERY - Date.now();
@@ -664,7 +962,7 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
664
962
  }, wait);
665
963
  };
666
964
  const settle = () => {
667
- if (marks.length === 0) {
965
+ if (marks.length === 0 && !selectionScrolled) {
668
966
  return;
669
967
  }
670
968
  clearTimeout(settleTimer);
@@ -706,36 +1004,80 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
706
1004
  // runs before any of theirs), nor does what lies under it, and a click is reported. No tab
707
1005
  // stop, by choice: it would join the page's focus order, which the content controls, and the
708
1006
  // layer is hidden from assistive technology; the host's own list of marks is the keyboard way.
1007
+ //
1008
+ // A press is read and stopped through the platform's own functions and getters, kept now
1009
+ // (P105), as the navigation guard reads its events (P099): content that later patches
1010
+ // Event's, MouseEvent's or DOMRect's prototypes (or Function's call) neither hears a press
1011
+ // through this listener nor makes it misread one. Narrowing only: content can still cover
1012
+ // the layer, reach its nodes through other built-ins, and tell that a press happened.
1013
+ const stopPress = Event.prototype.stopImmediatePropagation;
1014
+ // The platform's preventDefault, kept before a tab's shell locks its own over it (P099).
1015
+ const cancelPress = preventNavigation;
1016
+ const targetOf = getterOf(Event.prototype, "target");
1017
+ const typeOf = getterOf(Event.prototype, "type");
1018
+ const buttonOf = getterOf(MouseEvent.prototype, "button");
1019
+ const clientXOf = getterOf(MouseEvent.prototype, "clientX");
1020
+ const clientYOf = getterOf(MouseEvent.prototype, "clientY");
1021
+ const leftOf = getterOf(DOMRectReadOnly.prototype, "left");
1022
+ const topOf = getterOf(DOMRectReadOnly.prototype, "top");
1023
+ const widthOf = getterOf(DOMRectReadOnly.prototype, "width");
1024
+ const heightOf = getterOf(DOMRectReadOnly.prototype, "height");
1025
+ const markerBox = (element) => {
1026
+ const rect = callOf(elementRect, element, []);
1027
+ return { x: callOf(leftOf, rect, []), y: callOf(topOf, rect, []), width: callOf(widthOf, rect, []), height: callOf(heightOf, rect, []) };
1028
+ };
709
1029
  const markerAt = (x, y) => {
710
1030
  for (let i = markers.length - 1; i >= 0; i -= 1) {
711
- const rect = elementRect.call(markers[i].element);
712
- if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
1031
+ const rect = markerBox(markers[i].element);
1032
+ if (x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height) {
713
1033
  return markers[i];
714
1034
  }
715
1035
  }
716
1036
  return null;
717
1037
  };
1038
+ const isShown = (id) => {
1039
+ for (let i = 0; i < marks.length; i += 1) {
1040
+ if (marks[i].id === id) {
1041
+ return true;
1042
+ }
1043
+ }
1044
+ return false;
1045
+ };
718
1046
  const onMarker = (event) => {
719
- if (layer === null || event.target !== layer) {
1047
+ if (layer === null || callOf(targetOf, event, []) !== layer) {
720
1048
  return;
721
1049
  }
722
- event.stopImmediatePropagation();
723
- // No focus moves, no selection changes, no menu; a touch still makes its click.
724
- if (CANCELLED[event.type] === 1) {
725
- event.preventDefault();
1050
+ callOf(stopPress, event, []);
1051
+ const type = callOf(typeOf, event, []);
1052
+ // No focus moves, no selection changes, no menu; a touch still makes its click (on WebKit,
1053
+ // since the marker has a listener of its own, P105).
1054
+ if (CANCELLED[type] === 1) {
1055
+ callOf(cancelPress, event, []);
1056
+ }
1057
+ if (HOVERS[type] === 1 || HOVERS[type] === 0) {
1058
+ const hit = HOVERS[type] === 1 ? markerAt(callOf(clientXOf, event, []), callOf(clientYOf, event, [])) : null;
1059
+ const id = hit === null ? null : hit.id;
1060
+ if (id !== hot) {
1061
+ hot = id;
1062
+ redraw();
1063
+ }
726
1064
  }
727
- if (event.type === "click" && event.isTrusted && event.button === 0) {
728
- const hit = markerAt(event.clientX, event.clientY);
729
- if (hit !== null && marks.some((mark) => mark.id === hit.id)) {
730
- tell(M.activated, { id: hit.id, rect: box(elementRect.call(hit.element)) });
1065
+ // isTrusted is the event's own, unforgeable.
1066
+ if (type === "click" && event.isTrusted && callOf(buttonOf, event, []) === 0) {
1067
+ const hit = markerAt(callOf(clientXOf, event, []), callOf(clientYOf, event, []));
1068
+ if (hit !== null && isShown(hit.id)) {
1069
+ tell(M.activated, { id: hit.id, rect: markerBox(hit.element) });
731
1070
  }
732
1071
  }
733
1072
  };
734
1073
  // The pointer moving over a marker is stopped too. Narrowing only: the content still sees
735
1074
  // the pointer leave its own element for the layer (relatedTarget), the layer's :hover and
736
1075
  // :active, and the frame's user activation, so it can tell a marker was pressed, and
737
- // roughly where; it can't act on or cancel the click.
1076
+ // roughly where. Content that patches no built-in can't act on or cancel the click; one that
1077
+ // does can still cover the layer or reach its nodes (P105).
738
1078
  const CANCELLED = { mousedown: 1, mouseup: 1, click: 1, dblclick: 1, auxclick: 1, contextmenu: 1 };
1079
+ // The pointer on a marker (1), or leaving the layer for the content (0).
1080
+ const HOVERS = { pointerover: 1, pointermove: 1, pointerout: 0, pointerleave: 0 };
739
1081
  for (const type of ["pointerdown", "pointerup", "pointercancel", "mousedown", "mouseup", "click", "dblclick", "auxclick", "contextmenu", "touchstart", "touchend", "touchcancel", "pointerover", "pointerout", "pointerenter", "pointerleave", "pointermove", "mouseover", "mouseout", "mouseenter", "mouseleave", "mousemove"]) {
740
1082
  window.addEventListener(type, onMarker, true);
741
1083
  }
@@ -759,11 +1101,12 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
759
1101
  mode = { elements: false, text: false };
760
1102
  hover = null;
761
1103
  reported = null;
1104
+ reportedBox = null;
762
1105
  setCursor(false);
763
1106
  draw();
764
1107
  };
765
- // The content's own handlers never see the pointer while an element is being picked; a
766
- // finger outlines what it is on as it goes down.
1108
+ // The content's own handlers never see the pointer while an element is being picked (content
1109
+ // that patches Event.prototype can: P105); a finger outlines what it is on as it goes down.
767
1110
  let pressed = null;
768
1111
  const swallow = (event) => {
769
1112
  if (mode.elements) {
@@ -826,35 +1169,44 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
826
1169
  }
827
1170
  }, true);
828
1171
 
829
- // Selecting text: each selection that settles, and its clearing; again after a scroll.
1172
+ // Selecting text: each selection that settles, and its clearing; after a scroll, the same
1173
+ // selection again only if its box moved, on the follow-ups' clock (P105: re-sent after every
1174
+ // settle, an honest page's scrolling spent the budget its marker's click needed).
830
1175
  let reported = null;
1176
+ let reportedBox = null;
831
1177
  let selectionTimer = 0;
832
- const reportSelection = (again) => {
1178
+ // Whether it told the host anything.
1179
+ const reportSelection = (following) => {
833
1180
  if (!mode.text) {
834
- return;
1181
+ return false;
835
1182
  }
836
1183
  const selection = selectionOf.call(document);
837
1184
  if (selection === null || selection.isCollapsed || selection.rangeCount === 0) {
838
1185
  if (reported !== null) {
839
1186
  reported = null;
1187
+ reportedBox = null;
840
1188
  tell(M.unselected, {});
1189
+ return true;
841
1190
  }
842
- return;
1191
+ return false;
843
1192
  }
844
1193
  const range = selection.getRangeAt(0);
845
1194
  if (!document.body || !document.body.contains(range.commonAncestorContainer)) {
846
- return;
1195
+ return false;
847
1196
  }
848
1197
  const anchor = textAnchor(range, textIndex());
849
1198
  if (anchor === null) {
850
- return;
1199
+ return false;
851
1200
  }
852
1201
  const key = anchor.selectors[1].start + ":" + anchor.selectors[1].end;
853
- if (key === reported && !again) {
854
- return;
1202
+ const rect = box(rangeRect.call(range));
1203
+ if (key === reported && !(following && apart(reportedBox, rect))) {
1204
+ return false;
855
1205
  }
856
1206
  reported = key;
857
- tell(M.selected, { anchor, rect: box(rangeRect.call(range)) });
1207
+ reportedBox = rect;
1208
+ tell(M.selected, { anchor, rect });
1209
+ return true;
858
1210
  };
859
1211
  document.addEventListener("selectionchange", () => {
860
1212
  if (mode.text) {
@@ -862,11 +1214,10 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
862
1214
  selectionTimer = setTimeout(() => reportSelection(false), 250);
863
1215
  }
864
1216
  });
865
- let scrollTimer = 0;
866
1217
  window.addEventListener("scroll", () => {
867
1218
  if (reported !== null) {
868
- clearTimeout(scrollTimer);
869
- scrollTimer = setTimeout(() => reportSelection(true), 150);
1219
+ selectionScrolled = true;
1220
+ settle();
870
1221
  }
871
1222
  }, true);
872
1223
 
@@ -884,6 +1235,7 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
884
1235
  mode = { elements: params.elements === true, text: params.text === true };
885
1236
  hover = null;
886
1237
  reported = null;
1238
+ reportedBox = null;
887
1239
  setCursor(mode.elements);
888
1240
  draw();
889
1241
  reportSelection(false);
@@ -911,6 +1263,7 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
911
1263
  pendingFocus = null;
912
1264
  marks = [];
913
1265
  active = null;
1266
+ hot = null;
914
1267
  draw();
915
1268
  break;
916
1269
  default: