@preprio/toolkit 0.6.0-alpha.9 → 1.0.0-rc.2

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 (116) hide show
  1. package/README.md +111 -1363
  2. package/dist/astro/index.cjs +1555 -182
  3. package/dist/astro/index.d.cts +201 -1
  4. package/dist/astro/index.d.ts +201 -1
  5. package/dist/astro/index.js +1557 -29
  6. package/dist/chunk-A2J7R4LR.js +256 -0
  7. package/dist/{chunk-5QIWVDP2.js → chunk-DBKZWOXA.js} +1 -1
  8. package/dist/{chunk-WQBKQG4R.js → chunk-EWXBE3JD.js} +6 -1
  9. package/dist/chunk-KM2GME62.js +1255 -0
  10. package/dist/{chunk-J66UOCK6.js → chunk-LJA5K4KM.js} +1680 -579
  11. package/dist/chunk-UTKH7DOI.js +58 -0
  12. package/dist/chunk-V7MCHPE7.js +85 -0
  13. package/dist/chunk-Y7JWV7WV.js +374 -0
  14. package/dist/codegen/index.cjs +82 -0
  15. package/dist/codegen/index.d.cts +70 -0
  16. package/dist/codegen/index.d.ts +70 -0
  17. package/dist/codegen/index.js +64 -0
  18. package/dist/index.cjs +3729 -553
  19. package/dist/index.d.cts +403 -19
  20. package/dist/index.d.ts +403 -19
  21. package/dist/index.js +345 -24
  22. package/dist/live-preview-HCBNBC6C.js +19 -0
  23. package/dist/nextjs/components.cjs +1872 -754
  24. package/dist/nextjs/components.d.cts +5 -51
  25. package/dist/nextjs/components.d.ts +5 -51
  26. package/dist/nextjs/components.js +8 -299
  27. package/dist/nextjs/index.cjs +1228 -181
  28. package/dist/nextjs/index.d.cts +247 -92
  29. package/dist/nextjs/index.d.ts +247 -92
  30. package/dist/nextjs/index.js +1629 -111
  31. package/dist/nextjs/live-action.cjs +298 -0
  32. package/dist/nextjs/live-action.d.cts +12 -0
  33. package/dist/nextjs/live-action.d.ts +12 -0
  34. package/dist/nextjs/live-action.js +68 -0
  35. package/dist/nextjs/live.cjs +2010 -0
  36. package/dist/nextjs/live.d.cts +54 -0
  37. package/dist/nextjs/live.d.ts +54 -0
  38. package/dist/nextjs/live.js +287 -0
  39. package/dist/nuxt/chunk-5RBZPRQN.js +350 -0
  40. package/dist/nuxt/chunk-LUKVPOJ2.js +32 -0
  41. package/dist/nuxt/index.cjs +15 -16
  42. package/dist/nuxt/index.d.cts +167 -6
  43. package/dist/nuxt/index.d.ts +167 -6
  44. package/dist/nuxt/index.js +402 -15
  45. package/dist/nuxt/live-preview-KO4IKWTX.js +1234 -0
  46. package/dist/nuxt/live.cjs +1928 -0
  47. package/dist/nuxt/live.d.cts +45 -0
  48. package/dist/nuxt/live.d.ts +45 -0
  49. package/dist/nuxt/live.js +216 -0
  50. package/dist/{types-BYH9XqmN.d.cts → pixel-DqU7NvgW.d.cts} +102 -5
  51. package/dist/{types-BYH9XqmN.d.ts → pixel-DqU7NvgW.d.ts} +102 -5
  52. package/dist/react/components.cjs +1865 -480
  53. package/dist/react/components.d.cts +43 -8
  54. package/dist/react/components.d.ts +43 -8
  55. package/dist/react/components.js +1865 -480
  56. package/dist/sveltekit/chunk-5RBZPRQN.js +350 -0
  57. package/dist/sveltekit/chunk-LUKVPOJ2.js +32 -0
  58. package/dist/sveltekit/index.cjs +15 -16
  59. package/dist/sveltekit/index.d.cts +111 -10
  60. package/dist/sveltekit/index.d.ts +111 -10
  61. package/dist/sveltekit/index.js +398 -15
  62. package/dist/sveltekit/live-preview-KO4IKWTX.js +1234 -0
  63. package/dist/sveltekit/live.cjs +1940 -0
  64. package/dist/sveltekit/live.d.cts +61 -0
  65. package/dist/sveltekit/live.d.ts +61 -0
  66. package/dist/sveltekit/live.js +220 -0
  67. package/package.json +132 -71
  68. package/src/astro/PreprToolbar.astro +7 -1
  69. package/src/astro/PreprTrackingPixel.astro +2 -4
  70. package/src/nuxt/PreprToolbar.vue +12 -1
  71. package/src/nuxt/PreprTrackingPixel.vue +2 -4
  72. package/src/sveltekit/PreprToolbar.svelte +17 -2
  73. package/src/sveltekit/PreprTrackingPixel.svelte +2 -4
  74. package/dist/astro/chunk-UN4JADNU.js +0 -173
  75. package/dist/astro/graphql.cjs +0 -1078
  76. package/dist/astro/graphql.d.cts +0 -300
  77. package/dist/astro/graphql.d.ts +0 -300
  78. package/dist/astro/graphql.js +0 -984
  79. package/dist/astro/index-XT_z-RYT.d.cts +0 -130
  80. package/dist/astro/index-XT_z-RYT.d.ts +0 -130
  81. package/dist/chunk-3NCEVJJ3.js +0 -10
  82. package/dist/chunk-S5RWVMDJ.js +0 -148
  83. package/dist/chunk-XL4Y7FGW.js +0 -499
  84. package/dist/graphql/codegen.cjs +0 -557
  85. package/dist/graphql/codegen.d.cts +0 -23
  86. package/dist/graphql/codegen.d.ts +0 -23
  87. package/dist/graphql/codegen.js +0 -99
  88. package/dist/graphql.cjs +0 -1020
  89. package/dist/graphql.d.cts +0 -335
  90. package/dist/graphql.d.ts +0 -335
  91. package/dist/graphql.js +0 -448
  92. package/dist/nextjs/chunk-CMV6ZP6E.js +0 -549
  93. package/dist/nextjs/graphql.cjs +0 -1836
  94. package/dist/nextjs/graphql.d.cts +0 -498
  95. package/dist/nextjs/graphql.d.ts +0 -498
  96. package/dist/nextjs/graphql.js +0 -1422
  97. package/dist/nextjs/server-BL-sqZvu.d.cts +0 -156
  98. package/dist/nextjs/server-BL-sqZvu.d.ts +0 -156
  99. package/dist/nuxt/chunk-XWOABVMW.js +0 -417
  100. package/dist/nuxt/graphql.cjs +0 -1085
  101. package/dist/nuxt/graphql.d.cts +0 -297
  102. package/dist/nuxt/graphql.d.ts +0 -297
  103. package/dist/nuxt/graphql.js +0 -985
  104. package/dist/nuxt/server-8v6OHbsw.d.cts +0 -158
  105. package/dist/nuxt/server-8v6OHbsw.d.ts +0 -158
  106. package/dist/pixel-DwW7cXJm.d.cts +0 -49
  107. package/dist/pixel-DwW7cXJm.d.ts +0 -49
  108. package/dist/server-Brr1UgtW.d.ts +0 -59
  109. package/dist/server-DJuS3YU0.d.cts +0 -59
  110. package/dist/sveltekit/chunk-3S5RA6G5.js +0 -413
  111. package/dist/sveltekit/graphql.cjs +0 -1091
  112. package/dist/sveltekit/graphql.d.cts +0 -302
  113. package/dist/sveltekit/graphql.d.ts +0 -302
  114. package/dist/sveltekit/graphql.js +0 -991
  115. package/dist/sveltekit/server-CO847mEV.d.cts +0 -98
  116. package/dist/sveltekit/server-CO847mEV.d.ts +0 -98
