sanity-plugin-visual-editor 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +263 -16
  3. package/TESTING.md +133 -0
  4. package/dist/PreviewBar-D_rw0bhP.js +3503 -0
  5. package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
  6. package/dist/bar.d.ts +22 -0
  7. package/dist/bar.js +67 -0
  8. package/dist/bar.js.map +1 -0
  9. package/dist/cloudflare.d.ts +87 -0
  10. package/dist/cloudflare.js +1134 -0
  11. package/dist/cloudflare.js.map +1 -0
  12. package/dist/data-D0qotTtt.d.ts +177 -0
  13. package/dist/host-x2eXr-LJ.js +619 -0
  14. package/dist/host-x2eXr-LJ.js.map +1 -0
  15. package/dist/host.d.ts +162 -0
  16. package/dist/host.js +3 -0
  17. package/dist/index-hDzatlg7.d.ts +276 -0
  18. package/dist/index.d.ts +18 -18
  19. package/dist/index.js +7 -8
  20. package/dist/link-search-JtZkxz4k.js +14 -0
  21. package/dist/link-search-JtZkxz4k.js.map +1 -0
  22. package/dist/next-client.d.ts +22 -0
  23. package/dist/next-client.js +112 -0
  24. package/dist/next-client.js.map +1 -0
  25. package/dist/next.d.ts +135 -0
  26. package/dist/next.js +176 -0
  27. package/dist/next.js.map +1 -0
  28. package/dist/node-labels-CDiW5rMq.js +122 -0
  29. package/dist/node-labels-CDiW5rMq.js.map +1 -0
  30. package/dist/page-documents-BFFcH8lD.d.ts +54 -0
  31. package/dist/page-documents-mGfw_flR.js +67 -0
  32. package/dist/page-documents-mGfw_flR.js.map +1 -0
  33. package/dist/perspective-BmS9TVtr.js +106 -0
  34. package/dist/perspective-BmS9TVtr.js.map +1 -0
  35. package/dist/preview-links-BZDZyIey.js +119 -0
  36. package/dist/preview-links-BZDZyIey.js.map +1 -0
  37. package/dist/preview-links-DM6BCiLV.d.ts +87 -0
  38. package/dist/protocol-BNO38gYy.js +280 -0
  39. package/dist/protocol-BNO38gYy.js.map +1 -0
  40. package/dist/protocol-BnRCy2wJ.d.ts +386 -0
  41. package/dist/server-B8MqMyaN.js +748 -0
  42. package/dist/server-B8MqMyaN.js.map +1 -0
  43. package/dist/server.d.ts +4 -0
  44. package/dist/server.js +3 -0
  45. package/dist/shell-DZotxRXX.d.ts +37 -0
  46. package/dist/studio.d.ts +93 -0
  47. package/dist/studio.js +1263 -0
  48. package/dist/studio.js.map +1 -0
  49. package/dist/sveltekit.d.ts +281 -0
  50. package/dist/sveltekit.js +394 -0
  51. package/dist/sveltekit.js.map +1 -0
  52. package/package.json +120 -39
  53. package/dist/index.d.mts +0 -21
  54. package/dist/index.js.map +0 -1
  55. package/dist/index.mjs +0 -8
  56. package/dist/index.mjs.map +0 -1
  57. package/sanity.json +0 -8
  58. package/src/index.ts +0 -27
  59. package/v2-incompatible.js +0 -11
