@plannotator/ui 0.38.2 → 0.40.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.
@@ -116,6 +116,7 @@
116
116
  var pendingPinKey = null; // target key for the primary pinpoint target (multi-select)
117
117
  var pendingPinLabel = null; // semantic label captured for the primary target
118
118
  var pendingPinPoint = null; // normalized {x,y} click point inside the pinned element's rect
119
+ var pendingPinContext = null; // agent-facing element context for the primary target (see buildElementContext)
119
120
  var pendingPinViaPinpoint = false; // pinpoint drafts survive scroll-out (see postSelectionRect)
120
121
  // Multi-select is ARMED EXPLICITLY by the parent (arm-multi-select), and only
121
122
  // when the comment composer owns the draft. The bridge must never accept a
@@ -242,6 +243,7 @@
242
243
  pinpoint: (extras && extras.pinpoint) || undefined,
243
244
  targetKey: (extras && extras.targetKey) || undefined,
244
245
  targetLabel: (extras && extras.targetLabel) || undefined,
246
+ context: (extras && extras.context) || undefined,
245
247
  rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height }
246
248
  });
247
249
  renderAnnotationOverlay(); // draft selection highlight (overlay-projected)
@@ -464,6 +466,13 @@
464
466
  scrollToAnnotation(e.data.id, e.data.behavior === 'auto' ? 'auto' : 'smooth');
465
467
  }
466
468
 
469
+ else if (type === PREFIX + 'scroll-to-fragment') {
470
+ // A linked document opened from an in-page link carried a #fragment.
471
+ // The srcdoc document has no URL of its own, so the parent cannot set
472
+ // one: it replays the fragment here once the new document is ready.
473
+ scrollToLocalFragment(typeof e.data.fragment === 'string' ? e.data.fragment : '');
474
+ }
475
+
467
476
  else if (type === PREFIX + 'focus-mark') {
468
477
  focusAnnotationRecord(typeof e.data.id === 'string' ? e.data.id : null, false);
469
478
  }
@@ -2504,8 +2513,441 @@
2504
2513
  return el;
2505
2514
  }
2506
2515
 
