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
package/dist/studio.js ADDED
@@ -0,0 +1,1263 @@
1
+ import { a as PaneResizer, c as panelLayout, l as readNumber, o as DocumentPanel, s as applyEdit, t as PreviewBarView, u as store } from "./PreviewBar-D_rw0bhP.js";
2
+ import { l as perspectiveStack, m as serializePerspective } from "./perspective-BmS9TVtr.js";
3
+ import { n as createNodeDescriber, t as clientDocumentFetcher } from "./node-labels-CDiW5rMq.js";
4
+ import { t as findPageDocumentRule } from "./page-documents-mGfw_flR.js";
5
+ import { d as isPreviewBarMessage, k as sameOriginPath, r as PREVIEW_BAR_FRAME_NAME } from "./protocol-BNO38gYy.js";
6
+ import { createContext, createElement, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
7
+ import { Box, Button, Card, Flex, Spinner, Stack, Text } from "@sanity/ui";
8
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
+ import ErrorOutlineIcon from "@sanity/icons/ErrorOutline";
10
+ import DesktopIcon from "@sanity/icons/Desktop";
11
+ import { fetchSharedAccessQuery, urlSearchParamPreviewPathname, urlSearchParamPreviewSecret } from "@sanity/preview-url-secret/constants";
12
+ import EditIcon from "@sanity/icons/Edit";
13
+ import * as sanityModule from "sanity";
14
+ import { FormRow, definePlugin, getPublishedId, getVersionFromId, isDocumentSchemaType, useActiveReleases, useClient, useCurrentUser, useDocumentPreviewStore, useDocumentStore, usePerspective, useProject, useSchema, useWorkspace } from "sanity";
15
+ import { route, useRouter } from "sanity/router";
16
+ import { useEditor } from "@portabletext/editor";
17
+ import { createPreviewSecret } from "@sanity/preview-url-secret/create-secret";
18
+ import ChevronRightIcon from "@sanity/icons/ChevronRight";
19
+ import InfoOutlineIcon from "@sanity/icons/InfoOutline";
20
+ import WarningOutlineIcon from "@sanity/icons/WarningOutline";
21
+ import { PresentationDocumentContext } from "sanity/_singletons";
22
+ import { DocumentPane, PaneLayout, PaneRouterContext, StructureToolProvider } from "sanity/structure";
23
+ const SYSTEM_FIELDS = /* @__PURE__ */ new Set([
24
+ "_rev",
25
+ "_updatedAt",
26
+ "_createdAt",
27
+ "_system"
28
+ ]), RichTextContext = createContext(null), RichTextPathContext = createContext(null);
29
+ /** `value` with `replacement` at `path` (object keys, array indexes, `{ _key }` array items). */
30
+ function setAtPath(value, path, replacement) {
31
+ if (!path.length) return replacement;
32
+ let [head, ...rest] = path;
33
+ if (Array.isArray(value)) {
34
+ let index = typeof head == "number" ? head : typeof head == "object" && head && "_key" in head ? value.findIndex((item) => item?._key === head._key) : -1;
35
+ if (index < 0 || index >= value.length) return value;
36
+ let copy = [...value];
37
+ return copy[index] = setAtPath(copy[index], rest, replacement), copy;
38
+ }
39
+ if (typeof head != "string") return value;
40
+ let object = value ?? {};
41
+ return {
42
+ ...object,
43
+ [head]: setAtPath(object[head], rest, replacement)
44
+ };
45
+ }
46
+ /** A Portable Text field: an array whose members include a `block` type. */
47
+ function isRichText(schemaType) {
48
+ return schemaType.jsonType === "array" && schemaType.of.some((member) => {
49
+ for (let type = member; type; type = type.type) if (type.name === "block") return !0;
50
+ return !1;
51
+ });
52
+ }
53
+ function createTransport(endpoint, studioPath, source) {
54
+ let seq = 0, disabled = !1, session = null, socket = null, opening = null, socketRetryAt = 0, senders = /* @__PURE__ */ new Map();
55
+ function post(document) {
56
+ return fetch(endpoint, {
57
+ method: "POST",
58
+ credentials: "same-origin",
59
+ headers: { "content-type": "application/json" },
60
+ body: JSON.stringify({
61
+ document,
62
+ seq: ++seq
63
+ })
64
+ });
65
+ }
66
+ /** Trade a fresh preview secret for the live-edit cookie. Shared by concurrent callers. */
67
+ function startSession(client, userId) {
68
+ return session ??= (async () => {
69
+ try {
70
+ let { secret } = await createPreviewSecret(client, source, `${location.origin}${studioPath}`, userId), url = `${endpoint}/session?sanity-preview-secret=${encodeURIComponent(secret)}`;
71
+ return (await fetch(url, {
72
+ method: "POST",
73
+ credentials: "same-origin",
74
+ headers: { "content-type": "application/json" },
75
+ body: "{}"
76
+ })).ok;
77
+ } catch {
78
+ return !1;
79
+ } finally {
80
+ setTimeout(() => session = null, 5e3);
81
+ }
82
+ })(), session;
83
+ }
84
+ /** Open the edit socket; `null` if it closes first (no session cookie, or no hub). */
85
+ function openSocket() {
86
+ return new Promise((resolve) => {
87
+ let url = new URL(`${endpoint}/socket`, location.href);
88
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
89
+ let ws = new WebSocket(url), ping, timeout = setTimeout(() => ws.close(), 5e3);
90
+ ws.addEventListener("open", () => {
91
+ clearTimeout(timeout), ping = setInterval(() => ws.send("ping"), 2e4), resolve(ws);
92
+ }), ws.addEventListener("close", () => {
93
+ clearTimeout(timeout), clearInterval(ping), socket === ws && (socket = null), resolve(null);
94
+ });
95
+ });
96
+ }
97
+ /** The edit socket, opened on first use and reopened after it drops. */
98
+ function editSocket(client, userId) {
99
+ return socket?.readyState === WebSocket.OPEN ? Promise.resolve(socket) : Date.now() < socketRetryAt ? Promise.resolve(null) : (opening ??= (async () => {
100
+ let ws = await openSocket();
101
+ return !ws && await startSession(client, userId) && (ws = await openSocket()), ws || (socketRetryAt = Date.now() + 3e4), socket = ws, ws;
102
+ })().finally(() => opening = null), opening);
103
+ }
104
+ async function send(document, client, userId) {
105
+ if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({
106
+ document,
107
+ seq: ++seq
108
+ }));
109
+ else {
110
+ editSocket(client, userId);
111
+ try {
112
+ let response = await post(document);
113
+ response.status === 401 && await startSession(client, userId) && (response = await post(document)), (response.status === 404 || response.status === 503) && (disabled = !0);
114
+ } catch {}
115
+ }
116
+ }
117
+ function queue(document, client, userId) {
118
+ if (disabled) return;
119
+ let sender = senders.get(document._id);
120
+ if (sender || senders.set(document._id, sender = {
121
+ pending: null,
122
+ timer: null
123
+ }), sender.pending = document, sender.timer) return;
124
+ let flush = () => {
125
+ let next = sender.pending;
126
+ sender.pending = null, next ? (send(next, client, userId), sender.timer = setTimeout(flush, 16)) : sender.timer = null;
127
+ };
128
+ flush();
129
+ }
130
+ return {
131
+ editSocket,
132
+ queue
133
+ };
134
+ }
135
+ /** Inside each rich-text editor: reports the editor's value on every patch. */
136
+ function LiveRichTextPlugins(props) {
137
+ return /* @__PURE__ */ jsxs(Fragment, { children: [props.renderDefault(props), /* @__PURE__ */ jsx(RichTextPatches, {})] });
138
+ }
139
+ function RichTextPatches() {
140
+ let editor = useEditor(), report = useContext(RichTextContext), path = useContext(RichTextPathContext);
141
+ return useEffect(() => {
142
+ if (!report || !path) return;
143
+ let subscription = editor.on("patch", () => report(path, editor.getSnapshot().context.value), { batch: !0 });
144
+ return () => subscription.unsubscribe();
145
+ }, [
146
+ editor,
147
+ report,
148
+ path
149
+ ]), null;
150
+ }
151
+ function createLiveDocumentInput(transport) {
152
+ return function LiveDocumentInput(props) {
153
+ let value = props.value, client = useClient({ apiVersion: "2025-02-19" }), user = useCurrentUser(), last = useRef(null), latest = useRef(value);
154
+ latest.current = value;
155
+ let richText = useRef(/* @__PURE__ */ new Map()), id = value?._id;
156
+ useEffect(() => {
157
+ id && transport.editSocket(client, user?.id);
158
+ }, [
159
+ id,
160
+ client,
161
+ user?.id
162
+ ]);
163
+ let broadcast = useCallback((base) => {
164
+ if (!base?._id || !base._id.startsWith("drafts.")) return;
165
+ let doc = base, now = Date.now();
166
+ for (let [key, override] of richText.current) now - override.at > 2e3 ? richText.current.delete(key) : doc = setAtPath(doc, override.path, override.blocks);
167
+ let json = JSON.stringify(doc, (key, field) => SYSTEM_FIELDS.has(key) ? void 0 : field);
168
+ last.current === null ? last.current = json : json !== last.current && (last.current = json, transport.queue(doc, client, user?.id));
169
+ }, [client, user?.id]);
170
+ useEffect(() => broadcast(value), [value, broadcast]);
171
+ let reportRichText = useCallback((path, blocks) => {
172
+ blocks !== void 0 && (richText.current.set(JSON.stringify(path), {
173
+ path,
174
+ blocks,
175
+ at: Date.now()
176
+ }), broadcast(latest.current));
177
+ }, [broadcast]);
178
+ return /* @__PURE__ */ jsx(RichTextContext.Provider, {
179
+ value: reportRichText,
180
+ children: props.renderDefault(props)
181
+ });
182
+ };
183
+ }
184
+ /** Streams unsaved edits of the open document to the realtime preview hub. */
185
+ const liveEditPlugin = definePlugin((options) => {
186
+ let LiveDocumentInput = createLiveDocumentInput(createTransport((options?.endpoint ?? "/api/preview/live-edit").replace(/\/+$/, ""), options?.studioPath ?? "/studio", options?.source ?? "visual-editor-live-edit"));
187
+ function LiveEditInput(props) {
188
+ return isDocumentSchemaType(props.schemaType) ? /* @__PURE__ */ jsx(LiveDocumentInput, { ...props }) : isRichText(props.schemaType) ? /* @__PURE__ */ jsx(RichTextPathContext.Provider, {
189
+ value: props.path,
190
+ children: props.renderDefault(props)
191
+ }) : props.renderDefault(props);
192
+ }
193
+ return {
194
+ name: "sanity-plugin-visual-editor/live-edit",
195
+ form: { components: {
196
+ input: LiveEditInput,
197
+ portableText: { plugins: LiveRichTextPlugins }
198
+ } }
199
+ };
200
+ }), NO_LOCATIONS$1 = { locations: [] };
201
+ function isSubscribable(value) {
202
+ return typeof value?.subscribe == "function";
203
+ }
204
+ /** Presentation's `useDocumentLocations`: the resolver's state, live. */
205
+ function useDocumentLocations({ id, version, schemaType, resolvers }) {
206
+ let documentStore = useDocumentStore(), previewStore = useDocumentPreviewStore(), { perspectiveStack } = usePerspective(), resolver = typeof resolvers == "function" ? resolvers : resolvers[schemaType.name], [result, setResult] = useState({
207
+ state: NO_LOCATIONS$1,
208
+ status: resolver ? "resolving" : "empty"
209
+ }), stackKey = JSON.stringify(perspectiveStack);
210
+ return useEffect(() => {
211
+ if (!resolver) {
212
+ setResult({
213
+ state: NO_LOCATIONS$1,
214
+ status: "empty"
215
+ });
216
+ return;
217
+ }
218
+ let settle = (state) => setResult(state ? {
219
+ state,
220
+ status: "resolved"
221
+ } : {
222
+ state: NO_LOCATIONS$1,
223
+ status: "empty"
224
+ });
225
+ if (typeof resolver == "object" && "select" in resolver && "resolve" in resolver) {
226
+ let subscription = previewStore.observeForPreview({
227
+ _type: "reference",
228
+ _ref: id
229
+ }, {
230
+ ...schemaType,
231
+ preview: { select: resolver.select }
232
+ }, { perspective: perspectiveStack }).subscribe((preview) => settle(resolver.resolve(preview.snapshot ?? null)));
233
+ return () => subscription.unsubscribe();
234
+ }
235
+ let source = typeof resolver == "function" ? resolver({
236
+ id,
237
+ type: schemaType.name,
238
+ version,
239
+ perspectiveStack
240
+ }, { documentStore }) : resolver;
241
+ if (!isSubscribable(source)) {
242
+ settle(source);
243
+ return;
244
+ }
245
+ let subscription = source.subscribe(settle);
246
+ return () => subscription.unsubscribe();
247
+ }, [
248
+ resolver,
249
+ id,
250
+ version,
251
+ schemaType,
252
+ documentStore,
253
+ previewStore,
254
+ stackKey
255
+ ]), result;
256
+ }
257
+ const TONE_ICONS = {
258
+ positive: InfoOutlineIcon,
259
+ caution: WarningOutlineIcon,
260
+ critical: ErrorOutlineIcon
261
+ };
262
+ /** ui5's `Icon size={1}` in the Studio: 21px, pulled in by `-0.375rem`. */
263
+ function BannerIcon({ icon, style }) {
264
+ return /* @__PURE__ */ jsx("span", {
265
+ "aria-hidden": "true",
266
+ style: {
267
+ display: "block",
268
+ fontSize: 21,
269
+ lineHeight: 0,
270
+ margin: "-0.375rem",
271
+ ...style
272
+ },
273
+ children: createElement(icon, { style: { display: "block" } })
274
+ });
275
+ }
276
+ function countLabel(count) {
277
+ return count === 0 ? "Not used on any pages" : count === 1 ? "Used on one page" : `Used on ${count} pages`;
278
+ }
279
+ /** A page the document is on: opens the Visual Editor there, keeping the Studio's perspective. */
280
+ function LocationItem({ location, toolName }) {
281
+ let { basePath } = useWorkspace(), router = useRouter(), search = new URLSearchParams({ preview: location.href });
282
+ if (typeof window < "u") {
283
+ let current = new URLSearchParams(window.location.search);
284
+ for (let key of ["perspective", "excludedPerspectives"]) {
285
+ let value = current.get(key);
286
+ value && search.set(key, value);
287
+ }
288
+ }
289
+ let href = `${basePath.replace(/\/$/, "")}/${toolName}?${search}`, Icon = location.icon ?? DesktopIcon;
290
+ return /* @__PURE__ */ jsx(Card, {
291
+ as: "a",
292
+ href,
293
+ padding: 3,
294
+ radius: 1,
295
+ tone: "inherit",
296
+ onClick: (event) => {
297
+ event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0 || (event.preventDefault(), router.navigateUrl({ path: href }));
298
+ },
299
+ children: /* @__PURE__ */ jsxs(Flex, {
300
+ gap: 3,
301
+ children: [/* @__PURE__ */ jsx(Box, {
302
+ flex: "none",
303
+ children: /* @__PURE__ */ jsx(BannerIcon, { icon: Icon })
304
+ }), /* @__PURE__ */ jsxs(Flex, {
305
+ flex: 1,
306
+ gap: 2,
307
+ direction: "column",
308
+ children: [/* @__PURE__ */ jsx(Text, {
309
+ size: 1,
310
+ weight: "medium",
311
+ as: "div",
312
+ children: location.title
313
+ }), location.showHref !== !1 && /* @__PURE__ */ jsx(Text, {
314
+ muted: !0,
315
+ size: 1,
316
+ textOverflow: "ellipsis",
317
+ as: "div",
318
+ children: location.href
319
+ })]
320
+ })]
321
+ })
322
+ });
323
+ }
324
+ /** Presentation's `LocationsBanner`. */
325
+ function LocationsBanner({ id, version, schemaType, resolvers, toolName }) {
326
+ let { state, status } = useDocumentLocations({
327
+ id,
328
+ version,
329
+ schemaType,
330
+ resolvers
331
+ }), [expanded, setExpanded] = useState(!1);
332
+ if (status === "empty") return null;
333
+ let { locations, message, tone } = state, count = locations?.length ?? 0, resolving = status === "resolving", title = resolving ? "Resolving locations..." : message || countLabel(count), ToneIcon = tone ? TONE_ICONS[tone] : void 0, content;
334
+ return content = locations ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Card, {
335
+ as: count ? "button" : void 0,
336
+ onClick: count ? () => setExpanded((value) => !value) : void 0,
337
+ padding: 3,
338
+ radius: 1,
339
+ tone: "inherit",
340
+ children: /* @__PURE__ */ jsxs(Flex, {
341
+ gap: 3,
342
+ children: [/* @__PURE__ */ jsx(Box, {
343
+ flex: "none",
344
+ children: resolving ? /* @__PURE__ */ jsx(Spinner, { size: 1 }) : count === 0 ? /* @__PURE__ */ jsx(BannerIcon, { icon: InfoOutlineIcon }) : /* @__PURE__ */ jsx(BannerIcon, {
345
+ icon: ChevronRightIcon,
346
+ style: {
347
+ transform: `rotate(${expanded ? "90deg" : 0})`,
348
+ transition: "transform 100ms ease-in-out"
349
+ }
350
+ })
351
+ }), /* @__PURE__ */ jsx(Box, {
352
+ flex: 1,
353
+ children: /* @__PURE__ */ jsx(Text, {
354
+ size: 1,
355
+ weight: "medium",
356
+ as: "div",
357
+ children: title
358
+ })
359
+ })]
360
+ })
361
+ }), /* @__PURE__ */ jsx(Flex, {
362
+ hidden: !expanded,
363
+ marginTop: 1,
364
+ gap: 1,
365
+ direction: "column",
366
+ children: locations.map((location) => /* @__PURE__ */ jsx(LocationItem, {
367
+ location,
368
+ toolName
369
+ }, location.href))
370
+ })] }) : /* @__PURE__ */ jsxs(Flex, {
371
+ align: "flex-start",
372
+ gap: 3,
373
+ padding: 3,
374
+ children: [ToneIcon && /* @__PURE__ */ jsx(Box, {
375
+ flex: "none",
376
+ children: /* @__PURE__ */ jsx(BannerIcon, { icon: ToneIcon })
377
+ }), /* @__PURE__ */ jsx(Box, {
378
+ flex: 1,
379
+ children: /* @__PURE__ */ jsx(Text, {
380
+ size: 1,
381
+ weight: "medium",
382
+ as: "div",
383
+ children: title
384
+ })
385
+ })]
386
+ }), /* @__PURE__ */ jsx(FormRow, { children: /* @__PURE__ */ jsx("div", {
387
+ style: {
388
+ display: "flex",
389
+ flexDirection: "column",
390
+ gap: 8,
391
+ marginBottom: 20
392
+ },
393
+ children: /* @__PURE__ */ jsx(Card, {
394
+ padding: 1,
395
+ radius: 2,
396
+ border: !0,
397
+ tone,
398
+ children: /* @__PURE__ */ jsx("div", {
399
+ style: { margin: -1 },
400
+ children: content
401
+ })
402
+ })
403
+ }) });
404
+ }
405
+ /**
406
+ * The document form's input: the banner above the form, as Presentation's. Not inside the preview
407
+ * bar's own document panes (the Visual Editor's, the site's), which sit beside the page already;
408
+ * they provide `PresentationDocumentContext` to hide Presentation's banner, and that hides this one.
409
+ */
410
+ function locationsInput(resolvers, toolName) {
411
+ return function VisualEditorDocumentInput(props) {
412
+ let inPreviewBarPane = useContext(PresentationDocumentContext) !== null, value = props.value;
413
+ return inPreviewBarPane || !isDocumentSchemaType(props.schemaType) || !value?._id ? props.renderDefault(props) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(LocationsBanner, {
414
+ id: getPublishedId(value._id),
415
+ version: getVersionFromId(value._id),
416
+ schemaType: props.schemaType,
417
+ resolvers,
418
+ toolName
419
+ }), props.renderDefault(props)] });
420
+ };
421
+ }
422
+ /**
423
+ * The bar's data in the Visual Editor tool, from the Studio instead of the site, so the bar
424
+ * renders the moment the tool does (as Presentation's toolbar does): the workspace (title, icon,
425
+ * base path, project), the project's name, the active releases (live, from the Studio's releases
426
+ * store), the Studio's perspective, and Presentation's "Share this preview" state (read with the
427
+ * editor's own client). What the Studio can't know, the tool's options say.
428
+ */
429
+ function useStudioBarData({ barPath, links, searchTypes }) {
430
+ let workspace = useWorkspace(), project = useProject(), schema = useSchema(), { data: releases, error: releasesError } = useActiveReleases(), { selectedPerspectiveName, excludedPerspectives } = usePerspective(), client = useClient({ apiVersion: "2025-02-19" }), [sharing, setSharing] = useState(!1);
431
+ useEffect(() => {
432
+ if (!links) return;
433
+ let cancelled = !1;
434
+ return client.fetch(fetchSharedAccessQuery, {}, { tag: "preview-bar.sharing" }).then((secret) => {
435
+ cancelled || setSharing(!!secret);
436
+ }).catch(() => {}), () => {
437
+ cancelled = !0;
438
+ };
439
+ }, [client, links]);
440
+ let releaseList = releases, perspective = serializePerspective(perspectiveStack({
441
+ selected: selectedPerspectiveName ?? "drafts",
442
+ releases: releaseList,
443
+ excluded: excludedPerspectives ?? []
444
+ })), searchKey = searchTypes?.join(",");
445
+ return useMemo(() => ({
446
+ brand: {
447
+ title: workspace.title,
448
+ icon: workspace.icon,
449
+ project: project?.displayName
450
+ },
451
+ studioPath: workspace.basePath || "/",
452
+ projectId: workspace.projectId,
453
+ basePath: barPath,
454
+ releases: releaseList,
455
+ releasesError: !!releasesError,
456
+ sharing,
457
+ links,
458
+ perspective,
459
+ pageDocuments: !1,
460
+ search: (searchTypes ?? []).map((type) => ({
461
+ kind: type,
462
+ title: schema.get(type)?.title ?? type
463
+ }))
464
+ }), [
465
+ workspace,
466
+ project,
467
+ releaseList,
468
+ releasesError,
469
+ sharing,
470
+ links,
471
+ barPath,
472
+ schema,
473
+ searchKey
474
+ ]);
475
+ }
476
+ /**
477
+ * The Visual Editor tool: Presentation's layout with the preview bar. The bar runs along the top,
478
+ * rendered natively in the Studio (`PreviewBarView`, with the Studio's own context), the site
479
+ * (framed under `PREVIEW_BAR_FRAME_NAME`, at desktop width or as a 375px phone) fills the middle,
480
+ * and the Studio's own document pane sits on the right.
481
+ *
482
+ * The tool is the bar's host, through the same `sanity-visual-editor:*` messages the site's host
483
+ * uses (in process, no frame), and talks to the framed site's `mountPreviewBarFrame`: paths,
484
+ * refreshes after a perspective switch, navigation from search. The site is framed on its origin,
485
+ * which must be this Studio's origin (an embedded Studio). The bar's data comes from the Studio
486
+ * (`useStudioBarData`), so it renders with the tool; the site is only asked to store the
487
+ * perspective cookie, mint share links and resolve search results.
488
+ *
489
+ * The tool's own layout uses the Studio's CSS variables and plain elements.
490
+ */
491
+ /** Device widths: Presentation's narrow viewport, and a portrait tablet. */
492
+ const VIEWPORT_WIDTHS = {
493
+ tablet: 768,
494
+ mobile: 375
495
+ }, structure = {
496
+ DocumentPane,
497
+ PaneLayout,
498
+ PaneRouterContext,
499
+ StructureToolProvider
500
+ }, NO_LOCATIONS = {
501
+ options: [{}],
502
+ register: () => () => {}
503
+ };
504
+ function sameSelection(a, b) {
505
+ return a.selected === b.selected && [...a.excluded].sort().join() === [...b.excluded].sort().join();
506
+ }
507
+ function publishedId(id) {
508
+ return id.replace(/^drafts\./, "").replace(/^versions\.[^.]+\./, "");
509
+ }
510
+ const SKELETON_CSS = "\n@keyframes preview-bar-skeleton {\n from { background-color: var(--card-skeleton-color-from, #eeeef1); }\n to { background-color: var(--card-skeleton-color-to, #f7f7f8); }\n}\n.preview-bar-skeleton { background-color: var(--card-skeleton-color-from, #eeeef1); border-radius: 3px; animation: preview-bar-skeleton 0.9s ease-in-out infinite alternate; }\n";
511
+ function Bone({ width, height, style }) {
512
+ return /* @__PURE__ */ jsx("div", {
513
+ className: "preview-bar-skeleton",
514
+ style: {
515
+ width,
516
+ height,
517
+ flex: "none",
518
+ ...style
519
+ }
520
+ });
521
+ }
522
+ /** The page area until the framed site reports its first page: one bone over the whole page. */
523
+ function PageSkeleton() {
524
+ return /* @__PURE__ */ jsx("div", {
525
+ "aria-busy": "true",
526
+ "aria-label": "Loading the page",
527
+ className: "preview-bar-skeleton",
528
+ style: {
529
+ position: "absolute",
530
+ inset: 0,
531
+ borderRadius: 0
532
+ },
533
+ children: /* @__PURE__ */ jsx("style", { children: SKELETON_CSS })
534
+ });
535
+ }
536
+ /**
537
+ * The page area when the site can't be shown: preview mode couldn't be enabled (`message`), or
538
+ * the page loaded but never connected (Presentation's "Unable to connect").
539
+ */
540
+ function PageError({ message, enablePath, pageUrl, onRetry }) {
541
+ return /* @__PURE__ */ jsx(Flex, {
542
+ align: "center",
543
+ justify: "center",
544
+ padding: 4,
545
+ style: {
546
+ position: "absolute",
547
+ inset: 0,
548
+ overflow: "auto"
549
+ },
550
+ children: /* @__PURE__ */ jsx(Card, {
551
+ role: "alert",
552
+ padding: 4,
553
+ radius: 3,
554
+ shadow: 1,
555
+ style: {
556
+ maxWidth: 440,
557
+ width: "100%"
558
+ },
559
+ children: /* @__PURE__ */ jsxs(Stack, {
560
+ gap: 4,
561
+ children: [
562
+ /* @__PURE__ */ jsx(Text, {
563
+ size: 2,
564
+ weight: "semibold",
565
+ children: message ? "Couldn’t open the preview" : "Unable to connect to the page"
566
+ }),
567
+ message ? /* @__PURE__ */ jsx(Text, {
568
+ size: 1,
569
+ muted: !0,
570
+ children: message
571
+ }) : /* @__PURE__ */ jsxs(Stack, {
572
+ gap: 3,
573
+ children: [/* @__PURE__ */ jsx(Text, {
574
+ size: 1,
575
+ muted: !0,
576
+ children: "The page loaded but didn’t connect to the Visual Editor. Check that:"
577
+ }), /* @__PURE__ */ jsxs("ul", {
578
+ style: {
579
+ margin: 0,
580
+ paddingLeft: 20,
581
+ display: "grid",
582
+ gap: 12
583
+ },
584
+ children: [
585
+ /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(Text, {
586
+ size: 1,
587
+ muted: !0,
588
+ children: [
589
+ /* @__PURE__ */ jsx("code", { children: "previewMode.enable" }),
590
+ " (",
591
+ /* @__PURE__ */ jsx("code", { children: enablePath }),
592
+ ") is your site’s preview-mode route, and its secret check passes"
593
+ ]
594
+ }) }),
595
+ /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(Text, {
596
+ size: 1,
597
+ muted: !0,
598
+ children: "the page loads without an error"
599
+ }) }),
600
+ /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(Text, {
601
+ size: 1,
602
+ muted: !0,
603
+ children: [
604
+ "your layout calls ",
605
+ /* @__PURE__ */ jsx("code", { children: "mountPreviewBarFrame" }),
606
+ " when",
607
+ " ",
608
+ /* @__PURE__ */ jsx("code", { children: "isPreviewBarFrame()" }),
609
+ " is true"
610
+ ]
611
+ }) })
612
+ ]
613
+ })]
614
+ }),
615
+ /* @__PURE__ */ jsxs(Flex, {
616
+ gap: 2,
617
+ children: [/* @__PURE__ */ jsx(Button, {
618
+ mode: "default",
619
+ tone: "primary",
620
+ text: "Retry",
621
+ onClick: onRetry
622
+ }), pageUrl && /* @__PURE__ */ jsx(Button, {
623
+ as: "a",
624
+ mode: "ghost",
625
+ text: "Open in new tab",
626
+ href: pageUrl,
627
+ target: "_blank",
628
+ rel: "noopener"
629
+ })]
630
+ })
631
+ ]
632
+ })
633
+ })
634
+ });
635
+ }
636
+ /**
637
+ * The pane column until the page's document is known, laid out as the Studio's document pane is
638
+ * (measured at 420px): the 50px header with the Published and Draft chips and its icon buttons,
639
+ * the title's breadcrumb, the type label and the title, and the footer's status, Publish and
640
+ * actions. No fields: they differ per type.
641
+ */
642
+ function PaneSkeleton() {
643
+ let round = { borderRadius: 999 }, icon = (right) => /* @__PURE__ */ jsx(Bone, {
644
+ width: 17,
645
+ height: 17,
646
+ style: {
647
+ position: "absolute",
648
+ top: 16,
649
+ right,
650
+ ...round
651
+ }
652
+ });
653
+ return /* @__PURE__ */ jsxs("div", {
654
+ "aria-busy": "true",
655
+ "aria-label": "Loading the document",
656
+ style: {
657
+ position: "relative",
658
+ height: "100%"
659
+ },
660
+ children: [
661
+ /* @__PURE__ */ jsx("style", { children: SKELETON_CSS }),
662
+ /* @__PURE__ */ jsxs("div", {
663
+ style: {
664
+ position: "relative",
665
+ height: 50,
666
+ borderBottom: "1px solid var(--card-border-color)"
667
+ },
668
+ children: [
669
+ /* @__PURE__ */ jsxs("div", {
670
+ style: {
671
+ position: "absolute",
672
+ top: 12,
673
+ left: 12,
674
+ display: "flex",
675
+ gap: 4
676
+ },
677
+ children: [/* @__PURE__ */ jsx(Bone, {
678
+ width: 98,
679
+ height: 25,
680
+ style: round
681
+ }), /* @__PURE__ */ jsx(Bone, {
682
+ width: 68,
683
+ height: 25,
684
+ style: round
685
+ })]
686
+ }),
687
+ icon(16),
688
+ icon(45),
689
+ icon(74),
690
+ icon(103)
691
+ ]
692
+ }),
693
+ /* @__PURE__ */ jsx("div", {
694
+ style: {
695
+ position: "absolute",
696
+ left: 20,
697
+ right: 20,
698
+ top: 69
699
+ },
700
+ children: /* @__PURE__ */ jsx(Bone, {
701
+ width: 96,
702
+ height: 12
703
+ })
704
+ }),
705
+ /* @__PURE__ */ jsx("div", {
706
+ style: {
707
+ position: "absolute",
708
+ left: 20,
709
+ right: 20,
710
+ top: 131
711
+ },
712
+ children: /* @__PURE__ */ jsx(Bone, {
713
+ width: 36,
714
+ height: 12
715
+ })
716
+ }),
717
+ /* @__PURE__ */ jsx("div", {
718
+ style: {
719
+ position: "absolute",
720
+ left: 20,
721
+ right: 20,
722
+ top: 159
723
+ },
724
+ children: /* @__PURE__ */ jsx(Bone, {
725
+ width: "45%",
726
+ height: 21
727
+ })
728
+ }),
729
+ /* @__PURE__ */ jsxs("div", {
730
+ style: {
731
+ position: "absolute",
732
+ left: 16,
733
+ right: 16,
734
+ bottom: 12,
735
+ height: 25,
736
+ display: "flex",
737
+ alignItems: "center",
738
+ gap: 8
739
+ },
740
+ children: [
741
+ /* @__PURE__ */ jsx(Bone, {
742
+ width: 21,
743
+ height: 21,
744
+ style: round
745
+ }),
746
+ /* @__PURE__ */ jsx(Bone, {
747
+ width: 68,
748
+ height: 12
749
+ }),
750
+ /* @__PURE__ */ jsx("div", { style: { flex: 1 } }),
751
+ /* @__PURE__ */ jsx(Bone, {
752
+ width: 79,
753
+ height: 25
754
+ }),
755
+ /* @__PURE__ */ jsx(Bone, {
756
+ width: 17,
757
+ height: 17,
758
+ style: {
759
+ ...round,
760
+ margin: "0 4px"
761
+ }
762
+ })
763
+ ]
764
+ })
765
+ ]
766
+ });
767
+ }
768
+ /** The tool pane's width, apart from the site pane's (the tool's pane is full height). */
769
+ const PANE_WIDTH_KEY = "sanity-visual-editor:visual-editor-pane-width";
770
+ /** An element's width, kept current: the tool lays out by its own space, not the window's. */
771
+ function useElementWidth(ref) {
772
+ let [width, setWidth] = useState(() => window.innerWidth);
773
+ return useLayoutEffect(() => {
774
+ let element = ref.current;
775
+ if (!element) return;
776
+ setWidth(element.getBoundingClientRect().width);
777
+ let observer = new ResizeObserver(([entry]) => {
778
+ entry && setWidth(entry.contentRect.width);
779
+ });
780
+ return observer.observe(element), () => observer.disconnect();
781
+ }, [ref]), width;
782
+ }
783
+ function VisualEditorTool({ tool }) {
784
+ let options = tool.options ?? {}, barPath = options.barPath ?? "/__visual-editor", enablePath = options.previewUrl?.previewMode?.enable ?? "/preview/enable", rootRef = useRef(null), toolWidth = useElementWidth(rootRef), narrow = toolWidth < 900, [narrowView, setNarrowView] = useState("preview"), [preferredPaneWidth, setPreferredPaneWidth] = useState(() => readNumber(PANE_WIDTH_KEY) ?? options.paneWidth ?? 420), paneWidth = panelLayout(preferredPaneWidth, toolWidth).width, [resizing, setResizing] = useState(!1), paneWidthRef = useRef(paneWidth);
785
+ paneWidthRef.current = paneWidth;
786
+ let paneResize = useMemo(() => ({
787
+ start: () => setResizing(!0),
788
+ to: (width) => setPreferredPaneWidth(width),
789
+ end: () => {
790
+ setResizing(!1), setPreferredPaneWidth(paneWidthRef.current), store("localStorage", PANE_WIDTH_KEY, String(paneWidthRef.current));
791
+ }
792
+ }), []), origin = window.location.origin, router = useRouter(), { basePath } = useWorkspace(), basePathRef = useRef(basePath);
793
+ basePathRef.current = basePath;
794
+ let routerRef = useRef(router);
795
+ routerRef.current = router;
796
+ let initialPath = useMemo(() => {
797
+ let preview = new URLSearchParams(router.state._searchParams ?? []).get("preview");
798
+ return sameOriginPath(preview) ?? options.previewUrl?.initial ?? "/";
799
+ }, []), barData = useStudioBarData({
800
+ barPath,
801
+ links: options.links ?? !0,
802
+ searchTypes: options.searchTypes
803
+ }), { selectedPerspectiveName, excludedPerspectives, perspectiveStack } = usePerspective(), studioSelection = useMemo(() => ({
804
+ selected: selectedPerspectiveName ?? "drafts",
805
+ excluded: excludedPerspectives ?? []
806
+ }), [selectedPerspectiveName, excludedPerspectives]), studioSelectionRef = useRef(studioSelection);
807
+ studioSelectionRef.current = studioSelection;
808
+ /** Stores a perspective in the site's cookie; `false` outside preview mode (the route 404s). */
809
+ let storePerspective = useCallback(async (selection) => (await fetch(`${barPath}/perspective`, {
810
+ method: "POST",
811
+ credentials: "same-origin",
812
+ headers: { "content-type": "application/json" },
813
+ body: JSON.stringify(selection)
814
+ })).ok, [barPath]), client = useClient({ apiVersion: "2025-02-19" }), currentUser = useCurrentUser(), [frameSrc, setFrameSrc] = useState(null), [frameError, setFrameError] = useState(null), [attempt, setAttempt] = useState(0), perspectiveStored = useRef(!1);
815
+ useEffect(() => {
816
+ let cancelled = !1;
817
+ async function start() {
818
+ let stored = await storePerspective(studioSelectionRef.current).catch(() => !1);
819
+ if (cancelled) return;
820
+ if (stored) {
821
+ perspectiveStored.current = !0, setFrameSrc(new URL(initialPath, origin).toString());
822
+ return;
823
+ }
824
+ let { secret } = await createPreviewSecret(client, "sanity-plugin-visual-editor/visual-editor", window.location.href, currentUser?.id);
825
+ if (cancelled) return;
826
+ let url = new URL(enablePath, origin);
827
+ url.searchParams.set(urlSearchParamPreviewSecret, secret), url.searchParams.set(urlSearchParamPreviewPathname, initialPath), setFrameSrc(url.toString());
828
+ }
829
+ return start().catch((error) => {
830
+ console.error("sanity-visual-editor: could not enable preview mode", error), cancelled || setFrameError("Couldn’t open the preview. Check that you can edit this dataset.");
831
+ }), () => {
832
+ cancelled = !0;
833
+ };
834
+ }, [attempt]);
835
+ let siteFrame = useRef(null), [viewport, setViewport] = useState("desktop"), device = viewport === "desktop" ? null : VIEWPORT_WIDTHS[viewport], [path, setPath] = useState(null), [mainDocument, setMainDocument] = useState(null), [mainDocumentLoaded, setMainDocumentLoaded] = useState(!1), [stack, setStack] = useState([]), [paneWanted, setPaneWanted] = useState(!0), barListeners = useRef(/* @__PURE__ */ new Set()), postToBar = useCallback((message) => {
836
+ for (let listener of barListeners.current) listener(message);
837
+ }, []), handleBarMessage = useRef(() => {}), pathRef = useRef(null), barHost = useMemo(() => ({
838
+ post: (message) => handleBarMessage.current(message),
839
+ subscribe(listener) {
840
+ return barListeners.current.add(listener), () => barListeners.current.delete(listener);
841
+ },
842
+ initialPath: () => pathRef.current
843
+ }), []), postToSite = useCallback((message) => siteFrame.current?.contentWindow?.postMessage(message, origin), [origin]), schema = useSchema(), describerKey = JSON.stringify(perspectiveStack), describer = useMemo(() => createNodeDescriber(schema, clientDocumentFetcher(client, perspectiveStack)), [
844
+ schema,
845
+ client,
846
+ describerKey
847
+ ]), describerRef = useRef(describer);
848
+ describerRef.current = describer;
849
+ let reportFocus = useCallback((focus) => postToSite({
850
+ type: "sanity-visual-editor:focus",
851
+ id: focus?.id ?? "",
852
+ path: focus?.path ?? ""
853
+ }), [postToSite]), pathKnown = path !== null;
854
+ useEffect(() => {
855
+ pathKnown && !perspectiveStored.current && (perspectiveStored.current = !0, storePerspective(studioSelectionRef.current).then((stored) => {
856
+ stored && postToSite({ type: "sanity-visual-editor:refresh" });
857
+ }).catch(() => {}));
858
+ }, [
859
+ pathKnown,
860
+ storePerspective,
861
+ postToSite
862
+ ]);
863
+ let mainDocuments = options.resolve?.mainDocuments ?? options.mainDocuments, stackKey = JSON.stringify(perspectiveStack), documentPath = path ?? initialPath;
864
+ useEffect(() => {
865
+ let cancelled = !1, lookup;
866
+ if (mainDocuments) {
867
+ let rule = findPageDocumentRule(mainDocuments, documentPath, origin);
868
+ lookup = rule ? client.withConfig({ perspective: perspectiveStack }).fetch(`*[${rule.filter}][0]{_id, _type}`, rule.params, { tag: "preview-bar.main-document" }) : Promise.resolve(null);
869
+ } else lookup = fetch(`${barPath}/document?${new URLSearchParams({ path: documentPath })}`, { credentials: "same-origin" }).then((response) => response.ok ? response.json() : { document: null }).then(({ document }) => document);
870
+ return lookup.then((document) => {
871
+ cancelled || setMainDocument(document ? {
872
+ id: publishedId(document._id),
873
+ type: document._type
874
+ } : null);
875
+ }).catch(() => {
876
+ cancelled || setMainDocument(null);
877
+ }).finally(() => {
878
+ cancelled || setMainDocumentLoaded(!0);
879
+ }), () => {
880
+ cancelled = !0;
881
+ };
882
+ }, [
883
+ documentPath,
884
+ barPath,
885
+ mainDocuments,
886
+ client,
887
+ stackKey
888
+ ]), useEffect(() => {
889
+ paneWanted && setStack((current) => mainDocument ? current[0]?.id === mainDocument.id ? current : [{
890
+ id: mainDocument.id,
891
+ type: mainDocument.type,
892
+ params: {}
893
+ }] : []);
894
+ }, [mainDocument, paneWanted]), useEffect(() => {
895
+ mainDocumentLoaded && postToBar({
896
+ type: "sanity-visual-editor:page-document",
897
+ document: mainDocument
898
+ });
899
+ }, [
900
+ mainDocument,
901
+ mainDocumentLoaded,
902
+ postToBar
903
+ ]);
904
+ let paneOpen = stack.length > 0, paneLoading = paneWanted && !mainDocumentLoaded, columnOpen = paneOpen || paneLoading, editorAvailable = mainDocument !== null, view = narrowView === "document" && columnOpen ? "document" : "preview", barEditorOpen = narrow ? view === "document" : columnOpen;
905
+ useEffect(() => {
906
+ postToBar({
907
+ type: "sanity-visual-editor:editor-state",
908
+ open: barEditorOpen,
909
+ available: editorAvailable,
910
+ toggle: narrow
911
+ });
912
+ }, [
913
+ barEditorOpen,
914
+ editorAvailable,
915
+ narrow,
916
+ postToBar
917
+ ]);
918
+ let changeStack = useCallback((next) => {
919
+ next.length === 0 && (setPaneWanted(!1), setNarrowView("preview")), setStack(next);
920
+ }, []), lastBarSelection = useRef(null);
921
+ useEffect(() => {
922
+ let fromBar = lastBarSelection.current;
923
+ fromBar && !sameSelection(fromBar, studioSelection) && postToBar({
924
+ type: "sanity-visual-editor:set-perspective",
925
+ selection: studioSelection
926
+ });
927
+ }, [studioSelection, postToBar]);
928
+ let menu = options.menu, barOptions = useMemo(() => ({ menu: {
929
+ code: menu?.code,
930
+ editPreferences: menu?.preferences ? () => routerRef.current.navigateIntent("edit", menu.preferences) : void 0
931
+ } }), [menu]), onIntent = useCallback((name, params) => {
932
+ name === "edit" && params.id && params.type ? setStack((current) => [...current, {
933
+ id: params.id,
934
+ type: params.type,
935
+ params: {}
936
+ }]) : routerRef.current.navigateIntent(name, params);
937
+ }, []), inspectorRef = useRef(!1), latest = useRef({
938
+ path,
939
+ barEditorOpen,
940
+ studioSelection,
941
+ mainDocument,
942
+ mainDocumentLoaded,
943
+ stack
944
+ });
945
+ latest.current = {
946
+ path,
947
+ barEditorOpen,
948
+ studioSelection,
949
+ mainDocument,
950
+ mainDocumentLoaded,
951
+ stack
952
+ }, pathRef.current = path;
953
+ let narrowRef = useRef(narrow);
954
+ narrowRef.current = narrow;
955
+ /**
956
+ * Edit: the page's document. Narrow, a pane already open (perhaps on another document) is behind
957
+ * the page, so it's shown as it is.
958
+ */
959
+ let openEditor = useCallback(() => {
960
+ let { mainDocument: main, stack: current } = latest.current;
961
+ current.length && narrowRef.current ? setNarrowView("document") : main && (setPaneWanted(!0), setStack([{
962
+ id: main.id,
963
+ type: main.type,
964
+ params: {}
965
+ }]), setNarrowView("document"));
966
+ }, []);
967
+ handleBarMessage.current = (message) => {
968
+ switch (message.type) {
969
+ case "sanity-visual-editor:ready":
970
+ queueMicrotask(() => {
971
+ let { path: current, barEditorOpen: open, mainDocument: main, mainDocumentLoaded: loaded } = latest.current;
972
+ current && postToBar({
973
+ type: "sanity-visual-editor:path",
974
+ path: current
975
+ }), postToBar({
976
+ type: "sanity-visual-editor:editor-state",
977
+ open,
978
+ available: main !== null,
979
+ toggle: narrowRef.current
980
+ }), loaded && postToBar({
981
+ type: "sanity-visual-editor:page-document",
982
+ document: main
983
+ });
984
+ });
985
+ break;
986
+ case "sanity-visual-editor:refresh":
987
+ postToSite({ type: "sanity-visual-editor:refresh" });
988
+ break;
989
+ case "sanity-visual-editor:navigate":
990
+ postToSite({
991
+ type: "sanity-visual-editor:navigate",
992
+ href: message.href
993
+ });
994
+ break;
995
+ case "sanity-visual-editor:viewport":
996
+ setViewport(message.mode);
997
+ break;
998
+ case "sanity-visual-editor:open-document": {
999
+ let { id, type, template, templateParameters } = message.document, entry = {
1000
+ id,
1001
+ type,
1002
+ params: {},
1003
+ template,
1004
+ templateParameters
1005
+ };
1006
+ setPaneWanted(!0), setNarrowView("document"), setStack((current) => !template && id === latest.current.mainDocument?.id ? [entry] : current.length ? [...current, entry] : [entry]);
1007
+ break;
1008
+ }
1009
+ case "sanity-visual-editor:perspective": {
1010
+ if (lastBarSelection.current = message.selection, sameSelection(message.selection, latest.current.studioSelection)) break;
1011
+ let { selected, excluded } = message.selection;
1012
+ routerRef.current.navigate({ stickyParams: {
1013
+ perspective: selected === "drafts" ? null : selected,
1014
+ excludedPerspectives: excluded.length ? excluded.join(",") : null
1015
+ } });
1016
+ break;
1017
+ }
1018
+ case "sanity-visual-editor:open-editor":
1019
+ openEditor();
1020
+ break;
1021
+ case "sanity-visual-editor:close-editor":
1022
+ setNarrowView("preview");
1023
+ break;
1024
+ case "sanity-visual-editor:inspector":
1025
+ inspectorRef.current = message.active, postToSite(message);
1026
+ break;
1027
+ case "sanity-visual-editor:studio-home": routerRef.current.navigateUrl({ path: basePathRef.current || "/" });
1028
+ }
1029
+ }, useEffect(() => {
1030
+ function onMessage(event) {
1031
+ if (event.origin !== origin || event.source !== siteFrame.current?.contentWindow || !isPreviewBarMessage(event.data)) return;
1032
+ let message = event.data;
1033
+ switch (message.type) {
1034
+ case "sanity-visual-editor:frame-path": {
1035
+ setPath(message.path), setConnectFailed(!1), postToSite({
1036
+ type: "sanity-visual-editor:inspector",
1037
+ active: inspectorRef.current
1038
+ }), postToBar({
1039
+ type: "sanity-visual-editor:path",
1040
+ path: message.path
1041
+ });
1042
+ let { state, navigate } = routerRef.current, params = (state._searchParams ?? []).filter(([key]) => key !== "preview");
1043
+ navigate({
1044
+ ...state,
1045
+ _searchParams: [...params, ["preview", message.path]]
1046
+ }, { replace: !0 });
1047
+ break;
1048
+ }
1049
+ case "sanity-visual-editor:refreshed":
1050
+ postToBar({ type: "sanity-visual-editor:refreshed" });
1051
+ break;
1052
+ case "sanity-visual-editor:edit": {
1053
+ let { stack: current, mainDocument: main } = latest.current;
1054
+ setPaneWanted(!0), setNarrowView("document");
1055
+ let base = current.length || !main ? current : [{
1056
+ id: main.id,
1057
+ type: main.type,
1058
+ params: {}
1059
+ }];
1060
+ applyEdit(base, message, main?.id ?? null, setStack);
1061
+ break;
1062
+ }
1063
+ case "sanity-visual-editor:toggle-inspector":
1064
+ postToBar(message);
1065
+ break;
1066
+ case "sanity-visual-editor:describe":
1067
+ describerRef.current(message.nodes).then((labels) => postToSite({
1068
+ type: "sanity-visual-editor:labels",
1069
+ labels
1070
+ })).catch((error) => console.warn("sanity-visual-editor: could not describe the page", error));
1071
+ break;
1072
+ case "sanity-visual-editor:live-status": postToBar(message);
1073
+ }
1074
+ }
1075
+ return window.addEventListener("message", onMessage), () => window.removeEventListener("message", onMessage);
1076
+ }, [
1077
+ origin,
1078
+ postToBar,
1079
+ postToSite
1080
+ ]);
1081
+ let [frameLoads, setFrameLoads] = useState(0), [connectFailed, setConnectFailed] = useState(!1);
1082
+ useEffect(() => {
1083
+ if (frameLoads === 0 || path !== null) return;
1084
+ let timer = setTimeout(() => setConnectFailed(!0), 8e3);
1085
+ return () => clearTimeout(timer);
1086
+ }, [frameLoads, path]);
1087
+ let retry = useCallback(() => {
1088
+ setConnectFailed(!1), setFrameError(null), setFrameLoads(0), setPath(null), setFrameSrc(null), perspectiveStored.current = !1, setAttempt((value) => value + 1);
1089
+ }, []), pageLoading = path === null && !frameError && !connectFailed, documentShown = narrow && view === "document";
1090
+ return /* @__PURE__ */ jsxs("div", {
1091
+ ref: rootRef,
1092
+ style: {
1093
+ position: "relative",
1094
+ display: "flex",
1095
+ height: "100%",
1096
+ minHeight: 0,
1097
+ background: "var(--card-bg-color)"
1098
+ },
1099
+ children: [/* @__PURE__ */ jsxs("div", {
1100
+ style: {
1101
+ display: "flex",
1102
+ flexDirection: "column",
1103
+ flex: 1,
1104
+ minWidth: 0,
1105
+ minHeight: 0
1106
+ },
1107
+ children: [/* @__PURE__ */ jsx("div", {
1108
+ style: {
1109
+ position: "relative",
1110
+ flex: "none",
1111
+ height: 50
1112
+ },
1113
+ children: /* @__PURE__ */ jsx(PreviewBarView, {
1114
+ data: barData,
1115
+ host: barHost,
1116
+ sanity: sanityModule,
1117
+ options: barOptions,
1118
+ editorState: {
1119
+ open: barEditorOpen,
1120
+ available: editorAvailable,
1121
+ toggle: narrow
1122
+ },
1123
+ pageDocument: mainDocumentLoaded ? mainDocument : void 0
1124
+ })
1125
+ }), /* @__PURE__ */ jsxs("div", {
1126
+ style: {
1127
+ position: "relative",
1128
+ display: "flex",
1129
+ justifyContent: "safe center",
1130
+ flex: 1,
1131
+ minHeight: 0,
1132
+ overflowX: device ? "auto" : "hidden",
1133
+ overflowY: "hidden",
1134
+ background: "var(--card-muted-bg-color, var(--card-bg-color))",
1135
+ visibility: documentShown ? "hidden" : "visible"
1136
+ },
1137
+ children: [
1138
+ frameSrc ? /* @__PURE__ */ jsx("iframe", {
1139
+ ref: siteFrame,
1140
+ name: PREVIEW_BAR_FRAME_NAME,
1141
+ onLoad: () => setFrameLoads((value) => value + 1),
1142
+ title: "Preview",
1143
+ src: frameSrc,
1144
+ allow: "clipboard-write",
1145
+ style: {
1146
+ display: "block",
1147
+ flex: "none",
1148
+ width: device ?? "100%",
1149
+ maxWidth: "none",
1150
+ height: device ? "calc(100% - 8px)" : "100%",
1151
+ margin: device ? "4px 0" : 0,
1152
+ border: 0,
1153
+ background: "var(--card-bg-color)",
1154
+ boxShadow: device ? "0 0 0 1px var(--card-border-color)" : "none",
1155
+ pointerEvents: resizing ? "none" : void 0,
1156
+ transition: [
1157
+ "width",
1158
+ "height",
1159
+ "margin"
1160
+ ].map((property) => `${property} 300ms cubic-bezier(0.2, 0, 0, 1)`).join(", ")
1161
+ }
1162
+ }, attempt) : null,
1163
+ pageLoading && /* @__PURE__ */ jsx(PageSkeleton, {}),
1164
+ (frameError || connectFailed) && /* @__PURE__ */ jsx(PageError, {
1165
+ message: frameError,
1166
+ enablePath,
1167
+ pageUrl: frameError ? null : new URL(path ?? initialPath, origin).toString(),
1168
+ onRetry: retry
1169
+ })
1170
+ ]
1171
+ })]
1172
+ }), (paneOpen || paneLoading) && /* @__PURE__ */ jsxs("div", {
1173
+ "data-preview-bar-panel": "",
1174
+ style: {
1175
+ position: "relative",
1176
+ flex: "none",
1177
+ width: paneWidth,
1178
+ height: "100%",
1179
+ minHeight: 0,
1180
+ overflow: "hidden",
1181
+ borderLeft: "1px solid var(--card-border-color)",
1182
+ ...narrow && {
1183
+ position: "absolute",
1184
+ top: 50,
1185
+ right: 0,
1186
+ bottom: 0,
1187
+ left: 0,
1188
+ width: "auto",
1189
+ height: "auto",
1190
+ borderLeft: 0,
1191
+ visibility: documentShown ? "visible" : "hidden"
1192
+ }
1193
+ },
1194
+ children: [!narrow && /* @__PURE__ */ jsx(PaneResizer, {
1195
+ width: paneWidth,
1196
+ side: "right",
1197
+ resize: paneResize
1198
+ }), paneOpen ? /* @__PURE__ */ jsx(PresentationDocumentContext.Provider, {
1199
+ value: NO_LOCATIONS,
1200
+ children: /* @__PURE__ */ jsx(DocumentPanel, {
1201
+ structure,
1202
+ stack,
1203
+ onChange: changeStack,
1204
+ onIntent,
1205
+ onFocusPath: reportFocus,
1206
+ fallback: /* @__PURE__ */ jsx(PaneSkeleton, {})
1207
+ })
1208
+ }) : /* @__PURE__ */ jsx(PaneSkeleton, {})]
1209
+ })]
1210
+ });
1211
+ }
1212
+ /**
1213
+ * `sanity-plugin-visual-editor/studio`: the Visual Editor tool for the Studio. Presentation's layout with
1214
+ * the preview bar on top, the site in the middle (desktop or a 375px phone) and the document pane
1215
+ * on the right. The bar's **Edit** on the site opens a page here (`visualEditor` bar option).
1216
+ *
1217
+ * ```ts
1218
+ * // sanity.config.ts
1219
+ * import {visualEditorTool} from 'sanity-plugin-visual-editor/studio'
1220
+ * plugins: [visualEditorTool({previewUrl: {previewMode: {enable: '/preview/enable'}}})]
1221
+ * ```
1222
+ */
1223
+ /**
1224
+ * Presentation's `defineLocations`, for `resolve.locations`: types a resolver, does nothing else.
1225
+ * The same resolvers work in both tools.
1226
+ */
1227
+ function defineLocations(resolver) {
1228
+ return resolver;
1229
+ }
1230
+ /** Presentation's `defineDocuments`, for `resolve.mainDocuments`: types the list, nothing else. */
1231
+ function defineDocuments(resolvers) {
1232
+ return resolvers;
1233
+ }
1234
+ /**
1235
+ * The Studio's navbar, except in the Visual Editor, where the preview bar is the toolbar (the
1236
+ * approach of `studio.components.navbar` middleware that renders nothing for one tool).
1237
+ */
1238
+ function navbarFor(toolName) {
1239
+ return function VisualEditorNavbar(props) {
1240
+ let { state } = useRouter();
1241
+ return state.tool === toolName ? null : props.renderDefault(props);
1242
+ };
1243
+ }
1244
+ const visualEditor = definePlugin((options) => {
1245
+ let settings = options ?? {}, toolName = settings.name ?? "visual-editor", locations = settings.resolve?.locations, liveEdit = settings.liveEdit ?? !0;
1246
+ return {
1247
+ name: "sanity-plugin-visual-editor/visual-editor",
1248
+ ...locations ? { form: { components: { input: locationsInput(locations, toolName) } } } : {},
1249
+ ...settings.hideStudioNavbar === !1 ? {} : { studio: { components: { navbar: navbarFor(toolName) } } },
1250
+ ...liveEdit === !1 ? {} : { plugins: [liveEditPlugin(liveEdit === !0 ? void 0 : liveEdit)] },
1251
+ tools: [{
1252
+ name: toolName,
1253
+ title: settings.title ?? "Visual Editor",
1254
+ icon: EditIcon,
1255
+ options: settings,
1256
+ router: route.create("/", { __unsafe_disableScopedSearchParams: !0 }),
1257
+ component: (props) => createElement(VisualEditorTool, props)
1258
+ }]
1259
+ };
1260
+ }), visualEditorTool = visualEditor;
1261
+ export { defineDocuments, defineLocations, liveEditPlugin, visualEditor, visualEditorTool };
1262
+
1263
+ //# sourceMappingURL=studio.js.map