@@ -1,20 +1,503 @@
1
- import {
2
- createElementCache,
3
- createScopedLogger,
4
- decodeStega,
5
- initDebugLogger,
6
- sendPreprEvent,
7
- setTrustedParentOrigin,
8
- throttle
9
- } from "./chunk-S5RWVMDJ.js";
10
1
  import {
11
2
  ALL_FEATURES_ENABLED,
12
3
  VERSION,
13
4
  resolveFeatures
14
- } from "./chunk-5QIWVDP2.js";
5
+ } from "./chunk-DBKZWOXA.js";
6
+ import {
7
+ createIframeBridge,
8
+ isLocale,
9
+ t
10
+ } from "./chunk-Y7JWV7WV.js";
11
+ import {
12
+ ATTR_ENCODED,
13
+ ATTR_FIELD,
14
+ ATTR_HREF,
15
+ ATTR_ID,
16
+ ATTR_LOCALE,
17
+ COOKIE_PREVIEW_MODE,
18
+ COOKIE_SEGMENT,
19
+ COOKIE_TOOLBAR_OPEN,
20
+ COOKIE_VARIANT,
21
+ ENCODED_SELECTOR,
22
+ ONE_YEAR_SECONDS,
23
+ PARAM_HIDE_BAR,
24
+ PARAM_SEGMENT,
25
+ PARAM_VARIANT,
26
+ SEGMENT_ALL_OTHER_USERS,
27
+ TOOLBAR_TAG
28
+ } from "./chunk-UTKH7DOI.js";
29
+ import {
30
+ createScopedLogger,
31
+ initDebugLogger,
32
+ sendPreprEvent,
33
+ sharedState
34
+ } from "./chunk-V7MCHPE7.js";
35
+
36
+ // src/core/stega/clean.ts
37
+ import { vercelStegaClean, vercelStegaDecode } from "@vercel/stega";
38
+ var debug = createScopedLogger("stega:clean");
39
+ function stegaClean(text) {
40
+ if (!text) return text;
41
+ return vercelStegaClean(text);
42
+ }
43
+ function decodeStega(str) {
44
+ if (!str) return null;
45
+ try {
46
+ const decoded = vercelStegaDecode(str);
47
+ if (decoded?.href) {
48
+ return decoded;
49
+ }
50
+ } catch (error) {
51
+ debug.log("error decoding stega data", error);
52
+ const match = str.match(/{"origin.*?}/);
53
+ if (match) {
54
+ try {
55
+ const decodedMatch = vercelStegaDecode(match[0]);
56
+ if (decodedMatch?.href) {
57
+ return decodedMatch;
58
+ }
59
+ } catch (innerError) {
60
+ debug.log("error decoding stega regex match", innerError);
61
+ }
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+
67
+ // src/core/visual-editor/overlay.ts
68
+ var HOST_TAG = "prepr-visual-editor";
69
+ var SCROLL_SETTLE_MS = 120;
70
+ var LABEL_SPACE_PX = 22;
71
+ var BOX_PADDING_PX = 3;
72
+ var LABEL_MARGIN_PX = 4;
73
+ var PROBE_POINTS = [
74
+ [0.5, 0.5],
75
+ [0.15, 0.2],
76
+ [0.85, 0.2],
77
+ [0.15, 0.8],
78
+ [0.85, 0.8]
79
+ ];
80
+ function overlapsBox(area, rect) {
81
+ return area.left < rect.right + BOX_PADDING_PX && area.right > rect.left - BOX_PADDING_PX && area.top < rect.bottom + BOX_PADDING_PX && area.bottom > rect.top - BOX_PADDING_PX;
82
+ }
83
+ function overlaps(a2, b2) {
84
+ return a2.left < b2.right && b2.left < a2.right && a2.top < b2.bottom && b2.top < a2.bottom;
85
+ }
86
+ function coverOf(hit, target, x2, y2) {
87
+ let cover = hit.getBoundingClientRect();
88
+ for (let el = hit.parentElement; el && !el.contains(target) && el !== document.body; el = el.parentElement) {
89
+ const r2 = el.getBoundingClientRect();
90
+ if (x2 < r2.left || x2 >= r2.right || y2 < r2.top || y2 >= r2.bottom) break;
91
+ cover = r2;
92
+ }
93
+ return cover;
94
+ }
95
+ function mergeAreas(areas) {
96
+ const merged = areas.slice();
97
+ for (let i2 = 0; i2 < merged.length; i2++) {
98
+ for (let j2 = i2 + 1; j2 < merged.length; j2++) {
99
+ if (!overlaps(merged[i2], merged[j2])) continue;
100
+ merged[i2] = {
101
+ left: Math.min(merged[i2].left, merged[j2].left),
102
+ top: Math.min(merged[i2].top, merged[j2].top),
103
+ right: Math.max(merged[i2].right, merged[j2].right),
104
+ bottom: Math.max(merged[i2].bottom, merged[j2].bottom)
105
+ };
106
+ merged.splice(j2, 1);
107
+ j2 = i2;
108
+ }
109
+ }
110
+ return merged;
111
+ }
112
+ function findCovers(target, rect) {
113
+ const width = window.innerWidth;
114
+ const height = window.innerHeight;
115
+ const covers = [];
116
+ const seen = /* @__PURE__ */ new Set();
117
+ let probed = false;
118
+ let reached = false;
119
+ for (const [fx, fy] of PROBE_POINTS) {
120
+ const x2 = rect.left + rect.width * fx;
121
+ const y2 = rect.top + rect.height * fy;
122
+ if (x2 < 0 || y2 < 0 || x2 >= width || y2 >= height) continue;
123
+ probed = true;
124
+ const hit = document.elementFromPoint(x2, y2);
125
+ if (!hit || hit === target || target.contains(hit)) {
126
+ reached = true;
127
+ continue;
128
+ }
129
+ if (seen.has(hit)) continue;
130
+ seen.add(hit);
131
+ if (covers.some(
132
+ (c2) => x2 >= c2.left && x2 < c2.right && y2 >= c2.top && y2 < c2.bottom
133
+ )) {
134
+ continue;
135
+ }
136
+ covers.push(coverOf(hit, target, x2, y2));
137
+ }
138
+ if (!probed) return [];
139
+ return reached ? mergeAreas(covers) : null;
140
+ }
141
+ function clipPath(x2, y2, covers) {
142
+ const far = 1e5;
143
+ const points = [
144
+ `${-far}px ${-far}px`,
145
+ `${far}px ${-far}px`,
146
+ `${far}px ${far}px`,
147
+ `${-far}px ${far}px`,
148
+ `${-far}px ${-far}px`
149
+ ];
150
+ for (const c2 of covers) {
151
+ const l2 = c2.left - x2;
152
+ const t3 = c2.top - y2;
153
+ const r2 = c2.right - x2;
154
+ const b2 = c2.bottom - y2;
155
+ points.push(
156
+ `${l2}px ${t3}px`,
157
+ `${r2}px ${t3}px`,
158
+ `${r2}px ${b2}px`,
159
+ `${l2}px ${b2}px`,
160
+ `${l2}px ${t3}px`,
161
+ `${-far}px ${-far}px`
162
+ );
163
+ }
164
+ return `polygon(evenodd, ${points.join(", ")})`;
165
+ }
166
+ var STYLES = `
167
+ :host {
168
+ all: initial;
169
+ position: fixed;
170
+ inset: 0;
171
+ pointer-events: none;
172
+ z-index: 2147483646;
173
+ contain: strict;
174
+ }
175
+ .box {
176
+ position: absolute;
177
+ top: 0;
178
+ left: 0;
179
+ box-sizing: border-box;
180
+ border-radius: 6px;
181
+ opacity: 0;
182
+ will-change: transform, width, height;
183
+ transition:
184
+ transform 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
185
+ width 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
186
+ height 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
187
+ opacity 140ms ease;
188
+ }
189
+ .box[data-visible] { opacity: 1; }
190
+ .box[data-instant], :host([data-scrolling]) .box {
191
+ transition: opacity 140ms ease;
192
+ }
193
+ .hover {
194
+ border: 1.5px solid rgba(79, 70, 229, 0.9);
195
+ background: rgba(79, 70, 229, 0.06);
196
+ }
197
+ .selected {
198
+ border: 2px solid #4f46e5;
199
+ box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.18);
200
+ }
201
+ .label {
202
+ position: absolute;
203
+ left: -2px;
204
+ bottom: 100%;
205
+ margin-bottom: 4px;
206
+ padding: 3px 7px;
207
+ border-radius: 5px;
208
+ background: #4f46e5;
209
+ color: #fff;
210
+ font: 500 11px/1.3 ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
211
+ letter-spacing: 0.01em;
212
+ white-space: nowrap;
213
+ display: flex;
214
+ max-width: 240px;
215
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.25);
216
+ }
217
+ .text {
218
+ min-width: 0;
219
+ overflow: hidden;
220
+ text-overflow: ellipsis;
221
+ }
222
+ .hover .label { background: rgba(79, 70, 229, 0.92); }
223
+ /* Content of another item than the one open in the editor: still clickable,
224
+ but visibly not part of the item being edited. */
225
+ .hover[data-item-kind='other'] {
226
+ border: 1.5px dashed #a5b4fc;
227
+ background: rgba(100, 116, 139, 0.05);
228
+ }
229
+ .hover[data-item-kind='other'] .label { background: #64748b; }
230
+ .hover[data-item-kind='referenced'] {
231
+ border: 1.5px solid #a5b4fc;
232
+ background: rgba(79, 70, 229, 0.03);
233
+ }
234
+ .hover[data-item-kind='referenced'] .label { background: #818cf8; }
235
+ .box[data-label-covered] .label { visibility: hidden; }
236
+ .box[data-label-inside] .label {
237
+ bottom: auto;
238
+ top: 2px;
239
+ left: 2px;
240
+ margin: 0;
241
+ }
242
+ /* A clickable hover label (edit mode on the live site). Only while shown, so
243
+ a fading box never leaves an invisible click target behind. */
244
+ :host([data-label-action]) .hover[data-visible] .label {
245
+ pointer-events: auto;
246
+ cursor: pointer;
247
+ }
248
+ :host([data-label-action]) .hover .label::after {
249
+ content: '\\2197';
250
+ margin-left: 5px;
251
+ }
252
+ :host([data-label-action]) .hover .label:hover { background: #4338ca; }
253
+ /* Bridges the gap between the label and its element, so the pointer can
254
+ travel from one to the other without the hover ending on the way. */
255
+ :host([data-label-action]) .hover .label::before {
256
+ content: '';
257
+ position: absolute;
258
+ left: 0;
259
+ right: 0;
260
+ top: 100%;
261
+ height: ${LABEL_MARGIN_PX + BOX_PADDING_PX + 2}px;
262
+ }
263
+ @media (prefers-reduced-motion: reduce) {
264
+ .box { transition: opacity 80ms linear; }
265
+ }
266
+ `;
267
+ var VisualEditorOverlay = class {
268
+ constructor(options = {}) {
269
+ this.host = null;
270
+ this.hoverBox = null;
271
+ this.selectedBox = null;
272
+ this.frame = null;
273
+ this.scrollTimeout = null;
274
+ this.resizeObserver = null;
275
+ this.onLabelClick = options.onLabelClick;
276
+ }
277
+ mount() {
278
+ if (this.host) return;
279
+ const host = document.createElement(HOST_TAG);
280
+ const shadow = host.attachShadow({ mode: "open" });
281
+ const style = document.createElement("style");
282
+ style.textContent = STYLES;
283
+ shadow.appendChild(style);
284
+ this.hoverBox = this.createBox(shadow, "hover");
285
+ this.selectedBox = this.createBox(shadow, "selected");
286
+ const onLabelClick = this.onLabelClick;
287
+ if (onLabelClick) {
288
+ host.setAttribute("data-label-action", "");
289
+ const hoverBox = this.hoverBox;
290
+ hoverBox.label.addEventListener("click", () => {
291
+ if (hoverBox.target) onLabelClick(hoverBox.target);
292
+ });
293
+ }
294
+ document.documentElement.appendChild(host);
295
+ this.host = host;
296
+ if (typeof ResizeObserver !== "undefined") {
297
+ this.resizeObserver = new ResizeObserver(() => this.schedule());
298
+ }
299
+ }
300
+ unmount() {
301
+ if (this.frame !== null) cancelAnimationFrame(this.frame);
302
+ if (this.scrollTimeout) clearTimeout(this.scrollTimeout);
303
+ this.frame = null;
304
+ this.scrollTimeout = null;
305
+ this.resizeObserver?.disconnect();
306
+ this.resizeObserver = null;
307
+ this.host?.remove();
308
+ this.host = null;
309
+ this.hoverBox = null;
310
+ this.selectedBox = null;
311
+ }
312
+ /**
313
+ * Whether a pointer event target is this chrome: events from inside the
314
+ * shadow root reach the page retargeted to its host.
315
+ */
316
+ owns(node) {
317
+ return node !== null && node === this.host;
318
+ }
319
+ getHoverTarget() {
320
+ return this.hoverBox?.target ?? null;
321
+ }
322
+ getSelectedTarget() {
323
+ return this.selectedBox?.target ?? null;
324
+ }
325
+ setHover(target, label, options = {}) {
326
+ if (target) {
327
+ this.hoverBox?.root.setAttribute(
328
+ "data-item-kind",
329
+ options.kind ?? "current"
330
+ );
331
+ }
332
+ this.retarget(this.hoverBox, target, label);
333
+ }
334
+ setSelected(target, label) {
335
+ this.retarget(this.selectedBox, target, label);
336
+ }
337
+ /** Call on every scroll; positions follow in the next frame, untransitioned. */
338
+ onScroll() {
339
+ if (!this.host) return;
340
+ this.host.setAttribute("data-scrolling", "");
341
+ if (this.scrollTimeout) clearTimeout(this.scrollTimeout);
342
+ this.scrollTimeout = setTimeout(() => {
343
+ this.host?.removeAttribute("data-scrolling");
344
+ this.scrollTimeout = null;
345
+ }, SCROLL_SETTLE_MS);
346
+ this.schedule();
347
+ }
348
+ /** Re-measure both boxes in the next animation frame. */
349
+ schedule() {
350
+ if (this.frame !== null || !this.host) return;
351
+ this.frame = requestAnimationFrame(() => {
352
+ this.frame = null;
353
+ this.render();
354
+ });
355
+ }
356
+ createBox(shadow, kind) {
357
+ const root = document.createElement("div");
358
+ root.className = `box ${kind}`;
359
+ const label = document.createElement("div");
360
+ label.className = "label";
361
+ const text = document.createElement("span");
362
+ text.className = "text";
363
+ label.appendChild(text);
364
+ root.appendChild(label);
365
+ shadow.appendChild(root);
366
+ return { root, label, text, target: null };
367
+ }
368
+ retarget(box, target, label) {
369
+ if (!box || box.target === target) return;
370
+ const previous = box.target;
371
+ if (previous) this.resizeObserver?.unobserve(previous);
372
+ box.target = target;
373
+ if (target) {
374
+ this.resizeObserver?.observe(target);
375
+ box.text.textContent = label;
376
+ if (!box.root.hasAttribute("data-visible")) {
377
+ box.root.setAttribute("data-instant", "");
378
+ }
379
+ }
380
+ this.schedule();
381
+ }
382
+ render() {
383
+ const hover = this.hoverBox ? this.measure(this.hoverBox) : null;
384
+ const selected = this.selectedBox ? this.measure(this.selectedBox) : null;
385
+ if (this.hoverBox) this.paint(this.hoverBox, hover, selected);
386
+ if (this.selectedBox) this.paint(this.selectedBox, selected, hover);
387
+ }
388
+ measure(box) {
389
+ const target = box.target;
390
+ if (!target) return null;
391
+ if (!target.isConnected) {
392
+ this.resizeObserver?.unobserve(target);
393
+ box.target = null;
394
+ return null;
395
+ }
396
+ const rect = target.getBoundingClientRect();
397
+ if (rect.width === 0 && rect.height === 0) return null;
398
+ const covers = findCovers(target, rect);
399
+ if (!covers) return null;
400
+ return {
401
+ rect,
402
+ covers,
403
+ labelWidth: covers.length ? box.label.offsetWidth : 0,
404
+ labelHeight: covers.length ? box.label.offsetHeight : 0
405
+ };
406
+ }
407
+ paint(box, measurement, other = null) {
408
+ const root = box.root;
409
+ if (!measurement) {
410
+ root.removeAttribute("data-visible");
411
+ return;
412
+ }
413
+ const { rect, covers } = measurement;
414
+ const x2 = rect.left - BOX_PADDING_PX;
415
+ const y2 = rect.top - BOX_PADDING_PX;
416
+ const labelAbove = {
417
+ left: x2 - 2,
418
+ top: y2 - LABEL_SPACE_PX,
419
+ right: x2 - 2 + (measurement.labelWidth || Math.min(240, rect.width)),
420
+ bottom: y2
421
+ };
422
+ const labelInside = y2 < LABEL_SPACE_PX || other !== null && other.rect !== rect && overlapsBox(labelAbove, other.rect);
423
+ root.style.transform = `translate3d(${x2}px, ${y2}px, 0)`;
424
+ root.style.width = `${rect.width + BOX_PADDING_PX * 2}px`;
425
+ root.style.height = `${rect.height + BOX_PADDING_PX * 2}px`;
426
+ root.toggleAttribute("data-label-inside", labelInside);
427
+ root.style.clipPath = covers.length ? clipPath(x2, y2, covers) : "";
428
+ const labelLeft = labelInside ? x2 + 2 : x2 - 2;
429
+ const labelTop = labelInside ? y2 + 2 : y2 - LABEL_MARGIN_PX - measurement.labelHeight;
430
+ const label = {
431
+ left: labelLeft,
432
+ top: labelTop,
433
+ right: labelLeft + measurement.labelWidth,
434
+ bottom: labelTop + measurement.labelHeight
435
+ };
436
+ root.toggleAttribute(
437
+ "data-label-covered",
438
+ covers.some((c2) => overlaps(c2, label))
439
+ );
440
+ if (root.hasAttribute("data-instant")) {
441
+ root.setAttribute("data-visible", "");
442
+ requestAnimationFrame(() => root.removeAttribute("data-instant"));
443
+ return;
444
+ }
445
+ root.setAttribute("data-visible", "");
446
+ }
447
+ };
448
+
449
+ // src/core/visual-editor/field-path.ts
450
+ var INDEX_SEGMENT = /^\d+$/;
451
+ var WORD_SEPARATORS = /[_-]+/g;
452
+ function normalizeFieldPath(path) {
453
+ return path.split(".").map(
454
+ (segment) => INDEX_SEGMENT.test(segment) ? String(Number.parseInt(segment, 10)) : segment
455
+ ).join(".");
456
+ }
457
+ var GENERIC_LEAVES = /* @__PURE__ */ new Set(["value", "text", "body", "content", "label"]);
458
+ function humanize(name) {
459
+ const words = name.replace(WORD_SEPARATORS, " ").trim();
460
+ return words.charAt(0).toUpperCase() + words.slice(1);
461
+ }
462
+ function fieldLabel(path, locale = "en") {
463
+ if (!path) return t("visualEditor.edit", locale);
464
+ const segments = path.split(".").filter((s2) => s2 && s2 !== "items" && !INDEX_SEGMENT.test(s2));
465
+ const name = segments[segments.length - 1];
466
+ if (!name) return t("visualEditor.edit", locale);
467
+ const parent = segments[segments.length - 2];
468
+ if (parent && GENERIC_LEAVES.has(name)) {
469
+ return `${humanize(parent)} \u203A ${humanize(name)}`;
470
+ }
471
+ return humanize(name);
472
+ }
473
+ function findFieldElement(lookup) {
474
+ if (!lookup.field) return null;
475
+ const candidates = document.querySelectorAll(ENCODED_SELECTOR);
476
+ if (lookup.entryId) {
477
+ for (const candidate of candidates) {
478
+ if (candidate.getAttribute("data-prepr-entry-id") === lookup.entryId) {
479
+ return candidate;
480
+ }
481
+ }
482
+ }
483
+ for (const path of [lookup.field, lookup.fieldById]) {
484
+ if (!path) continue;
485
+ const wanted = normalizeFieldPath(path);
486
+ for (const candidate of candidates) {
487
+ const field = candidate.getAttribute(ATTR_FIELD);
488
+ if (!field || normalizeFieldPath(field) !== wanted) continue;
489
+ if (lookup.id && candidate.getAttribute(ATTR_ID) !== lookup.id) {
490
+ continue;
491
+ }
492
+ return candidate;
493
+ }
494
+ }
495
+ return null;
496
+ }
15
497
 
16
498
  // src/core/stega/dom.ts
17
499
  var IGNORED_ANCESTORS = "script, style, noscript";
500
+ var AUTO_ENTRY_ATTR = "data-prepr-entry-auto";
18
501
  function isIgnoredTextNode(node) {
19
502
  if (node.parentElement?.closest(IGNORED_ANCESTORS)) return true;
20
503
  return !node.textContent?.trim();
@@ -42,22 +525,69 @@ function isRenderedElement(element) {
42
525
  if (!style) return true;
43
526
  return style.visibility !== "hidden" && style.display !== "none";
44
527
  }
528
+ function parseEditHref(href) {
529
+ try {
530
+ const url = new URL(href, window.location.origin);
531
+ return {
532
+ id: url.pathname.split("/").pop() || void 0,
533
+ field: url.searchParams.get("field") || void 0,
534
+ locale: url.searchParams.get("locale") || void 0,
535
+ // Added by the toolkit's `annotateEditLinks`, not by Prepr.
536
+ entry: url.searchParams.get("entry") || void 0
537
+ };
538
+ } catch {
539
+ return {};
540
+ }
541
+ }
542
+ function setOrRemove(element, name, value) {
543
+ if (value) {
544
+ element.setAttribute(name, value);
545
+ } else {
546
+ element.removeAttribute(name);
547
+ }
548
+ }
45
549
  function tagEncodedElement(element, decoded) {
46
- element.setAttribute("data-prepr-encoded", "");
47
- element.setAttribute("data-prepr-href", decoded.href);
550
+ if (isSiteTagged(element)) return false;
551
+ element.setAttribute(ATTR_ENCODED, "");
552
+ element.setAttribute(ATTR_HREF, decoded.href);
48
553
  element.setAttribute("data-prepr-origin", decoded.origin);
554
+ const { id, field, locale, entry } = parseEditHref(decoded.href);
555
+ setOrRemove(element, ATTR_ID, id);
556
+ const fieldHint = element.getAttribute("data-prepr-edit-target")?.trim() || void 0;
557
+ setOrRemove(element, ATTR_FIELD, field ?? fieldHint);
558
+ setOrRemove(element, ATTR_LOCALE, locale);
559
+ const siteEntry = element.hasAttribute("data-prepr-entry-id") && !element.hasAttribute(AUTO_ENTRY_ATTR);
560
+ if (!siteEntry) {
561
+ setOrRemove(element, "data-prepr-entry-id", entry);
562
+ setOrRemove(element, AUTO_ENTRY_ATTR, entry && "true");
563
+ }
564
+ return true;
565
+ }
566
+ function isSiteTagged(element) {
567
+ return element.hasAttribute(ATTR_ENCODED) && !element.hasAttribute(ATTR_HREF);
568
+ }
569
+ function readEditPayload(element) {
570
+ return {
571
+ href: element.getAttribute(ATTR_HREF) ?? "",
572
+ origin: element.getAttribute("data-prepr-origin") ?? "",
573
+ id: element.getAttribute(ATTR_ID) ?? void 0,
574
+ field: element.getAttribute(ATTR_FIELD) ?? void 0,
575
+ locale: element.getAttribute(ATTR_LOCALE) ?? void 0,
576
+ entryId: element.getAttribute("data-prepr-entry-id") || void 0
577
+ };
49
578
  }
50
579
 
51
580
  // src/core/stega/elements.ts
52
- var debug = createScopedLogger("stega:elements");
581
+ var debug2 = createScopedLogger("stega:elements");
53
582
  var StegaElements = class {
54
583
  constructor(decode = decodeStega) {
55
584
  this.observer = null;
585
+ this.rescanTimer = null;
56
586
  this.decode = decode;
57
587
  }
58
588
  getElements() {
59
589
  if (!this.elements) {
60
- this.elements = document.querySelectorAll("[data-prepr-encoded]");
590
+ this.elements = document.querySelectorAll(ENCODED_SELECTOR);
61
591
  }
62
592
  return this.elements;
63
593
  }
@@ -66,7 +596,7 @@ var StegaElements = class {
66
596
  const decoded = this.decode(node.textContent);
67
597
  if (!decoded?.href) return false;
68
598
  const target = resolveEditTarget(node);
69
- if (!target || target.hasAttribute("data-prepr-encoded")) return false;
599
+ if (!target || target.hasAttribute(ATTR_ENCODED)) return false;
70
600
  tagEncodedElement(target, decoded);
71
601
  return true;
72
602
  }
@@ -84,7 +614,7 @@ var StegaElements = class {
84
614
  */
85
615
  scanDocument(skipIfTagged = false) {
86
616
  if (skipIfTagged) {
87
- const existing = document.querySelectorAll("[data-prepr-encoded]");
617
+ const existing = document.querySelectorAll(ENCODED_SELECTOR);
88
618
  if (existing.length > 0) {
89
619
  this.elements = existing;
90
620
  return;
@@ -94,16 +624,13 @@ var StegaElements = class {
94
624
  walkTextNodes(document.body, (textNode) => {
95
625
  if (this.tagFromTextNode(textNode)) encodedCount++;
96
626
  });
97
- debug.log("document scan complete, encoded", encodedCount, "elements");
98
- this.elements = document.querySelectorAll("[data-prepr-encoded]");
627
+ debug2.log("document scan complete, encoded", encodedCount, "elements");
628
+ this.elements = document.querySelectorAll(ENCODED_SELECTOR);
99
629
  }
100
630
  /** `onUpdate` fires after each debounced batch, for refreshing derived state. */
101
631
  setupMutationObserver(onUpdate) {
102
- if (this.observer) {
103
- this.observer.disconnect();
104
- }
632
+ this.disconnectObserver();
105
633
  let pending = [];
106
- let debounceTimeout = null;
107
634
  const processMutations = () => {
108
635
  const addedNodes = /* @__PURE__ */ new Set();
109
636
  pending.forEach((mutation) => {
@@ -119,13 +646,13 @@ var StegaElements = class {
119
646
  if (node.isConnected) this.scanNode(node);
120
647
  });
121
648
  pending = [];
122
- this.elements = document.querySelectorAll("[data-prepr-encoded]");
649
+ this.elements = document.querySelectorAll(ENCODED_SELECTOR);
123
650
  onUpdate?.();
124
651
  };
125
652
  this.observer = new MutationObserver((mutations) => {
126
653
  pending.push(...mutations);
127
- if (debounceTimeout) clearTimeout(debounceTimeout);
128
- debounceTimeout = setTimeout(processMutations, 100);
654
+ if (this.rescanTimer) clearTimeout(this.rescanTimer);
655
+ this.rescanTimer = setTimeout(processMutations, 100);
129
656
  });
130
657
  this.observer.observe(document.body, {
131
658
  childList: true,
@@ -137,231 +664,27 @@ var StegaElements = class {
137
664
  attributeFilter: ["class", "style", "hidden", "open", "aria-expanded"]
138
665
  });
139
666
  }
140
- /** Drops the active class but keeps the data attributes, unlike cleanup(). */
141
- cleanupVisuals() {
142
- document.querySelectorAll(".prepr-overlay-active").forEach((element) => element.classList.remove("prepr-overlay-active"));
143
- }
144
- cleanup() {
145
- if (this.observer) {
146
- this.observer.disconnect();
147
- this.observer = null;
148
- }
149
- document.querySelectorAll("[data-prepr-encoded]").forEach((element) => {
150
- element.removeAttribute("data-prepr-encoded");
151
- element.removeAttribute("data-prepr-href");
152
- element.removeAttribute("data-prepr-origin");
153
- element.classList.remove("prepr-overlay-active");
154
- });
667
+ /**
668
+ * Stops watching for new content. Tags stay on their elements: the page's
669
+ * stega characters are stripped once they are read, so a tag removed here
670
+ * could never be rebuilt when edit mode is turned back on.
671
+ */
672
+ disconnect() {
673
+ this.disconnectObserver();
155
674
  this.elements = void 0;
156
675
  }
157
- };
158
-
159
- // src/core/stega/overlay.ts
160
- var debug2 = createScopedLogger("stega:overlay");
161
- var StegaOverlay = class {
162
- constructor(onEdit) {
163
- this.overlay = null;
164
- this.tooltip = null;
165
- this.hideTimeout = null;
166
- this.currentElement = null;
167
- this.onEdit = onEdit;
168
- }
169
- create() {
170
- const overlay = document.createElement("div");
171
- overlay.className = "prepr-overlay";
172
- overlay.style.display = "none";
173
- const tooltip = document.createElement("div");
174
- tooltip.className = "prepr-tooltip";
175
- tooltip.style.display = "none";
176
- document.body.appendChild(overlay);
177
- document.body.appendChild(tooltip);
178
- this.overlay = overlay;
179
- this.tooltip = tooltip;
180
- return { overlay, tooltip };
181
- }
182
- getTooltip() {
183
- return this.tooltip;
184
- }
185
- hasCurrentElement() {
186
- return this.currentElement !== null;
187
- }
188
- clearHideTimeout() {
189
- if (this.hideTimeout) {
190
- clearTimeout(this.hideTimeout);
191
- this.hideTimeout = null;
192
- }
193
- }
194
- show(element) {
195
- if (!this.overlay || !this.tooltip) return;
196
- this.clearHideTimeout();
197
- if (this.currentElement && this.currentElement !== element) {
198
- this.currentElement.classList.remove("prepr-overlay-active");
199
- }
200
- const rect = element.getBoundingClientRect();
201
- const href = element.getAttribute("data-prepr-href");
202
- const origin = element.getAttribute("data-prepr-origin");
203
- const id = element.getAttribute("data-prepr-id") ?? void 0;
204
- const field = element.getAttribute("data-prepr-field") ?? void 0;
205
- debug2.log("showing overlay", { href, origin });
206
- const overlay = this.overlay;
207
- overlay.style.display = "block";
208
- overlay.style.top = `${rect.top + window.scrollY - 2}px`;
209
- overlay.style.left = `${rect.left + window.scrollX - 4}px`;
210
- overlay.style.width = `${rect.width + 8}px`;
211
- overlay.style.height = `${rect.height + 4}px`;
212
- const tooltip = this.tooltip;
213
- if (href && origin) {
214
- const MIN_WIDTH_FOR_TEXT = 80;
215
- const isCompact = rect.width < MIN_WIDTH_FOR_TEXT;
216
- tooltip.textContent = isCompact ? "\u2197" : `${origin} \u2197`;
217
- tooltip.style.display = "block";
218
- tooltip.style.minWidth = isCompact ? "auto" : "80px";
219
- requestAnimationFrame(() => {
220
- let top = rect.top + window.scrollY - tooltip.clientHeight - 2;
221
- let left = rect.right + 4 - tooltip.clientWidth;
222
- const minTop = window.scrollY + 4;
223
- const maxTop = window.scrollY + window.innerHeight - tooltip.clientHeight - 4;
224
- const minLeft = window.scrollX + 4;
225
- const maxLeft = window.scrollX + window.innerWidth - tooltip.clientWidth - 4;
226
- const below = top < minTop;
227
- if (below) {
228
- top = rect.bottom + window.scrollY + 2;
229
- }
230
- top = Math.max(minTop, Math.min(top, maxTop));
231
- left = Math.max(minLeft, Math.min(left, maxLeft));
232
- tooltip.dataset.preprPlacement = below ? "below" : "above";
233
- tooltip.style.top = `${top}px`;
234
- tooltip.style.left = `${left}px`;
235
- });
236
- tooltip.onclick = () => {
237
- this.onEdit({ href, origin, id, field });
238
- };
239
- }
240
- this.currentElement = element;
241
- element.classList.add("prepr-overlay-active");
242
- }
243
- hideImmediate() {
244
- this.clearHideTimeout();
245
- if (this.overlay) this.overlay.style.display = "none";
246
- if (this.tooltip) this.tooltip.style.display = "none";
247
- if (this.currentElement) {
248
- this.currentElement.classList.remove("prepr-overlay-active");
249
- this.currentElement = null;
250
- }
251
- }
252
- hide() {
253
- if (!this.overlay || !this.tooltip) return;
254
- this.clearHideTimeout();
255
- this.hideTimeout = setTimeout(() => this.hideImmediate(), 100);
256
- }
257
- cleanup() {
258
- this.clearHideTimeout();
259
- if (this.overlay) {
260
- this.overlay.style.display = "none";
261
- this.overlay.parentNode?.removeChild(this.overlay);
262
- this.overlay = null;
263
- }
264
- if (this.tooltip) {
265
- this.tooltip.style.display = "none";
266
- this.tooltip.parentNode?.removeChild(this.tooltip);
267
- this.tooltip = null;
268
- }
269
- if (this.currentElement) {
270
- this.currentElement.classList.remove("prepr-overlay-active");
271
- this.currentElement = null;
272
- }
273
- }
274
- };
275
-
276
- // src/core/stega/proximity.ts
277
- var debug3 = createScopedLogger("stega:proximity");
278
- var StegaProximity = class {
279
- constructor() {
280
- this.highlighted = /* @__PURE__ */ new Set();
281
- this.visible = /* @__PURE__ */ new Set();
676
+ // A rescan already scheduled must not run after the observer stopped: it
677
+ // would tag elements and call `onUpdate` on a controller that was shut down.
678
+ disconnectObserver() {
679
+ this.observer?.disconnect();
282
680
  this.observer = null;
283
- this.getEncodedElements = createElementCache(
284
- "[data-prepr-encoded]",
285
- 200
286
- );
287
- }
288
- /** Call after the encoded element set changes — rebuilds the observer. */
289
- refreshObserving() {
290
- try {
291
- if (typeof IntersectionObserver === "undefined") return;
292
- if (this.observer) {
293
- this.observer.disconnect();
294
- this.observer = null;
295
- }
296
- this.visible = /* @__PURE__ */ new Set();
297
- this.observer = new IntersectionObserver(
298
- (entries) => {
299
- entries.forEach((entry) => {
300
- const el = entry.target;
301
- if (entry.isIntersecting) {
302
- this.visible.add(el);
303
- } else {
304
- this.visible.delete(el);
305
- }
306
- });
307
- },
308
- { root: null, rootMargin: "0px", threshold: 0 }
309
- );
310
- const nodes = this.getEncodedElements();
311
- nodes.forEach((el) => this.observer.observe(el));
312
- debug3.log("observing", nodes.length, "encoded elements");
313
- } catch (error) {
314
- debug3.log("error setting up IntersectionObserver", error);
315
- }
316
- }
317
- stopObserving() {
318
- if (this.observer) {
319
- this.observer.disconnect();
320
- this.observer = null;
321
- this.visible.clear();
322
- }
323
- }
324
- updateElementGradients(cursorX, cursorY) {
325
- const candidates = this.visible.size > 0 ? Array.from(this.visible) : Array.from(this.getEncodedElements());
326
- const newHighlighted = /* @__PURE__ */ new Set();
327
- candidates.forEach((element) => {
328
- const rect = element.getBoundingClientRect();
329
- const distance = Math.min(
330
- Math.abs(cursorX - rect.left),
331
- Math.abs(cursorX - rect.right),
332
- Math.abs(cursorY - rect.top),
333
- Math.abs(cursorY - rect.bottom)
334
- );
335
- if (distance < 150) {
336
- const relativeX = cursorX - rect.left;
337
- const relativeY = cursorY - rect.top;
338
- element.style.setProperty("--cursor-x", `${relativeX}px`);
339
- element.style.setProperty("--cursor-y", `${relativeY}px`);
340
- const baseGradientSize = Math.max(
341
- 150,
342
- Math.max(rect.width, rect.height) * 1.1
343
- );
344
- const distanceScale = Math.max(0, (400 - distance) / 400);
345
- const gradientSize = baseGradientSize * distanceScale;
346
- element.style.setProperty("--gradient-size", `${gradientSize}px`);
347
- element.classList.add("prepr-proximity-highlight");
348
- newHighlighted.add(element);
349
- } else {
350
- element.classList.remove("prepr-proximity-highlight");
351
- }
352
- });
353
- this.highlighted = newHighlighted;
354
- }
355
- clearAllHighlights() {
356
- this.highlighted.forEach(
357
- (element) => element.classList.remove("prepr-proximity-highlight")
358
- );
359
- this.highlighted.clear();
681
+ if (this.rescanTimer) clearTimeout(this.rescanTimer);
682
+ this.rescanTimer = null;
360
683
  }
361
684
  };
362
685
 
363
686
  // src/core/stega/stega.generated.ts
364
- var STEGA_STYLES = '[data-prepr-encoded]{position:relative}.prepr-overlay{pointer-events:none;z-index:10000;border:2px solid #4f46e5;border-radius:4px 0 4px 4px;transition:all .2s ease-in-out;position:absolute}.prepr-tooltip{color:#fff;white-space:nowrap;z-index:10001;text-align:center;pointer-events:auto;cursor:pointer;background-color:#4f46e5;border-radius:4px 4px 0 0;min-width:80px;padding:4px 8px;font-size:12px;line-height:1;transition:opacity .2s ease-in-out;position:absolute}.prepr-tooltip[data-prepr-placement=below]{border-radius:0 0 4px 4px}.prepr-tooltip:hover{background-color:#4338ca}.prepr-proximity-highlight{z-index:1;position:relative}.prepr-proximity-highlight,.prepr-proximity-highlight *{overflow:visible!important}.prepr-proximity-highlight:before{content:"";pointer-events:none;background:radial-gradient(circle var(--gradient-size) at var(--cursor-x) var(--cursor-y), #4f46e526 0%, #2563eb00 70%);z-index:9999;border:2px solid #4f46e526;border-radius:4px;transition:all .2s;position:absolute;top:-2px;bottom:-2px;left:-4px;right:-4px;overflow:visible}';
687
+ var STEGA_STYLES = '@property --prepr-presence{syntax:"<number>";inherits:true;initial-value:1}[data-prepr-encoded]{outline:1px dashed rgb(79 70 229/calc(.3 * var(--prepr-presence,1)));outline-offset:2px}';
365
688
 
366
689
  // src/core/stega/styles.ts
367
690
  var STEGA_STYLE_MARKER = "data-prepr-stega";
@@ -381,45 +704,79 @@ function removeStegaStyles() {
381
704
  }
382
705
 
383
706
  // src/core/stega/scan.ts
384
- var debug4 = createScopedLogger("stega:scan");
385
- var EDITOR_MODE_STYLES = "[data-prepr-encoded]{cursor:pointer}";
707
+ var debug3 = createScopedLogger("stega:scan");
708
+ var PRESENCE_FADE_MS = 400;
709
+ var EDITOR_MODE_STYLES = `${ENCODED_SELECTOR}{cursor:pointer}`;
710
+ function fadeInPresence() {
711
+ const root = document.documentElement;
712
+ if (typeof root.animate !== "function") return;
713
+ if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
714
+ root.animate(
715
+ { "--prepr-presence": ["0", "1"] },
716
+ { duration: PRESENCE_FADE_MS, easing: "ease-out" }
717
+ );
718
+ }
386
719
  function createStegaController(opts) {
387
720
  const tooltipEnabled = opts.tooltip ?? true;
388
- const overlay = new StegaOverlay(opts.onEdit);
389
- const proximity = new StegaProximity();
721
+ const locale = opts.locale ?? "en";
390
722
  const elements = new StegaElements();
723
+ const overlay = new VisualEditorOverlay({
724
+ onLabelClick: (target) => opts.onEdit(readEditPayload(target))
725
+ });
391
726
  let initialized = false;
392
- let throttledMouseMove = null;
393
- const handleTooltipMouseEnter = () => {
394
- overlay.clearHideTimeout();
727
+ let pointerFrame = null;
728
+ let pointerTarget = null;
729
+ let pointerX = 0;
730
+ let pointerY = 0;
731
+ let hitTestPending = false;
732
+ const updateHover = () => {
733
+ pointerFrame = null;
734
+ if (hitTestPending) {
735
+ hitTestPending = false;
736
+ pointerTarget = document.elementFromPoint(pointerX, pointerY);
737
+ }
738
+ if (overlay.owns(pointerTarget)) return;
739
+ const encoded = pointerTarget instanceof Element ? pointerTarget.closest(ENCODED_SELECTOR) : null;
740
+ overlay.setHover(
741
+ encoded,
742
+ encoded ? fieldLabel(encoded.getAttribute(ATTR_FIELD), locale) : ""
743
+ );
395
744
  };
396
- const handleTooltipMouseLeave = () => {
397
- if (!overlay.hasCurrentElement()) {
398
- overlay.hide();
745
+ const scheduleHover = () => {
746
+ if (pointerFrame === null) {
747
+ pointerFrame = requestAnimationFrame(updateHover);
399
748
  }
400
749
  };
750
+ const handlePointer = (e2) => {
751
+ pointerTarget = e2.target;
752
+ pointerX = e2.clientX;
753
+ pointerY = e2.clientY;
754
+ hitTestPending = false;
755
+ scheduleHover();
756
+ };
757
+ const handlePointerLeave = () => {
758
+ pointerTarget = null;
759
+ hitTestPending = false;
760
+ overlay.setHover(null, "");
761
+ };
401
762
  const handleScroll = () => {
402
- overlay.hideImmediate();
403
- proximity.clearAllHighlights();
763
+ overlay.onScroll();
764
+ if (pointerTarget === null) return;
765
+ hitTestPending = true;
766
+ scheduleHover();
404
767
  };
768
+ const handleResize = () => overlay.schedule();
405
769
  const handleClick = (e2) => {
406
770
  const target = e2.target;
407
- const encoded = target?.closest(
408
- "[data-prepr-encoded]"
409
- );
771
+ const encoded = target?.closest(ENCODED_SELECTOR);
410
772
  if (!encoded) return;
411
773
  e2.preventDefault();
412
774
  e2.stopPropagation();
413
- opts.onEdit({
414
- href: encoded.getAttribute("data-prepr-href") ?? "",
415
- origin: encoded.getAttribute("data-prepr-origin") ?? "",
416
- id: encoded.getAttribute("data-prepr-id") ?? void 0,
417
- field: encoded.getAttribute("data-prepr-field") ?? void 0
418
- });
775
+ opts.onEdit(readEditPayload(encoded));
419
776
  };
420
777
  const start = () => {
421
778
  if (initialized) {
422
- debug4.log("already initialized, skipping setup");
779
+ debug3.log("already initialized, skipping setup");
423
780
  return;
424
781
  }
425
782
  if (!tooltipEnabled) {
@@ -429,124 +786,95 @@ function createStegaController(opts) {
429
786
  });
430
787
  document.addEventListener("click", handleClick, { capture: true });
431
788
  initialized = true;
432
- debug4.log("stega controller started (editor mode)");
789
+ debug3.log("stega controller started (headless)");
433
790
  return;
434
791
  }
435
792
  injectStegaStyles();
436
- const { tooltip } = overlay.create();
437
- tooltip.addEventListener("mouseenter", handleTooltipMouseEnter);
438
- tooltip.addEventListener("mouseleave", handleTooltipMouseLeave);
793
+ fadeInPresence();
794
+ overlay.mount();
439
795
  elements.scanDocument(true);
440
- proximity.refreshObserving();
441
- elements.setupMutationObserver(() => proximity.refreshObserving());
442
- throttledMouseMove = throttle((e2) => {
443
- const mouseEvent = e2;
444
- const target = mouseEvent.target;
445
- if (!target) return;
446
- if (target.closest(".prepr-tooltip")) return;
447
- proximity.updateElementGradients(mouseEvent.clientX, mouseEvent.clientY);
448
- const encoded = target.closest("[data-prepr-encoded]");
449
- if (encoded) {
450
- overlay.show(encoded);
451
- } else {
452
- overlay.hide();
453
- }
454
- }, 16);
455
- document.addEventListener("mousemove", throttledMouseMove, {
456
- passive: true
796
+ elements.setupMutationObserver(() => {
797
+ if (pointerTarget === null) return;
798
+ hitTestPending = true;
799
+ scheduleHover();
457
800
  });
801
+ document.addEventListener("pointermove", handlePointer, { passive: true });
802
+ document.addEventListener("pointerdown", handlePointer, { passive: true });
803
+ document.documentElement.addEventListener(
804
+ "pointerleave",
805
+ handlePointerLeave
806
+ );
458
807
  window.addEventListener("scroll", handleScroll, {
459
808
  capture: true,
460
809
  passive: true
461
810
  });
811
+ window.addEventListener("resize", handleResize, { passive: true });
462
812
  initialized = true;
463
- debug4.log("stega controller started");
813
+ debug3.log("stega controller started");
464
814
  };
465
815
  const stop = () => {
466
816
  if (!initialized) return;
817
+ initialized = false;
467
818
  if (!tooltipEnabled) {
468
819
  document.removeEventListener("click", handleClick, { capture: true });
469
- elements.cleanup();
820
+ elements.disconnect();
470
821
  removeStegaStyles();
471
- initialized = false;
472
- debug4.log("stega controller stopped (editor mode)");
822
+ debug3.log("stega controller stopped (headless)");
473
823
  return;
474
824
  }
475
- if (throttledMouseMove) {
476
- document.removeEventListener("mousemove", throttledMouseMove);
477
- throttledMouseMove.cancel();
478
- throttledMouseMove = null;
479
- }
825
+ if (pointerFrame !== null) cancelAnimationFrame(pointerFrame);
826
+ pointerFrame = null;
827
+ pointerTarget = null;
828
+ hitTestPending = false;
829
+ document.removeEventListener("pointermove", handlePointer);
830
+ document.removeEventListener("pointerdown", handlePointer);
831
+ document.documentElement.removeEventListener(
832
+ "pointerleave",
833
+ handlePointerLeave
834
+ );
480
835
  window.removeEventListener("scroll", handleScroll, { capture: true });
481
- const tooltip = overlay.getTooltip();
482
- if (tooltip) {
483
- tooltip.removeEventListener("mouseenter", handleTooltipMouseEnter);
484
- tooltip.removeEventListener("mouseleave", handleTooltipMouseLeave);
485
- }
486
- overlay.cleanup();
487
- proximity.clearAllHighlights();
488
- proximity.stopObserving();
489
- elements.cleanup();
836
+ window.removeEventListener("resize", handleResize);
837
+ overlay.unmount();
838
+ elements.disconnect();
490
839
  removeStegaStyles();
491
- initialized = false;
492
- debug4.log("stega controller stopped");
840
+ debug3.log("stega controller stopped");
493
841
  };
494
842
  return { start, stop };
495
843
  }
496
844
 
497
845
  // src/core/stega/auto-clean.ts
498
846
  import { vercelStegaSplit } from "@vercel/stega";
499
- var debug5 = createScopedLogger("stega:auto-clean");
500
- var HYDRATION_RETRY_MS = 100;
847
+ var debug4 = createScopedLogger("stega:auto-clean");
848
+ var cleanedNodes = /* @__PURE__ */ new WeakMap();
501
849
  function createStegaAutoClean(options) {
502
850
  const stripText = options?.enabled ?? true;
503
851
  let observer = null;
504
852
  let processing = false;
505
- let cleaned = /* @__PURE__ */ new WeakMap();
506
853
  let pendingHidden = /* @__PURE__ */ new Set();
507
854
  let pendingDirty = /* @__PURE__ */ new Set();
508
855
  let debounceTimeout = null;
509
- const isHydrated = options?.isHydrated;
510
- let pendingHydration = /* @__PURE__ */ new Set();
511
- let hydrationTimeout = null;
512
- function retryPendingHydration() {
513
- hydrationTimeout = null;
514
- processing = true;
515
- const batch = [...pendingHydration];
516
- pendingHydration.clear();
517
- batch.forEach((textNode) => {
518
- if (textNode.isConnected) cleanTextNode(textNode);
519
- });
520
- processing = false;
521
- }
522
856
  function cleanTextNode(textNode) {
523
857
  if (isIgnoredTextNode(textNode)) return false;
524
- if (isHydrated && !isHydrated(textNode)) {
525
- pendingHydration.add(textNode);
526
- hydrationTimeout ?? (hydrationTimeout = setTimeout(
527
- retryPendingHydration,
528
- HYDRATION_RETRY_MS
529
- ));
530
- return false;
531
- }
532
858
  const textContent = textNode.textContent;
533
- const info = cleaned.get(textNode);
859
+ const info = cleanedNodes.get(textNode);
534
860
  const settled = stripText ? info?.cleaned : info?.original;
535
861
  if (info && textContent === settled) {
536
862
  if (!info.decoded) return false;
537
863
  const shown = resolveEditTarget(textNode);
538
- if (!shown) return false;
864
+ if (!shown) {
865
+ pendingHidden.add(textNode);
866
+ return false;
867
+ }
539
868
  pendingHidden.delete(textNode);
540
- if (shown.hasAttribute("data-prepr-encoded")) return false;
541
- tagEncodedElement(shown, info.decoded);
542
- return true;
869
+ if (shown.hasAttribute(ATTR_ENCODED)) return false;
870
+ return tagEncodedElement(shown, info.decoded);
543
871
  }
544
872
  try {
545
873
  const { cleaned: stripped, encoded } = vercelStegaSplit(textContent);
546
874
  if (!encoded || stripped === textContent) return false;
547
875
  const decoded = decodeStega(textContent);
548
876
  if (!decoded?.href && !stripText) return false;
549
- cleaned.set(textNode, {
877
+ cleanedNodes.set(textNode, {
550
878
  original: textContent,
551
879
  cleaned: stripped,
552
880
  decoded: decoded?.href ? decoded : null
@@ -556,12 +884,11 @@ function createStegaAutoClean(options) {
556
884
  const target = resolveEditTarget(textNode);
557
885
  if (target) {
558
886
  pendingHidden.delete(textNode);
559
- tagEncodedElement(target, decoded);
560
- return true;
887
+ return tagEncodedElement(target, decoded);
561
888
  }
562
889
  pendingHidden.add(textNode);
563
890
  } catch (error) {
564
- debug5.log("error cleaning text node", error);
891
+ debug4.log("error cleaning text node", error);
565
892
  }
566
893
  return false;
567
894
  }
@@ -588,7 +915,7 @@ function createStegaAutoClean(options) {
588
915
  }
589
916
  if (mutation.type === "characterData" && mutation.target.nodeType === Node.TEXT_NODE) {
590
917
  const textNode = mutation.target;
591
- const info = cleaned.get(textNode);
918
+ const info = cleanedNodes.get(textNode);
592
919
  const text = textNode.textContent ?? "";
593
920
  const settled = stripText ? info?.cleaned : info?.original;
594
921
  if (text !== settled && vercelStegaSplit(text).encoded) {
@@ -631,7 +958,16 @@ function createStegaAutoClean(options) {
631
958
  retryPendingHidden();
632
959
  }, 50);
633
960
  }
961
+ let resizeTimeout = null;
962
+ function handleResize() {
963
+ if (pendingHidden.size === 0 || resizeTimeout) return;
964
+ resizeTimeout = setTimeout(() => {
965
+ resizeTimeout = null;
966
+ retryPendingHidden();
967
+ }, 100);
968
+ }
634
969
  function setupObserver() {
970
+ window.addEventListener("resize", handleResize, { passive: true });
635
971
  observer = new MutationObserver(handleMutations);
636
972
  observer.observe(document.body, {
637
973
  childList: true,
@@ -647,30 +983,59 @@ function createStegaAutoClean(options) {
647
983
  if (observer || typeof window === "undefined") return;
648
984
  scanAndClean();
649
985
  setupObserver();
650
- debug5.log("stega auto-clean started");
986
+ debug4.log("stega auto-clean started");
651
987
  }
652
988
  function stop() {
653
989
  if (debounceTimeout) {
654
990
  clearTimeout(debounceTimeout);
655
991
  debounceTimeout = null;
656
992
  }
657
- if (hydrationTimeout) {
658
- clearTimeout(hydrationTimeout);
659
- hydrationTimeout = null;
993
+ if (resizeTimeout) {
994
+ clearTimeout(resizeTimeout);
995
+ resizeTimeout = null;
660
996
  }
661
997
  if (observer) {
662
998
  observer.disconnect();
663
999
  observer = null;
1000
+ window.removeEventListener("resize", handleResize);
664
1001
  }
665
- cleaned = /* @__PURE__ */ new WeakMap();
666
1002
  pendingHidden = /* @__PURE__ */ new Set();
667
1003
  pendingDirty = /* @__PURE__ */ new Set();
668
- pendingHydration = /* @__PURE__ */ new Set();
669
- debug5.log("stega auto-clean stopped");
1004
+ debug4.log("stega auto-clean stopped");
670
1005
  }
671
1006
  return { start, stop };
672
1007
  }
673
1008
 
1009
+ // src/core/stega/scroll-to-field.ts
1010
+ var debug5 = createScopedLogger("stega:scroll");
1011
+ var FLASH_DURATION_MS = 1200;
1012
+ var flashTimeout = null;
1013
+ function scrollToField(request) {
1014
+ const { field, id } = request;
1015
+ if (!field) return false;
1016
+ const candidates = document.querySelectorAll(ENCODED_SELECTOR);
1017
+ let target = null;
1018
+ for (const candidate of candidates) {
1019
+ if (candidate.getAttribute(ATTR_FIELD) !== field) continue;
1020
+ if (id && candidate.getAttribute(ATTR_ID) !== id) continue;
1021
+ target = candidate;
1022
+ break;
1023
+ }
1024
+ if (!target) {
1025
+ debug5.log("no element found for field", field);
1026
+ return false;
1027
+ }
1028
+ target.scrollIntoView({ behavior: "smooth", block: "center" });
1029
+ if (flashTimeout) clearTimeout(flashTimeout);
1030
+ document.querySelectorAll(".prepr-overlay-active").forEach((el) => el.classList.remove("prepr-overlay-active"));
1031
+ target.classList.add("prepr-overlay-active");
1032
+ flashTimeout = setTimeout(() => {
1033
+ target.classList.remove("prepr-overlay-active");
1034
+ flashTimeout = null;
1035
+ }, FLASH_DURATION_MS);
1036
+ return true;
1037
+ }
1038
+
674
1039
  // src/core/store.ts
675
1040
  var DEFAULT_STATE = {
676
1041
  locale: "en",
@@ -707,11 +1072,11 @@ function createToolbarStore(initial = {}) {
707
1072
  return { get, set, subscribe };
708
1073
  }
709
1074
 
710
- // ../../node_modules/.pnpm/preact@10.29.7/node_modules/preact/dist/preact.mjs
1075
+ // ../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/dist/preact.mjs
711
1076
  var n;
712
1077
  var l;
713
1078
  var u;
714
- var t;
1079
+ var t2;
715
1080
  var i;
716
1081
  var r;
717
1082
  var o;
@@ -778,8 +1143,8 @@ function H() {
778
1143
  }
779
1144
  }
780
1145
  function L(n2, l2, u3, t3, i2, r2, o2, e2, f3, c2, a2) {
781
- var s2, h2, p2, v2, y2, _2, g2, m2 = t3 && t3.__k || w, b2 = l2.length;
782
- for (f3 = T(u3, l2, m2, f3, b2), s2 = 0; s2 < b2; s2++) null != (p2 = u3.__k[s2]) && (h2 = -1 != p2.__i && m2[p2.__i] || d, p2.__i = s2, _2 = q(n2, p2, h2, i2, r2, o2, e2, f3, c2, a2), v2 = p2.__e, p2.ref && h2.ref != p2.ref && (h2.ref && J(h2.ref, null, p2), a2.push(p2.ref, p2.__c || v2, p2)), null == y2 && null != v2 && (y2 = v2), (g2 = !!(4 & p2.__u)) || h2.__k === p2.__k ? (f3 = j(p2, f3, n2, g2), g2 && h2.__e && (h2.__e = null)) : "function" == typeof p2.type && void 0 !== _2 ? f3 = _2 : v2 && (f3 = v2.nextSibling), p2.__u &= -7);
1146
+ var s2, h2, p2, v2, y2, _2, g2 = t3 && t3.__k || w, m2 = l2.length;
1147
+ for (f3 = T(u3, l2, g2, f3, m2), s2 = 0; s2 < m2; s2++) null != (p2 = u3.__k[s2]) && (h2 = -1 != p2.__i && g2[p2.__i] || d, p2.__i = s2, _2 = q(n2, p2, h2, i2, r2, o2, e2, f3, c2, a2), v2 = p2.__e, p2.ref && h2.ref != p2.ref && (h2.ref && J(h2.ref, null, p2), a2.push(p2.ref, p2.__c || v2, p2)), null == y2 && null != v2 && (y2 = v2), 4 & p2.__u ? (f3 = j(p2, f3, n2), h2.__e && (h2.__e = null)) : "function" == typeof p2.type && void 0 !== _2 ? f3 = _2 : v2 && (f3 = v2.nextSibling), p2.__u &= -7);
783
1148
  return u3.__e = y2, f3;
784
1149
  }
785
1150
  function T(n2, l2, u3, t3, i2) {
@@ -788,13 +1153,13 @@ function T(n2, l2, u3, t3, i2) {
788
1153
  if (s2) for (r2 = 0; r2 < a2; r2++) null != (e2 = u3[r2]) && 0 == (2 & e2.__u) && (e2.__e == t3 && (t3 = $(e2)), K(e2, e2));
789
1154
  return t3;
790
1155
  }
791
- function j(n2, l2, u3, t3) {
792
- var i2, r2;
1156
+ function j(n2, l2, u3) {
1157
+ var t3, i2;
793
1158
  if ("function" == typeof n2.type) {
794
- for (i2 = n2.__k, r2 = 0; i2 && r2 < i2.length; r2++) i2[r2] && (i2[r2].__ = n2, l2 = j(i2[r2], l2, u3, t3));
1159
+ for (t3 = n2.__k, i2 = 0; t3 && i2 < t3.length; i2++) t3[i2] && (t3[i2].__ = n2, l2 = j(t3[i2], l2, u3));
795
1160
  return l2;
796
1161
  }
797
- n2.__e != l2 && (t3 && (l2 && n2.type && !l2.parentNode && (l2 = $(n2)), u3.insertBefore(n2.__e, l2 || null)), l2 = n2.__e);
1162
+ n2.__e != l2 && (l2 && n2.type && !l2.parentNode && (l2 = $(n2)), l2 = u3.insertBefore(n2.__e, l2 || null));
798
1163
  do {
799
1164
  l2 = l2 && l2.nextSibling;
800
1165
  } while (null != l2 && 8 == l2.nodeType);
@@ -840,35 +1205,35 @@ function V(n2) {
840
1205
  };
841
1206
  }
842
1207
  function q(n2, u3, t3, i2, r2, o2, e2, f3, c2, a2) {
843
- var s2, h2, p2, v2, y2, d2, _2, k2, x2, M, $2, I2, P2, A2, H2, T2, j2 = u3.type;
1208
+ var s2, h2, p2, v2, y2, d2, _2, k2, x2, M, I2, P2, A2, H2, T2, j2, F = u3.type;
844
1209
  if (void 0 !== u3.constructor) return null;
845
1210
  128 & t3.__u && (c2 = !!(32 & t3.__u), o2 = [f3 = u3.__e = t3.__e]), (s2 = l.__b) && s2(u3);
846
- n: if ("function" == typeof j2) {
1211
+ n: if ("function" == typeof F) {
847
1212
  h2 = e2.length;
848
1213
  try {
849
- if (x2 = u3.props, M = j2.prototype && j2.prototype.render, $2 = (s2 = j2.contextType) && i2[s2.__c], I2 = s2 ? $2 ? $2.props.value : s2.__ : i2, t3.__c ? k2 = (p2 = u3.__c = t3.__c).__ = p2.__E : (M ? u3.__c = p2 = new j2(x2, I2) : (u3.__c = p2 = new C(x2, I2), p2.constructor = j2, p2.render = Q), $2 && $2.sub(p2), p2.state || (p2.state = {}), p2.__n = i2, v2 = p2.__d = true, p2.__h = [], p2._sb = []), M && null == p2.__s && (p2.__s = p2.state), M && null != j2.getDerivedStateFromProps && (p2.__s == p2.state && (p2.__s = m({}, p2.__s)), m(p2.__s, j2.getDerivedStateFromProps(x2, p2.__s))), y2 = p2.props, d2 = p2.state, p2.__v = u3, v2) M && null == j2.getDerivedStateFromProps && null != p2.componentWillMount && p2.componentWillMount(), M && null != p2.componentDidMount && p2.__h.push(p2.componentDidMount);
1214
+ if (x2 = u3.props, M = F.prototype && F.prototype.render, I2 = (s2 = F.contextType) && i2[s2.__c], P2 = s2 ? I2 ? I2.props.value : s2.__ : i2, t3.__c ? k2 = (p2 = u3.__c = t3.__c).__ = p2.__E : (M ? u3.__c = p2 = new F(x2, P2) : (u3.__c = p2 = new C(x2, P2), p2.constructor = F, p2.render = Q), I2 && I2.sub(p2), p2.state || (p2.state = {}), p2.__n = i2, v2 = p2.__d = true, p2.__h = [], p2._sb = []), M && null == p2.__s && (p2.__s = p2.state), M && null != F.getDerivedStateFromProps && (p2.__s == p2.state && (p2.__s = m({}, p2.__s)), m(p2.__s, F.getDerivedStateFromProps(x2, p2.__s))), y2 = p2.props, d2 = p2.state, p2.__v = u3, v2) M && null == F.getDerivedStateFromProps && null != p2.componentWillMount && p2.componentWillMount(), M && null != p2.componentDidMount && p2.__h.push(p2.componentDidMount);
850
1215
  else {
851
- if (M && null == j2.getDerivedStateFromProps && x2 !== y2 && null != p2.componentWillReceiveProps && p2.componentWillReceiveProps(x2, I2), u3.__v == t3.__v || !p2.__e && null != p2.shouldComponentUpdate && false === p2.shouldComponentUpdate(x2, p2.__s, I2)) {
1216
+ if (M && null == F.getDerivedStateFromProps && x2 !== y2 && null != p2.componentWillReceiveProps && p2.componentWillReceiveProps(x2, P2), u3.__v == t3.__v || !p2.__e && null != p2.shouldComponentUpdate && false === p2.shouldComponentUpdate(x2, p2.__s, P2)) {
852
1217
  u3.__v != t3.__v && (p2.props = x2, p2.state = p2.__s, p2.__d = false), u3.__e = t3.__e, u3.__k = t3.__k, u3.__k.some(function(n3) {
853
1218
  n3 && (n3.__ = u3);
854
- }), w.push.apply(p2.__h, p2._sb), p2._sb = [], p2.__h.length && e2.push(p2);
1219
+ }), w.push.apply(p2.__h, p2._sb), p2._sb = [], p2.__h.length && e2.push(p2), f3 = $(t3);
855
1220
  break n;
856
1221
  }
857
- null != p2.componentWillUpdate && p2.componentWillUpdate(x2, p2.__s, I2), M && null != p2.componentDidUpdate && p2.__h.push(function() {
1222
+ null != p2.componentWillUpdate && p2.componentWillUpdate(x2, p2.__s, P2), M && null != p2.componentDidUpdate && p2.__h.push(function() {
858
1223
  p2.componentDidUpdate(y2, d2, _2);
859
1224
  });
860
1225
  }
861
- if (p2.context = I2, p2.props = x2, p2.__P = n2, p2.__e = false, P2 = l.__r, A2 = 0, M) p2.state = p2.__s, p2.__d = false, P2 && P2(u3), s2 = p2.render(p2.props, p2.state, p2.context), w.push.apply(p2.__h, p2._sb), p2._sb = [];
1226
+ if (p2.context = P2, p2.props = x2, p2.__P = n2, p2.__e = false, A2 = l.__r, H2 = 0, M) p2.state = p2.__s, p2.__d = false, A2 && A2(u3), s2 = p2.render(p2.props, p2.state, p2.context), w.push.apply(p2.__h, p2._sb), p2._sb = [];
862
1227
  else do {
863
- p2.__d = false, P2 && P2(u3), s2 = p2.render(p2.props, p2.state, p2.context), p2.state = p2.__s;
864
- } while (p2.__d && ++A2 < 25);
865
- p2.state = p2.__s, null != p2.getChildContext && (i2 = m(m({}, i2), p2.getChildContext())), M && !v2 && null != p2.getSnapshotBeforeUpdate && (_2 = p2.getSnapshotBeforeUpdate(y2, d2)), H2 = null != s2 && s2.type === S && null == s2.key ? E(s2.props.children) : s2, f3 = L(n2, g(H2) ? H2 : [H2], u3, t3, i2, r2, o2, e2, f3, c2, a2), p2.base = u3.__e, u3.__u &= -161, p2.__h.length && e2.push(p2), k2 && (p2.__E = p2.__ = null);
1228
+ p2.__d = false, A2 && A2(u3), s2 = p2.render(p2.props, p2.state, p2.context), p2.state = p2.__s;
1229
+ } while (p2.__d && ++H2 < 25);
1230
+ p2.state = p2.__s, null != p2.getChildContext && (i2 = m(m({}, i2), p2.getChildContext())), M && !v2 && null != p2.getSnapshotBeforeUpdate && (_2 = p2.getSnapshotBeforeUpdate(y2, d2)), T2 = null != s2 && s2.type === S && null == s2.key ? E(s2.props.children) : s2, f3 = L(n2, g(T2) ? T2 : [T2], u3, t3, i2, r2, o2, e2, f3, c2, a2), p2.base = u3.__e, u3.__u &= -161, p2.__h.length && e2.push(p2), k2 && (p2.__E = p2.__ = null);
866
1231
  } catch (n3) {
867
1232
  if (e2.length = h2, u3.__v = null, c2 || null != o2) {
868
1233
  if (n3.then) {
869
1234
  for (u3.__u |= c2 ? 160 : 128; f3 && 8 == f3.nodeType && f3.nextSibling; ) f3 = f3.nextSibling;
870
1235
  null != o2 && (o2[o2.indexOf(f3)] = null), u3.__e = f3;
871
- } else if (null != o2) for (T2 = o2.length; T2--; ) b(o2[T2]);
1236
+ } else if (null != o2) for (j2 = o2.length; j2--; ) b(o2[j2]);
872
1237
  } else u3.__e = t3.__e;
873
1238
  null == u3.__k && (u3.__k = t3.__k || []), n3.then || B(u3), l.__e(n3, u3, t3);
874
1239
  }
@@ -953,7 +1318,7 @@ n = w.slice, l = { __e: function(n2, l2, u3, t3) {
953
1318
  n2 = l3;
954
1319
  }
955
1320
  throw n2;
956
- } }, u = 0, t = function(n2) {
1321
+ } }, u = 0, t2 = function(n2) {
957
1322
  return null != n2 && void 0 === n2.constructor;
958
1323
  }, C.prototype.setState = function(n2, l2) {
959
1324
  var u3;
@@ -989,9 +1354,9 @@ var CLOSE_ICON_SVG = `<svg width="10" height="10" viewBox="0 0 10 10" fill="none
989
1354
  </svg>`;
990
1355
 
991
1356
  // src/core/ui/toolbar.generated.ts
992
- var TOOLBAR_CSS = ":host{--prepr-primary:#4338ca;--prepr-bg:#eef2ff;--prepr-text:#1f2937;--prepr-radius:8px;--prepr-shadow:0px 0px 40px 0px #1f29373d;--prepr-z-index:10000;--prepr-primary-50:#eef2ff;--prepr-primary-100:#e0e7ff;--prepr-primary-800:#3730a3;--prepr-indigo-600:#4f46e5;--prepr-indigo-50:#eef2ff;--prepr-indigo-700:#4338ca;--prepr-secondary-400:#fb923c;--prepr-secondary-500:#f97316;--prepr-gray-100:#f3f4f6;--prepr-gray-200:#e5e7eb;--prepr-gray-300:#d1d5db;--prepr-gray-400:#9ca3af;--prepr-gray-500:#6b7280;--prepr-gray-700:#374151;--prepr-gray-800:#1f2937;--prepr-gray-900:#111827;--prepr-shadow-sm:0px 0px 12px 0px #c3c3c3cc;color:var(--prepr-text);box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;font-size:14px;line-height:1.5}:host *,:host :before,:host :after,*,:before,:after{box-sizing:border-box}button{font-family:inherit;font-size:inherit;margin:0}.prepr-regular-text{font-size:.875rem;font-weight:500;line-height:1.5}.prepr-backdrop{z-index:calc(var(--prepr-z-index) - 1);opacity:0;pointer-events:none;background:#0000001a;transition:opacity .2s ease-in-out;position:fixed;top:0;bottom:0;left:0;right:0}.prepr-backdrop[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-container{z-index:var(--prepr-z-index);justify-content:flex-end;align-items:center;display:flex;position:fixed;top:calc(50% - 64px);right:0}.prepr-toggle-holder{padding:.5rem}.prepr-toggle{cursor:pointer;background:var(--prepr-primary);color:#fff;border:none;border-radius:9999px;justify-content:center;align-items:center;width:2.25rem;height:2.25rem;display:flex}.prepr-toggle>span{display:flex}.prepr-toggle svg{color:#fff}.prepr-panel{z-index:var(--prepr-z-index);opacity:0;pointer-events:none;justify-content:flex-end;padding:.75rem;transition:opacity .2s ease-in-out;display:flex;position:fixed;top:50%;right:0;transform:translateY(-50%)}.prepr-panel[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-content{box-shadow:var(--prepr-shadow);border-radius:var(--prepr-radius);background:var(--prepr-bg);flex-direction:column;gap:2.5rem;width:100%;padding:1.5rem;display:flex}@media (min-width:640px){.prepr-panel{margin-right:4rem;padding:0}.prepr-content{width:502px;padding:2.5rem}}.prepr-header{justify-content:space-between;align-items:center;gap:.5rem;display:flex}.prepr-header-left{align-items:flex-start;gap:.75rem;display:flex}.prepr-badge{background:var(--prepr-primary-100);height:1.5rem;color:var(--prepr-primary);border-radius:4px;align-items:center;padding:.25rem .75rem;font-size:.875rem;display:flex}.prepr-header-close{cursor:pointer;background:var(--prepr-primary-100);width:2rem;height:2rem;color:var(--prepr-gray-700);border:none;border-radius:6px;justify-content:center;align-items:center;display:flex}.prepr-section{flex-direction:column;gap:.5rem;display:flex}.prepr-section-label{color:var(--prepr-gray-400);font-size:.875rem}.prepr-row{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:.5rem 1.5rem;display:flex}.prepr-row-title{color:var(--prepr-gray-800);margin:0;font-size:1rem;font-weight:600}.prepr-radiogroup{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);background:#fff;align-items:center;gap:.25rem;height:2.5rem;padding:.25rem;display:flex}.prepr-radiogroup[data-disabled=true]{cursor:not-allowed;opacity:.5}.prepr-radiogroup[data-disabled=true] .prepr-radio{pointer-events:none}.prepr-radio{cursor:pointer;white-space:nowrap;text-align:center;height:2rem;color:var(--prepr-gray-900);background:0 0;border:none;border-radius:6px;justify-content:center;align-items:center;padding:.5rem 1.125rem;font-size:.875rem;font-weight:500;transition:all .2s ease-in-out;display:flex}.prepr-radio[data-checked=true]{background:var(--prepr-indigo-600);color:#fff;box-shadow:var(--prepr-shadow-sm)}.prepr-radio[data-checked=true][data-off=true]{background:var(--prepr-gray-800);color:#fff}.prepr-radio-variant{width:82px}.prepr-listbox{position:relative}.prepr-segment-button{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);width:240px;height:2.5rem;color:var(--prepr-gray-500);cursor:pointer;background:#fff;flex-shrink:0;align-items:center;gap:.5rem;padding:0 .5rem;font-size:.875rem;font-weight:500;display:flex;overflow:hidden}@media (min-width:768px){.prepr-segment-button{padding:0 1rem}}.prepr-segment-button:disabled{cursor:not-allowed;background:var(--prepr-gray-200);color:var(--prepr-gray-400)}.prepr-segment-button[aria-expanded=true]{border-bottom-color:#fff;border-bottom-right-radius:0;border-bottom-left-radius:0}.prepr-segment-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-segment-caret{color:var(--prepr-gray-800);display:flex}.prepr-options{z-index:calc(var(--prepr-z-index) + 1);border-left:1px solid var(--prepr-gray-300);border-right:1px solid var(--prepr-gray-300);border-bottom:1px solid var(--prepr-gray-300);-ms-overflow-style:none;scrollbar-width:none;background:#fff;border-radius:0 0 6px 6px;width:240px;max-height:300px;margin:0;padding:0;list-style:none;position:absolute;top:100%;left:0;overflow-y:auto;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-options::-webkit-scrollbar{display:none}.prepr-options[hidden]{display:none}.prepr-option-search{background:#fff;padding:.5rem;position:-webkit-sticky;position:sticky;top:0}.prepr-segment-search{border:1px solid var(--prepr-gray-300);border-radius:var(--prepr-radius);width:100%;height:2rem;font:inherit;color:var(--prepr-gray-900);box-sizing:border-box;background:#fff;padding:0 .5rem;font-size:.875rem}.prepr-segment-search::placeholder{color:var(--prepr-gray-400)}.prepr-segment-search:focus{border-color:var(--prepr-gray-400);outline:none}.prepr-option{cursor:pointer;width:100%;color:var(--prepr-gray-900);background:#fff;align-items:center;padding:.5rem 1rem;font-size:.875rem;font-weight:500;display:flex}.prepr-option:hover{background:var(--prepr-gray-100)}.prepr-option[aria-selected=true]{background:var(--prepr-indigo-50);color:var(--prepr-indigo-700)}.prepr-option-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-reset{background:var(--prepr-secondary-400);color:#fff;cursor:pointer;border:none;border-radius:6px;justify-content:center;align-items:center;gap:.5rem;width:100%;height:2.5rem;padding:.5rem .75rem;font-size:.875rem;font-weight:500;display:flex}.prepr-reset:hover:not(:disabled){background:var(--prepr-secondary-500)}.prepr-reset:disabled{background:var(--prepr-gray-400);color:var(--prepr-gray-500);cursor:not-allowed}@media (min-width:768px){.prepr-reset{width:108px}}.prepr-indicators{z-index:var(--prepr-z-index);gap:.75rem;display:flex;position:fixed;bottom:1.5rem;right:1.5rem}.prepr-status-pill{background:var(--prepr-primary);color:#fff;cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-status-pill[data-interactive=false]{cursor:default;opacity:1;color:#fff}.prepr-status-pill[data-interactive=true]:hover{background:var(--prepr-primary-800)}.prepr-status-pill[hidden]{display:none}.prepr-status-viewing{color:#fff9;font-size:10px}.prepr-status-segment{text-overflow:ellipsis;white-space:nowrap;max-width:120px;display:inline-block;overflow:hidden}.prepr-status-variant{text-overflow:ellipsis;white-space:nowrap;background:#fff3;border-radius:4px;max-width:80px;padding:0 .5rem;display:inline-block;overflow:hidden}.prepr-status-x{color:#fff;width:.75rem;height:.75rem}.prepr-close-edit-pill{background:var(--prepr-primary-50);color:var(--prepr-gray-800);cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-close-edit-pill:hover{background:var(--prepr-primary-100)}.prepr-close-edit-pill[hidden]{display:none}.prepr-close-edit-x{width:1rem;height:1rem;color:var(--prepr-gray-500);transition:color .15s}.prepr-close-edit-pill:hover .prepr-close-edit-x{color:var(--prepr-gray-700)}.prepr-tip{z-index:calc(var(--prepr-z-index) + 2);overflow-wrap:break-word;background:var(--prepr-gray-900);color:#fff;pointer-events:none;border-radius:6px;width:auto;max-width:min(420px,100vw - 16px);padding:.5rem .75rem;font-size:.75rem;font-weight:500;position:fixed;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-tip-arrow{border-left:6px solid #0000;border-right:6px solid #0000;border-top:6px solid var(--prepr-gray-900);width:0;height:0;position:absolute;top:100%;transform:translate(-50%)}[hidden]{display:none!important}@keyframes prepr-fade-in{0%{opacity:0}to{opacity:1}}";
1357
+ var TOOLBAR_CSS = ":host{--prepr-primary:#4338ca;--prepr-bg:#eef2ff;--prepr-text:#1f2937;--prepr-radius:8px;--prepr-shadow:0px 0px 40px 0px #1f29373d;--prepr-z-index:10000;--prepr-primary-50:#eef2ff;--prepr-primary-100:#e0e7ff;--prepr-primary-800:#3730a3;--prepr-indigo-600:#4f46e5;--prepr-indigo-50:#eef2ff;--prepr-indigo-700:#4338ca;--prepr-secondary-400:#fb923c;--prepr-secondary-500:#f97316;--prepr-gray-100:#f3f4f6;--prepr-gray-200:#e5e7eb;--prepr-gray-300:#d1d5db;--prepr-gray-400:#9ca3af;--prepr-gray-500:#6b7280;--prepr-gray-700:#374151;--prepr-gray-800:#1f2937;--prepr-gray-900:#111827;--prepr-shadow-sm:0px 0px 12px 0px #c3c3c3cc;color:var(--prepr-text);box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;font-size:14px;line-height:1.5}:host *,:host :before,:host :after,*,:before,:after{box-sizing:border-box}button{font-family:inherit;font-size:inherit;margin:0}.prepr-regular-text{font-size:.875rem;font-weight:500;line-height:1.5}.prepr-backdrop{z-index:calc(var(--prepr-z-index) - 1);opacity:0;pointer-events:none;background:#0000001a;transition:opacity .2s ease-in-out;position:fixed;top:0;bottom:0;left:0;right:0}.prepr-backdrop[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-container{z-index:var(--prepr-z-index);justify-content:flex-end;align-items:center;display:flex;position:fixed;top:calc(50% - 64px);right:0}.prepr-toggle-holder{padding:.5rem}.prepr-toggle{cursor:pointer;background:var(--prepr-primary);color:#fff;border:none;border-radius:9999px;justify-content:center;align-items:center;width:2.25rem;height:2.25rem;display:flex}.prepr-toggle>span{display:flex}.prepr-toggle svg{color:#fff}.prepr-panel{z-index:var(--prepr-z-index);opacity:0;pointer-events:none;justify-content:flex-end;padding:.75rem;transition:opacity .2s ease-in-out;display:flex;position:fixed;top:50%;right:0;transform:translateY(-50%)}.prepr-panel[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-content{box-shadow:var(--prepr-shadow);border-radius:var(--prepr-radius);background:var(--prepr-bg);flex-direction:column;gap:2.5rem;width:100%;padding:1.5rem;display:flex}@media (min-width:640px){.prepr-panel{margin-right:4rem;padding:0}.prepr-content{width:502px;padding:2.5rem}}.prepr-header{justify-content:space-between;align-items:center;gap:.5rem;display:flex}.prepr-header-left{align-items:flex-start;gap:.75rem;display:flex}.prepr-badge{background:var(--prepr-primary-100);height:1.5rem;color:var(--prepr-primary);border-radius:4px;align-items:center;padding:.25rem .75rem;font-size:.875rem;display:flex}.prepr-header-close{cursor:pointer;background:var(--prepr-primary-100);width:2rem;height:2rem;color:var(--prepr-gray-700);border:none;border-radius:6px;justify-content:center;align-items:center;display:flex}.prepr-section{flex-direction:column;gap:.5rem;display:flex}.prepr-section-label{color:var(--prepr-gray-400);font-size:.875rem}.prepr-row{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:.5rem 1.5rem;display:flex}.prepr-row-title{color:var(--prepr-gray-800);margin:0;font-size:1rem;font-weight:600}.prepr-radiogroup{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);background:#fff;align-items:center;gap:.25rem;height:2.5rem;padding:.25rem;display:flex}.prepr-radiogroup[data-disabled=true]{cursor:not-allowed;opacity:.5}.prepr-radiogroup[data-disabled=true] .prepr-radio{pointer-events:none}.prepr-radio{cursor:pointer;white-space:nowrap;text-align:center;height:2rem;color:var(--prepr-gray-900);background:0 0;border:none;border-radius:6px;justify-content:center;align-items:center;padding:.5rem 1.125rem;font-size:.875rem;font-weight:500;transition:all .2s ease-in-out;display:flex}.prepr-radio[data-checked=true]{background:var(--prepr-indigo-600);color:#fff;box-shadow:var(--prepr-shadow-sm)}.prepr-radio[data-checked=true][data-off=true]{background:var(--prepr-gray-800);color:#fff}.prepr-radio-variant{width:82px}.prepr-listbox{position:relative}.prepr-segment-button{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);width:240px;height:2.5rem;color:var(--prepr-gray-500);cursor:pointer;background:#fff;flex-shrink:0;align-items:center;gap:.5rem;padding:0 .5rem;font-size:.875rem;font-weight:500;display:flex;overflow:hidden}@media (min-width:768px){.prepr-segment-button{padding:0 1rem}}.prepr-segment-button:disabled{cursor:not-allowed;background:var(--prepr-gray-200);color:var(--prepr-gray-400)}.prepr-segment-button[aria-expanded=true]{border-bottom-color:#fff;border-bottom-right-radius:0;border-bottom-left-radius:0}.prepr-segment-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-segment-caret{color:var(--prepr-gray-800);display:flex}.prepr-options{z-index:calc(var(--prepr-z-index) + 1);border-left:1px solid var(--prepr-gray-300);border-right:1px solid var(--prepr-gray-300);border-bottom:1px solid var(--prepr-gray-300);-ms-overflow-style:none;scrollbar-width:none;background:#fff;border-radius:0 0 6px 6px;width:240px;max-height:300px;margin:0;padding:0;list-style:none;position:absolute;top:100%;left:0;overflow-y:auto;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-options::-webkit-scrollbar{display:none}.prepr-options[hidden]{display:none}.prepr-option-search{background:#fff;padding:.5rem;position:sticky;top:0}.prepr-segment-search{border:1px solid var(--prepr-gray-300);border-radius:var(--prepr-radius);width:100%;height:2rem;font:inherit;color:var(--prepr-gray-900);box-sizing:border-box;background:#fff;padding:0 .5rem;font-size:.875rem}@media (pointer:coarse){.prepr-segment-search{font-size:16px}}.prepr-segment-search::placeholder{color:var(--prepr-gray-400)}.prepr-segment-search:focus{border-color:var(--prepr-gray-400);outline:none}.prepr-option{cursor:pointer;width:100%;color:var(--prepr-gray-900);background:#fff;align-items:center;padding:.5rem 1rem;font-size:.875rem;font-weight:500;display:flex}.prepr-option:hover{background:var(--prepr-gray-100)}.prepr-option[aria-selected=true]{background:var(--prepr-indigo-50);color:var(--prepr-indigo-700)}.prepr-option-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-reset{background:var(--prepr-secondary-400);color:#fff;cursor:pointer;border:none;border-radius:6px;justify-content:center;align-items:center;gap:.5rem;width:100%;height:2.5rem;padding:.5rem .75rem;font-size:.875rem;font-weight:500;display:flex}.prepr-reset:hover:not(:disabled){background:var(--prepr-secondary-500)}.prepr-reset:disabled{background:var(--prepr-gray-400);color:var(--prepr-gray-500);cursor:not-allowed}@media (min-width:768px){.prepr-reset{width:108px}}.prepr-indicators{z-index:var(--prepr-z-index);gap:.75rem;display:flex;position:fixed;bottom:1.5rem;right:1.5rem}.prepr-status-pill{background:var(--prepr-primary);color:#fff;cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-status-pill[data-interactive=false]{cursor:default;opacity:1;color:#fff}.prepr-status-pill[data-interactive=true]:hover{background:var(--prepr-primary-800)}.prepr-status-pill[hidden]{display:none}.prepr-status-viewing{color:#fff9;font-size:10px}.prepr-status-segment{text-overflow:ellipsis;white-space:nowrap;max-width:120px;display:inline-block;overflow:hidden}.prepr-status-variant{text-overflow:ellipsis;white-space:nowrap;background:#fff3;border-radius:4px;max-width:80px;padding:0 .5rem;display:inline-block;overflow:hidden}.prepr-status-x{color:#fff;width:.75rem;height:.75rem}.prepr-close-edit-pill{background:var(--prepr-primary-50);color:var(--prepr-gray-800);cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-close-edit-pill:hover{background:var(--prepr-primary-100)}.prepr-close-edit-pill[hidden]{display:none}.prepr-close-edit-x{width:1rem;height:1rem;color:var(--prepr-gray-500);transition:color .15s}.prepr-close-edit-pill:hover .prepr-close-edit-x{color:var(--prepr-gray-700)}.prepr-tip{z-index:calc(var(--prepr-z-index) + 2);overflow-wrap:break-word;background:var(--prepr-gray-900);color:#fff;pointer-events:none;border-radius:6px;width:auto;max-width:min(420px,100vw - 16px);padding:.5rem .75rem;font-size:.75rem;font-weight:500;position:fixed;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-tip-arrow{border-left:6px solid #0000;border-right:6px solid #0000;border-top:6px solid var(--prepr-gray-900);width:0;height:0;position:absolute;top:100%;transform:translate(-50%)}[hidden]{display:none!important}@keyframes prepr-fade-in{0%{opacity:0}to{opacity:1}}";
993
1358
 
994
- // ../../node_modules/.pnpm/preact@10.29.7/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs
1359
+ // ../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs
995
1360
  var f2 = 0;
996
1361
  function u2(e2, t3, n2, o2, i2, u3) {
997
1362
  t3 || (t3 = {});
@@ -1238,7 +1603,7 @@ function StatusPill({
1238
1603
  handlers
1239
1604
  }) {
1240
1605
  const { features } = state;
1241
- const defaultSegmentName = state.segments.find((s2) => s2._id === "all_other_users")?.name ?? t3("adaptiveContent.allOtherUsers");
1606
+ const defaultSegmentName = state.segments.find((s2) => s2._id === SEGMENT_ALL_OTHER_USERS)?.name ?? t3("adaptiveContent.allOtherUsers");
1242
1607
  let segmentLabel;
1243
1608
  if (!state.previewMode || !features.segments) {
1244
1609
  segmentLabel = t3("common.user");
@@ -1419,7 +1784,6 @@ function Panel({
1419
1784
  }
1420
1785
 
1421
1786
  // src/core/ui/toolbar-element.ts
1422
- var TAG_NAME = "prepr-toolbar";
1423
1787
  var HTMLElementBase = typeof HTMLElement === "undefined" ? class {
1424
1788
  } : HTMLElement;
1425
1789
  var PreprToolbarElement = class extends HTMLElementBase {
@@ -1493,6 +1857,13 @@ var PreprToolbarElement = class extends HTMLElementBase {
1493
1857
  document.addEventListener("mousedown", this.onDocumentMouseDown);
1494
1858
  this.renderPanel(store.get());
1495
1859
  }
1860
+ /**
1861
+ * Re-wires a toolbar that was detached and attached again, e.g. when a
1862
+ * framework replaces `<body>` on navigation and the element is moved back.
1863
+ */
1864
+ connectedCallback() {
1865
+ if (this.store && !this.unsubscribe) this.connect(this.store, this.t);
1866
+ }
1496
1867
  disconnectedCallback() {
1497
1868
  this.unsubscribe?.();
1498
1869
  this.unsubscribe = null;
@@ -1679,30 +2050,22 @@ var PreprToolbarElement = class extends HTMLElementBase {
1679
2050
  };
1680
2051
  function definePreprToolbar() {
1681
2052
  if (typeof customElements === "undefined") return;
1682
- if (!customElements.get(TAG_NAME)) {
1683
- customElements.define(TAG_NAME, PreprToolbarElement);
2053
+ if (!customElements.get(TOOLBAR_TAG)) {
2054
+ customElements.define(TOOLBAR_TAG, PreprToolbarElement);
1684
2055
  }
1685
2056
  }
1686
2057
 
1687
- // src/core/constants.ts
1688
- var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
1689
- var COOKIE_TOOLBAR_OPEN = "Prepr-Toolbar-Open";
1690
- var COOKIE_SEGMENT = "Prepr-Segments";
1691
- var COOKIE_VARIANT = "Prepr-ABtesting";
1692
- var COOKIE_UID = "__prepr_uid";
1693
- var COOKIE_HUBSPOT = "hubspotutk";
1694
- var PARAM_SEGMENT = "prepr_preview_segment";
1695
- var PARAM_VARIANT = "prepr_preview_ab";
1696
- var PARAM_HIDE_BAR = "prepr_hide_bar";
1697
- var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
1698
-
1699
2058
  // src/core/cookies.ts
1700
2059
  function getCookie(name) {
1701
2060
  if (typeof document === "undefined") return null;
1702
2061
  const match = document.cookie.split("; ").find((row) => row.startsWith(`${name}=`));
1703
2062
  if (!match) return null;
1704
2063
  const value = match.slice(name.length + 1);
1705
- return decodeURIComponent(value);
2064
+ try {
2065
+ return decodeURIComponent(value);
2066
+ } catch {
2067
+ return value;
2068
+ }
1706
2069
  }
1707
2070
  function setCookie(name, value, options = {}) {
1708
2071
  if (typeof document === "undefined") return;
@@ -1736,156 +2099,6 @@ function crossSiteCookieOptions() {
1736
2099
  return { sameSite: "None", secure: true };
1737
2100
  }
1738
2101
 
1739
- // src/core/locales/en.json
1740
- var en_default = {
1741
- common: {
1742
- viewingAs: "Viewing as:",
1743
- user: "User",
1744
- off: "Off",
1745
- on: "On",
1746
- reset: "Reset",
1747
- toolbar: "Toolbar"
1748
- },
1749
- adaptiveContent: {
1750
- adaptiveContent: "Adaptive content",
1751
- enablePreview: "Preview mode",
1752
- segment: "Segment",
1753
- ABVariant: "A/B variant",
1754
- chooseSegment: "Choose segment",
1755
- searchSegments: "Search segments",
1756
- none: "No segments",
1757
- allOtherUsers: "All other users",
1758
- offDescription: "View the site as a real user (use cookies)",
1759
- onDescription: "Use the toolbar to simulate segments and A/B variants"
1760
- },
1761
- editingTools: {
1762
- editingTools: "Editing tools",
1763
- editMode: "Edit mode",
1764
- ariaCloseEditMode: "Close edit mode"
1765
- }
1766
- };
1767
-
1768
- // src/core/locales/nl.json
1769
- var nl_default = {
1770
- common: {
1771
- viewingAs: "Bekijken als:",
1772
- user: "Gebruiker",
1773
- off: "Uit",
1774
- on: "Aan",
1775
- reset: "Resetten",
1776
- toolbar: "Toolbar"
1777
- },
1778
- adaptiveContent: {
1779
- adaptiveContent: "Adaptieve inhoud",
1780
- enablePreview: "Preview modus",
1781
- segment: "Segment",
1782
- ABVariant: "A/B-variant",
1783
- chooseSegment: "Kies segment",
1784
- searchSegments: "Zoek segmenten",
1785
- none: "Geen segmenten",
1786
- allOtherUsers: "Alle andere gebruikers",
1787
- offDescription: "Bekijk de site als een echte gebruiker (gebruik cookies)",
1788
- onDescription: "Gebruik de werkbalk om segmenten en A/B-varianten te simuleren"
1789
- },
1790
- editingTools: {
1791
- editingTools: "Editing Tools",
1792
- editMode: "Edit mode",
1793
- ariaCloseEditMode: "Edit mode sluiten"
1794
- }
1795
- };
1796
-
1797
- // src/core/i18n.ts
1798
- var dictionaries = {
1799
- en: en_default,
1800
- nl: nl_default
1801
- };
1802
- var LOCALES = Object.keys(dictionaries);
1803
- function isLocale(value) {
1804
- return typeof value === "string" && value in dictionaries;
1805
- }
1806
- function getDict(locale) {
1807
- return isLocale(locale) ? dictionaries[locale] : dictionaries.en;
1808
- }
1809
- function getFromPath(obj, path) {
1810
- return path.split(".").reduce(
1811
- (acc, key) => acc && typeof acc === "object" ? acc[key] : void 0,
1812
- obj
1813
- );
1814
- }
1815
- function format(message, vars) {
1816
- if (!vars) return message;
1817
- return Object.keys(vars).reduce(
1818
- (acc, k2) => acc.replace(new RegExp(`\\{${k2}\\}`, "g"), String(vars[k2])),
1819
- message
1820
- );
1821
- }
1822
- function t2(key, locale, vars) {
1823
- const dict = getDict(locale);
1824
- const msg = getFromPath(dict, key);
1825
- if (typeof msg === "string") return format(msg, vars);
1826
- return key;
1827
- }
1828
-
1829
- // src/core/iframe-bridge.ts
1830
- var EDITOR_BASE_DOMAIN = "prepr.io";
1831
- function isAllowedEditorOrigin(origin, allowed) {
1832
- if (allowed) return allowed.includes(origin);
1833
- let url;
1834
- try {
1835
- url = new URL(origin);
1836
- } catch {
1837
- return false;
1838
- }
1839
- if (url.protocol !== "https:" || url.port !== "") return false;
1840
- const suffix = `.${EDITOR_BASE_DOMAIN}`;
1841
- if (!url.hostname.endsWith(suffix)) return false;
1842
- const label = url.hostname.slice(0, -suffix.length);
1843
- return label.length > 0 && !label.includes(".");
1844
- }
1845
- function createIframeBridge(store, options = {}) {
1846
- const allowedOrigins = options.allowedEditorOrigins;
1847
- let parentOrigin = null;
1848
- const onKeyDown = (event) => {
1849
- const key = event.key.toLowerCase();
1850
- const blocked = (event.ctrlKey || event.metaKey) && ["s", "p", "l"].includes(key);
1851
- if (blocked) event.preventDefault();
1852
- };
1853
- const onMessage = (evt) => {
1854
- const data = evt?.data;
1855
- if (data?.event === "prepr:initVE" && !parentOrigin) {
1856
- if (!isAllowedEditorOrigin(evt.origin, allowedOrigins)) return;
1857
- parentOrigin = evt.origin;
1858
- setTrustedParentOrigin(parentOrigin);
1859
- if (data.scrollPosition != null) {
1860
- const top = data.scrollPosition;
1861
- setTimeout(() => window.scrollTo(0, top), 1);
1862
- }
1863
- store?.set({ previewMode: true, editMode: data.editMode ?? true });
1864
- }
1865
- if (!parentOrigin || evt.origin !== parentOrigin) return;
1866
- if (data?.event === "prepr:getScrollPosition") {
1867
- const currentScrollY = window.scrollY || document.documentElement.scrollTop;
1868
- sendPreprEvent("getScrollPosition", { value: currentScrollY });
1869
- }
1870
- };
1871
- return {
1872
- start() {
1873
- const features = store?.get().features;
1874
- sendPreprEvent("loaded", features ? { features } : void 0, {
1875
- allowUntrustedTarget: true
1876
- });
1877
- window.addEventListener("keydown", onKeyDown);
1878
- window.addEventListener("message", onMessage);
1879
- },
1880
- stop() {
1881
- window.removeEventListener("keydown", onKeyDown);
1882
- window.removeEventListener("message", onMessage);
1883
- parentOrigin = null;
1884
- setTrustedParentOrigin(null);
1885
- }
1886
- };
1887
- }
1888
-
1889
2102
  // src/core/toolbar-change-handler.ts
1890
2103
  function cookieOpts() {
1891
2104
  return {
@@ -1984,8 +2197,840 @@ function splitPath(full) {
1984
2197
  return [full.slice(0, index), full.slice(index + 1)];
1985
2198
  }
1986
2199
 
2200
+ // src/core/visual-editor/asset-images.ts
2201
+ var MAX_URL_LENGTH = 4096;
2202
+ var MIN_KEY_SEGMENTS = 2;
2203
+ var TRANSFORM_OPTION = /^[a-z]{1,3}_[\w.-]*$/i;
2204
+ var FORMAT_PLACEHOLDER = "{format}";
2205
+ var PROXY_PARAMS = ["url", "href", "src", "image"];
2206
+ var ABSOLUTE_HTTP = /^https?:\/\//i;
2207
+ var SOURCE_URL_ATTRIBUTES = ["src", "data-src"];
2208
+ var SOURCE_SET_ATTRIBUTES = ["srcset", "data-srcset"];
2209
+ var ASSET_ATTR = "data-prepr-asset";
2210
+ var REMOVED_ATTR = "data-prepr-removed";
2211
+ var ASSET_SOURCE_ATTRIBUTES = [
2212
+ ...SOURCE_URL_ATTRIBUTES,
2213
+ ...SOURCE_SET_ATTRIBUTES
2214
+ ];
2215
+ var TAG_ATTRIBUTES = [
2216
+ ATTR_ENCODED,
2217
+ ATTR_ID,
2218
+ ATTR_FIELD,
2219
+ "data-prepr-entry-id",
2220
+ ASSET_ATTR,
2221
+ REMOVED_ATTR
2222
+ ];
2223
+ function decodeSegment(segment) {
2224
+ try {
2225
+ return decodeURIComponent(segment);
2226
+ } catch {
2227
+ return segment;
2228
+ }
2229
+ }
2230
+ function isTransformSegment(segment) {
2231
+ return segment === FORMAT_PLACEHOLDER || segment.split(",").every((option) => TRANSFORM_OPTION.test(option));
2232
+ }
2233
+ function assetKey(url, depth = 0) {
2234
+ if (!url || url.length > MAX_URL_LENGTH) return null;
2235
+ let parsed;
2236
+ try {
2237
+ parsed = new URL(url, "https://base.invalid");
2238
+ } catch {
2239
+ return null;
2240
+ }
2241
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
2242
+ if (depth === 0) {
2243
+ for (const name of PROXY_PARAMS) {
2244
+ const inner = parsed.searchParams.get(name);
2245
+ if (inner && ABSOLUTE_HTTP.test(inner)) return assetKey(inner, 1);
2246
+ }
2247
+ }
2248
+ const segments = parsed.pathname.split("/").filter(Boolean).map(decodeSegment);
2249
+ const file = segments.pop();
2250
+ if (!file) return null;
2251
+ const kept = segments.filter((segment) => !isTransformSegment(segment));
2252
+ kept.push(file);
2253
+ return kept.length >= MIN_KEY_SEGMENTS ? kept.join("/") : null;
2254
+ }
2255
+ function srcsetUrls(srcset) {
2256
+ const urls = [];
2257
+ let expectUrl = true;
2258
+ for (const token of srcset.split(/\s+/)) {
2259
+ if (!token) continue;
2260
+ if (!expectUrl) {
2261
+ const comma = token.indexOf(",");
2262
+ if (comma === -1) continue;
2263
+ expectUrl = true;
2264
+ const rest = token.slice(comma + 1);
2265
+ if (!rest) continue;
2266
+ urls.push(rest.replace(/,+$/, ""));
2267
+ expectUrl = rest.endsWith(",");
2268
+ continue;
2269
+ }
2270
+ const url = token.replace(/^,+|,+$/g, "");
2271
+ if (url) urls.push(url);
2272
+ expectUrl = token.endsWith(",");
2273
+ }
2274
+ return urls;
2275
+ }
2276
+ function createAssetIndex(assets) {
2277
+ const index = /* @__PURE__ */ new Map();
2278
+ for (const asset of assets) {
2279
+ const key = assetKey(asset.key);
2280
+ if (key && !index.has(key)) index.set(key, asset);
2281
+ }
2282
+ return index;
2283
+ }
2284
+ function urlsOf(img) {
2285
+ const urls = [];
2286
+ const collect = (el) => {
2287
+ for (const name of SOURCE_URL_ATTRIBUTES) {
2288
+ const value = el.getAttribute(name);
2289
+ if (value) urls.push(value);
2290
+ }
2291
+ for (const name of SOURCE_SET_ATTRIBUTES) {
2292
+ const value = el.getAttribute(name);
2293
+ if (value) urls.push(...srcsetUrls(value));
2294
+ }
2295
+ };
2296
+ collect(img);
2297
+ const picture = img.parentElement;
2298
+ if (picture?.tagName === "PICTURE") {
2299
+ for (const source of picture.children) {
2300
+ if (source.tagName === "SOURCE") collect(source);
2301
+ }
2302
+ }
2303
+ return urls;
2304
+ }
2305
+ function matchAsset(img, index, keys) {
2306
+ for (const url of urlsOf(img)) {
2307
+ let key = keys.get(url);
2308
+ if (key === void 0) {
2309
+ key = assetKey(url);
2310
+ keys.set(url, key);
2311
+ }
2312
+ const asset = key ? index.get(key) : void 0;
2313
+ if (asset) return asset;
2314
+ }
2315
+ return void 0;
2316
+ }
2317
+ function setIfChanged(el, name, value) {
2318
+ if (value === null) {
2319
+ if (el.hasAttribute(name)) el.removeAttribute(name);
2320
+ } else if (el.getAttribute(name) !== value) {
2321
+ el.setAttribute(name, value);
2322
+ }
2323
+ }
2324
+ function untagAssetImage(img) {
2325
+ for (const name of TAG_ATTRIBUTES) img.removeAttribute(name);
2326
+ }
2327
+ var TEXT_FIELD_SELECTOR = `${ENCODED_SELECTOR}:not([${ASSET_ATTR}])`;
2328
+ function besideOtherItem(img, isCurrentItem) {
2329
+ for (let block = img.parentElement; block && block !== document.body; block = block.parentElement) {
2330
+ const texts = block.querySelectorAll(TEXT_FIELD_SELECTOR);
2331
+ if (texts.length === 0) continue;
2332
+ for (const text of texts) {
2333
+ if (isCurrentItem(text)) return false;
2334
+ }
2335
+ return true;
2336
+ }
2337
+ return false;
2338
+ }
2339
+ function tagAssetImages(index, itemId, keys, options = {}) {
2340
+ const { isCurrentItem, removed } = options;
2341
+ let showsRemoved = false;
2342
+ for (const img of document.getElementsByTagName("img")) {
2343
+ const ours = img.hasAttribute(ASSET_ATTR);
2344
+ let match = index.size ? matchAsset(img, index, keys) : void 0;
2345
+ let isRemoved = false;
2346
+ if (!match && removed?.size) {
2347
+ match = matchAsset(img, removed, keys);
2348
+ isRemoved = match !== void 0;
2349
+ }
2350
+ if (!ours && img.hasAttribute(ATTR_ENCODED)) {
2351
+ const mark = isRemoved && (!isCurrentItem || isCurrentItem(img));
2352
+ setIfChanged(img, REMOVED_ATTR, mark ? "" : null);
2353
+ showsRemoved || (showsRemoved = mark);
2354
+ continue;
2355
+ }
2356
+ const asset = match && isCurrentItem && besideOtherItem(img, isCurrentItem) ? void 0 : match;
2357
+ if (!asset) {
2358
+ if (ours) untagAssetImage(img);
2359
+ continue;
2360
+ }
2361
+ setIfChanged(img, ATTR_ENCODED, "");
2362
+ setIfChanged(img, ASSET_ATTR, "");
2363
+ setIfChanged(img, ATTR_ID, itemId);
2364
+ setIfChanged(img, ATTR_FIELD, asset.field);
2365
+ setIfChanged(img, "data-prepr-entry-id", asset.entryId ?? null);
2366
+ setIfChanged(img, REMOVED_ATTR, isRemoved ? "" : null);
2367
+ showsRemoved || (showsRemoved = isRemoved);
2368
+ }
2369
+ return showsRemoved;
2370
+ }
2371
+ function untagAssetImages() {
2372
+ document.querySelectorAll(`img[${ASSET_ATTR}]`).forEach(untagAssetImage);
2373
+ document.querySelectorAll(`img[${REMOVED_ATTR}]`).forEach((img) => img.removeAttribute(REMOVED_ATTR));
2374
+ }
2375
+
2376
+ // src/core/visual-editor/item-scope.ts
2377
+ var REFERENCE_ATTR = "data-prepr-reference";
2378
+ var REFERENCE_SELECTOR = `[${REFERENCE_ATTR}]`;
2379
+ var OTHER_ITEM_ATTR = "data-prepr-other-item";
2380
+ var OTHER_ITEM_SELECTOR = `[${OTHER_ITEM_ATTR}="on"],[${OTHER_ITEM_ATTR}="off"]`;
2381
+ var CHROME_SELECTOR = "header, footer, nav, [role=banner], [role=contentinfo], [role=navigation]";
2382
+ var SECTIONING_SELECTOR = "article, aside, main, nav, section";
2383
+ var PLAIN_HEADER_FOOTER = "header:not([role]), footer:not([role])";
2384
+ function createItemScope() {
2385
+ let currentItemId = null;
2386
+ let references = null;
2387
+ let ownComponents = /* @__PURE__ */ new Set();
2388
+ const isCurrentItem = (el) => {
2389
+ if (currentItemId === null) return true;
2390
+ const id = el.getAttribute(ATTR_ID);
2391
+ return !id || id === currentItemId || ownComponents.has(id);
2392
+ };
2393
+ const linkedIdOf = (el) => {
2394
+ if (!references) return null;
2395
+ const id = el.getAttribute(ATTR_ID) ?? "";
2396
+ if (references.has(id)) return id;
2397
+ let container = el.closest(REFERENCE_SELECTOR);
2398
+ while (container) {
2399
+ const linked = container.getAttribute(REFERENCE_ATTR) ?? "";
2400
+ if (references.has(linked)) return linked;
2401
+ container = container.parentElement?.closest(REFERENCE_SELECTOR) ?? null;
2402
+ }
2403
+ return null;
2404
+ };
2405
+ const inSiteChrome = (el) => {
2406
+ let chrome = el.closest(CHROME_SELECTOR);
2407
+ while (chrome) {
2408
+ if (!chrome.matches(PLAIN_HEADER_FOOTER) || !chrome.parentElement?.closest(SECTIONING_SELECTOR)) {
2409
+ return true;
2410
+ }
2411
+ chrome = chrome.parentElement?.closest(CHROME_SELECTOR) ?? null;
2412
+ }
2413
+ return false;
2414
+ };
2415
+ const showsOtherItem = (el) => {
2416
+ const choice = el.closest(OTHER_ITEM_SELECTOR);
2417
+ if (choice) return choice.getAttribute(OTHER_ITEM_ATTR) === "on";
2418
+ return !inSiteChrome(el);
2419
+ };
2420
+ const itemKind = (el) => {
2421
+ if (isCurrentItem(el)) return "current";
2422
+ if (!references) return "other";
2423
+ if (linkedIdOf(el)) return "referenced";
2424
+ return showsOtherItem(el) ? "other" : null;
2425
+ };
2426
+ const referenceFieldOf = (el) => {
2427
+ const linked = linkedIdOf(el);
2428
+ return linked ? references?.get(linked) : void 0;
2429
+ };
2430
+ return {
2431
+ currentItemId: () => currentItemId,
2432
+ setCurrentItem(itemId) {
2433
+ currentItemId = itemId;
2434
+ },
2435
+ setComponents(componentIds) {
2436
+ ownComponents = new Set(componentIds);
2437
+ },
2438
+ setReferences(list) {
2439
+ references = /* @__PURE__ */ new Map();
2440
+ for (const { id, field } of list) {
2441
+ if (!references.has(id)) references.set(id, field);
2442
+ }
2443
+ },
2444
+ isCurrentItem,
2445
+ linkedIdOf,
2446
+ itemKind,
2447
+ referenceFieldOf
2448
+ };
2449
+ }
2450
+
2451
+ // src/core/visual-editor/list-items.ts
2452
+ function listItemIn(encoded, target) {
2453
+ if (!(target instanceof Element)) return null;
2454
+ const li = target.closest("li");
2455
+ if (!li || !encoded.contains(li) || !li.parentElement) return null;
2456
+ const items = Array.from(li.parentElement.children).filter(
2457
+ (child) => child.tagName === "LI"
2458
+ );
2459
+ return { element: li, index: items.indexOf(li) };
2460
+ }
2461
+ function nthListItem(encoded, block) {
2462
+ const list = encoded.querySelector("ul, ol");
2463
+ if (!list) return null;
2464
+ const items = Array.from(list.children).filter(
2465
+ (child) => child.tagName === "LI"
2466
+ );
2467
+ return items[block] ?? null;
2468
+ }
2469
+
2470
+ // src/core/visual-editor/navigation-guard.ts
2471
+ var debug6 = createScopedLogger("navigation-guard");
2472
+ var trimSlash = (path) => path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
2473
+ function resolve(url) {
2474
+ try {
2475
+ return new URL(url, document.baseURI);
2476
+ } catch {
2477
+ return null;
2478
+ }
2479
+ }
2480
+ function leavesPage(url) {
2481
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
2482
+ const here = window.location;
2483
+ return url.origin !== here.origin || trimSlash(url.pathname) !== trimSlash(here.pathname);
2484
+ }
2485
+ function leavingLinkHref(target) {
2486
+ if (!(target instanceof Element)) return null;
2487
+ const link = target.closest("a[href]");
2488
+ if (!link || link.hasAttribute("download")) return null;
2489
+ const linkTarget = link.getAttribute("target");
2490
+ if (linkTarget && linkTarget !== "_self") return null;
2491
+ const href = link.getAttribute("href") ?? "";
2492
+ if (href.startsWith("#")) return null;
2493
+ const url = resolve(href);
2494
+ return url && leavesPage(url) ? url.href : null;
2495
+ }
2496
+ function submitterAttr(submitter, attr) {
2497
+ if (!submitter?.hasAttribute(attr)) return null;
2498
+ if (attr === "formaction") return submitter.formAction;
2499
+ if (attr === "formmethod") return submitter.formMethod;
2500
+ return submitter.formTarget;
2501
+ }
2502
+ function submissionUrl(form, submitter) {
2503
+ const method = (submitterAttr(submitter, "formmethod") ?? form.method).toLowerCase();
2504
+ if (method === "dialog") return null;
2505
+ const target = submitterAttr(submitter, "formtarget") ?? form.target;
2506
+ if (target && target !== "_self") return null;
2507
+ const url = resolve(
2508
+ submitterAttr(submitter, "formaction") ?? (form.action || location.href)
2509
+ );
2510
+ if (!url) return null;
2511
+ if (method === "get") {
2512
+ let data;
2513
+ try {
2514
+ data = new FormData(form, submitter);
2515
+ } catch {
2516
+ data = new FormData(form);
2517
+ }
2518
+ const query = new URLSearchParams();
2519
+ data.forEach((value, key) => {
2520
+ query.append(key, typeof value === "string" ? value : value.name);
2521
+ });
2522
+ url.search = query.toString();
2523
+ }
2524
+ return url;
2525
+ }
2526
+ function createNavigationGuard(opts) {
2527
+ let active = false;
2528
+ let permitted = null;
2529
+ let pendingForm = null;
2530
+ let originalPush = null;
2531
+ let guardedPush = null;
2532
+ const isPermitted = (url) => permitted === url.href;
2533
+ const guarding = () => active && opts.showsEditedContent();
2534
+ const report = (href) => {
2535
+ debug6.log("blocked navigation to", href);
2536
+ opts.onBlocked(href);
2537
+ };
2538
+ const onSubmit = (e2) => {
2539
+ if (e2.defaultPrevented || !(e2.target instanceof HTMLFormElement)) return;
2540
+ if (!guarding()) return;
2541
+ const submitter = e2.submitter ?? null;
2542
+ const url = submissionUrl(e2.target, submitter);
2543
+ if (!url || !leavesPage(url) || isPermitted(url)) return;
2544
+ e2.preventDefault();
2545
+ pendingForm = { form: e2.target, submitter, href: url.href };
2546
+ report(url.href);
2547
+ };
2548
+ const onNavigate = (event) => {
2549
+ const e2 = event;
2550
+ if (e2.navigationType === "traverse" || e2.navigationType === "reload") {
2551
+ return;
2552
+ }
2553
+ if (!e2.cancelable || e2.hashChange || e2.downloadRequest !== null) return;
2554
+ if (!guarding()) return;
2555
+ if (e2.navigationType === "replace" && e2.destination.sameDocument) return;
2556
+ const url = resolve(e2.destination.url);
2557
+ if (!url || !leavesPage(url) || isPermitted(url)) return;
2558
+ e2.preventDefault();
2559
+ report(url.href);
2560
+ if (e2.destination.sameDocument) window.location.reload();
2561
+ };
2562
+ const navigation = () => window.navigation;
2563
+ function installPushGuard() {
2564
+ const original = history.pushState;
2565
+ const guard = function(data, unused, url) {
2566
+ if (guarding() && guardedPush === guard && url != null) {
2567
+ const target = resolve(url);
2568
+ if (target && leavesPage(target) && !isPermitted(target)) {
2569
+ report(target.href);
2570
+ window.location.reload();
2571
+ return;
2572
+ }
2573
+ }
2574
+ return original.call(this, data, unused, url);
2575
+ };
2576
+ originalPush = original;
2577
+ guardedPush = guard;
2578
+ history.pushState = guard;
2579
+ }
2580
+ function uninstallPushGuard() {
2581
+ if (history.pushState === guardedPush && originalPush) {
2582
+ history.pushState = originalPush;
2583
+ }
2584
+ originalPush = null;
2585
+ guardedPush = null;
2586
+ }
2587
+ return {
2588
+ start() {
2589
+ if (active) return;
2590
+ active = true;
2591
+ installPushGuard();
2592
+ window.addEventListener("submit", onSubmit);
2593
+ navigation()?.addEventListener("navigate", onNavigate);
2594
+ },
2595
+ stop() {
2596
+ if (!active) return;
2597
+ active = false;
2598
+ uninstallPushGuard();
2599
+ window.removeEventListener("submit", onSubmit);
2600
+ navigation()?.removeEventListener("navigate", onNavigate);
2601
+ pendingForm = null;
2602
+ },
2603
+ isActive: guarding,
2604
+ block(href) {
2605
+ report(href);
2606
+ },
2607
+ permit(href) {
2608
+ permitted = resolve(href)?.href ?? null;
2609
+ },
2610
+ allow(href) {
2611
+ const url = resolve(href);
2612
+ if (!url || url.protocol !== "http:" && url.protocol !== "https:") {
2613
+ debug6.warn("ignored navigation to unsupported URL");
2614
+ return;
2615
+ }
2616
+ permitted = url.href;
2617
+ const form = pendingForm;
2618
+ pendingForm = null;
2619
+ if (form && form.href === url.href && form.form.isConnected) {
2620
+ try {
2621
+ form.form.requestSubmit(form.submitter ?? void 0);
2622
+ } catch {
2623
+ form.form.requestSubmit();
2624
+ }
2625
+ return;
2626
+ }
2627
+ window.location.assign(url.href);
2628
+ }
2629
+ };
2630
+ }
2631
+
2632
+ // src/core/visual-editor/index.ts
2633
+ var debug7 = createScopedLogger("visual-editor");
2634
+ var CURSOR_STYLE_MARKER = "data-prepr-visual-editor";
2635
+ var REMOVED_STYLES = `img[${REMOVED_ATTR}]{opacity:.2!important;transition:opacity .2s ease}@media (prefers-reduced-motion:reduce){img[${REMOVED_ATTR}]{transition:none}}`;
2636
+ var CURSOR_STYLES = `${ENCODED_SELECTOR}{cursor:pointer}html[data-prepr-ve-suspended] ${ENCODED_SELECTOR}{cursor:auto}${REMOVED_STYLES}`;
2637
+ var SUSPENDED_ATTR = "data-prepr-ve-suspended";
2638
+ var FIND_RETRY_MS = 150;
2639
+ var FIND_RETRIES = 6;
2640
+ var MAX_CACHED_KEYS = 2e3;
2641
+ var SAVED_FADE_MS = 1e4;
2642
+ var LAYOUT_MUTATIONS = {
2643
+ childList: true,
2644
+ subtree: true,
2645
+ characterData: true,
2646
+ attributes: true,
2647
+ attributeFilter: [
2648
+ "class",
2649
+ "style",
2650
+ "hidden",
2651
+ "open",
2652
+ ATTR_ENCODED,
2653
+ // An image swapped by a carousel or lazy loader can show another asset.
2654
+ ...ASSET_SOURCE_ATTRIBUTES
2655
+ ]
2656
+ };
2657
+ function scrollIntoFrame(el) {
2658
+ const rect = el.getBoundingClientRect();
2659
+ const offset = Math.max(0, (window.innerHeight - rect.height) / 2);
2660
+ window.scrollTo({
2661
+ top: Math.max(0, window.scrollY + rect.top - offset),
2662
+ behavior: "smooth"
2663
+ });
2664
+ }
2665
+ var isVisible = (el) => typeof el.checkVisibility === "function" ? el.checkVisibility() : el.getClientRects().length > 0;
2666
+ function createVisualEditor(opts) {
2667
+ const overlay = new VisualEditorOverlay();
2668
+ let running = false;
2669
+ const scope = createItemScope();
2670
+ const { isCurrentItem, itemKind, linkedIdOf, referenceFieldOf } = scope;
2671
+ let locale = opts.locale ?? "en";
2672
+ let suspended = false;
2673
+ let pointerFrame = null;
2674
+ let lastPointerTarget = null;
2675
+ let lastPointerX = 0;
2676
+ let lastPointerY = 0;
2677
+ let mutationFrame = null;
2678
+ let mutationObserver = null;
2679
+ let selection = null;
2680
+ let findTimeout = null;
2681
+ let settlePendingFind = null;
2682
+ let guardEnabled = false;
2683
+ let assetIndex = /* @__PURE__ */ new Map();
2684
+ const assetKeys = /* @__PURE__ */ new Map();
2685
+ const removedAssets = /* @__PURE__ */ new Map();
2686
+ let saved = false;
2687
+ let savedTimeout = null;
2688
+ const guard = createNavigationGuard({
2689
+ onBlocked: (href) => opts.onNavigationBlocked?.(href),
2690
+ showsEditedContent: () => showsEditedContent()
2691
+ });
2692
+ const encodedFrom = (node) => node instanceof Element ? node.closest(ENCODED_SELECTOR) : null;
2693
+ const labelFor = (el) => fieldLabel(el.getAttribute(ATTR_FIELD), locale);
2694
+ const showsEditedContent = () => {
2695
+ for (const el of document.querySelectorAll(ENCODED_SELECTOR)) {
2696
+ if (isCurrentItem(el) && isVisible(el)) return true;
2697
+ }
2698
+ return false;
2699
+ };
2700
+ const hoverLabel = (el, kind) => {
2701
+ if (kind === "other") {
2702
+ return `${labelFor(el)} \xB7 ${t("visualEditor.otherItem", locale)}`;
2703
+ }
2704
+ if (kind === "referenced") {
2705
+ const via = referenceFieldOf(el);
2706
+ const prefix = via ? `${fieldLabel(via, locale)} \u203A ` : "";
2707
+ return `${prefix}${labelFor(el)} \xB7 ${t("visualEditor.linkedItem", locale)}`;
2708
+ }
2709
+ return labelFor(el);
2710
+ };
2711
+ const setSuspended = (value) => {
2712
+ if (suspended === value) return;
2713
+ suspended = value;
2714
+ document.documentElement.toggleAttribute(SUSPENDED_ATTR, value);
2715
+ if (value) overlay.setHover(null, "");
2716
+ };
2717
+ const updateHover = () => {
2718
+ pointerFrame = null;
2719
+ overlay.schedule();
2720
+ if (suspended) return;
2721
+ const encoded = encodedFrom(lastPointerTarget);
2722
+ const target = encoded === overlay.getSelectedTarget() ? null : encoded;
2723
+ if (!target) {
2724
+ overlay.setHover(null, "");
2725
+ return;
2726
+ }
2727
+ const kind = itemKind(target);
2728
+ if (!kind) {
2729
+ overlay.setHover(null, "");
2730
+ return;
2731
+ }
2732
+ overlay.setHover(target, hoverLabel(target, kind), { kind });
2733
+ };
2734
+ const handlePointerMove = (e2) => {
2735
+ setSuspended(e2.altKey);
2736
+ lastPointerTarget = e2.target;
2737
+ lastPointerX = e2.clientX;
2738
+ lastPointerY = e2.clientY;
2739
+ if (pointerFrame === null) {
2740
+ pointerFrame = requestAnimationFrame(updateHover);
2741
+ }
2742
+ };
2743
+ const handlePointerLeave = () => {
2744
+ lastPointerTarget = null;
2745
+ overlay.setHover(null, "");
2746
+ };
2747
+ const handleClick = (e2) => {
2748
+ if (e2.altKey) {
2749
+ const href = leavingLinkHref(e2.target);
2750
+ if (href && guard.isActive()) guard.permit(href);
2751
+ return;
2752
+ }
2753
+ const encoded = encodedFrom(e2.target);
2754
+ const kind = encoded ? itemKind(encoded) : null;
2755
+ if (!encoded || !kind) {
2756
+ clearSelection();
2757
+ if (e2.ctrlKey || e2.metaKey || e2.shiftKey || !showsEditedContent()) return;
2758
+ const href = leavingLinkHref(e2.target);
2759
+ if (!href) return;
2760
+ e2.preventDefault();
2761
+ if (guard.isActive()) {
2762
+ e2.stopPropagation();
2763
+ guard.block(href);
2764
+ }
2765
+ return;
2766
+ }
2767
+ if (kind === "other" && (e2.ctrlKey || e2.metaKey || e2.shiftKey)) return;
2768
+ e2.preventDefault();
2769
+ e2.stopPropagation();
2770
+ const item = listItemIn(encoded, e2.target);
2771
+ if (kind === "current")
2772
+ select(item?.element ?? encoded, encoded, item?.index);
2773
+ const referenceField = kind === "referenced" ? referenceFieldOf(encoded) : void 0;
2774
+ const linkedId = kind === "referenced" ? linkedIdOf(encoded) : null;
2775
+ const linkHref = kind === "other" ? leavingLinkHref(e2.target) : null;
2776
+ opts.onEdit({
2777
+ ...readEditPayload(encoded),
2778
+ ...linkedId && { id: linkedId },
2779
+ ...item && { block: item.index },
2780
+ ...referenceField && { referenceField },
2781
+ ...linkHref && { linkHref }
2782
+ });
2783
+ };
2784
+ const handleKey = (e2) => {
2785
+ if (e2.key === "Alt") setSuspended(e2.type === "keydown");
2786
+ if (e2.type === "keydown" && e2.key === "Escape") {
2787
+ clearSelection();
2788
+ }
2789
+ };
2790
+ const handleBlur = () => setSuspended(false);
2791
+ const handleScroll = () => overlay.onScroll();
2792
+ const handleResize = () => overlay.schedule();
2793
+ const handleSettled = () => overlay.schedule();
2794
+ function select(el, field, block) {
2795
+ const entryId = field.getAttribute("data-prepr-entry-id");
2796
+ selection = {
2797
+ lookup: {
2798
+ field: field.getAttribute(ATTR_FIELD) ?? "",
2799
+ id: field.getAttribute(ATTR_ID) ?? void 0,
2800
+ ...entryId && { entryId },
2801
+ ...block !== void 0 && { block }
2802
+ },
2803
+ label: field
2804
+ };
2805
+ overlay.setSelected(el, labelFor(field));
2806
+ if (overlay.getHoverTarget() === el) overlay.setHover(null, "");
2807
+ }
2808
+ function clearSelection() {
2809
+ selection = null;
2810
+ overlay.setSelected(null, "");
2811
+ }
2812
+ function reselect() {
2813
+ if (!selection) return;
2814
+ const current = overlay.getSelectedTarget();
2815
+ if (current?.isConnected && selection.label.isConnected) return;
2816
+ const found = findFieldElement(selection.lookup);
2817
+ if (!found || !isCurrentItem(found)) {
2818
+ overlay.setSelected(null, "");
2819
+ return;
2820
+ }
2821
+ const { block } = selection.lookup;
2822
+ const el = block !== void 0 ? nthListItem(found, block) ?? found : found;
2823
+ select(el, found, block);
2824
+ }
2825
+ const hasAssets = () => assetIndex.size > 0 || removedAssets.size > 0;
2826
+ function tagAssets() {
2827
+ if (assetKeys.size > MAX_CACHED_KEYS) assetKeys.clear();
2828
+ const showsRemoved = tagAssetImages(
2829
+ assetIndex,
2830
+ scope.currentItemId(),
2831
+ assetKeys,
2832
+ {
2833
+ isCurrentItem: (el) => isCurrentItem(el),
2834
+ removed: removedAssets
2835
+ }
2836
+ );
2837
+ if (saved && !showsRemoved) forgetRemoved();
2838
+ }
2839
+ function forgetRemoved() {
2840
+ saved = false;
2841
+ if (savedTimeout) clearTimeout(savedTimeout);
2842
+ savedTimeout = null;
2843
+ if (!removedAssets.size) return;
2844
+ removedAssets.clear();
2845
+ if (running) tagAssets();
2846
+ }
2847
+ function itemSaved() {
2848
+ if (!removedAssets.size) return;
2849
+ saved = true;
2850
+ if (savedTimeout) clearTimeout(savedTimeout);
2851
+ savedTimeout = setTimeout(forgetRemoved, SAVED_FADE_MS);
2852
+ }
2853
+ const handleLayoutFrame = () => {
2854
+ mutationFrame = null;
2855
+ if (hasAssets()) tagAssets();
2856
+ reselect();
2857
+ const hovered = overlay.getHoverTarget();
2858
+ if (hovered && !hovered.isConnected) {
2859
+ lastPointerTarget = document.elementFromPoint(lastPointerX, lastPointerY);
2860
+ updateHover();
2861
+ return;
2862
+ }
2863
+ overlay.schedule();
2864
+ };
2865
+ const handleMutations = () => {
2866
+ if (mutationFrame !== null) return;
2867
+ if (!selection && !overlay.getHoverTarget() && !hasAssets()) return;
2868
+ mutationFrame = requestAnimationFrame(handleLayoutFrame);
2869
+ };
2870
+ function injectCursorStyles() {
2871
+ if (document.querySelector(`style[${CURSOR_STYLE_MARKER}]`)) return;
2872
+ const style = document.createElement("style");
2873
+ style.setAttribute(CURSOR_STYLE_MARKER, "");
2874
+ style.textContent = CURSOR_STYLES;
2875
+ document.head.appendChild(style);
2876
+ }
2877
+ function start() {
2878
+ if (running) return;
2879
+ running = true;
2880
+ overlay.mount();
2881
+ injectCursorStyles();
2882
+ document.addEventListener("pointermove", handlePointerMove, {
2883
+ passive: true
2884
+ });
2885
+ document.documentElement.addEventListener(
2886
+ "pointerleave",
2887
+ handlePointerLeave
2888
+ );
2889
+ document.addEventListener("click", handleClick, { capture: true });
2890
+ window.addEventListener("keydown", handleKey);
2891
+ window.addEventListener("keyup", handleKey);
2892
+ window.addEventListener("blur", handleBlur);
2893
+ window.addEventListener("scroll", handleScroll, {
2894
+ capture: true,
2895
+ passive: true
2896
+ });
2897
+ window.addEventListener("resize", handleResize, { passive: true });
2898
+ document.addEventListener("transitionend", handleSettled, {
2899
+ capture: true,
2900
+ passive: true
2901
+ });
2902
+ document.addEventListener("animationend", handleSettled, {
2903
+ capture: true,
2904
+ passive: true
2905
+ });
2906
+ mutationObserver = new MutationObserver(handleMutations);
2907
+ mutationObserver.observe(document.body, LAYOUT_MUTATIONS);
2908
+ if (hasAssets()) tagAssets();
2909
+ syncGuard();
2910
+ debug7.log("visual editor started");
2911
+ }
2912
+ function stop() {
2913
+ if (!running) return;
2914
+ running = false;
2915
+ if (pointerFrame !== null) cancelAnimationFrame(pointerFrame);
2916
+ if (mutationFrame !== null) cancelAnimationFrame(mutationFrame);
2917
+ mutationObserver?.disconnect();
2918
+ mutationObserver = null;
2919
+ cancelFind();
2920
+ pointerFrame = null;
2921
+ mutationFrame = null;
2922
+ selection = null;
2923
+ lastPointerTarget = null;
2924
+ setSuspended(false);
2925
+ document.removeEventListener("pointermove", handlePointerMove);
2926
+ document.documentElement.removeEventListener(
2927
+ "pointerleave",
2928
+ handlePointerLeave
2929
+ );
2930
+ document.removeEventListener("click", handleClick, { capture: true });
2931
+ window.removeEventListener("keydown", handleKey);
2932
+ window.removeEventListener("keyup", handleKey);
2933
+ window.removeEventListener("blur", handleBlur);
2934
+ window.removeEventListener("scroll", handleScroll, { capture: true });
2935
+ window.removeEventListener("resize", handleResize);
2936
+ document.removeEventListener("transitionend", handleSettled, {
2937
+ capture: true
2938
+ });
2939
+ document.removeEventListener("animationend", handleSettled, {
2940
+ capture: true
2941
+ });
2942
+ document.querySelectorAll(`style[${CURSOR_STYLE_MARKER}]`).forEach((node) => node.remove());
2943
+ overlay.unmount();
2944
+ untagAssetImages();
2945
+ guard.stop();
2946
+ debug7.log("visual editor stopped");
2947
+ }
2948
+ function cancelFind() {
2949
+ if (findTimeout) clearTimeout(findTimeout);
2950
+ findTimeout = null;
2951
+ settlePendingFind?.();
2952
+ settlePendingFind = null;
2953
+ }
2954
+ function focusField(lookup) {
2955
+ cancelFind();
2956
+ return new Promise((resolve2) => {
2957
+ let attempt = 0;
2958
+ const finish = (found) => {
2959
+ settlePendingFind = null;
2960
+ resolve2(found);
2961
+ };
2962
+ settlePendingFind = () => resolve2(false);
2963
+ const tryFind = () => {
2964
+ findTimeout = null;
2965
+ const found = findFieldElement(lookup);
2966
+ if (found) {
2967
+ const el = lookup.block !== void 0 ? nthListItem(found, lookup.block) ?? found : found;
2968
+ scrollIntoFrame(el);
2969
+ if (running && isCurrentItem(found)) select(el, found, lookup.block);
2970
+ finish(true);
2971
+ return;
2972
+ }
2973
+ if (++attempt >= FIND_RETRIES) {
2974
+ debug7.log("no element renders field", lookup.field);
2975
+ finish(false);
2976
+ return;
2977
+ }
2978
+ findTimeout = setTimeout(tryFind, FIND_RETRY_MS);
2979
+ };
2980
+ tryFind();
2981
+ });
2982
+ }
2983
+ function setCurrentItem(itemId, referenceList, componentIds) {
2984
+ if (itemId !== scope.currentItemId()) forgetRemoved();
2985
+ scope.setCurrentItem(itemId);
2986
+ if (referenceList) setReferences(referenceList, componentIds);
2987
+ else if (componentIds) scope.setComponents(componentIds);
2988
+ if (running && hasAssets()) tagAssets();
2989
+ const selected = overlay.getSelectedTarget();
2990
+ const owner = selected ? encodedFrom(selected) : null;
2991
+ if (owner && !isCurrentItem(owner)) clearSelection();
2992
+ }
2993
+ function setAssets(assets) {
2994
+ const hadAssets = hasAssets();
2995
+ const next = createAssetIndex(assets);
2996
+ for (const [key, asset] of assetIndex) {
2997
+ if (!next.has(key)) removedAssets.set(key, asset);
2998
+ }
2999
+ for (const key of next.keys()) removedAssets.delete(key);
3000
+ assetIndex = next;
3001
+ if (running && (hadAssets || hasAssets())) tagAssets();
3002
+ }
3003
+ function setReferences(referenceList, componentIds) {
3004
+ if (componentIds) scope.setComponents(componentIds);
3005
+ scope.setReferences(referenceList);
3006
+ }
3007
+ function setLocale(value) {
3008
+ locale = value;
3009
+ }
3010
+ function syncGuard() {
3011
+ if (running && guardEnabled) guard.start();
3012
+ else guard.stop();
3013
+ }
3014
+ function setNavigationGuard(enabled) {
3015
+ guardEnabled = enabled;
3016
+ syncGuard();
3017
+ }
3018
+ return {
3019
+ start,
3020
+ stop,
3021
+ setCurrentItem,
3022
+ setReferences,
3023
+ setAssets,
3024
+ itemSaved,
3025
+ setLocale,
3026
+ focusField,
3027
+ setNavigationGuard,
3028
+ allowNavigation: (href) => guard.allow(href)
3029
+ };
3030
+ }
3031
+
1987
3032
  // src/core/create-preview.ts
1988
- var debug6 = createScopedLogger("create-preview");
3033
+ var debug8 = createScopedLogger("create-preview");
1989
3034
  var controllerStores = /* @__PURE__ */ new WeakMap();
1990
3035
  function defaultNavigation() {
1991
3036
  return {
@@ -2001,8 +3046,14 @@ function safeEditUrl(href) {
2001
3046
  return null;
2002
3047
  }
2003
3048
  }
2004
- function buildSegments(data) {
2005
- return [{ _id: "all_other_users", name: "All other users" }, ...data];
3049
+ function buildSegments(data, locale) {
3050
+ return [
3051
+ {
3052
+ _id: SEGMENT_ALL_OTHER_USERS,
3053
+ name: t("adaptiveContent.allOtherUsers", locale)
3054
+ },
3055
+ ...data
3056
+ ];
2006
3057
  }
2007
3058
  function resolveLocale(options) {
2008
3059
  const explicit = options?.locale;
@@ -2023,11 +3074,23 @@ function createPreprPreview(opts = {}) {
2023
3074
  if (typeof window === "undefined" || typeof document === "undefined") {
2024
3075
  return noop();
2025
3076
  }
3077
+ if (options?.strictMode) {
3078
+ const shared = sharedState();
3079
+ shared.strictMode = true;
3080
+ if (shared.liveAnnouncedStrict === false) {
3081
+ sendPreprEvent(
3082
+ "live_ready",
3083
+ { strictMode: true },
3084
+ { allowUntrustedTarget: true }
3085
+ );
3086
+ shared.liveAnnouncedStrict = true;
3087
+ }
3088
+ }
2026
3089
  const isIframe = window.parent !== window;
2027
3090
  const search = new URLSearchParams(window.location.search);
2028
3091
  const hideBar = search.get(PARAM_HIDE_BAR) === "true";
2029
3092
  if (hideBar) {
2030
- debug6.log(`${PARAM_HIDE_BAR}=true \u2014 no visible toolbar`);
3093
+ debug8.log(`${PARAM_HIDE_BAR}=true \u2014 no visible toolbar`);
2031
3094
  }
2032
3095
  const mountUi = (options?.ui ?? true) && !isIframe && !hideBar;
2033
3096
  const locale = resolveLocale(options);
@@ -2041,7 +3104,7 @@ function createPreprPreview(opts = {}) {
2041
3104
  const store = createToolbarStore({
2042
3105
  locale,
2043
3106
  features,
2044
- segments: features.segments ? buildSegments(props?.segments ?? props?.data ?? []) : [],
3107
+ segments: features.segments ? buildSegments(props?.segments ?? props?.data ?? [], locale) : [],
2045
3108
  selectedSegment: features.segments ? props?.activeSegment ?? cookieSegment ?? null : null,
2046
3109
  selectedVariant,
2047
3110
  previewMode,
@@ -2051,39 +3114,55 @@ function createPreprPreview(opts = {}) {
2051
3114
  let el = null;
2052
3115
  if (mountUi) {
2053
3116
  definePreprToolbar();
2054
- el = document.createElement("prepr-toolbar");
3117
+ el = document.createElement(TOOLBAR_TAG);
2055
3118
  document.body.appendChild(el);
2056
- el.connect(store, (key) => t2(key, locale));
3119
+ el.connect(store, (key) => t(key, locale));
2057
3120
  }
2058
3121
  const editingEnabled = features.editMode || isIframe;
2059
- const stega = createStegaController({
2060
- // The CMS deep-link tooltip is chrome, so it follows the same decision as
2061
- // the bar: noise inside the editor (clicking the element itself requests
2062
- // the edit there), and unwanted in a headless preview that asked for no UI.
2063
- tooltip: mountUi,
2064
- // In the editor, ask the parent to focus the field instead of opening a new
2065
- // tab. Standalone previews keep the window.open behaviour.
2066
- onEdit: ({ href, origin, id, field }) => {
2067
- const safeHref = href ? safeEditUrl(href) : null;
2068
- if (href && !safeHref) {
2069
- debug6.warn("ignored edit request with unsupported href scheme");
2070
- return;
2071
- }
2072
- if (isIframe) {
2073
- sendPreprEvent("field_edit_requested", {
2074
- href: safeHref ?? void 0,
2075
- origin,
2076
- id,
2077
- field
2078
- });
2079
- } else if (safeHref) {
2080
- window.open(safeHref, "_blank", "noopener,noreferrer");
2081
- }
3122
+ const onEdit = ({
3123
+ href,
3124
+ id,
3125
+ field,
3126
+ locale: contentLocale,
3127
+ block,
3128
+ entryId,
3129
+ referenceField,
3130
+ linkHref
3131
+ }) => {
3132
+ const safeHref = href ? safeEditUrl(href) : null;
3133
+ if (href && !safeHref) {
3134
+ debug8.warn("ignored edit request with unsupported href scheme");
3135
+ return;
2082
3136
  }
3137
+ if (isIframe) {
3138
+ sendPreprEvent("field_edit_requested", {
3139
+ id,
3140
+ field,
3141
+ locale: contentLocale,
3142
+ ...block !== void 0 && { block },
3143
+ ...entryId && { entryId },
3144
+ ...referenceField && { referenceField },
3145
+ ...linkHref && { linkHref }
3146
+ });
3147
+ } else if (safeHref) {
3148
+ window.open(safeHref, "_blank", "noopener,noreferrer");
3149
+ }
3150
+ };
3151
+ const visualEditor = isIframe ? createVisualEditor({
3152
+ onEdit,
3153
+ locale,
3154
+ onNavigationBlocked: (href) => sendPreprEvent("navigation_blocked", { href })
3155
+ }) : null;
3156
+ const stega = visualEditor ?? createStegaController({
3157
+ // The edit-mode marks and hover label are chrome, so they follow the
3158
+ // same decision as the bar: unwanted in a headless preview that asked
3159
+ // for no UI.
3160
+ tooltip: mountUi,
3161
+ onEdit,
3162
+ locale
2083
3163
  });
2084
3164
  const autoClean = createStegaAutoClean({
2085
- enabled: options?.autoClean,
2086
- isHydrated: opts.isHydrated
3165
+ enabled: options?.autoClean
2087
3166
  });
2088
3167
  autoClean.start();
2089
3168
  const handleChange = createChangeHandler({
@@ -2102,7 +3181,36 @@ function createPreprPreview(opts = {}) {
2102
3181
  handleChange(before, state);
2103
3182
  });
2104
3183
  const bridge = createIframeBridge(store, {
2105
- allowedEditorOrigins: options?.allowedEditorOrigins
3184
+ allowedEditorOrigins: options?.allowedEditorOrigins,
3185
+ onHandshake: ({
3186
+ itemId,
3187
+ referencedIds,
3188
+ componentIds,
3189
+ uiLocale,
3190
+ navigationGuard,
3191
+ assets
3192
+ }) => {
3193
+ if (uiLocale) visualEditor?.setLocale(uiLocale);
3194
+ visualEditor?.setCurrentItem(itemId ?? null, referencedIds, componentIds);
3195
+ visualEditor?.setNavigationGuard(navigationGuard === true);
3196
+ if (assets) visualEditor?.setAssets(assets);
3197
+ },
3198
+ onAssets: (assets) => visualEditor?.setAssets(assets),
3199
+ onAllowNavigation: (href) => visualEditor?.allowNavigation(href),
3200
+ onItemChanged: () => visualEditor?.itemSaved(),
3201
+ onReferences: (referencedIds, componentIds) => visualEditor?.setReferences(referencedIds, componentIds),
3202
+ // The editor selecting a field scrolls the matching element into view. The
3203
+ // lookup relies on the attributes the stega scan writes, so it finds
3204
+ // nothing until encoded content has been tagged.
3205
+ onScrollToField: ({ field, id, block, entryId, fieldById }) => {
3206
+ if (visualEditor) {
3207
+ void visualEditor.focusField({ field, id, block, entryId, fieldById });
3208
+ return;
3209
+ }
3210
+ if (!scrollToField({ field, id })) {
3211
+ debug8.log("no element on this page renders field", field);
3212
+ }
3213
+ }
2106
3214
  });
2107
3215
  sendPreprEvent(
2108
3216
  "getScrollPosition",
@@ -2122,7 +3230,7 @@ function createPreprPreview(opts = {}) {
2122
3230
  bridge.stop();
2123
3231
  }
2124
3232
  el?.remove();
2125
- debug6.log("preview destroyed");
3233
+ debug8.log("preview destroyed");
2126
3234
  }
2127
3235
  const controller = { destroy };
2128
3236
  controllerStores.set(controller, store);
@@ -2195,15 +3303,8 @@ function setTrackingParam(key, value) {
2195
3303
  }
2196
3304
 
2197
3305
  export {
2198
- COOKIE_PREVIEW_MODE,
2199
- COOKIE_SEGMENT,
2200
- COOKIE_VARIANT,
2201
- COOKIE_UID,
2202
- COOKIE_HUBSPOT,
2203
- PARAM_SEGMENT,
2204
- PARAM_VARIANT,
2205
- PARAM_HIDE_BAR,
2206
- ONE_YEAR_SECONDS,
3306
+ stegaClean,
3307
+ decodeStega,
2207
3308
  createToolbarStore,
2208
3309
  PreprToolbarElement,
2209
3310
  definePreprToolbar,