2516
+ // --- Element context: a bounded, agent-facing description of a pinpointed
2517
+ // element, captured at click time (only the bridge can see the DOM). It is
2518
+ // purely descriptive and NEVER consulted by restore (that is the anchor's
2519
+ // job): the exported feedback prints it so an agent working in the app's
2520
+ // source can find the element without having the page. Everything here is
2521
+ // page-controlled, so the parent re-validates and re-caps it all at the
2522
+ // trust boundary; this side keeps the wire payload honest.
2523
+ //
2524
+ // Constraints (the "smart" part is that they adapt to the element):
2525
+ // - attributes are an ALLOWLIST (a page cannot add a key); no form values,
2526
+ // no on* handlers, no style, no script/style/template contents ever;
2527
+ // - href/src URLs lose their query and fragment (tokens live there),
2528
+ // relative ones included, and data: URIs keep only their media-type
2529
+ // prefix;
2530
+ // - the outline tries two levels of children, falls back to one, then to a
2531
+ // per-tag count, whichever first fits CTX_MAX_OUTLINE, so a click on a
2532
+ // whole <main> costs the same bytes as a click on a chip;
2533
+ // - text is innerText (rendered words, not the DOM soup), word-boundary
2534
+ // truncated;
2535
+ // - the serialized context stays under a byte budget by shedding the
2536
+ // expendable fields in a fixed order; tag/id/role/name/page never shed.
2537
+ var CTX_MAX_BYTES = 2048; // primary target
2538
+ var CTX_MAX_BYTES_EXTRA = 1024; // each shift-click additional target
2539
+ var CTX_MAX_TEXT = 300;
2540
+ var CTX_MAX_OUTLINE = 600;
2541
+ var CTX_MAX_PATH_SEGMENTS = 8;
2542
+ var CTX_MAX_CLASSES = 8;
2543
+ var CTX_MAX_ATTRS = 10;
2544
+ var CTX_MAX_ATTR_VALUE = 120;
2545
+ var CTX_MAX_CHILDREN = 6;
2546
+ var CONTEXT_ATTRS = ['href', 'src', 'alt', 'title', 'type', 'name', 'role', 'placeholder', 'for', 'target', 'rel',
2547
+ 'aria-label', 'aria-labelledby', 'aria-describedby', 'aria-current', 'aria-expanded', 'aria-hidden', 'aria-controls',
2548
+ 'data-annotate', 'data-testid', 'data-test', 'data-test-id', 'data-cy', 'data-qa', 'data-component', 'data-id'];
2549
+ var CONTEXT_SKIP_TAGS = { SCRIPT: 1, STYLE: 1, TEMPLATE: 1, NOSCRIPT: 1 };
2550
+ var CONTEXT_IMPLICIT_ROLE = { NAV: 'navigation', MAIN: 'main', HEADER: 'banner', FOOTER: 'contentinfo', ASIDE: 'complementary',
2551
+ ARTICLE: 'article', SECTION: 'region', FORM: 'form', BUTTON: 'button', A: 'link', IMG: 'img', TABLE: 'table', UL: 'list',
2552
+ OL: 'list', LI: 'listitem', H1: 'heading', H2: 'heading', H3: 'heading', H4: 'heading', H5: 'heading', H6: 'heading',
2553
+ DIALOG: 'dialog', INPUT: 'textbox', TEXTAREA: 'textbox', SELECT: 'combobox', SUMMARY: 'button', PROGRESS: 'progressbar' };
2554
+ var CONTEXT_LANDMARK_SELECTOR = 'main,nav,header,footer,aside,article,section,form,dialog,[role]';
2555
+
2556
+ // Collapse control characters and whitespace runs; the parent does it again.
2557
+ function ctxCollapse(value, max) {
2558
+ var s = String(value == null ? '' : value).replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/\s+/g, ' ').trim();
2559
+ return max ? ctxTruncate(s, max) : s;
2560
+ }
2561
+
2562
+ // Word-boundary truncation with an ellipsis, never splitting a surrogate pair.
2563
+ function ctxTruncate(s, max) {
2564
+ if (s.length <= max) return s;
2565
+ var cut = s.lastIndexOf(' ', max - 1);
2566
+ if (cut < max * 0.6) cut = max - 1;
2567
+ var last = s.charCodeAt(cut - 1);
2568
+ if (last >= 0xd800 && last <= 0xdbff) cut -= 1;
2569
+ return s.slice(0, cut) + '…';
2570
+ }
2571
+
2572
+ function ctxBytes(value) {
2573
+ var json = JSON.stringify(value);
2574
+ try { return new TextEncoder().encode(json).length; } catch (ex) {}
2575
+ try { return unescape(encodeURIComponent(json)).length; } catch (ex2) { return json.length * 2; }
2576
+ }
2577
+
2578
+ // URL attribute values: keep what locates the element in source, drop
2579
+ // what identifies the user. The path survives in every form; the query and
2580
+ // the fragment never do — a relative URL carries the same per-visit state an
2581
+ // absolute one does (session ids, and the implicit-flow tokens that live in
2582
+ // the fragment specifically), so it is scrubbed the same way.
2583
+ function ctxScrubUrl(value) {
2584
+ var v = String(value).trim();
2585
+ if (/^javascript:/i.test(v)) return null;
2586
+ if (/^data:/i.test(v)) {
2587
+ var comma = v.indexOf(',');
2588
+ return (comma > 0 ? v.slice(0, Math.min(comma, 40)) : v.slice(0, 40)) + ',…';
2589
+ }
2590
+ if (/^https?:\/\//i.test(v)) {
2591
+ try {
2592
+ var u = new URL(v);
2593
+ return u.origin + u.pathname + (u.search || u.hash ? '?…' : '');
2594
+ } catch (ex) { return ctxTruncate(v, CTX_MAX_ATTR_VALUE); }
2595
+ }
2596
+ var mark = v.search(/[?#]/);
2597
+ if (mark >= 0) return v.slice(0, mark) + '?…';
2598
+ return v;
2599
+ }
2600
+
2601
+ function ctxAttrs(el) {
2602
+ var out = [];
2603
+ if (!el.getAttribute) return out;
2604
+ for (var i = 0; i < CONTEXT_ATTRS.length && out.length < CTX_MAX_ATTRS; i++) {
2605
+ var name = CONTEXT_ATTRS[i];
2606
+ var value = el.getAttribute(name);
2607
+ if (value == null) continue;
2608
+ if (name === 'href' || name === 'src') {
2609
+ value = ctxScrubUrl(value);
2610
+ if (value == null) continue;
2611
+ }
2612
+ out.push([name, ctxCollapse(value, CTX_MAX_ATTR_VALUE)]);
2613
+ }
2614
+ return out;
2615
+ }
2616
+
2617
+ function ctxClasses(el) {
2618
+ var out = [];
2619
+ if (!el.classList) return out;
2620
+ for (var i = 0; i < el.classList.length && out.length < CTX_MAX_CLASSES; i++) {
2621
+ var cls = String(el.classList[i]);
2622
+ if (!cls || isLikelyGeneratedClass(cls)) continue;
2623
+ out.push(ctxTruncate(cls, 48));
2624
+ }
2625
+ if (el.classList.length > out.length && out.length === CTX_MAX_CLASSES) out.push('+' + (el.classList.length - out.length) + ' more');
2626
+ return out;
2627
+ }
2628
+
2629
+ function ctxFirstClass(el) {
2630
+ if (!el.classList) return null;
2631
+ for (var i = 0; i < el.classList.length; i++) {
2632
+ var cls = String(el.classList[i]);
2633
+ if (cls && !isLikelyGeneratedClass(cls)) return ctxTruncate(cls, 48);
2634
+ }
2635
+ return null;
2636
+ }
2637
+
2638
+ function ctxRole(el) {
2639
+ var explicit = el.getAttribute && el.getAttribute('role');
2640
+ if (explicit && explicit.trim()) return ctxCollapse(explicit, 32);
2641
+ if (el.tagName === 'A' && !(el.getAttribute && el.getAttribute('href'))) return null;
2642
+ return CONTEXT_IMPLICIT_ROLE[el.tagName] || null;
2643
+ }
2644
+
2645
+ function ctxText(el) {
2646
+ var raw = typeof el.innerText === 'string' && el.innerText ? el.innerText : (el.textContent || '');
2647
+ return ctxCollapse(raw, CTX_MAX_TEXT);
2648
+ }
2649
+
2650
+ // Accessible name, in the practical order: aria-label, aria-labelledby,
2651
+ // alt, title, a <label for>, then the element's own short text.
2652
+ function ctxName(el) {
2653
+ if (!el.getAttribute) return null;
2654
+ var aria = el.getAttribute('aria-label');
2655
+ if (aria && aria.trim()) return ctxCollapse(aria, 120);
2656
+ var by = el.getAttribute('aria-labelledby');
2657
+ if (by && by.trim()) {
2658
+ var ids = by.trim().split(/\s+/);
2659
+ var parts = [];
2660
+ for (var i = 0; i < ids.length && i < 4; i++) {
2661
+ var ref = document.getElementById(ids[i]);
2662
+ if (ref) parts.push(ref.textContent || '');
2663
+ }
2664
+ var joined = ctxCollapse(parts.join(' '), 120);
2665
+ if (joined) return joined;
2666
+ }
2667
+ var alt = el.getAttribute('alt');
2668
+ if (alt && alt.trim()) return ctxCollapse(alt, 120);
2669
+ var title = el.getAttribute('title');
2670
+ if (title && title.trim()) return ctxCollapse(title, 120);
2671
+ if (el.id && typeof CSS !== 'undefined' && CSS.escape) {
2672
+ var label = null;
2673
+ try { label = document.querySelector('label[for="' + CSS.escape(el.id) + '"]'); } catch (ex) {}
2674
+ if (label) {
2675
+ var labelText = ctxCollapse(label.textContent, 120);
2676
+ if (labelText) return labelText;
2677
+ }
2678
+ }
2679
+ var own = ctxCollapse(el.textContent, 120);
2680
+ return own && own.length <= 80 ? own : null;
2681
+ }
2682
+
2683
+ // One path segment: tag, then the strongest cheap identity it carries, and
2684
+ // a position only when a same-tag sibling would otherwise read the same.
2685
+ function ctxSegment(el) {
2686
+ var seg = el.tagName.toLowerCase();
2687
+ if (el.id) return seg + '#' + ctxCollapse(el.id, 60);
2688
+ var cls = ctxFirstClass(el);
2689
+ if (cls) seg += '.' + cls;
2690
+ var hook = el.getAttribute && (el.getAttribute('data-testid') || el.getAttribute('data-component'));
2691
+ if (hook) seg += '[' + (el.getAttribute('data-testid') ? 'data-testid' : 'data-component') + '="' + ctxCollapse(hook, 40) + '"]';
2692
+ // A position only when a same-tag sibling would read identically (same
2693
+ // first class, same hook): p.beta among p.alpha / p.gamma needs none,
2694
+ // the fourth of forty identical <li class="row"> does.
2695
+ var parent = el.parentElement;
2696
+ if (parent) {
2697
+ var same = 0;
2698
+ var index = 0;
2699
+ var typeIndex = 0;
2700
+ var typeCount = 0;
2701
+ for (var i = 0; i < parent.children.length; i++) {
2702
+ var sibling = parent.children[i];
2703
+ if (sibling.tagName !== el.tagName) continue;
2704
+ typeCount++;
2705
+ if (sibling === el) typeIndex = typeCount;
2706
+ if (sibling.id) continue;
2707
+ if (ctxFirstClass(sibling) === cls && !!(sibling.getAttribute && (sibling.getAttribute('data-testid') || sibling.getAttribute('data-component'))) === !!hook) {
2708
+ same++;
2709
+ if (sibling === el) index = same;
2710
+ }
2711
+ }
2712
+ if (same > 1) seg += ':nth-of-type(' + typeIndex + ')';
2713
+ }
2714
+ return seg;
2715
+ }
2716
+
2717
+ function ctxPath(el) {
2718
+ var parts = [];
2719
+ var current = el;
2720
+ while (current && current.nodeType === 1 && current !== document.documentElement) {
2721
+ if (parts.length >= CTX_MAX_PATH_SEGMENTS) { parts.unshift('…'); break; }
2722
+ parts.unshift(ctxSegment(current));
2723
+ if (current === document.body) break;
2724
+ current = current.parentElement;
2725
+ }
2726
+ return parts.join(' > ');
2727
+ }
2728
+
2729
+ function ctxIsSkipped(node) {
2730
+ return !node || node.nodeType !== 1 || CONTEXT_SKIP_TAGS[node.tagName] || isViewerOverlayNode(node);
2731
+ }
2732
+
2733
+ function ctxElementChildren(el) {
2734
+ var kids = [];
2735
+ for (var i = 0; i < el.children.length; i++) {
2736
+ if (!ctxIsSkipped(el.children[i])) kids.push(el.children[i]);
2737
+ }
2738
+ return kids;
2739
+ }
2740
+
2741
+ function ctxTagCounts(nodes) {
2742
+ var counts = {};
2743
+ var order = [];
2744
+ for (var i = 0; i < nodes.length; i++) {
2745
+ var tag = nodes[i].tagName.toLowerCase();
2746
+ if (!counts[tag]) { counts[tag] = 0; order.push(tag); }
2747
+ counts[tag]++;
2748
+ }
2749
+ var out = [];
2750
+ for (var j = 0; j < order.length && j < 4; j++) out.push(order[j] + '×' + counts[order[j]]);
2751
+ if (order.length > 4) out.push('…');
2752
+ return out.join(', ');
2753
+ }
2754
+
2755
+ function ctxAttrString(pairs) {
2756
+ var s = '';
2757
+ for (var i = 0; i < pairs.length; i++) s += ' ' + pairs[i][0] + '="' + pairs[i][1].replace(/"/g, '&quot;') + '"';
2758
+ return s;
2759
+ }
2760
+
2761
+ // id and up to four author classes on an opening tag: the grep keys, first.
2762
+ function ctxIdentityString(el) {
2763
+ var s = '';
2764
+ if (el.id) s += ' id="' + ctxCollapse(el.id, 60) + '"';
2765
+ var classes = [];
2766
+ if (el.classList) {
2767
+ for (var i = 0; i < el.classList.length && classes.length < 4; i++) {
2768
+ var cls = String(el.classList[i]);
2769
+ if (cls && !isLikelyGeneratedClass(cls)) classes.push(ctxTruncate(cls, 48));
2770
+ }
2771
+ }
2772
+ if (classes.length) s += ' class="' + classes.join(' ') + '"';
2773
+ return s;
2774
+ }
2775
+
2776
+ // A child rendered inside the outline: its tag with one identity hook, its
2777
+ // own short text when it has no element children, an ellipsis otherwise.
2778
+ function ctxChildTag(child, depth) {
2779
+ var tag = child.tagName.toLowerCase();
2780
+ var open = '<' + tag;
2781
+ if (child.id) open += ' id="' + ctxCollapse(child.id, 60) + '"';
2782
+ else {
2783
+ var cls = ctxFirstClass(child);
2784
+ if (cls) open += ' class="' + cls + '"';
2785
+ }
2786
+ var hook = child.getAttribute && child.getAttribute('data-testid');
2787
+ if (hook) open += ' data-testid="' + ctxCollapse(hook, 40) + '"';
2788
+ if (tag === 'a' && child.getAttribute('href')) {
2789
+ var href = ctxScrubUrl(child.getAttribute('href'));
2790
+ if (href) open += ' href="' + ctxCollapse(href, 60) + '"';
2791
+ }
2792
+ open += '>';
2793
+ var kids = ctxElementChildren(child);
2794
+ if (!kids.length) {
2795
+ var own = ctxCollapse(child.textContent, 40);
2796
+ return open + own + '</' + tag + '>';
2797
+ }
2798
+ if (depth <= 1) {
2799
+ var leafText = ctxCollapse(child.textContent, 40);
2800
+ return open + (leafText || '…') + '</' + tag + '>';
2801
+ }
2802
+ var lines = [open];
2803
+ var shown = kids.slice(0, CTX_MAX_CHILDREN);
2804
+ for (var i = 0; i < shown.length; i++) lines.push(' ' + ctxChildTag(shown[i], depth - 1));
2805
+ if (kids.length > shown.length) lines.push(' <!-- +' + (kids.length - shown.length) + ' more: ' + ctxTagCounts(kids.slice(shown.length)) + ' -->');
2806
+ lines.push('</' + tag + '>');
2807
+ return lines.join('\n');
2808
+ }
2809
+
2810
+ function ctxOutlineAtDepth(el, attrs, kids, depth) {
2811
+ var tag = el.tagName.toLowerCase();
2812
+ var open = '<' + tag + ctxIdentityString(el) + ctxAttrString(attrs) + '>';
2813
+ if (!kids.length) {
2814
+ var own = ctxCollapse(el.textContent, 80);
2815
+ return open + own + '</' + tag + '>';
2816
+ }
2817
+ if (depth <= 0) return open + '<!-- ' + kids.length + ' children: ' + ctxTagCounts(kids) + ' -->' + '</' + tag + '>';
2818
+ var lines = [open];
2819
+ var shown = kids.slice(0, CTX_MAX_CHILDREN);
2820
+ for (var i = 0; i < shown.length; i++) {
2821
+ var rendered = ctxChildTag(shown[i], depth);
2822
+ var childLines = rendered.split('\n');
2823
+ for (var j = 0; j < childLines.length; j++) lines.push(' ' + childLines[j]);
2824
+ }
2825
+ if (kids.length > shown.length) lines.push(' <!-- +' + (kids.length - shown.length) + ' more: ' + ctxTagCounts(kids.slice(shown.length)) + ' -->');
2826
+ lines.push('</' + tag + '>');
2827
+ return lines.join('\n');
2828
+ }
2829
+
2830
+ // Adaptive depth: two levels, then one, then a per-tag count — the first
2831
+ // that fits the outline cap. A whole-page container never costs more than a chip.
2832
+ function ctxOutline(el, attrs) {
2833
+ var kids = ctxElementChildren(el);
2834
+ var depths = [2, 1, 0];
2835
+ for (var i = 0; i < depths.length; i++) {
2836
+ var out = ctxOutlineAtDepth(el, attrs, kids, depths[i]);
2837
+ if (out.length <= CTX_MAX_OUTLINE) return out;
2838
+ }
2839
+ return ctxTruncate(ctxOutlineAtDepth(el, attrs, kids, 0), CTX_MAX_OUTLINE);
2840
+ }
2841
+
2842
+ function ctxLandmark(el) {
2843
+ var parent = el.parentElement;
2844
+ if (!parent || !parent.closest) return null;
2845
+ var region = null;
2846
+ try { region = parent.closest(CONTEXT_LANDMARK_SELECTOR); } catch (ex) { return null; }
2847
+ if (!region || region === document.body) return null;
2848
+ var seg = ctxSegment(region);
2849
+ var name = region.getAttribute('aria-label');
2850
+ if (name && name.trim()) seg += ' "' + ctxCollapse(name, 60) + '"';
2851
+ return ctxTruncate(seg, 80);
2852
+ }
2853
+
2854
+ // The nearest heading ABOVE the element in document order (or one that
2855
+ // contains it): the section it sits in, which often names the source file.
2856
+ function ctxHeading(el) {
2857
+ var headings = document.querySelectorAll('h1,h2,h3,h4,h5,h6');
2858
+ var best = null;
2859
+ for (var i = 0; i < headings.length && i < 500; i++) {
2860
+ var h = headings[i];
2861
+ var pos = el.compareDocumentPosition(h);
2862
+ if (pos & 2 || pos & 8) best = h; // PRECEDING or CONTAINS
2863
+ else if (pos & 4) break; // FOLLOWING: every later heading follows too
2864
+ }
2865
+ if (!best) return null;
2866
+ var text = ctxCollapse(best.textContent, 120);
2867
+ return text ? best.tagName.toLowerCase() + ' "' + text + '"' : null;
2868
+ }
2869
+
2870
+ // The cheapest safe framework hint: an author-placed component marker on
2871
+ // the element or a near ancestor. Deliberately no React fiber reads.
2872
+ function ctxComponent(el) {
2873
+ var current = el;
2874
+ for (var depth = 0; current && current.nodeType === 1 && depth < 6; depth++) {
2875
+ var attrs = ['data-component', 'data-testid', 'data-qa'];
2876
+ for (var i = 0; i < attrs.length; i++) {
2877
+ var value = current.getAttribute && current.getAttribute(attrs[i]);
2878
+ if (value && value.trim()) return attrs[i] + '=' + ctxCollapse(value, 60);
2879
+ }
2880
+ current = current.parentElement;
2881
+ }
2882
+ return null;
2883
+ }
2884
+
2885
+ function ctxRect(el) {
2886
+ var r = el.getBoundingClientRect();
2887
+ return {
2888
+ x: Math.round(r.left), y: Math.round(r.top),
2889
+ w: Math.round(r.width), h: Math.round(r.height),
2890
+ vw: Math.round(window.innerWidth || 0), vh: Math.round(window.innerHeight || 0)
2891
+ };
2892
+ }
2893
+
2894
+ // Shed order when over budget: the fields an agent can live without first.
2895
+ var CTX_SHED_ORDER = ['outline', 'text', 'attrs', 'classes', 'path', 'heading', 'landmark', 'component'];
2896
+
2897
+ function buildElementContext(el, maxBytes) {
2898
+ if (!el || el.nodeType !== 1) return null;
2899
+ try {
2900
+ var attrs = ctxAttrs(el);
2901
+ var context = { tag: el.tagName.toLowerCase() };
2902
+ if (el.id) context.id = ctxCollapse(el.id, 100);
2903
+ var classes = ctxClasses(el);
2904
+ if (classes.length) context.classes = classes;
2905
+ context.path = ctxPath(el);
2906
+ var role = ctxRole(el);
2907
+ if (role) context.role = role;
2908
+ var name = ctxName(el);
2909
+ if (name) context.name = name;
2910
+ if (attrs.length) context.attrs = attrs;
2911
+ var text = ctxText(el);
2912
+ if (text) context.text = text;
2913
+ context.outline = ctxOutline(el, attrs);
2914
+ context.children = ctxElementChildren(el).length;
2915
+ context.rect = ctxRect(el);
2916
+ var landmark = ctxLandmark(el);
2917
+ if (landmark) context.landmark = landmark;
2918
+ var heading = ctxHeading(el);
2919
+ if (heading) context.heading = heading;
2920
+ var component = ctxComponent(el);
2921
+ if (component) context.component = component;
2922
+ if (LIVE) {
2923
+ context.page = { url: currentPageUrl() };
2924
+ var title = ctxCollapse(document.title, 200);
2925
+ if (title) context.page.title = title;
2926
+ }
2927
+ // Byte budget: shed whole fields in order; a shed attrs/classes array
2928
+ // first loses entries from the end before the field goes entirely.
2929
+ for (var s = 0; s < CTX_SHED_ORDER.length && ctxBytes(context) > maxBytes; s++) {
2930
+ var field = CTX_SHED_ORDER[s];
2931
+ if (context[field] === undefined) continue;
2932
+ if ((field === 'attrs' || field === 'classes') && context[field].length > 1) {
2933
+ while (context[field].length > 1 && ctxBytes(context) > maxBytes) context[field].pop();
2934
+ if (ctxBytes(context) <= maxBytes) break;
2935
+ }
2936
+ if (field === 'text' && context.text.length > 80) {
2937
+ context.text = ctxTruncate(context.text, 80);
2938
+ if (ctxBytes(context) <= maxBytes) break;
2939
+ }
2940
+ delete context[field];
2941
+ }
2942
+ return context;
2943
+ } catch (ex) {
2944
+ return null;
2945
+ }
2946
+ }
2947
+
2507
2948
  function clearPendingPin() {
2508
2949
  pendingPinEl = null;
2950
+ pendingPinContext = null;
2509
2951
  pendingPinAnchor = null;
2510
2952
  pendingPinKey = null;
2511
2953
  pendingPinLabel = null;
@@ -2626,6 +3068,7 @@
2626
3068
  pendingPinKey = next.key;
2627
3069
  pendingPinLabel = next.label;
2628
3070
  pendingPinPoint = next.point || null;
3071
+ pendingPinContext = next.context || null;
2629
3072
  // A promoted primary commits as an element pin: the original text
2630
3073
  // selection belonged to the removed element and no longer applies.
2631
3074
  pendingSelection = { element: true };
@@ -2684,15 +3127,17 @@
2684
3127
  if (anchor && point) anchor.point = point;
2685
3128
  var label = pinpointHoverLabel(el);
2686
3129
  var text = elementTargetText(el, label);
3130
+ var context = buildElementContext(el, CTX_MAX_BYTES_EXTRA);
2687
3131
  var key = makeTargetKey();
2688
3132
  var box = createMultiTargetBox(el);
2689
- pendingMultiTargets.push({ key: key, el: el, anchor: anchor, label: label, text: text, point: point, box: box });
3133
+ pendingMultiTargets.push({ key: key, el: el, anchor: anchor, label: label, text: text, point: point, context: context, box: box });
2690
3134
  postToParent({
2691
3135
  type: PREFIX + 'multi-target-added',
2692
3136
  key: key,
2693
3137
  label: label,
2694
3138
  text: text,
2695
- anchor: anchor || undefined
3139
+ anchor: anchor || undefined,
3140
+ context: context || undefined
2696
3141
  });
2697
3142
  }
2698
3143
 
@@ -2793,11 +3238,15 @@
2793
3238
  pendingPinPoint = normalizePointInElement(el, clickPoint);
2794
3239
  if (pendingPinAnchor && pendingPinPoint) pendingPinAnchor.point = pendingPinPoint;
2795
3240
  pendingPinViaPinpoint = !!viaPinpoint;
3241
+ // Agent-facing description, captured now while the element is in hand
3242
+ // (an SPA re-render or navigation may have replaced it by submit time).
3243
+ pendingPinContext = buildElementContext(el, CTX_MAX_BYTES);
2796
3244
  var extras = {
2797
3245
  anchor: pendingPinAnchor,
2798
3246
  pinpoint: !!viaPinpoint,
2799
3247
  targetKey: pendingPinKey,
2800
- targetLabel: pendingPinLabel
3248
+ targetLabel: pendingPinLabel,
3249
+ context: pendingPinContext
2801
3250
  };
2802
3251
  // Pinned outline: stronger accent box that tracks the element until the
2803
3252
  // composer resolves (create-mark or cancel-selection).
@@ -2839,10 +3288,79 @@
2839
3288
  pinpoint: !!viaPinpoint || undefined,
2840
3289
  targetKey: pendingPinKey || undefined,
2841
3290
  targetLabel: pendingPinLabel || undefined,
3291
+ context: pendingPinContext || undefined,
2842
3292
  rect: { top: r.top, left: r.left, width: r.width, height: r.height } });
2843
3293
  return true;
2844
3294
  }