@@ -0,0 +1,619 @@
1
+ import { _ as describeSanityPath, a as PREVIEW_BAR_POSITION_PARAM, b as matchFocusedNodes, d as isPreviewBarMessage, h as SANITY_NODE_ATTRIBUTE, l as isInspectorShortcut, u as isPreviewBarFrame, x as parseSanityNode } from "./protocol-BNO38gYy.js";
2
+ const SELECTOR = `[${SANITY_NODE_ATTRIBUTE}]`;
3
+ /** The nearest element at or above `start` whose `data-sanity` parses. */
4
+ function findSanityTarget(start) {
5
+ let element = null;
6
+ for (start instanceof Element ? element = start.closest(SELECTOR) : start instanceof Node && (element = start.parentElement?.closest(SELECTOR) ?? null); element;) {
7
+ let node = parseSanityNode(element.getAttribute(SANITY_NODE_ATTRIBUTE));
8
+ if (node) return {
9
+ element,
10
+ node
11
+ };
12
+ element = element.parentElement?.closest(SELECTOR) ?? null;
13
+ }
14
+ return null;
15
+ }
16
+ /** The editable ancestors above `element`, outermost first. */
17
+ function ancestors(element) {
18
+ let found = [], current = element.parentElement?.closest(SELECTOR) ?? null;
19
+ for (; current && found.length < 3;) {
20
+ let node = parseSanityNode(current.getAttribute(SANITY_NODE_ATTRIBUTE));
21
+ node && found.unshift({
22
+ element: current,
23
+ node
24
+ }), current = current.parentElement?.closest(SELECTOR) ?? null;
25
+ }
26
+ return found;
27
+ }
28
+ /** Every node on the page, in document order. */
29
+ function scanPage() {
30
+ let targets = [];
31
+ for (let element of document.querySelectorAll(SELECTOR)) {
32
+ let node = parseSanityNode(element.getAttribute(SANITY_NODE_ATTRIBUTE));
33
+ node && targets.push({
34
+ element,
35
+ node
36
+ });
37
+ }
38
+ return targets;
39
+ }
40
+ const nodeKey = (node) => `${node.id}\n${node.path}`;
41
+ function prefersReducedMotion() {
42
+ return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? !1;
43
+ }
44
+ function onScreen(rect) {
45
+ return rect.bottom > 0 && rect.right > 0 && rect.top < window.innerHeight && rect.left < window.innerWidth && (rect.width > 0 || rect.height > 0);
46
+ }
47
+ function mountClickToEdit(options) {
48
+ let available = options.active ?? !0, destroyed = !1, pointer = null, pointerTarget = null, needsResolve = !1, altHeld = !1, dismissed = !1, hovered = null, labelFor = null, lastRects = "", stableFrames = 0, frame = 0, tabWidth = 0, tabHeight = 0, pressed = null, labels = /* @__PURE__ */ new Map(), asked = /* @__PURE__ */ new Set(), toAsk = [], askQueued = !1, warned = /* @__PURE__ */ new Set(), scanned = [], scanSignature = "", scanTimer, idleHandle, focus = null, focusTargets = [], driftTargets = [], layer = document.createElement("sanity-plugin-visual-editor-overlay");
49
+ layer.setAttribute("aria-hidden", "true"), layer.style.zIndex = String(options.zIndex ?? 2147482999);
50
+ let shadow = layer.attachShadow({ mode: "open" }), style = document.createElement("style");
51
+ style.textContent = "\n:host {\n all: initial;\n position: fixed;\n inset: 0;\n pointer-events: none;\n contain: strict;\n --accent: #2276fc;\n --drift: #e5484d;\n font: 500 11px/16px -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", system-ui, sans-serif;\n}\n.box, .mark {\n position: absolute;\n top: 0;\n left: 0;\n display: none;\n box-sizing: border-box;\n border-radius: 2px;\n}\n.box {\n border: 1px solid var(--accent);\n background: rgb(34 118 252 / 0.06);\n}\n.mark[data-kind=\"focus\"] { border: 2px solid var(--accent); }\n.mark[data-kind=\"drift\"] { border: 1px dashed var(--drift); background: rgb(229 72 77 / 0.05); }\n.tab {\n position: absolute;\n top: 0;\n left: 0;\n display: none;\n align-items: baseline;\n gap: 6px;\n box-sizing: border-box;\n max-width: min(480px, calc(100vw - 8px));\n padding: 2px 6px;\n border-radius: 3px 3px 0 0;\n background: var(--accent);\n color: #fff;\n white-space: nowrap;\n}\n.tab[data-place=\"inside\"] { border-radius: 0 0 3px 0; }\n.tab[data-place=\"below\"] { border-radius: 0 0 3px 3px; }\n.tab[data-missing] { background: var(--drift); }\n/* Square the box's corner where the tab joins it. */\n.box[data-tab=\"above\"] { border-top-left-radius: 0; }\n.box[data-tab=\"below\"] { border-bottom-left-radius: 0; }\n.crumbs {\n flex: 0 1 auto;\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n opacity: 0.72;\n}\n.crumbs:empty { display: none; }\n.label { flex: none; font-weight: 600; }\n.note { flex: none; opacity: 0.85; }\n.note:empty { display: none; }\n";
52
+ let marks = document.createElement("div"), box = document.createElement("div");
53
+ box.className = "box";
54
+ let tab = document.createElement("div");
55
+ tab.className = "tab";
56
+ let crumbs = document.createElement("span");
57
+ crumbs.className = "crumbs";
58
+ let label = document.createElement("span");
59
+ label.className = "label";
60
+ let note = document.createElement("span");
61
+ note.className = "note", tab.append(crumbs, label, note), shadow.append(style, marks, box, tab), document.body.appendChild(layer);
62
+ let isActive = () => available && !destroyed;
63
+ function schedule() {
64
+ stableFrames = 0, !frame && !destroyed && (frame = requestAnimationFrame(tick));
65
+ }
66
+ function hideHover() {
67
+ box.style.display = "none", tab.style.display = "none";
68
+ }
69
+ function clearHover() {
70
+ hovered = null, labelFor = null, hideHover();
71
+ }
72
+ function hideAll() {
73
+ clearHover();
74
+ for (let mark of marks.children) mark.style.display = "none";
75
+ lastRects = "";
76
+ }
77
+ /** Hit-test again where the pointer is, on the next frame (a toggle, Alt released, a scroll). */
78
+ function resolveAtPointer() {
79
+ pointerTarget = null, needsResolve = !0;
80
+ }
81
+ function elementAtPointer() {
82
+ return pointer ? document.elementFromPoint(pointer.x, pointer.y) : null;
83
+ }
84
+ function ask(nodes) {
85
+ if (options.onDescribe) {
86
+ for (let node of nodes) {
87
+ let key = nodeKey(node);
88
+ labels.has(key) || asked.has(key) || (asked.add(key), toAsk.push(node));
89
+ }
90
+ toAsk.length && !askQueued && (askQueued = !0, queueMicrotask(flushAsk));
91
+ }
92
+ }
93
+ function flushAsk() {
94
+ askQueued = !1;
95
+ let nodes = toAsk;
96
+ if (toAsk = [], !destroyed) for (let start = 0; start < nodes.length; start += 500) options.onDescribe?.(nodes.slice(start, start + 500));
97
+ }
98
+ function labelOf(node) {
99
+ return labels.get(nodeKey(node))?.label || describeSanityPath(node.path);
100
+ }
101
+ function drawLabel(target) {
102
+ let above = ancestors(target.element);
103
+ ask([...above.map((item) => item.node), target.node]), crumbs.textContent = above.map((item) => labelOf(item.node)).join(" › "), label.textContent = labelOf(target.node);
104
+ let missing = labels.get(nodeKey(target.node))?.missing;
105
+ note.textContent = missing ? "not in the document" : "", tab.toggleAttribute("data-missing", !!missing), tab.style.display = "flex", tabWidth = tab.offsetWidth, tabHeight = tab.offsetHeight;
106
+ }
107
+ function refreshFocus() {
108
+ focusTargets = focus ? matchFocusedNodes(scanPage(), focus).slice(0, 40) : [];
109
+ }
110
+ function refreshDrift() {
111
+ driftTargets = scanned.filter((target) => labels.get(nodeKey(target.node))?.missing).slice(0, 40);
112
+ for (let target of driftTargets) {
113
+ let key = nodeKey(target.node);
114
+ warned.has(key) || (warned.add(key), console.warn(`sanity-visual-editor: data-sanity path "${target.node.path}" not found in ${target.node.type} "${target.node.id}"`, target.element));
115
+ }
116
+ }
117
+ function scan() {
118
+ if (idleHandle = void 0, !isActive()) return;
119
+ let targets = scanPage(), signature = targets.map((target) => target.element.getAttribute(SANITY_NODE_ATTRIBUTE)).join("\n");
120
+ scanned = targets, signature !== scanSignature && (scanSignature = signature, ask(targets.map((target) => target.node))), refreshDrift(), driftTargets.length && schedule(), scanTimer = setTimeout(scanWhenIdle, 4e3);
121
+ }
122
+ function scanWhenIdle() {
123
+ isActive() && options.onDescribe && ("requestIdleCallback" in window ? idleHandle = window.requestIdleCallback(scan, { timeout: 2e3 }) : scan());
124
+ }
125
+ function stopScanning() {
126
+ clearTimeout(scanTimer), idleHandle !== void 0 && "cancelIdleCallback" in window && window.cancelIdleCallback(idleHandle), idleHandle = void 0;
127
+ }
128
+ function markAt(index) {
129
+ let mark = marks.children[index];
130
+ return mark || (mark = document.createElement("div"), mark.className = "mark", marks.appendChild(mark)), mark;
131
+ }
132
+ function placeBox(element, rect) {
133
+ Object.assign(element.style, {
134
+ display: "block",
135
+ width: `${rect.width}px`,
136
+ height: `${rect.height}px`,
137
+ transform: `translate(${rect.left}px, ${rect.top}px)`
138
+ });
139
+ }
140
+ function placeTab(rect) {
141
+ let viewportWidth = document.documentElement.clientWidth || window.innerWidth, left = Math.max(4, Math.min(rect.left, viewportWidth - tabWidth - 4)), top = rect.top - tabHeight, place = "above";
142
+ top < 0 && (place = rect.height > tabHeight * 2 ? "inside" : "below", top = place === "inside" ? Math.max(rect.top, 0) : rect.bottom), tab.dataset.place = place, left === rect.left && place !== "inside" ? box.dataset.tab = place : delete box.dataset.tab, tab.style.display = "flex", tab.style.transform = `translate(${left}px, ${top}px)`;
143
+ }
144
+ function tick() {
145
+ if (frame = 0, !isActive() || altHeld) {
146
+ hideAll();
147
+ return;
148
+ }
149
+ if (dismissed) clearHover();
150
+ else if (needsResolve && (needsResolve = !1, hovered = findSanityTarget(pointerTarget ?? elementAtPointer()), pointerTarget = null), hovered && !hovered.element.isConnected && (hovered = findSanityTarget(elementAtPointer())), hovered) {
151
+ let attribute = hovered.element.getAttribute(SANITY_NODE_ATTRIBUTE), node = parseSanityNode(attribute);
152
+ if (!node) clearHover();
153
+ else {
154
+ hovered = {
155
+ element: hovered.element,
156
+ node
157
+ };
158
+ let known = labels.get(nodeKey(node)), drawnFor = `${attribute}\n${known?.label ?? ""}\n${known?.missing ?? ""}`;
159
+ drawnFor !== labelFor && (labelFor = drawnFor, lastRects = "", drawLabel(hovered));
160
+ }
161
+ } else clearHover();
162
+ focus && focusTargets.some((target) => !target.element.isConnected) && refreshFocus(), driftTargets = driftTargets.filter((target) => target.element.isConnected);
163
+ let outlined = [...focusTargets.map((target) => ({
164
+ target,
165
+ kind: "focus"
166
+ })), ...driftTargets.map((target) => ({
167
+ target,
168
+ kind: "drift"
169
+ }))], hoverRect = hovered?.element.getBoundingClientRect(), rects = outlined.map(({ target }) => target.element.getBoundingClientRect()), key = [hoverRect, ...rects].map((rect) => rect ? `${rect.left},${rect.top},${rect.width},${rect.height}` : "-").join(";");
170
+ if (key !== lastRects) {
171
+ lastRects = key, stableFrames = 0, hoverRect && (hoverRect.width > 0 || hoverRect.height > 0) ? (placeBox(box, hoverRect), placeTab(hoverRect)) : hideHover(), outlined.forEach(({ kind }, index) => {
172
+ let mark = markAt(index);
173
+ mark.dataset.kind = kind;
174
+ let rect = rects[index];
175
+ rect.width > 0 || rect.height > 0 ? placeBox(mark, rect) : mark.style.display = "none";
176
+ });
177
+ for (let index = outlined.length; index < marks.children.length; index++) marks.children[index].style.display = "none";
178
+ } else stableFrames++;
179
+ stableFrames < 20 && (hovered || outlined.length) && (frame = requestAnimationFrame(tick));
180
+ }
181
+ function onPointerMove(event) {
182
+ pointer = {
183
+ x: event.clientX,
184
+ y: event.clientY
185
+ }, altHeld = event.altKey, isActive() && (pointerTarget = event.target, needsResolve = !0, dismissed = !1, schedule());
186
+ }
187
+ function onPointerOut(event) {
188
+ let next = event.relatedTarget;
189
+ (!next || next instanceof HTMLIFrameElement) && (pointer = null, pointerTarget = null, needsResolve = !1, clearHover(), isActive() && schedule());
190
+ }
191
+ function onViewportChange() {
192
+ isActive() && (pointer && resolveAtPointer(), (hovered || pointer || focusTargets.length || driftTargets.length) && schedule());
193
+ }
194
+ function onKeyDown(event) {
195
+ if (event.key === "Alt") altHeld = !0, schedule();
196
+ else if (event.key === "Escape") {
197
+ if (!hovered || !isActive()) return;
198
+ dismissed = !0, schedule();
199
+ }
200
+ }
201
+ function onKeyUp(event) {
202
+ event.key === "Alt" && (altHeld = !1, isActive() && (resolveAtPointer(), schedule()));
203
+ }
204
+ function onBlur() {
205
+ altHeld && (altHeld = !1, schedule());
206
+ }
207
+ /** An unmodified primary press on an editable element, while click-to-edit is on. */
208
+ function interceptable(event) {
209
+ return !isActive() || event.button !== 0 || event.altKey || event.metaKey || event.ctrlKey || event.shiftKey ? null : findSanityTarget(event.target);
210
+ }
211
+ function swallow(event) {
212
+ event.preventDefault(), event.stopPropagation(), event.stopImmediatePropagation();
213
+ }
214
+ function onPointerDown(event) {
215
+ if (pressed = null, !event.isPrimary) return;
216
+ let target = interceptable(event);
217
+ target && (swallow(event), pressed = target.node);
218
+ }
219
+ function onPointerUp(event) {
220
+ pressed && swallow(event);
221
+ }
222
+ function onPointerCancel() {
223
+ pressed = null;
224
+ }
225
+ function onClick(event) {
226
+ let node = pressed;
227
+ node && (pressed = null, swallow(event), options.onEdit(node));
228
+ }
229
+ function onDragStart(event) {
230
+ (pressed || interceptable(event)) && event.preventDefault();
231
+ }
232
+ /** On again (the inspector): hover where the pointer is, outline focus, rescan. */
233
+ function activated() {
234
+ pressed = null, stopScanning(), isActive() ? (dismissed = !1, resolveAtPointer(), refreshFocus(), scanSignature = "", scanWhenIdle(), schedule()) : hideAll();
235
+ }
236
+ let capture = { capture: !0 }, passiveCapture = {
237
+ capture: !0,
238
+ passive: !0
239
+ };
240
+ return window.addEventListener("pointermove", onPointerMove, { passive: !0 }), window.addEventListener("pointerout", onPointerOut, passiveCapture), window.addEventListener("scroll", onViewportChange, passiveCapture), window.addEventListener("resize", onViewportChange, { passive: !0 }), window.addEventListener("keydown", onKeyDown, capture), window.addEventListener("keyup", onKeyUp, capture), window.addEventListener("blur", onBlur), window.addEventListener("pointerdown", onPointerDown, capture), window.addEventListener("pointerup", onPointerUp, capture), window.addEventListener("pointercancel", onPointerCancel, capture), window.addEventListener("click", onClick, capture), window.addEventListener("dragstart", onDragStart, capture), isActive() && scanWhenIdle(), {
241
+ setActive(next) {
242
+ destroyed || next === available || (available = next, activated());
243
+ },
244
+ setLabels(next) {
245
+ if (!destroyed) {
246
+ for (let item of next) {
247
+ let key = nodeKey(item);
248
+ asked.delete(key), labels.set(key, item.missing ? {
249
+ label: item.label,
250
+ missing: !0
251
+ } : { label: item.label });
252
+ }
253
+ refreshDrift(), labelFor = null, isActive() && schedule();
254
+ }
255
+ },
256
+ setFocus(next) {
257
+ if (destroyed || (focus = next && next.id && next.path ? next : null, refreshFocus(), !isActive())) return;
258
+ let first = focusTargets[0];
259
+ first && !focusTargets.some((target) => onScreen(target.element.getBoundingClientRect())) && first.element.scrollIntoView({
260
+ block: "center",
261
+ behavior: prefersReducedMotion() ? "auto" : "smooth"
262
+ }), schedule();
263
+ },
264
+ destroy() {
265
+ destroyed || (destroyed = !0, stopScanning(), cancelAnimationFrame(frame), window.removeEventListener("pointermove", onPointerMove), window.removeEventListener("pointerout", onPointerOut, passiveCapture), window.removeEventListener("scroll", onViewportChange, passiveCapture), window.removeEventListener("resize", onViewportChange), window.removeEventListener("keydown", onKeyDown, capture), window.removeEventListener("keyup", onKeyUp, capture), window.removeEventListener("blur", onBlur), window.removeEventListener("pointerdown", onPointerDown, capture), window.removeEventListener("pointerup", onPointerUp, capture), window.removeEventListener("pointercancel", onPointerCancel, capture), window.removeEventListener("click", onClick, capture), window.removeEventListener("dragstart", onDragStart, capture), layer.remove());
266
+ }
267
+ };
268
+ }
269
+ /**
270
+ * Storefront subscriber for the realtime preview hub: opens a WebSocket first (falling back to
271
+ * long polling where upgrades cannot open, such as Vite dev), resumes from its cursor, and calls
272
+ * `onChange` with changed query keys, pushed results, and remote-query labels.
273
+ */
274
+ const PREVIEW_SOCKET_PATH = "/api/preview/socket", PREVIEW_EVENTS_PATH = "/api/preview/events", RETRY_MS = 2e3;
275
+ /**
276
+ * Follow the realtime preview hub and call `onChange` with changed query keys and pushed results.
277
+ * When the hub cannot tell what was missed (it restarted or was redeployed), `onChange` is called
278
+ * with no keys (`keys: []`): refresh everything. Returns a function that stops following.
279
+ */
280
+ function subscribePreviewEvents(onChange, options) {
281
+ let socketPath = options?.socketPath ?? "/api/preview/socket", eventsPath = options?.eventsPath ?? "/api/preview/events", onStatus = options?.onStatus, params = options?.params ?? {}, urlFor = (path) => {
282
+ let url = new URL(path, location.href);
283
+ for (let [key, value] of Object.entries(params)) url.searchParams.set(key, value);
284
+ return cursor && url.searchParams.set("after", cursor), url;
285
+ }, controller = new AbortController(), cursor = "", socket = null, ping, retry, wake, timer, pending = /* @__PURE__ */ new Set(), results = {}, labels = {}, status = null, setStatus = (next) => {
286
+ status !== next && (status = next, onStatus?.(next));
287
+ }, sleep = (ms) => new Promise((resolve) => {
288
+ wake = resolve, retry = setTimeout(() => {
289
+ wake = void 0, resolve();
290
+ }, ms);
291
+ }), flush = () => {
292
+ timer = void 0;
293
+ let keys = [...pending], change = {
294
+ keys,
295
+ results,
296
+ labels
297
+ };
298
+ pending.clear(), results = {}, labels = {}, keys.length && onChange(change);
299
+ }, receive = (data) => {
300
+ data.reset && cursor && onChange({
301
+ keys: [],
302
+ results: {},
303
+ labels: {}
304
+ }), cursor = data.cursor;
305
+ for (let event of data.events) for (let key of event.keys) pending.add(key), event.results && key in event.results ? results[key] = event.results[key] : delete results[key], event.labels?.[key] && (labels[key] = event.labels[key]);
306
+ pending.size && !timer && (timer = setTimeout(flush, 0));
307
+ }, openSocket = (failures) => {
308
+ if (controller.signal.aborted) return;
309
+ let url = urlFor(socketPath);
310
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
311
+ let opened = !1, timedOut = !1, ws = new WebSocket(url);
312
+ socket = ws;
313
+ let openTimeout = setTimeout(() => {
314
+ timedOut = !0, ws.close();
315
+ }, 1500);
316
+ ws.addEventListener("open", () => {
317
+ clearTimeout(openTimeout), opened = !0, setStatus("connected"), ping = setInterval(() => ws.send("ping"), 2e4);
318
+ }), ws.addEventListener("message", (event) => {
319
+ if (typeof event.data == "string" && event.data !== "pong") try {
320
+ receive(JSON.parse(event.data));
321
+ } catch {}
322
+ }), ws.addEventListener("close", () => {
323
+ if (clearTimeout(openTimeout), clearInterval(ping), socket === ws && (socket = null), controller.signal.aborted) return;
324
+ let nextFailures = opened ? 0 : failures + 1;
325
+ timedOut || nextFailures >= 2 ? poll() : sleep(RETRY_MS).then(() => openSocket(nextFailures));
326
+ });
327
+ }, poll = async () => {
328
+ let fails = 0;
329
+ for (setStatus("polling"); !controller.signal.aborted;) try {
330
+ let response = await fetch(urlFor(eventsPath), {
331
+ credentials: "same-origin",
332
+ signal: controller.signal
333
+ });
334
+ if (response.status === 204 || response.status === 403) return;
335
+ if (!response.ok) throw Error(`HTTP ${response.status}`);
336
+ fails = 0, setStatus("polling"), receive(await response.json());
337
+ } catch {
338
+ if (controller.signal.aborted) return;
339
+ fails += 1, fails >= 2 && setStatus("offline"), await sleep(RETRY_MS);
340
+ }
341
+ };
342
+ return openSocket(0), () => {
343
+ controller.abort(), clearInterval(ping), clearTimeout(retry), clearTimeout(timer), wake?.(), wake = void 0, socket?.close();
344
+ };
345
+ }
346
+ /**
347
+ * The site side of the bar, with no React or Sanity UI: a same-origin iframe framing the bar's
348
+ * route, mounted only in preview mode. Framework adapters call `mountPreviewBarHost` with their own
349
+ * `refresh` (rerun the page's data in place) and `navigate` (client-side navigation).
350
+ *
351
+ * Same layout as Shopify's theme preview bar: the frame is always a full viewport tall and pinned to
352
+ * the bar's edge (bottom by default, or top) of a bar-height wrapper that clips it. Opening a menu only stops the clipping, so the
353
+ * frame's viewport never changes and its popovers position once, with no relayout. The wrapper is a
354
+ * manual popover, so it sits in the top layer above every stacking context.
355
+ *
356
+ * With the document pane open the wrapper grows to the full viewport and a `clip-path` cuts it to
357
+ * an L: the pane's full-height column (on the left or right) plus the bar, which narrows to sit
358
+ * beside it. Clipped-out areas take no pointer events, so the rest of the page stays clickable,
359
+ * and the page gets padding on the pane's side so its content reflows beside the pane.
360
+ *
361
+ * Click-to-edit (`overlay.ts`) runs only in the Visual Editor tool's frame (`mountPreviewBarFrame`),
362
+ * not on the site.
363
+ */
364
+ /**
365
+ * Whether this window should show the bar: the top window only. The Studio's Visual Editor frames
366
+ * the site with its own bar, and other embeds (thumbnails) shouldn't get one.
367
+ */
368
+ function isTopWindow() {
369
+ return typeof window < "u" && window.self === window.top;
370
+ }
371
+ function isEditable(target) {
372
+ return !!target?.closest?.("input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]");
373
+ }
374
+ function editMessage(node) {
375
+ return {
376
+ type: "sanity-visual-editor:edit",
377
+ id: node.id,
378
+ documentType: node.type,
379
+ path: node.path
380
+ };
381
+ }
382
+ function currentPath() {
383
+ return window.location.pathname + window.location.search;
384
+ }
385
+ /** The bar's height including the safe area on its edge, as a CSS length. */
386
+ function barHeight(position) {
387
+ return `(50px + env(safe-area-inset-${position}, 0px))`;
388
+ }
389
+ /**
390
+ * The frame's clip while the pane is open: the union of the pane's full-height column (`side`) and
391
+ * the bar's full-width strip (`position`), as a polygon in the wrapper's coordinates.
392
+ */
393
+ function panelClipPath(side, position, width, barHeightCss) {
394
+ let inner = side === "right" ? `calc(100% - ${width}px)` : `${width}px`, strip = position === "bottom" ? `calc(100% - ${barHeightCss})` : `calc${barHeightCss}`;
395
+ return `polygon(${(position === "bottom" ? side === "right" ? [
396
+ `0 ${strip}`,
397
+ `${inner} ${strip}`,
398
+ `${inner} 0`,
399
+ "100% 0",
400
+ "100% 100%",
401
+ "0 100%"
402
+ ] : [
403
+ "0 0",
404
+ `${inner} 0`,
405
+ `${inner} ${strip}`,
406
+ `100% ${strip}`,
407
+ "100% 100%",
408
+ "0 100%"
409
+ ] : side === "right" ? [
410
+ "0 0",
411
+ "100% 0",
412
+ "100% 100%",
413
+ `${inner} 100%`,
414
+ `${inner} ${strip}`,
415
+ `0 ${strip}`
416
+ ] : [
417
+ "0 0",
418
+ "100% 0",
419
+ `100% ${strip}`,
420
+ `${inner} ${strip}`,
421
+ `${inner} 100%`,
422
+ "0 100%"
423
+ ]).join(", ")})`;
424
+ }
425
+ function mountPreviewBarHost(options) {
426
+ let basePath = options.basePath ?? "/__visual-editor", position = options.position === "top" ? "top" : "bottom", BAR_HEIGHT = barHeight(position), path = options.path ?? currentPath(), destroyed = !1, liveStatus = null, overlayOpen = !1, panelWidth = 0, panelSide = "left", wrapper = document.createElement("div");
427
+ wrapper.setAttribute("popover", "manual"), wrapper.dataset.sanityPreviewBar = "", Object.assign(wrapper.style, {
428
+ position: "fixed",
429
+ inset: position === "top" ? "0 0 auto 0" : "auto 0 0 0",
430
+ zIndex: "2147483000",
431
+ boxSizing: "border-box",
432
+ width: "100%",
433
+ height: `calc${BAR_HEIGHT}`,
434
+ margin: "0",
435
+ padding: "0",
436
+ border: "0",
437
+ overflow: "hidden",
438
+ background: "transparent"
439
+ });
440
+ let iframe = document.createElement("iframe");
441
+ iframe.src = position === "top" ? `${basePath}?${PREVIEW_BAR_POSITION_PARAM}=top` : basePath, iframe.title = "Sanity preview bar", iframe.allow = "clipboard-write", iframe.setAttribute("sandbox", "allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox allow-top-navigation"), Object.assign(iframe.style, {
442
+ position: "absolute",
443
+ [position]: `env(safe-area-inset-${position}, 0px)`,
444
+ left: "0",
445
+ display: "block",
446
+ width: "100%",
447
+ height: "100dvh",
448
+ border: "0",
449
+ colorScheme: "normal"
450
+ }), wrapper.appendChild(iframe), document.body.appendChild(wrapper), "showPopover" in wrapper && wrapper.showPopover();
451
+ let root = document.documentElement;
452
+ root.style.setProperty(`padding-${position}`, "50px");
453
+ /** Clipping for the current overlay and pane state. */
454
+ function layout() {
455
+ let panel = panelWidth > 0;
456
+ wrapper.style.height = panel ? "100dvh" : `calc${BAR_HEIGHT}`, wrapper.style.overflow = overlayOpen ? "visible" : "hidden", wrapper.style.clipPath = panel && !overlayOpen ? panelClipPath(panelSide, position, panelWidth, BAR_HEIGHT) : "", root.style.removeProperty("padding-left"), root.style.removeProperty("padding-right"), panel && window.innerWidth - panelWidth >= 360 && root.style.setProperty(`padding-${panelSide}`, `${panelWidth}px`);
457
+ }
458
+ function post(message) {
459
+ iframe.contentWindow?.postMessage(message, window.location.origin);
460
+ }
461
+ function hide() {
462
+ destroy();
463
+ }
464
+ function onMessage(event) {
465
+ if (event.origin === window.location.origin && event.source === iframe.contentWindow && isPreviewBarMessage(event.data)) switch (event.data.type) {
466
+ case "sanity-visual-editor:ready":
467
+ post({
468
+ type: "sanity-visual-editor:path",
469
+ path
470
+ }), liveStatus && post({
471
+ type: "sanity-visual-editor:live-status",
472
+ status: liveStatus
473
+ });
474
+ break;
475
+ case "sanity-visual-editor:hide":
476
+ hide();
477
+ break;
478
+ case "sanity-visual-editor:menu":
479
+ overlayOpen = event.data.open, layout();
480
+ break;
481
+ case "sanity-visual-editor:panel":
482
+ panelWidth = event.data.open ? Math.min(event.data.width, window.innerWidth) : 0, panelSide = event.data.side, layout();
483
+ break;
484
+ case "sanity-visual-editor:navigate":
485
+ options.navigate(event.data.href);
486
+ break;
487
+ case "sanity-visual-editor:refresh": Promise.resolve().then(() => options.refresh()).finally(() => post({ type: "sanity-visual-editor:refreshed" }));
488
+ }
489
+ }
490
+ function onKeyDown(event) {
491
+ let key = event.key.toLowerCase();
492
+ (event.metaKey || event.ctrlKey) && key === "k" ? (event.preventDefault(), post({ type: "sanity-visual-editor:search" })) : key !== "e" || event.metaKey || event.ctrlKey || event.altKey || event.repeat || event.isComposing || event.defaultPrevented || isEditable(event.target) || post({ type: "sanity-visual-editor:pane" });
493
+ }
494
+ function onResize() {
495
+ panelWidth > 0 && layout();
496
+ }
497
+ window.addEventListener("message", onMessage), window.addEventListener("keydown", onKeyDown), window.addEventListener("resize", onResize);
498
+ function destroy() {
499
+ destroyed || (destroyed = !0, window.removeEventListener("message", onMessage), window.removeEventListener("keydown", onKeyDown), window.removeEventListener("resize", onResize), root.style.removeProperty(`padding-${position}`), root.style.removeProperty("padding-left"), root.style.removeProperty("padding-right"), wrapper.remove());
500
+ }
501
+ return {
502
+ setPath(next) {
503
+ path = next, post({
504
+ type: "sanity-visual-editor:path",
505
+ path
506
+ });
507
+ },
508
+ setLiveStatus(status) {
509
+ liveStatus = status, post({
510
+ type: "sanity-visual-editor:live-status",
511
+ status
512
+ });
513
+ },
514
+ destroy
515
+ };
516
+ }
517
+ /**
518
+ * The site's side when the Studio's Visual Editor tool frames it (`isPreviewBarFrame()`): no bar
519
+ * here (the tool shows it above the frame), just the tool's messages. The page reports its path
520
+ * on load and after every navigation (`setPath`), reruns its data when the bar switches
521
+ * perspective, and navigates when a search result is picked. Only the parent window on this
522
+ * origin is listened to. Click-to-edit follows the bar's inspector; ⌘⇧I on the page toggles it.
523
+ */
524
+ function mountPreviewBarFrame(options) {
525
+ let path = options.path ?? currentPath(), destroyed = !1;
526
+ function post(message) {
527
+ window.parent.postMessage(message, window.location.origin);
528
+ }
529
+ function onMessage(event) {
530
+ if (event.origin === window.location.origin && event.source === window.parent && isPreviewBarMessage(event.data)) switch (event.data.type) {
531
+ case "sanity-visual-editor:ready":
532
+ post({
533
+ type: "sanity-visual-editor:frame-path",
534
+ path
535
+ });
536
+ break;
537
+ case "sanity-visual-editor:navigate":
538
+ options.navigate(event.data.href);
539
+ break;
540
+ case "sanity-visual-editor:refresh":
541
+ Promise.resolve().then(() => options.refresh()).finally(() => post({ type: "sanity-visual-editor:refreshed" }));
542
+ break;
543
+ case "sanity-visual-editor:inspector":
544
+ clickToEdit?.setActive(event.data.active);
545
+ break;
546
+ case "sanity-visual-editor:labels":
547
+ clickToEdit?.setLabels(event.data.labels);
548
+ break;
549
+ case "sanity-visual-editor:focus": clickToEdit?.setFocus(event.data);
550
+ }
551
+ }
552
+ function onKeyDown(event) {
553
+ isInspectorShortcut(event) && (event.preventDefault(), post({ type: "sanity-visual-editor:toggle-inspector" }));
554
+ }
555
+ let clickToEdit = options.clickToEdit === !1 ? null : mountClickToEdit({
556
+ active: !1,
557
+ onEdit: (node) => post(editMessage(node)),
558
+ onDescribe: (nodes) => post({
559
+ type: "sanity-visual-editor:describe",
560
+ nodes
561
+ })
562
+ });
563
+ return window.addEventListener("message", onMessage), clickToEdit && window.addEventListener("keydown", onKeyDown), post({
564
+ type: "sanity-visual-editor:frame-path",
565
+ path
566
+ }), {
567
+ setPath(next) {
568
+ path = next, destroyed || post({
569
+ type: "sanity-visual-editor:frame-path",
570
+ path
571
+ });
572
+ },
573
+ setLiveStatus(status) {
574
+ destroyed || post({
575
+ type: "sanity-visual-editor:live-status",
576
+ status
577
+ });
578
+ },
579
+ destroy() {
580
+ destroyed = !0, window.removeEventListener("message", onMessage), window.removeEventListener("keydown", onKeyDown), clickToEdit?.destroy();
581
+ }
582
+ };
583
+ }
584
+ /**
585
+ * One-call storefront entry point: automatically skips non-preview pages, `?studio-preview`
586
+ * thumbnails, and third-party iframes; mounts `mountPreviewBarFrame` inside the Studio Visual
587
+ * Editor or `mountPreviewBarHost` in the top window; and subscribes to realtime preview events.
588
+ */
589
+ function connectVisualEditor(options) {
590
+ let { enabled, live = !0, onLiveChange, socketPath, eventsPath, onStatus, ...hostOptions } = options, frame = isPreviewBarFrame(), studioPreview = typeof window < "u" && new URLSearchParams(window.location.search).has("studio-preview");
591
+ if (!enabled || studioPreview || !isTopWindow() && !frame) return {
592
+ setPath() {},
593
+ setLiveStatus() {},
594
+ destroy() {}
595
+ };
596
+ let host = frame ? mountPreviewBarFrame(hostOptions) : mountPreviewBarHost(hostOptions), stopLive = live === !1 ? void 0 : subscribePreviewEvents((change) => {
597
+ onLiveChange ? onLiveChange(change) : hostOptions.refresh();
598
+ }, {
599
+ socketPath,
600
+ eventsPath,
601
+ onStatus(status) {
602
+ host.setLiveStatus(status), onStatus?.(status);
603
+ }
604
+ });
605
+ return {
606
+ setPath(next) {
607
+ host.setPath(next);
608
+ },
609
+ setLiveStatus(status) {
610
+ host.setLiveStatus(status);
611
+ },
612
+ destroy() {
613
+ stopLive?.(), host.destroy();
614
+ }
615
+ };
616
+ }
617
+ export { panelClipPath as a, subscribePreviewEvents as c, mountPreviewBarHost as i, findSanityTarget as l, isTopWindow as n, PREVIEW_EVENTS_PATH as o, mountPreviewBarFrame as r, PREVIEW_SOCKET_PATH as s, connectVisualEditor as t, mountClickToEdit as u };
618
+
619
+ //# sourceMappingURL=host-x2eXr-LJ.js.map