@decocms/blocks 8.17.0 → 8.18.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.
Files changed (88) hide show
  1. package/dist/v8/analytics/client.d.ts +48 -0
  2. package/dist/v8/analytics/client.d.ts.map +1 -0
  3. package/dist/v8/analytics/client.js +71 -0
  4. package/dist/v8/analytics/client.js.map +1 -0
  5. package/dist/v8/analytics/runtime/modules/click.d.ts +2 -0
  6. package/dist/v8/analytics/runtime/modules/click.d.ts.map +1 -0
  7. package/dist/v8/analytics/runtime/modules/click.js +48 -0
  8. package/dist/v8/analytics/runtime/modules/click.js.map +1 -0
  9. package/dist/v8/analytics/runtime/modules/commerce.d.ts +2 -0
  10. package/dist/v8/analytics/runtime/modules/commerce.d.ts.map +1 -0
  11. package/dist/v8/analytics/runtime/modules/commerce.js +41 -0
  12. package/dist/v8/analytics/runtime/modules/commerce.js.map +1 -0
  13. package/dist/v8/analytics/runtime/modules/consent.d.ts +33 -0
  14. package/dist/v8/analytics/runtime/modules/consent.d.ts.map +1 -0
  15. package/dist/v8/analytics/runtime/modules/consent.js +154 -0
  16. package/dist/v8/analytics/runtime/modules/consent.js.map +1 -0
  17. package/dist/v8/analytics/runtime/modules/deco.d.ts +2 -0
  18. package/dist/v8/analytics/runtime/modules/deco.d.ts.map +1 -0
  19. package/dist/v8/analytics/runtime/modules/deco.js +209 -0
  20. package/dist/v8/analytics/runtime/modules/deco.js.map +1 -0
  21. package/dist/v8/analytics/runtime/modules/engagement.d.ts +2 -0
  22. package/dist/v8/analytics/runtime/modules/engagement.d.ts.map +1 -0
  23. package/dist/v8/analytics/runtime/modules/engagement.js +128 -0
  24. package/dist/v8/analytics/runtime/modules/engagement.js.map +1 -0
  25. package/dist/v8/analytics/runtime/modules/errors.d.ts +2 -0
  26. package/dist/v8/analytics/runtime/modules/errors.d.ts.map +1 -0
  27. package/dist/v8/analytics/runtime/modules/errors.js +167 -0
  28. package/dist/v8/analytics/runtime/modules/errors.js.map +1 -0
  29. package/dist/v8/analytics/runtime/modules/heatmap.d.ts +2 -0
  30. package/dist/v8/analytics/runtime/modules/heatmap.d.ts.map +1 -0
  31. package/dist/v8/analytics/runtime/modules/heatmap.js +316 -0
  32. package/dist/v8/analytics/runtime/modules/heatmap.js.map +1 -0
  33. package/dist/v8/analytics/runtime/modules/vitals.d.ts +2 -0
  34. package/dist/v8/analytics/runtime/modules/vitals.d.ts.map +1 -0
  35. package/dist/v8/analytics/runtime/modules/vitals.js +119 -0
  36. package/dist/v8/analytics/runtime/modules/vitals.js.map +1 -0
  37. package/dist/v8/analytics/runtime/src/guards.d.ts +10 -0
  38. package/dist/v8/analytics/runtime/src/guards.d.ts.map +1 -0
  39. package/dist/v8/analytics/runtime/src/guards.js +70 -0
  40. package/dist/v8/analytics/runtime/src/guards.js.map +1 -0
  41. package/dist/v8/analytics/runtime/src/index.d.ts +2 -0
  42. package/dist/v8/analytics/runtime/src/index.d.ts.map +1 -0
  43. package/dist/v8/analytics/runtime/src/index.js +562 -0
  44. package/dist/v8/analytics/runtime/src/index.js.map +1 -0
  45. package/dist/v8/analytics/runtime/src/queue.d.ts +15 -0
  46. package/dist/v8/analytics/runtime/src/queue.d.ts.map +1 -0
  47. package/dist/v8/analytics/runtime/src/queue.js +36 -0
  48. package/dist/v8/analytics/runtime/src/queue.js.map +1 -0
  49. package/dist/v8/analytics/runtime/src/trim.d.ts +13 -0
  50. package/dist/v8/analytics/runtime/src/trim.d.ts.map +1 -0
  51. package/dist/v8/analytics/runtime/src/trim.js +38 -0
  52. package/dist/v8/analytics/runtime/src/trim.js.map +1 -0
  53. package/dist/v8/analytics/runtime/view/heat-core.d.ts +69 -0
  54. package/dist/v8/analytics/runtime/view/heat-core.d.ts.map +1 -0
  55. package/dist/v8/analytics/runtime/view/heat-core.js +314 -0
  56. package/dist/v8/analytics/runtime/view/heat-core.js.map +1 -0
  57. package/dist/v8/analytics/runtime/view/view.d.ts +51 -0
  58. package/dist/v8/analytics/runtime/view/view.d.ts.map +1 -0
  59. package/dist/v8/analytics/runtime/view/view.js +525 -0
  60. package/dist/v8/analytics/runtime/view/view.js.map +1 -0
  61. package/dist/v8/analytics/shared/anchor.d.ts +71 -0
  62. package/dist/v8/analytics/shared/anchor.d.ts.map +1 -0
  63. package/dist/v8/analytics/shared/anchor.js +155 -0
  64. package/dist/v8/analytics/shared/anchor.js.map +1 -0
  65. package/dist/v8/analytics/shared/contract.d.ts +294 -0
  66. package/dist/v8/analytics/shared/contract.d.ts.map +1 -0
  67. package/dist/v8/analytics/shared/contract.js +652 -0
  68. package/dist/v8/analytics/shared/contract.js.map +1 -0
  69. package/package.json +6 -1
  70. package/src/v8/analytics/client.ts +110 -0
  71. package/src/v8/analytics/runtime/globals.d.ts +36 -0
  72. package/src/v8/analytics/runtime/modules/click.ts +54 -0
  73. package/src/v8/analytics/runtime/modules/commerce.ts +73 -0
  74. package/src/v8/analytics/runtime/modules/consent.ts +150 -0
  75. package/src/v8/analytics/runtime/modules/deco.ts +207 -0
  76. package/src/v8/analytics/runtime/modules/engagement.ts +140 -0
  77. package/src/v8/analytics/runtime/modules/errors.ts +217 -0
  78. package/src/v8/analytics/runtime/modules/heatmap.ts +360 -0
  79. package/src/v8/analytics/runtime/modules/vitals.ts +128 -0
  80. package/src/v8/analytics/runtime/src/guards.ts +70 -0
  81. package/src/v8/analytics/runtime/src/index.ts +606 -0
  82. package/src/v8/analytics/runtime/src/queue.ts +40 -0
  83. package/src/v8/analytics/runtime/src/trim.ts +39 -0
  84. package/src/v8/analytics/runtime/view/heat-core.ts +335 -0
  85. package/src/v8/analytics/runtime/view/view.ts +596 -0
  86. package/src/v8/analytics/shared/anchor.ts +171 -0
  87. package/src/v8/analytics/shared/contract.ts +691 -0
  88. package/src/v8/analytics/tsconfig.json +14 -0