2845
3295
 
3296
+ // --- Local-site link navigation (srcdoc sessions only) ---
3297
+ // A srcdoc document has no URL of its own: its base URL is the PARENT page's,
3298
+ // which is the Plannotator server. So a plain link to 02-detail.html resolves
3299
+ // to http://localhost:<port>/02-detail.html, the server's catch-all answers
3300
+ // with the app itself, and the whole editor renders inside the annotated
3301
+ // frame. An in-page #section link is a cross-document navigation for the
3302
+ // same reason.
3303
+ //
3304
+ // The frame therefore never navigates itself. In-page fragments scroll here;
3305
+ // everything else is handed to the parent, which owns resolution against the
3306
+ // current document's directory and is the trust boundary for the href.
3307
+ // Registered BEFORE the pinpoint handler and never stopping propagation, so
3308
+ // an armed click still pins the link element exactly as it always did.
3309
+ //
3310
+ // Live app sessions are excluded outright: they navigate a real origin
3311
+ // through the proxy, which is the whole point of that surface.
3312
+ function scrollToLocalFragment(rawId) {
3313
+ var id = typeof rawId === 'string' ? rawId : '';
3314
+ try { id = decodeURIComponent(id); } catch (ex) {}
3315
+ if (!id) {
3316
+ try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch (ex) { window.scrollTo(0, 0); }
3317
+ return true;
3318
+ }
3319
+ var target = null;
3320
+ try { target = document.getElementById(id); } catch (ex) {}
3321
+ if (!target) {
3322
+ var named = document.getElementsByName(id);
3323
+ if (named && named.length) target = named[0];
3324
+ }
3325
+ if (!target) return false;
3326
+ try { target.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
3327
+ catch (ex) { target.scrollIntoView(); }
3328
+ return true;
3329
+ }
3330
+
3331
+ function navigableLinkHref(node) {
3332
+ var el = node && node.nodeType === 1 ? node : node && node.parentElement;
3333
+ if (!el || !el.closest) return '';
3334
+ var link = el.closest('a,area');
3335
+ if (!link) return '';
3336
+ var raw = link.getAttribute('href');
3337
+ // SVG anchors may only carry xlink:href.
3338
+ if (typeof raw !== 'string') raw = link.getAttribute('xlink:href');
3339
+ return typeof raw === 'string' ? raw.trim() : '';
3340
+ }
3341
+
3342
+ if (!LIVE) {
3343
+ document.addEventListener('click', function(e) {
3344
+ if (e.defaultPrevented || e.button !== 0) return;
3345
+ if (isViewerOverlayNode(e.target)) return; // markers own their clicks
3346
+ var raw = navigableLinkHref(e.target);
3347
+ if (!raw) return;
3348
+ // The page's own scripting, not a navigation: leave it alone.
3349
+ if (/^javascript:/i.test(raw)) return;
3350
+ if (raw.charAt(0) === '#') {
3351
+ e.preventDefault();
3352
+ scrollToLocalFragment(raw.slice(1));
3353
+ return;
3354
+ }
3355
+ e.preventDefault();
3356
+ // Armed pinpoint: the click belongs to annotation, and the capture-phase
3357
+ // pinpoint handler below is about to pin this element. Navigation is
3358
+ // already suppressed above, which is all this surface owes the click.
3359
+ if (annotateModeActive && currentInputMethod === 'pinpoint') return;
3360
+ postToParent({ type: PREFIX + 'link-click', href: raw.slice(0, 2048) });
3361
+ }, true);
3362
+ }
3363
+
2846
3364
  document.addEventListener('click', function(e) {
2847
3365
  if (!annotateModeActive || currentInputMethod !== 'pinpoint') return;
2848
3366
  // Real placed markers (and any other viewer overlay) own their clicks —
@@ -2918,15 +3436,21 @@
2918
3436
  }
2919
3437
  });
