sanity-plugin-visual-editor 1.0.0 → 1.1.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.
- package/LICENSE +1 -1
- package/README.md +137 -16
- package/TESTING.md +133 -0
- package/dist/PreviewBar-D_rw0bhP.js +3503 -0
- package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
- package/dist/bar.d.ts +22 -0
- package/dist/bar.js +67 -0
- package/dist/bar.js.map +1 -0
- package/dist/cloudflare.d.ts +76 -0
- package/dist/cloudflare.js +1071 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/data-D0qotTtt.d.ts +177 -0
- package/dist/host-DreYJEmR.js +615 -0
- package/dist/host-DreYJEmR.js.map +1 -0
- package/dist/host.d.ts +160 -0
- package/dist/host.js +3 -0
- package/dist/index-4Zm_NjhC.d.ts +221 -0
- package/dist/index.d.ts +18 -18
- package/dist/index.js +7 -8
- package/dist/link-search-JtZkxz4k.js +14 -0
- package/dist/link-search-JtZkxz4k.js.map +1 -0
- package/dist/link-session-Dr4YkKFy.js +52 -0
- package/dist/link-session-Dr4YkKFy.js.map +1 -0
- package/dist/next-client.d.ts +15 -0
- package/dist/next-client.js +78 -0
- package/dist/next-client.js.map +1 -0
- package/dist/next.d.ts +38 -0
- package/dist/next.js +117 -0
- package/dist/next.js.map +1 -0
- package/dist/node-labels-CDiW5rMq.js +122 -0
- package/dist/node-labels-CDiW5rMq.js.map +1 -0
- package/dist/page-documents-BFFcH8lD.d.ts +54 -0
- package/dist/page-documents-mGfw_flR.js +67 -0
- package/dist/page-documents-mGfw_flR.js.map +1 -0
- package/dist/perspective-BmS9TVtr.js +106 -0
- package/dist/perspective-BmS9TVtr.js.map +1 -0
- package/dist/preview-links-BZDZyIey.js +119 -0
- package/dist/preview-links-BZDZyIey.js.map +1 -0
- package/dist/preview-links-DM6BCiLV.d.ts +87 -0
- package/dist/protocol-BNO38gYy.js +280 -0
- package/dist/protocol-BNO38gYy.js.map +1 -0
- package/dist/protocol-BnRCy2wJ.d.ts +386 -0
- package/dist/server.d.ts +4 -0
- package/dist/server.js +495 -0
- package/dist/server.js.map +1 -0
- package/dist/shell-DZotxRXX.d.ts +37 -0
- package/dist/studio.d.ts +93 -0
- package/dist/studio.js +1263 -0
- package/dist/studio.js.map +1 -0
- package/dist/sveltekit.d.ts +281 -0
- package/dist/sveltekit.js +395 -0
- package/dist/sveltekit.js.map +1 -0
- package/package.json +120 -39
- package/dist/index.d.mts +0 -21
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -8
- package/dist/index.mjs.map +0 -1
- package/sanity.json +0 -8
- package/src/index.ts +0 -27
- package/v2-incompatible.js +0 -11
|
@@ -0,0 +1,615 @@
|
|
|
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, controller = new AbortController(), cursor = "", socket = null, ping, retry, wake, timer, pending = /* @__PURE__ */ new Set(), results = {}, labels = {}, status = null, setStatus = (next) => {
|
|
282
|
+
status !== next && (status = next, onStatus?.(next));
|
|
283
|
+
}, sleep = (ms) => new Promise((resolve) => {
|
|
284
|
+
wake = resolve, retry = setTimeout(() => {
|
|
285
|
+
wake = void 0, resolve();
|
|
286
|
+
}, ms);
|
|
287
|
+
}), flush = () => {
|
|
288
|
+
timer = void 0;
|
|
289
|
+
let keys = [...pending], change = {
|
|
290
|
+
keys,
|
|
291
|
+
results,
|
|
292
|
+
labels
|
|
293
|
+
};
|
|
294
|
+
pending.clear(), results = {}, labels = {}, keys.length && onChange(change);
|
|
295
|
+
}, receive = (data) => {
|
|
296
|
+
data.reset && cursor && onChange({
|
|
297
|
+
keys: [],
|
|
298
|
+
results: {},
|
|
299
|
+
labels: {}
|
|
300
|
+
}), cursor = data.cursor;
|
|
301
|
+
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]);
|
|
302
|
+
pending.size && !timer && (timer = setTimeout(flush, 0));
|
|
303
|
+
}, openSocket = (failures) => {
|
|
304
|
+
if (controller.signal.aborted) return;
|
|
305
|
+
let url = new URL(socketPath, location.href);
|
|
306
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:", cursor && url.searchParams.set("after", cursor);
|
|
307
|
+
let opened = !1, timedOut = !1, ws = new WebSocket(url);
|
|
308
|
+
socket = ws;
|
|
309
|
+
let openTimeout = setTimeout(() => {
|
|
310
|
+
timedOut = !0, ws.close();
|
|
311
|
+
}, 1500);
|
|
312
|
+
ws.addEventListener("open", () => {
|
|
313
|
+
clearTimeout(openTimeout), opened = !0, setStatus("connected"), ping = setInterval(() => ws.send("ping"), 2e4);
|
|
314
|
+
}), ws.addEventListener("message", (event) => {
|
|
315
|
+
if (typeof event.data == "string" && event.data !== "pong") try {
|
|
316
|
+
receive(JSON.parse(event.data));
|
|
317
|
+
} catch {}
|
|
318
|
+
}), ws.addEventListener("close", () => {
|
|
319
|
+
if (clearTimeout(openTimeout), clearInterval(ping), socket === ws && (socket = null), controller.signal.aborted) return;
|
|
320
|
+
let nextFailures = opened ? 0 : failures + 1;
|
|
321
|
+
timedOut || nextFailures >= 2 ? poll() : sleep(RETRY_MS).then(() => openSocket(nextFailures));
|
|
322
|
+
});
|
|
323
|
+
}, poll = async () => {
|
|
324
|
+
let fails = 0;
|
|
325
|
+
for (setStatus("polling"); !controller.signal.aborted;) try {
|
|
326
|
+
let url = cursor ? `${eventsPath}?after=${encodeURIComponent(cursor)}` : eventsPath, response = await fetch(url, {
|
|
327
|
+
credentials: "same-origin",
|
|
328
|
+
signal: controller.signal
|
|
329
|
+
});
|
|
330
|
+
if (response.status === 204 || response.status === 403) return;
|
|
331
|
+
if (!response.ok) throw Error(`HTTP ${response.status}`);
|
|
332
|
+
fails = 0, setStatus("polling"), receive(await response.json());
|
|
333
|
+
} catch {
|
|
334
|
+
if (controller.signal.aborted) return;
|
|
335
|
+
fails += 1, fails >= 2 && setStatus("offline"), await sleep(RETRY_MS);
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
return openSocket(0), () => {
|
|
339
|
+
controller.abort(), clearInterval(ping), clearTimeout(retry), clearTimeout(timer), wake?.(), wake = void 0, socket?.close();
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* The site side of the bar, with no React or Sanity UI: a same-origin iframe framing the bar's
|
|
344
|
+
* route, mounted only in preview mode. Framework adapters call `mountPreviewBarHost` with their own
|
|
345
|
+
* `refresh` (rerun the page's data in place) and `navigate` (client-side navigation).
|
|
346
|
+
*
|
|
347
|
+
* Same layout as Shopify's theme preview bar: the frame is always a full viewport tall and pinned to
|
|
348
|
+
* 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
|
|
349
|
+
* frame's viewport never changes and its popovers position once, with no relayout. The wrapper is a
|
|
350
|
+
* manual popover, so it sits in the top layer above every stacking context.
|
|
351
|
+
*
|
|
352
|
+
* With the document pane open the wrapper grows to the full viewport and a `clip-path` cuts it to
|
|
353
|
+
* an L: the pane's full-height column (on the left or right) plus the bar, which narrows to sit
|
|
354
|
+
* beside it. Clipped-out areas take no pointer events, so the rest of the page stays clickable,
|
|
355
|
+
* and the page gets padding on the pane's side so its content reflows beside the pane.
|
|
356
|
+
*
|
|
357
|
+
* Click-to-edit (`overlay.ts`) runs only in the Visual Editor tool's frame (`mountPreviewBarFrame`),
|
|
358
|
+
* not on the site.
|
|
359
|
+
*/
|
|
360
|
+
/**
|
|
361
|
+
* Whether this window should show the bar: the top window only. The Studio's Visual Editor frames
|
|
362
|
+
* the site with its own bar, and other embeds (thumbnails) shouldn't get one.
|
|
363
|
+
*/
|
|
364
|
+
function isTopWindow() {
|
|
365
|
+
return typeof window < "u" && window.self === window.top;
|
|
366
|
+
}
|
|
367
|
+
function isEditable(target) {
|
|
368
|
+
return !!target?.closest?.("input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]");
|
|
369
|
+
}
|
|
370
|
+
function editMessage(node) {
|
|
371
|
+
return {
|
|
372
|
+
type: "sanity-visual-editor:edit",
|
|
373
|
+
id: node.id,
|
|
374
|
+
documentType: node.type,
|
|
375
|
+
path: node.path
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function currentPath() {
|
|
379
|
+
return window.location.pathname + window.location.search;
|
|
380
|
+
}
|
|
381
|
+
/** The bar's height including the safe area on its edge, as a CSS length. */
|
|
382
|
+
function barHeight(position) {
|
|
383
|
+
return `(50px + env(safe-area-inset-${position}, 0px))`;
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* The frame's clip while the pane is open: the union of the pane's full-height column (`side`) and
|
|
387
|
+
* the bar's full-width strip (`position`), as a polygon in the wrapper's coordinates.
|
|
388
|
+
*/
|
|
389
|
+
function panelClipPath(side, position, width, barHeightCss) {
|
|
390
|
+
let inner = side === "right" ? `calc(100% - ${width}px)` : `${width}px`, strip = position === "bottom" ? `calc(100% - ${barHeightCss})` : `calc${barHeightCss}`;
|
|
391
|
+
return `polygon(${(position === "bottom" ? side === "right" ? [
|
|
392
|
+
`0 ${strip}`,
|
|
393
|
+
`${inner} ${strip}`,
|
|
394
|
+
`${inner} 0`,
|
|
395
|
+
"100% 0",
|
|
396
|
+
"100% 100%",
|
|
397
|
+
"0 100%"
|
|
398
|
+
] : [
|
|
399
|
+
"0 0",
|
|
400
|
+
`${inner} 0`,
|
|
401
|
+
`${inner} ${strip}`,
|
|
402
|
+
`100% ${strip}`,
|
|
403
|
+
"100% 100%",
|
|
404
|
+
"0 100%"
|
|
405
|
+
] : side === "right" ? [
|
|
406
|
+
"0 0",
|
|
407
|
+
"100% 0",
|
|
408
|
+
"100% 100%",
|
|
409
|
+
`${inner} 100%`,
|
|
410
|
+
`${inner} ${strip}`,
|
|
411
|
+
`0 ${strip}`
|
|
412
|
+
] : [
|
|
413
|
+
"0 0",
|
|
414
|
+
"100% 0",
|
|
415
|
+
`100% ${strip}`,
|
|
416
|
+
`${inner} ${strip}`,
|
|
417
|
+
`${inner} 100%`,
|
|
418
|
+
"0 100%"
|
|
419
|
+
]).join(", ")})`;
|
|
420
|
+
}
|
|
421
|
+
function mountPreviewBarHost(options) {
|
|
422
|
+
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");
|
|
423
|
+
wrapper.setAttribute("popover", "manual"), wrapper.dataset.sanityPreviewBar = "", Object.assign(wrapper.style, {
|
|
424
|
+
position: "fixed",
|
|
425
|
+
inset: position === "top" ? "0 0 auto 0" : "auto 0 0 0",
|
|
426
|
+
zIndex: "2147483000",
|
|
427
|
+
boxSizing: "border-box",
|
|
428
|
+
width: "100%",
|
|
429
|
+
height: `calc${BAR_HEIGHT}`,
|
|
430
|
+
margin: "0",
|
|
431
|
+
padding: "0",
|
|
432
|
+
border: "0",
|
|
433
|
+
overflow: "hidden",
|
|
434
|
+
background: "transparent"
|
|
435
|
+
});
|
|
436
|
+
let iframe = document.createElement("iframe");
|
|
437
|
+
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, {
|
|
438
|
+
position: "absolute",
|
|
439
|
+
[position]: `env(safe-area-inset-${position}, 0px)`,
|
|
440
|
+
left: "0",
|
|
441
|
+
display: "block",
|
|
442
|
+
width: "100%",
|
|
443
|
+
height: "100dvh",
|
|
444
|
+
border: "0",
|
|
445
|
+
colorScheme: "normal"
|
|
446
|
+
}), wrapper.appendChild(iframe), document.body.appendChild(wrapper), "showPopover" in wrapper && wrapper.showPopover();
|
|
447
|
+
let root = document.documentElement;
|
|
448
|
+
root.style.setProperty(`padding-${position}`, "50px");
|
|
449
|
+
/** Clipping for the current overlay and pane state. */
|
|
450
|
+
function layout() {
|
|
451
|
+
let panel = panelWidth > 0;
|
|
452
|
+
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`);
|
|
453
|
+
}
|
|
454
|
+
function post(message) {
|
|
455
|
+
iframe.contentWindow?.postMessage(message, window.location.origin);
|
|
456
|
+
}
|
|
457
|
+
function hide() {
|
|
458
|
+
destroy();
|
|
459
|
+
}
|
|
460
|
+
function onMessage(event) {
|
|
461
|
+
if (event.origin === window.location.origin && event.source === iframe.contentWindow && isPreviewBarMessage(event.data)) switch (event.data.type) {
|
|
462
|
+
case "sanity-visual-editor:ready":
|
|
463
|
+
post({
|
|
464
|
+
type: "sanity-visual-editor:path",
|
|
465
|
+
path
|
|
466
|
+
}), liveStatus && post({
|
|
467
|
+
type: "sanity-visual-editor:live-status",
|
|
468
|
+
status: liveStatus
|
|
469
|
+
});
|
|
470
|
+
break;
|
|
471
|
+
case "sanity-visual-editor:hide":
|
|
472
|
+
hide();
|
|
473
|
+
break;
|
|
474
|
+
case "sanity-visual-editor:menu":
|
|
475
|
+
overlayOpen = event.data.open, layout();
|
|
476
|
+
break;
|
|
477
|
+
case "sanity-visual-editor:panel":
|
|
478
|
+
panelWidth = event.data.open ? Math.min(event.data.width, window.innerWidth) : 0, panelSide = event.data.side, layout();
|
|
479
|
+
break;
|
|
480
|
+
case "sanity-visual-editor:navigate":
|
|
481
|
+
options.navigate(event.data.href);
|
|
482
|
+
break;
|
|
483
|
+
case "sanity-visual-editor:refresh": Promise.resolve().then(() => options.refresh()).finally(() => post({ type: "sanity-visual-editor:refreshed" }));
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
function onKeyDown(event) {
|
|
487
|
+
let key = event.key.toLowerCase();
|
|
488
|
+
(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" });
|
|
489
|
+
}
|
|
490
|
+
function onResize() {
|
|
491
|
+
panelWidth > 0 && layout();
|
|
492
|
+
}
|
|
493
|
+
window.addEventListener("message", onMessage), window.addEventListener("keydown", onKeyDown), window.addEventListener("resize", onResize);
|
|
494
|
+
function destroy() {
|
|
495
|
+
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());
|
|
496
|
+
}
|
|
497
|
+
return {
|
|
498
|
+
setPath(next) {
|
|
499
|
+
path = next, post({
|
|
500
|
+
type: "sanity-visual-editor:path",
|
|
501
|
+
path
|
|
502
|
+
});
|
|
503
|
+
},
|
|
504
|
+
setLiveStatus(status) {
|
|
505
|
+
liveStatus = status, post({
|
|
506
|
+
type: "sanity-visual-editor:live-status",
|
|
507
|
+
status
|
|
508
|
+
});
|
|
509
|
+
},
|
|
510
|
+
destroy
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* The site's side when the Studio's Visual Editor tool frames it (`isPreviewBarFrame()`): no bar
|
|
515
|
+
* here (the tool shows it above the frame), just the tool's messages. The page reports its path
|
|
516
|
+
* on load and after every navigation (`setPath`), reruns its data when the bar switches
|
|
517
|
+
* perspective, and navigates when a search result is picked. Only the parent window on this
|
|
518
|
+
* origin is listened to. Click-to-edit follows the bar's inspector; ⌘⇧I on the page toggles it.
|
|
519
|
+
*/
|
|
520
|
+
function mountPreviewBarFrame(options) {
|
|
521
|
+
let path = options.path ?? currentPath(), destroyed = !1;
|
|
522
|
+
function post(message) {
|
|
523
|
+
window.parent.postMessage(message, window.location.origin);
|
|
524
|
+
}
|
|
525
|
+
function onMessage(event) {
|
|
526
|
+
if (event.origin === window.location.origin && event.source === window.parent && isPreviewBarMessage(event.data)) switch (event.data.type) {
|
|
527
|
+
case "sanity-visual-editor:ready":
|
|
528
|
+
post({
|
|
529
|
+
type: "sanity-visual-editor:frame-path",
|
|
530
|
+
path
|
|
531
|
+
});
|
|
532
|
+
break;
|
|
533
|
+
case "sanity-visual-editor:navigate":
|
|
534
|
+
options.navigate(event.data.href);
|
|
535
|
+
break;
|
|
536
|
+
case "sanity-visual-editor:refresh":
|
|
537
|
+
Promise.resolve().then(() => options.refresh()).finally(() => post({ type: "sanity-visual-editor:refreshed" }));
|
|
538
|
+
break;
|
|
539
|
+
case "sanity-visual-editor:inspector":
|
|
540
|
+
clickToEdit?.setActive(event.data.active);
|
|
541
|
+
break;
|
|
542
|
+
case "sanity-visual-editor:labels":
|
|
543
|
+
clickToEdit?.setLabels(event.data.labels);
|
|
544
|
+
break;
|
|
545
|
+
case "sanity-visual-editor:focus": clickToEdit?.setFocus(event.data);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
function onKeyDown(event) {
|
|
549
|
+
isInspectorShortcut(event) && (event.preventDefault(), post({ type: "sanity-visual-editor:toggle-inspector" }));
|
|
550
|
+
}
|
|
551
|
+
let clickToEdit = options.clickToEdit === !1 ? null : mountClickToEdit({
|
|
552
|
+
active: !1,
|
|
553
|
+
onEdit: (node) => post(editMessage(node)),
|
|
554
|
+
onDescribe: (nodes) => post({
|
|
555
|
+
type: "sanity-visual-editor:describe",
|
|
556
|
+
nodes
|
|
557
|
+
})
|
|
558
|
+
});
|
|
559
|
+
return window.addEventListener("message", onMessage), clickToEdit && window.addEventListener("keydown", onKeyDown), post({
|
|
560
|
+
type: "sanity-visual-editor:frame-path",
|
|
561
|
+
path
|
|
562
|
+
}), {
|
|
563
|
+
setPath(next) {
|
|
564
|
+
path = next, destroyed || post({
|
|
565
|
+
type: "sanity-visual-editor:frame-path",
|
|
566
|
+
path
|
|
567
|
+
});
|
|
568
|
+
},
|
|
569
|
+
setLiveStatus(status) {
|
|
570
|
+
destroyed || post({
|
|
571
|
+
type: "sanity-visual-editor:live-status",
|
|
572
|
+
status
|
|
573
|
+
});
|
|
574
|
+
},
|
|
575
|
+
destroy() {
|
|
576
|
+
destroyed = !0, window.removeEventListener("message", onMessage), window.removeEventListener("keydown", onKeyDown), clickToEdit?.destroy();
|
|
577
|
+
}
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* One-call storefront entry point: automatically skips non-preview pages, `?studio-preview`
|
|
582
|
+
* thumbnails, and third-party iframes; mounts `mountPreviewBarFrame` inside the Studio Visual
|
|
583
|
+
* Editor or `mountPreviewBarHost` in the top window; and subscribes to realtime preview events.
|
|
584
|
+
*/
|
|
585
|
+
function connectVisualEditor(options) {
|
|
586
|
+
let { enabled, live = !0, onLiveChange, socketPath, eventsPath, onStatus, ...hostOptions } = options, frame = isPreviewBarFrame(), studioPreview = typeof window < "u" && new URLSearchParams(window.location.search).has("studio-preview");
|
|
587
|
+
if (!enabled || studioPreview || !isTopWindow() && !frame) return {
|
|
588
|
+
setPath() {},
|
|
589
|
+
setLiveStatus() {},
|
|
590
|
+
destroy() {}
|
|
591
|
+
};
|
|
592
|
+
let host = frame ? mountPreviewBarFrame(hostOptions) : mountPreviewBarHost(hostOptions), stopLive = live === !1 ? void 0 : subscribePreviewEvents((change) => {
|
|
593
|
+
onLiveChange ? onLiveChange(change) : hostOptions.refresh();
|
|
594
|
+
}, {
|
|
595
|
+
socketPath,
|
|
596
|
+
eventsPath,
|
|
597
|
+
onStatus(status) {
|
|
598
|
+
host.setLiveStatus(status), onStatus?.(status);
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
return {
|
|
602
|
+
setPath(next) {
|
|
603
|
+
host.setPath(next);
|
|
604
|
+
},
|
|
605
|
+
setLiveStatus(status) {
|
|
606
|
+
host.setLiveStatus(status);
|
|
607
|
+
},
|
|
608
|
+
destroy() {
|
|
609
|
+
stopLive?.(), host.destroy();
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
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 };
|
|
614
|
+
|
|
615
|
+
//# sourceMappingURL=host-DreYJEmR.js.map
|