@@ -0,0 +1,596 @@
1
+ /** View mode: the heatmap drawn over the LIVE site, inside Studio's iframe.
2
+ *
3
+ * Loaded by core ONLY when the page is framed and its URL carries `dq_view=1` (core then
4
+ * collects nothing at all: no pageview, no module, no beacon). A normal visitor never downloads
5
+ * this file. Everything here runs on the site's own origin, so it can hash the live DOM with the
6
+ * same `shared/anchor.ts` the runtime used on the click, measure boxes, and read element labels --
7
+ * which go to the parent frame and nowhere else.
8
+ *
9
+ * Trust: nothing is sent and nothing is accepted until a parent from the allow-list
10
+ * (`https://*.decocms.com`, localhost for development) sends `init`. From then on that one
11
+ * origin is pinned: every outgoing message is addressed to it, every incoming one must come from
12
+ * it and from `window.parent`. Protocol, versioned: docs/RUNTIME_API.md -> "View mode".
13
+ *
14
+ * The drawing is the insights-mcp PAGE_HEATMAP viewer's (heat-core.ts ported verbatim, heat-child
15
+ * adapted from a static snapshot to a live page): Gaussian density with p99 normalisation, the
16
+ * Térmica / Inferno ramps, scroll reach and fold lines, attention bands, section blocks.
17
+ */
18
+ import { anchorHash } from "../../shared/anchor.ts";
19
+ import { heatCore } from "./heat-core.ts";
20
+
21
+ export const VIEW_PROTOCOL = 1;
22
+ export const ALLOWED_PARENT =
23
+ /^(https:\/\/([a-z0-9-]+\.)*decocms\.com|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)$/;
24
+
25
+ type Row = Record<string, unknown>;
26
+ type Mode = "clicks" | "scroll" | "attention" | "sections";
27
+ export interface ViewData {
28
+ mode: Mode;
29
+ /** hmElements rows as the read surface returns them; `clicks` may be replaced by the parent
30
+ * with the weight of the selected click type (rage, dead, ...). */
31
+ elements: {
32
+ root: string;
33
+ el: string;
34
+ clicks: number | string;
35
+ cells?: Row | [number, number][];
36
+ }[];
37
+ grid?: { fixed: number | boolean; xb: number; yb: number; clicks: number | string }[];
38
+ /** hmScroll rows. */
39
+ depth?: { depth: number; views: number | string }[];
40
+ /** hmAttention rows. */
41
+ attention?: { band: number; ds: number | string }[];
42
+ /** hmSections rows. */
43
+ sections?: { root: string; reach_pct: number; avg_s: number; clicks?: number | string }[];
44
+ views?: number;
45
+ /** hmSummary.avg_fold (percent of the document). */
46
+ avgFold?: number | null;
47
+ scale?: number;
48
+ ramp?: "thermal" | "inferno";
49
+ opacity?: number;
50
+ log?: boolean;
51
+ radius?: number;
52
+ /** Share of grid clicks to paint for elements not on this page version (0 = none). */
53
+ gridShare?: number;
54
+ }
55
+
56
+ const H = heatCore();
57
+ const n = (v: unknown) => Number(v) || 0;
58
+ /** The read surface sends `el` in decimal (UInt64); the wire and anchor.ts use base36. */
59
+ const dec = (el: string) => (/^\d+$/.test(el) ? el : String(parseInt(el, 36)));
60
+ const norm = (s: string | null | undefined) => (s ?? "").replace(/\s+/g, " ").trim();
61
+
62
+ export function startView(win: Window = window) {
63
+ const doc = win.document,
64
+ root = doc.documentElement;
65
+ let origin = "";
66
+ const post = (m: Row) => {
67
+ if (origin) win.parent.postMessage({ dq: "hm", v: VIEW_PROTOCOL, ...m }, origin);
68
+ };
69
+
70
+ const css = doc.createElement("style");
71
+ css.textContent = `
72
+ dialog, [role=dialog], [aria-modal=true] { display: none !important; }
73
+ *, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; animation-iteration-count: 1 !important; transition: none !important; }
74
+ html { cursor: crosshair; }
75
+ .__hm { position: absolute; left: 0; top: 0; z-index: 2147483000; pointer-events: none; overflow: hidden; }
76
+ .__heat, .__wash { position: absolute; left: 0; top: 0; display: none; opacity: var(--op, .85); }
77
+ .__wash { width: 100%; height: 100%; mix-blend-mode: multiply; }
78
+ .__marks { position: absolute; inset: 0; }
79
+ .__line { position: absolute; left: 0; right: 0; height: 0; border-top: 2px dashed rgba(17,20,24,.85); }
80
+ .__line span { position: absolute; right: 12px; top: -13px; font: 600 12px/1 system-ui, -apple-system, "Segoe UI", sans-serif;
81
+ color: #fff; background: rgba(17,20,24,.88); padding: 6px 9px; border-radius: 999px; white-space: nowrap; }
82
+ .__line.__fold { border-top-color: #fff; box-shadow: 0 0 0 1px rgba(17,20,24,.5); }
83
+ .__line.__fold span { left: 12px; right: auto; background: #fff; color: #111418; box-shadow: 0 2px 10px rgba(0,0,0,.25); }
84
+ .__zone { position: absolute; box-sizing: border-box; border: 1.5px dashed rgba(17,20,24,.38); border-radius: 6px; }
85
+ .__zone span { position: absolute; right: 8px; top: 8px; font: 600 11.5px/1.2 system-ui, -apple-system, "Segoe UI", sans-serif; color: #fff;
86
+ background: rgba(17,20,24,.78); padding: 5px 9px; border-radius: 999px; white-space: nowrap; }
87
+ .__block { position: absolute; left: 0; right: 0; box-sizing: border-box; border: 3px solid var(--c); background: var(--f); }
88
+ .__block div { position: absolute; left: 10px; top: 10px; display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: baseline;
89
+ font: 500 13.5px/1.25 system-ui, -apple-system, "Segoe UI", sans-serif; color: #111418; background: rgba(255,255,255,.94);
90
+ padding: 7px 11px; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,.18); max-width: calc(100% - 20px); }
91
+ .__block div b { font-weight: 700; }
92
+ .__hl { position: absolute; display: none; box-sizing: border-box; border: 2px solid #fff; border-radius: 6px;
93
+ box-shadow: 0 0 0 2px #111418, 0 0 0 9999px rgba(17,20,24,.18); }`;
94
+ const mk = (cls: string, tag = "div") => {
95
+ const e = doc.createElement(tag);
96
+ e.className = cls;
97
+ return e;
98
+ };
99
+ const layer = mk("__hm"),
100
+ canvas = mk("__heat", "canvas") as HTMLCanvasElement,
101
+ wash = mk("__wash"),
102
+ marks = mk("__marks"),
103
+ hl = mk("__hl");
104
+ for (const c of [canvas, wash, marks, hl]) layer.appendChild(c);
105
+ const ours = (x: Node | null) => !!x && (x === layer || layer.contains(x) || x === css);
106
+
107
+ let data: ViewData | null = null;
108
+ let index = new Map<string, Element>(); // `${root}|${el decimal}` -> live element
109
+ let roots = new Map<string, Element>(); // root identity -> live element
110
+ let keyOf = new WeakMap<Element, string>(); // element -> key, for hover
111
+ let active: string | null = null,
112
+ hoverKey: string | null = null,
113
+ want = new Set<string>();
114
+ let docW = 0,
115
+ docH = 0;
116
+ let blocks: { key: string; y: number; h: number }[] = [];
117
+
118
+ /** Hash every element of the live page: any element can be an anchor (a click on plain text
119
+ * anchors on its target). Re-run on every snapshot, so it describes the page the heat is on. */
120
+ function reindex() {
121
+ index = new Map();
122
+ roots = new Map();
123
+ keyOf = new WeakMap();
124
+ for (const el of Array.from(doc.body.querySelectorAll("*"))) {
125
+ if (ours(el)) continue;
126
+ const h = anchorHash(el);
127
+ const k = `${h.root}|${parseInt(h.el, 36)}`;
128
+ if (!index.has(k)) index.set(k, el);
129
+ keyOf.set(el, k);
130
+ if (h.rootEl && !roots.has(h.root)) roots.set(h.root, h.rootEl);
131
+ }
132
+ }
133
+
134
+ const box = (el: Element | null | undefined) => {
135
+ if (!el) return null;
136
+ const r = el.getBoundingClientRect();
137
+ if (r.width < 2 || r.height < 2) return null;
138
+ const x = r.left + win.scrollX;
139
+ if (x >= docW - 1 || x + r.width <= 1) return null; // off-canvas slide / drawer
140
+ const cs = win.getComputedStyle(el);
141
+ if (cs.visibility === "hidden" || cs.opacity === "0") return null;
142
+ return { x, y: r.top + win.scrollY, w: r.width, h: r.height };
143
+ };
144
+
145
+ /** What a person would call the element. Read here, sent to the parent only. */
146
+ function labelOf(el: Element): string {
147
+ const a = norm(
148
+ el.getAttribute("aria-label") ?? el.getAttribute("alt") ?? el.getAttribute("title"),
149
+ );
150
+ if (a) return a.slice(0, 60);
151
+ const t = norm((el as HTMLElement).innerText ?? el.textContent);
152
+ if (t) return t.length > 48 ? `${t.slice(0, 46)}…` : t;
153
+ const img = el.querySelector("img[alt], [aria-label]");
154
+ const inner = norm(img?.getAttribute("alt") ?? img?.getAttribute("aria-label"));
155
+ if (inner) return inner.slice(0, 60);
156
+ const href = el.getAttribute("href");
157
+ if (href) {
158
+ try {
159
+ const u = new URL(href, doc.baseURI);
160
+ return u.pathname === "/"
161
+ ? "Link para a home"
162
+ : `Link para ${decodeURIComponent(u.pathname)}`;
163
+ } catch {
164
+ /* fall through */
165
+ }
166
+ }
167
+ return el.tagName === "IMG" ? "Imagem" : `<${el.tagName.toLowerCase()}>`;
168
+ }
169
+ const rootName = (r: string) => {
170
+ if (!r) return "Página";
171
+ if (r.startsWith("#")) return r;
172
+ const i = r.lastIndexOf("#"),
173
+ ord = Number(r.slice(i + 1)),
174
+ p = r.slice(0, i);
175
+ const base = p.startsWith("fs:")
176
+ ? p
177
+ .slice(3)
178
+ .replace(/-/g, " ")
179
+ .replace(/^./, (c) => c.toUpperCase())
180
+ : (p.split("/").pop() ?? p).replace(/\.tsx?$/, "");
181
+ return ord > 0 ? `${base} ${ord + 1}` : base;
182
+ };
183
+
184
+ function line(y: number, text: string, kind: string) {
185
+ const d = mk(`__line __${kind}`);
186
+ d.style.top = `${y}px`;
187
+ const s = doc.createElement("span");
188
+ s.textContent = text;
189
+ d.appendChild(s);
190
+ marks.appendChild(d);
191
+ }
192
+ function bands(values: ArrayLike<number>, ramp: string) {
193
+ const stops: string[] = [];
194
+ for (let i = 0; i < values.length; i++) {
195
+ stops.push(
196
+ `${H.rampCss(ramp, values[i], 0.16 + 0.44 * values[i])} ${(((i + 0.5) / values.length) * 100).toFixed(2)}%`,
197
+ );
198
+ }
199
+ wash.style.background = `linear-gradient(to bottom, ${stops.join(",")})`;
200
+ wash.style.display = "block";
201
+ }
202
+
203
+ function draw() {
204
+ if (!data || !origin) return;
205
+ if (!layer.isConnected) root.appendChild(layer);
206
+ if (!css.isConnected) (doc.head ?? root).appendChild(css);
207
+ const d = data,
208
+ ramp = d.ramp ?? "thermal",
209
+ views = Math.max(1, n(d.views));
210
+ docW = root.clientWidth;
211
+ docH = Math.max(doc.body.scrollHeight, root.scrollHeight);
212
+ layer.style.width = `${docW}px`;
213
+ layer.style.height = `${docH}px`;
214
+ layer.style.setProperty("--op", String(d.opacity ?? 0.85));
215
+ marks.textContent = "";
216
+ canvas.style.display = "none";
217
+ wash.style.display = "none";
218
+
219
+ const els = d.elements.map((e) => {
220
+ const cells = Array.isArray(e.cells)
221
+ ? e.cells
222
+ : Object.entries(e.cells ?? {}).map(([c, v]) => [Number(c), n(v)] as [number, number]);
223
+ return {
224
+ key: `${e.root}|${dec(String(e.el))}`,
225
+ sec: e.root,
226
+ el: dec(String(e.el)),
227
+ clicks: n(e.clicks),
228
+ cells,
229
+ };
230
+ });
231
+ const radius = d.radius ?? H.radiusFor(H.deviceOf(win.innerWidth) || "desktop");
232
+ const placed = H.place(
233
+ els,
234
+ (sec, el) => box(index.get(`${sec}|${el}`)),
235
+ (sec) => box(roots.get(sec)),
236
+ radius,
237
+ );
238
+ const reach = H.reachCurve(
239
+ (d.depth ?? []).map((r) => [n(r.depth), n(r.views)]),
240
+ views,
241
+ );
242
+ let legend: number[] = [];
243
+
244
+ if (d.mode === "clicks") {
245
+ const grid = d.grid ?? [];
246
+ const gridTotal = grid.reduce((s, g) => s + n(g.clicks), 0);
247
+ const missing = placed.total - placed.matchedClicks - placed.sectionClicks;
248
+ // ponytail: grid scaled by the unplaced share, not per-click exclusion (same as the viewer).
249
+ const share = gridTotal > 0 ? Math.min(1, (missing / gridTotal) * (d.gridShare ?? 1)) : 0;
250
+ const gp =
251
+ share > 0
252
+ ? H.gridPoints(
253
+ grid.map((g) => ({ fixed: !!g.fixed, xb: g.xb, yb: g.yb, clicks: n(g.clicks) })),
254
+ docW,
255
+ ).map(([x, y, w]) => [x, y, w * share] as [number, number, number])
256
+ : [];
257
+ const cell = Math.max(3, Math.ceil(docH / 30000));
258
+ const cur = H.density([...placed.points, ...gp], docW, docH, cell, radius);
259
+ canvas.width = cur.cols;
260
+ canvas.height = cur.rows;
261
+ canvas.style.width = `${cur.cols * cell}px`;
262
+ canvas.style.height = `${cur.rows * cell}px`;
263
+ // One sort for the p99 normalisation and the legend, not four.
264
+ const q = H.quantiles(cur.field, [0.5, 0.9, 0.99]);
265
+ const px = H.colorize(cur.field, q[2], H.lut(ramp), !!d.log);
266
+ canvas
267
+ .getContext("2d")!
268
+ .putImageData(
269
+ new ImageData(px as unknown as Uint8ClampedArray<ArrayBuffer>, cur.cols, cur.rows),
270
+ 0,
271
+ 0,
272
+ );
273
+ canvas.style.display = "block";
274
+ const area = (Math.PI * (radius / 2) ** 2 * 2) / (cell * cell);
275
+ legend = q.map((v) => v * area);
276
+ for (const [sec, z] of placed.sections) {
277
+ const zone = mk("__zone");
278
+ zone.style.cssText = `left:${z.box.x}px;top:${z.box.y}px;width:${z.box.w}px;height:${z.box.h}px`;
279
+ const chip = doc.createElement("span");
280
+ chip.textContent = `${Math.round(z.clicks * (d.scale ?? 1)).toLocaleString("pt-BR")} cliques em itens escondidos ou que mudaram`;
281
+ zone.appendChild(chip);
282
+ zone.dataset.key = `sec:${sec}`;
283
+ marks.appendChild(zone);
284
+ }
285
+ } else if (d.mode === "scroll") {
286
+ bands(
287
+ Array.from({ length: 100 }, (_, i) => reach[i]),
288
+ ramp,
289
+ );
290
+ if (d.avgFold)
291
+ line((d.avgFold / 100) * docH, `Dobra média, ${Math.round(d.avgFold)}% da página`, "fold");
292
+ for (const s of [0.75, 0.5, 0.25]) {
293
+ const at = H.depthAtReach(reach, s);
294
+ if (at < 100) line((at / 100) * docH, `${Math.round(s * 100)}% chegaram até aqui`, "reach");
295
+ }
296
+ } else if (d.mode === "attention") {
297
+ const b = H.attentionBands((d.attention ?? []).map((r) => [n(r.band), n(r.ds)]));
298
+ const max = Math.max(...b) || 1;
299
+ bands(
300
+ Array.from(b, (v) => v / max),
301
+ ramp,
302
+ );
303
+ legend = [max / 10 / views];
304
+ }
305
+
306
+ // Blocks: every Deco section / FastStore component root on this page, with what the read
307
+ // surface knows about it.
308
+ const stats = new Map((d.sections ?? []).map((s) => [s.root, s]));
309
+ const clicksBy = new Map<string, number>();
310
+ for (const e of els) clicksBy.set(e.sec, (clicksBy.get(e.sec) ?? 0) + e.clicks);
311
+ const out = [...roots]
312
+ .filter(([k]) => k && !k.startsWith("#"))
313
+ .flatMap(([key, el]) => {
314
+ const b = box(el);
315
+ if (!b) return [];
316
+ const s = stats.get(key);
317
+ return [
318
+ {
319
+ key,
320
+ name: rootName(key),
321
+ heading: norm(el.querySelector("h1, h2, h3")?.textContent).slice(0, 60),
322
+ y: b.y,
323
+ h: b.h,
324
+ clicks: clicksBy.get(key) ?? 0,
325
+ reach: s
326
+ ? n(s.reach_pct) / 100
327
+ : d.depth?.length
328
+ ? reach[Math.min(100, Math.floor((b.y / docH) * 100))]
329
+ : null,
330
+ seconds: s ? n(s.avg_s) : null,
331
+ },
332
+ ];
333
+ })
334
+ .sort((a, b) => a.y - b.y);
335
+ blocks = out.map(({ key, y, h }) => ({ key, y, h }));
336
+ if (d.mode === "sections") {
337
+ const maxC = Math.max(1, ...out.map((b) => b.clicks));
338
+ for (const b of out) {
339
+ const z = mk("__block"),
340
+ t = b.clicks / maxC;
341
+ z.dataset.key = `blk:${b.key}`;
342
+ z.style.cssText = `top:${b.y}px;height:${b.h}px;--c:${H.rampCss(ramp, 0.15 + 0.85 * t, 1)};--f:${H.rampCss(ramp, 0.15 + 0.85 * t, 0.08 + 0.2 * t)}`;
343
+ const chip = doc.createElement("div");
344
+ const parts = [
345
+ b.name,
346
+ `${Math.round(b.clicks * (d.scale ?? 1)).toLocaleString("pt-BR")} cliques`,
347
+ ];
348
+ if (b.reach != null) parts.push(`${Math.round(b.reach * 100)}% viram`);
349
+ if (b.seconds != null) parts.push(`${b.seconds.toFixed(1)} s em média`);
350
+ for (const p of parts) {
351
+ const s = doc.createElement(p === b.name ? "b" : "span");
352
+ s.textContent = p;
353
+ chip.appendChild(s);
354
+ }
355
+ z.appendChild(chip);
356
+ marks.appendChild(z);
357
+ }
358
+ }
359
+
360
+ paint(false);
361
+ const items = els.map((e) => {
362
+ const node = index.get(e.key),
363
+ b = box(node);
364
+ return {
365
+ key: e.key,
366
+ label: node ? labelOf(node) : "",
367
+ found: b ? "el" : placed.sections.has(e.sec) ? "sec" : "none",
368
+ y: b ? b.y : (placed.sections.get(e.sec)?.box.y ?? -1),
369
+ h: b ? b.h : 0,
370
+ };
371
+ });
372
+ post({
373
+ t: "placed",
374
+ items,
375
+ blocks: out,
376
+ height: docH,
377
+ width: docW,
378
+ legend,
379
+ stats: {
380
+ matched: placed.matchedClicks,
381
+ inSection: placed.sectionClicks,
382
+ total: placed.total,
383
+ matchRate: placed.total ? placed.matchedClicks / placed.total : null,
384
+ },
385
+ });
386
+ }
387
+
388
+ const boxOfKey = (key: string) => {
389
+ if (key.startsWith("blk:")) {
390
+ const b = blocks.find((x) => `blk:${x.key}` === key);
391
+ return b ? { x: 0, y: b.y, w: docW, h: b.h } : null;
392
+ }
393
+ return box(index.get(key));
394
+ };
395
+ function paint(scroll: boolean) {
396
+ const k = hoverKey ?? active,
397
+ b = k ? boxOfKey(k) : null;
398
+ if (!b) {
399
+ hl.style.display = "none";
400
+ return;
401
+ }
402
+ hl.style.cssText = `display:block;left:${b.x - 3}px;top:${b.y - 3}px;width:${b.w + 6}px;height:${b.h + 6}px`;
403
+ if (scroll) win.scrollTo({ top: Math.max(0, b.y - win.innerHeight / 3), behavior: "smooth" });
404
+ }
405
+
406
+ // ---- the print: the heat is drawn once and stays put -------------------------------------
407
+ // Redrawing it against the live DOM on every scroll frame and every mutation (carousels, lazy
408
+ // images) kept the store's main thread busy and made the page stutter. So the heat is a snapshot:
409
+ // hash the page, place, paint, and leave it. It is taken again only when what it shows changes:
410
+ // new data from the parent, a new width, a page that grew or shrank once it went quiet, and when
411
+ // someone comes back to the tab. In between the page stays live underneath (it scrolls, carousels
412
+ // turn, links hover); the heat does not follow it.
413
+ //
414
+ // There is deliberately NO clock. A periodic retake brings no new numbers -- the print redraws
415
+ // the page as it is NOW, and fresher figures only ever arrive as `data` -- so all it could do was
416
+ // spend a full re-hash and draw on the store's page at an arbitrary moment. Its one real job is
417
+ // healing drift (a carousel moved, a section swapped), and `visibilitychange` does that job
418
+ // better: it costs nothing while nobody is looking and fires exactly when someone looks again.
419
+ const QUIET_MS = 1000;
420
+ let timer = 0,
421
+ quiet = 0,
422
+ snapW = 0,
423
+ snapH = 0;
424
+ const snap = () => {
425
+ win.clearTimeout(timer);
426
+ timer = 0;
427
+ if (!data) return;
428
+ reindex();
429
+ draw();
430
+ snapW = docW;
431
+ snapH = docH;
432
+ };
433
+ const soon = () => {
434
+ if (!timer) timer = win.setTimeout(snap, 250);
435
+ };
436
+ /** Cleared with the overlay: a frame nobody is looking at holds no timer at all. This is the
437
+ * store's own page, and the tab can be left framed for a working day. */
438
+ const stop = () => {
439
+ win.clearTimeout(timer);
440
+ timer = 0;
441
+ win.clearTimeout(quiet);
442
+ quiet = 0;
443
+ snapW = snapH = 0;
444
+ };
445
+ /** A height change is acted on only after QUIET_MS without one, and never mid-scroll: lazy
446
+ * content arrives in bursts, and one snapshot after it settles is the one worth taking. */
447
+ const settle = () => {
448
+ win.clearTimeout(quiet);
449
+ quiet = win.setTimeout(() => {
450
+ quiet = 0;
451
+ if (data && Math.max(doc.body.scrollHeight, root.scrollHeight) !== snapH) soon();
452
+ }, QUIET_MS);
453
+ };
454
+ new ResizeObserver(settle).observe(doc.body);
455
+ win.addEventListener(
456
+ "resize",
457
+ () => {
458
+ if (data && root.clientWidth !== snapW) soon();
459
+ },
460
+ { passive: true },
461
+ );
462
+ win.addEventListener(
463
+ "scroll",
464
+ () => {
465
+ post({ t: "scroll", top: win.scrollY, vh: win.innerHeight, dh: docH });
466
+ if (quiet) settle();
467
+ },
468
+ { passive: true },
469
+ );
470
+ // Back to the tab after it was elsewhere: whatever the page did meanwhile, the print is redrawn
471
+ // over it before anyone reads it.
472
+ doc.addEventListener("visibilitychange", () => {
473
+ if (data && doc.visibilityState === "visible") soon();
474
+ });
475
+
476
+ // ---- hover and select: the page is a picture, nothing navigates -----------------------------
477
+ let mraf = 0;
478
+ doc.addEventListener(
479
+ "mousemove",
480
+ (ev) => {
481
+ if (mraf || !data) return;
482
+ mraf = win.requestAnimationFrame(() => {
483
+ mraf = 0;
484
+ const y = ev.clientY + win.scrollY;
485
+ if (data!.mode === "scroll" || data!.mode === "attention") {
486
+ post({
487
+ t: "hover",
488
+ key: null,
489
+ x: ev.clientX,
490
+ y: ev.clientY,
491
+ pct: docH ? Math.min(1, y / docH) : 0,
492
+ });
493
+ return;
494
+ }
495
+ let key: string | null = null;
496
+ if (data!.mode === "sections") {
497
+ const b = blocks.find((x) => y >= x.y && y <= x.y + x.h);
498
+ key = b ? `blk:${b.key}` : null;
499
+ } else {
500
+ for (
501
+ let el = doc.elementFromPoint(ev.clientX, ev.clientY);
502
+ el && el !== doc.body && !key;
503
+ el = el.parentElement
504
+ ) {
505
+ const k = keyOf.get(el);
506
+ if (k && want.has(k)) key = k;
507
+ }
508
+ }
509
+ if (key === hoverKey) return;
510
+ hoverKey = key;
511
+ paint(false);
512
+ const el = key && !key.startsWith("blk:") ? index.get(key) : null;
513
+ post({ t: "hover", key, label: el ? labelOf(el) : null, x: ev.clientX, y: ev.clientY });
514
+ });
515
+ },
516
+ { passive: true },
517
+ );
518
+ doc.addEventListener("mouseleave", () => {
519
+ hoverKey = null;
520
+ paint(false);
521
+ post({ t: "hover", key: null });
522
+ });
523
+ const block = (ev: Event) => {
524
+ ev.preventDefault();
525
+ ev.stopPropagation();
526
+ };
527
+ doc.addEventListener(
528
+ "click",
529
+ (ev) => {
530
+ block(ev);
531
+ if (hoverKey) post({ t: "select", key: hoverKey });
532
+ },
533
+ true,
534
+ );
535
+ doc.addEventListener("submit", block, true);
536
+ doc.addEventListener("auxclick", block, true);
537
+
538
+ // ---- the protocol ---------------------------------------------------------------------------
539
+ win.addEventListener("message", (e: MessageEvent) => {
540
+ if (e.source !== win.parent || !e.data || e.data.dq !== "hm") return;
541
+ if (!origin) {
542
+ // The handshake: the first message must be `init` from an allowed origin. It pins that origin.
543
+ if (e.data.t !== "init" || !ALLOWED_PARENT.test(e.origin)) return;
544
+ origin = e.origin;
545
+ reindex();
546
+ post({
547
+ t: "ready",
548
+ protocol: VIEW_PROTOCOL,
549
+ url: win.location.href,
550
+ title: doc.title,
551
+ width: root.clientWidth,
552
+ height: Math.max(doc.body.scrollHeight, root.scrollHeight),
553
+ anchors: index.size,
554
+ });
555
+ return;
556
+ }
557
+ if (e.origin !== origin) return;
558
+ const m = e.data;
559
+ if (m.t === "init")
560
+ post({
561
+ t: "ready",
562
+ protocol: VIEW_PROTOCOL,
563
+ url: win.location.href,
564
+ title: doc.title,
565
+ width: root.clientWidth,
566
+ height: docH,
567
+ anchors: index.size,
568
+ });
569
+ else if (m.t === "data" && m.d) {
570
+ data = m.d as ViewData;
571
+ want = new Set(data.elements.map((x) => `${x.root}|${dec(String(x.el))}`));
572
+ soon();
573
+ } else if (m.t === "highlight") {
574
+ active = typeof m.key === "string" ? m.key : null;
575
+ paint(!!m.scroll);
576
+ } else if (m.t === "scrollTo") {
577
+ const b = typeof m.key === "string" ? boxOfKey(m.key) : null;
578
+ win.scrollTo({
579
+ top: b ? Math.max(0, b.y - win.innerHeight / 3) : n(m.y),
580
+ behavior: "smooth",
581
+ });
582
+ } else if (m.t === "clear") {
583
+ data = null;
584
+ stop();
585
+ layer.remove();
586
+ css.remove();
587
+ }
588
+ });
589
+ // Exposed for tests only: the hash this view computes for an element, same as the runtime's.
590
+ (win as any).__dqViewKey = (el: Element) => {
591
+ const h = anchorHash(el);
592
+ return `${h.root}|${parseInt(h.el, 36)}`;
593
+ };
594
+ }
595
+
596
+ startView();