2920
3438
 
2921
- // Mod+Shift+A toggles Interact/Annotate from inside the iframe (the parent
2922
- // registers the same chord, but focus usually lives in here on live apps).
2923
- // Capture phase so the page cannot swallow the reserved chord; the parent
2924
- // answers with set-annotate-mode.
3439
+ // The two reserved header chords, mirrored from inside the iframe (the
3440
+ // parent registers both, but focus usually lives in here on live apps):
3441
+ // Mod+Shift+A toggles Interact/Annotate, Mod+Shift+X shows/hides the
3442
+ // floating tools over the page. Capture phase so the page cannot swallow
3443
+ // them; the parent owns both states and answers annotate with
3444
+ // set-annotate-mode. Disarming tears down any pending draft through that
3445
+ // same set-annotate-mode(false) handler, exactly as Esc does.
2925
3446
  document.addEventListener('keydown', function(e) {
2926
3447
  if (!(e.metaKey || e.ctrlKey) || !e.shiftKey || e.altKey) return;
2927
- if (e.key !== 'a' && e.key !== 'A') return;
3448
+ var message = null;
3449
+ if (e.key === 'a' || e.key === 'A') message = 'annotate-toggle';
3450
+ else if (e.key === 'x' || e.key === 'X') message = 'tools-toggle';
3451
+ if (!message) return;
2928
3452
  e.preventDefault();
2929
- postToParent({ type: PREFIX + 'annotate-toggle' });
3453
+ postToParent({ type: PREFIX + message });
2930
3454
  }, true);
2931
3455
 
2932
3456
  // Author opt-in: a plain click on any element tagged [data-annotate] pops the