@nocode-factory/sanity-kit 2.56.0 → 2.59.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 (47) hide show
  1. package/README.md +45 -8
  2. package/bin/item-types.mjs +131 -0
  3. package/bin/ncf-kit.mjs +121 -2
  4. package/dist/{finalUrl-IXF3zbT9.js → finalUrl-DYyjKCjh.js} +2 -1
  5. package/dist/finalUrl-DYyjKCjh.js.map +1 -0
  6. package/dist/{fixCrossLanguageReferences-CDczoic9.js → fixCrossLanguageReferences-C4A61VWW.js} +2 -2
  7. package/dist/{fixCrossLanguageReferences-CDczoic9.js.map → fixCrossLanguageReferences-C4A61VWW.js.map} +1 -1
  8. package/dist/{fixCrossLanguageReferences-C1VsmGsJ.d.ts → fixCrossLanguageReferences-CfFDSTD5.d.ts} +8 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.js +7240 -7011
  11. package/dist/index.js.map +1 -1
  12. package/dist/inherited-DZvM35P6.js +101 -0
  13. package/dist/inherited-DZvM35P6.js.map +1 -0
  14. package/dist/jsonld.js +1 -1
  15. package/dist/protocol-Bl7Yj2Ro.js +31 -0
  16. package/dist/protocol-Bl7Yj2Ro.js.map +1 -0
  17. package/dist/schema.d.ts +1 -1
  18. package/dist/schema.js +2 -2
  19. package/dist/web-edit.d.ts +192 -0
  20. package/dist/web-edit.js +144 -0
  21. package/dist/web-edit.js.map +1 -0
  22. package/dist/web-editing.d.ts +51 -0
  23. package/dist/web-editing.js +693 -0
  24. package/dist/web-editing.js.map +1 -0
  25. package/package.json +22 -2
  26. package/scripts/use-client.mjs +1 -1
  27. package/src/config/resolve.ts +1 -0
  28. package/src/config/types.ts +7 -1
  29. package/src/form/AssetSourceBrowser.tsx +68 -39
  30. package/src/index.ts +12 -5
  31. package/src/lib/i18nTemplates.ts +38 -4
  32. package/src/tools/collections/CollectionTable.tsx +116 -89
  33. package/src/tools/presentation/PagesNavigator.tsx +150 -56
  34. package/src/ui/PreviewEditBridge.tsx +74 -0
  35. package/src/version.ts +1 -1
  36. package/src/web/edit/ImageReplaceLayer.tsx +174 -0
  37. package/src/web/edit/InlineTextEditor.tsx +365 -0
  38. package/src/web/edit/InlineTextOverlay.tsx +43 -0
  39. package/src/web/edit/PreviewEditing.tsx +191 -0
  40. package/src/web/edit/index.ts +18 -0
  41. package/src/web/edit/inherited.ts +174 -0
  42. package/src/web/edit/labels.ts +37 -0
  43. package/src/web/edit/protocol.ts +47 -0
  44. package/src/web/edit/store.ts +98 -0
  45. package/src/web/edit/targets.ts +186 -0
  46. package/src/web/editing.ts +18 -0
  47. package/dist/finalUrl-IXF3zbT9.js.map +0 -1
@@ -0,0 +1,693 @@
1
+ 'use client'
2
+ import { t as REPLACE_IMAGE_MESSAGE } from "./protocol-Bl7Yj2Ro.js";
3
+ import { n as inheritedListValue, r as materializeInheritedList } from "./inherited-DZvM35P6.js";
4
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
+ import { createPortal } from "react-dom";
7
+ import { VERCEL_STEGA_REGEX, vercelStegaClean, vercelStegaDecode } from "@vercel/stega";
8
+ import { useDocuments } from "@sanity/visual-editing";
9
+ import { at, set, unset } from "@sanity/mutate";
10
+ import { getAtPath, parse } from "@sanity/mutate/path";
11
+ const DEFAULT_PREVIEW_EDITING_LABELS = {
12
+ fieldLabel: "Edit text",
13
+ save: "Save",
14
+ cancel: "Cancel",
15
+ saved: "Saved to draft",
16
+ inheritedNote: "Component default text: editing it here creates text specific to this page.",
17
+ replaceImage: "Replace this image",
18
+ editMode: "Edit mode",
19
+ browseMode: "Browse mode",
20
+ modeLabel: "Preview mode: edit or browse"
21
+ }, ACCENT = "var(--ncf-edit-accent, #2276fc)", CHIP = "var(--ncf-edit-chip, #1b1d21)", FONT = "var(--ncf-edit-font, ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif)";
22
+ let hovered = null, editing = null;
23
+ const listeners = /* @__PURE__ */ new Set(), emit = () => listeners.forEach((l) => l()), inlineEdit = {
24
+ subscribe(listener) {
25
+ return listeners.add(listener), () => listeners.delete(listener);
26
+ },
27
+ getHovered: () => hovered,
28
+ getEditing: () => editing,
29
+ setHovered(target) {
30
+ hovered = target;
31
+ },
32
+ clearHovered(element) {
33
+ hovered?.element === element && (hovered = null);
34
+ },
35
+ open(target) {
36
+ editing = target, emit();
37
+ },
38
+ close() {
39
+ editing = null, emit();
40
+ }
41
+ }, EDIT_MODE_ATTRIBUTE = "data-ncf-edit-mode", PREVIEW_EDIT_ATTRIBUTE = "data-ncf-preview-edit", EDIT_MODE_STORAGE_KEY = "ncf-preview-mode", defaultEditMode = () => typeof document < "u" && document.documentElement.getAttribute("data-ncf-edit-mode") !== "browse";
42
+ let editModeResolver = defaultEditMode;
43
+ function setEditModeResolver(resolver) {
44
+ editModeResolver = resolver ?? defaultEditMode;
45
+ }
46
+ function isEditMode() {
47
+ try {
48
+ return editModeResolver();
49
+ } catch {
50
+ return !1;
51
+ }
52
+ }
53
+ /** Nombre de textes marqués (stega) dans un texte affiché. */
54
+ function stegaRuns(text) {
55
+ return text.match(VERCEL_STEGA_REGEX)?.length ?? 0;
56
+ }
57
+ /**
58
+ * Texte modifiable sur place : champ chaîne, ou morceau d'un texte riche qui a SON
59
+ * élément (un seul texte marqué dedans : titre en lignes, passage en italique ;
60
+ * dans un paragraphe fait de plusieurs morceaux, l'éditeur masquerait tout le
61
+ * paragraphe pour n'en modifier qu'une partie : panneau). Jamais un alt (une
62
+ * image n'est pas un texte, même repérée par son alt), un élément sans texte, ni
63
+ * un slug (une adresse se change dans le panneau, qui crée la 301).
64
+ */
65
+ function isInlineEditablePath(type, path, element) {
66
+ return !(type !== "string" || /(^|\.)alt$/.test(path) || element.matches("img, picture, video, svg, canvas, iframe") || !element.textContent?.trim() || /\.children\[[^\]]+\]\.text$/.test(path) && stegaRuns(element.textContent ?? "") !== 1 || /(^|\.)slug\.current$/.test(path) || path.endsWith(".current"));
67
+ }
68
+ /** Chemin d'un morceau de texte riche (jamais retiré, seulement vidé). */
69
+ const isSpanTextPath = (path) => /\.children\[[^\]]+\]\.text$/.test(path);
70
+ function studioOrigin() {
71
+ let ancestor = window.location.ancestorOrigins?.[0];
72
+ if (ancestor) return ancestor;
73
+ try {
74
+ return document.referrer ? new URL(document.referrer).origin : null;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+ /** Hauteur du header du site (`--header-height`, px ou rem), 0 sinon. */
80
+ function headerHeight() {
81
+ let root = getComputedStyle(document.documentElement), raw = root.getPropertyValue("--header-height").trim();
82
+ return (parseFloat(raw) || 0) * (raw.endsWith("rem") ? parseFloat(root.fontSize) || 16 : 1);
83
+ }
84
+ /** Rectangle visible : rogné par les ancêtres qui coupent, la fenêtre et le header. */
85
+ function visibleRect(element) {
86
+ let r = element.getBoundingClientRect(), top = Math.max(r.top, headerHeight()), left = Math.max(r.left, 0), right = Math.min(r.right, window.innerWidth), bottom = Math.min(r.bottom, window.innerHeight);
87
+ for (let n = element.parentElement; n && n !== document.body; n = n.parentElement) {
88
+ let cs = getComputedStyle(n);
89
+ if (cs.overflowX === "visible" && cs.overflowY === "visible") continue;
90
+ let c = n.getBoundingClientRect();
91
+ top = Math.max(top, c.top), left = Math.max(left, c.left), right = Math.min(right, c.right), bottom = Math.min(bottom, c.bottom);
92
+ }
93
+ return {
94
+ top,
95
+ left,
96
+ right,
97
+ bottom
98
+ };
99
+ }
100
+ /**
101
+ * Image éditable sous la souris, même RECOUVERTE par des calques décoratifs
102
+ * (dégradé, voile, bloc de titre en plein cadre) : on parcourt la pile d'éléments
103
+ * sous le point et on traverse tout calque sans texte. Un vrai texte (ou un champ
104
+ * de saisie) posé sur l'image garde la priorité, pour rester modifiable.
105
+ */
106
+ const VISIBLE_TEXT = /[^\s​-‍⁠]/;
107
+ function hasOwnText(el) {
108
+ for (let n of el.childNodes) if (n.nodeType === Node.TEXT_NODE && VISIBLE_TEXT.test(n.textContent ?? "")) return !0;
109
+ return !1;
110
+ }
111
+ function imageAt(x, y) {
112
+ for (let el of document.elementsFromPoint(x, y)) {
113
+ let image = el.closest("[data-edit-image][data-edit-doc][data-edit-type]");
114
+ if (image) return image;
115
+ if (hasOwnText(el) || el.matches("input, textarea, select, button, [contenteditable]")) return null;
116
+ }
117
+ return null;
118
+ }
119
+ function ImageReplaceLayer({ label }) {
120
+ let [target, setTarget] = useState(null), [pos, setPos] = useState(null);
121
+ return useEffect(() => {
122
+ if (window.parent === window) return;
123
+ let frame = 0, onMove = (event) => {
124
+ let { clientX, clientY } = event;
125
+ cancelAnimationFrame(frame), frame = requestAnimationFrame(() => {
126
+ let el = isEditMode() ? imageAt(clientX, clientY) : null;
127
+ setTarget((prev) => prev === el ? prev : el);
128
+ });
129
+ }, onLeaveWindow = (event) => {
130
+ event.relatedTarget || setTarget(null);
131
+ }, onClick = (event) => {
132
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || !isEditMode()) return;
133
+ let el = imageAt(event.clientX, event.clientY), origin = studioOrigin();
134
+ el && origin && (event.preventDefault(), setTarget(null), window.parent.postMessage({
135
+ type: REPLACE_IMAGE_MESSAGE,
136
+ documentId: el.getAttribute("data-edit-doc"),
137
+ documentType: el.getAttribute("data-edit-type"),
138
+ path: el.getAttribute("data-edit-image")
139
+ }, origin));
140
+ };
141
+ return document.addEventListener("pointermove", onMove, { passive: !0 }), document.documentElement.addEventListener("pointerout", onLeaveWindow, { passive: !0 }), window.addEventListener("click", onClick, { capture: !0 }), () => {
142
+ cancelAnimationFrame(frame), document.removeEventListener("pointermove", onMove), document.documentElement.removeEventListener("pointerout", onLeaveWindow), window.removeEventListener("click", onClick, { capture: !0 });
143
+ };
144
+ }, []), useEffect(() => {
145
+ if (!target) return;
146
+ let frame = 0, measure = () => {
147
+ let v = visibleRect(target), center = Math.min(Math.max((v.left + v.right) / 2, 118), window.innerWidth - 110 - 8), next = v.bottom - v.top < 40 || v.right - v.left < 40 ? null : {
148
+ top: Math.round(v.top + 16),
149
+ left: Math.round(center)
150
+ };
151
+ setPos((prev) => prev && next && prev.top === next.top && prev.left === next.left ? prev : next), frame = requestAnimationFrame(measure);
152
+ };
153
+ return measure(), () => {
154
+ cancelAnimationFrame(frame), setPos(null);
155
+ };
156
+ }, [target]), !target || !pos ? null : createPortal(/* @__PURE__ */ jsxs("span", {
157
+ "aria-hidden": !0,
158
+ style: {
159
+ pointerEvents: "none",
160
+ position: "fixed",
161
+ zIndex: 2147482e3,
162
+ top: pos.top,
163
+ left: pos.left,
164
+ transform: "translateX(-50%)",
165
+ display: "flex",
166
+ alignItems: "center",
167
+ gap: 8,
168
+ padding: "6px 12px 6px 8px",
169
+ borderRadius: 999,
170
+ background: CHIP,
171
+ color: "#fff",
172
+ boxShadow: "0 8px 24px rgba(0,0,0,0.25)",
173
+ font: `500 13px/1 ${FONT}`,
174
+ whiteSpace: "nowrap"
175
+ },
176
+ children: [/* @__PURE__ */ jsxs("svg", {
177
+ viewBox: "0 0 16 16",
178
+ width: "14",
179
+ height: "14",
180
+ fill: "none",
181
+ stroke: "currentColor",
182
+ strokeWidth: "1.5",
183
+ strokeLinecap: "round",
184
+ strokeLinejoin: "round",
185
+ children: [
186
+ /* @__PURE__ */ jsx("rect", {
187
+ x: "2",
188
+ y: "3",
189
+ width: "12",
190
+ height: "10",
191
+ rx: "1.5"
192
+ }),
193
+ /* @__PURE__ */ jsx("circle", {
194
+ cx: "6",
195
+ cy: "6.5",
196
+ r: "1.2"
197
+ }),
198
+ /* @__PURE__ */ jsx("path", { d: "M14 10.5l-3.5-3.5L4 13" })
199
+ ]
200
+ }), label]
201
+ }), document.body);
202
+ }
203
+ /**
204
+ * Éditeur de texte SUR PLACE : au clic sur un texte modifiable, un champ de
205
+ * saisie prend sa place exacte, dans sa typographie. Entrée ou clic ailleurs =
206
+ * enregistré dans le BROUILLON (patch du seul champ, par le canal de l'aperçu),
207
+ * Échap = annulé. Le panneau du Studio s'ouvre en même temps sur le champ
208
+ * (comportement de Sanity, conservé). Rien n'est publié.
209
+ */
210
+ function InlineTextEditor({ labels }) {
211
+ let target = useSyncExternalStore(inlineEdit.subscribe, inlineEdit.getEditing, () => null);
212
+ return useEffect(() => {
213
+ let onClick = (event) => {
214
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || !isEditMode()) return;
215
+ let hovered = inlineEdit.getHovered() ?? inheritedListTarget(event.target);
216
+ hovered && event.target instanceof Node && hovered.element.contains(event.target) && inlineEdit.getEditing()?.element !== hovered.element && (event.preventDefault(), inlineEdit.open(hovered));
217
+ };
218
+ return window.addEventListener("click", onClick, { capture: !0 }), () => window.removeEventListener("click", onClick, { capture: !0 });
219
+ }, []), target ? createPortal(/* @__PURE__ */ jsx(EditorSession, {
220
+ target,
221
+ labels
222
+ }, `${target.node.id}:${target.node.path}`), document.body) : null;
223
+ }
224
+ function inheritedListFor(path) {
225
+ for (let script of document.querySelectorAll("script[data-ncf-inherited-list]")) {
226
+ let listPath = script.dataset.ncfInheritedList ?? "";
227
+ if (listPath && path.startsWith(`${listPath}[`)) try {
228
+ return {
229
+ path: listPath,
230
+ items: JSON.parse(script.textContent ?? "[]")
231
+ };
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+ return null;
237
+ }
238
+ function inheritedValueFor(path) {
239
+ for (let script of document.querySelectorAll("script[data-ncf-inherited-value]")) if (script.dataset.ncfInheritedValue === path) try {
240
+ let value = JSON.parse(script.textContent ?? "null");
241
+ return typeof value == "string" ? value : null;
242
+ } catch {
243
+ return null;
244
+ }
245
+ return null;
246
+ }
247
+ /**
248
+ * Ligne d'une liste héritée : Sanity n'active pas son composant sur un élément
249
+ * que la page n'a pas encore (pas de crayon), mais chaque texte porte sa ligne
250
+ * exacte (stega). Le clic sur un tel texte ouvre l'éditeur directement.
251
+ */
252
+ function inheritedListTarget(target) {
253
+ let el = target instanceof Element ? target : null;
254
+ for (let depth = 0; el && depth < 5; depth++, el = el.parentElement) {
255
+ let info = vercelStegaDecode(el.textContent ?? "");
256
+ if (!info?.href) continue;
257
+ let href = decodeURIComponent(info.href), id = /[;/]id=([^;?]+)/.exec(href)?.[1]?.replace(/^drafts\./, ""), type = /;type=([^;?]+)/.exec(href)?.[1], path = /;path=([^;?]+)/.exec(href)?.[1];
258
+ return !id || !path || !inheritedListFor(path) || !(el instanceof HTMLElement) ? null : {
259
+ element: el,
260
+ node: {
261
+ id,
262
+ type,
263
+ path
264
+ }
265
+ };
266
+ }
267
+ return null;
268
+ }
269
+ const TYPO_PROPS = [
270
+ "font-family",
271
+ "font-size",
272
+ "font-weight",
273
+ "font-style",
274
+ "font-variant",
275
+ "font-feature-settings",
276
+ "line-height",
277
+ "letter-spacing",
278
+ "word-spacing",
279
+ "text-transform",
280
+ "text-align",
281
+ "color"
282
+ ];
283
+ /**
284
+ * Typographie du texte affiché : celle de l'élément qui porte le premier morceau
285
+ * de texte (un titre découpé pour une animation garde ses mots dans des sous-éléments).
286
+ */
287
+ function textStyle(element) {
288
+ let host = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, { acceptNode: (n) => n.textContent?.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP }).nextNode()?.parentElement ?? element, cs = getComputedStyle(host), style = {};
289
+ for (let prop of TYPO_PROPS) style[prop.replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = cs.getPropertyValue(prop);
290
+ return style;
291
+ }
292
+ const sameBox = (a, b) => !!a && a.top === b.top && a.left === b.left && a.width === b.width && a.height === b.height, CHIP_STYLE = {
293
+ position: "absolute",
294
+ left: 0,
295
+ display: "flex",
296
+ alignItems: "center",
297
+ gap: 4,
298
+ padding: 4,
299
+ borderRadius: 999,
300
+ background: CHIP,
301
+ color: "#fff",
302
+ boxShadow: "0 8px 24px rgba(0,0,0,0.25)",
303
+ font: `500 13px/1 ${FONT}`,
304
+ fontStyle: "normal",
305
+ textTransform: "none",
306
+ letterSpacing: "normal",
307
+ whiteSpace: "nowrap"
308
+ }, BUTTON_STYLE = {
309
+ display: "flex",
310
+ alignItems: "center",
311
+ gap: 8,
312
+ padding: "7px 12px",
313
+ border: 0,
314
+ borderRadius: 999,
315
+ font: "inherit",
316
+ cursor: "pointer"
317
+ }, KBD_STYLE = {
318
+ font: `11px/1 ${FONT}`,
319
+ opacity: .7
320
+ };
321
+ function EditorSession({ target, labels }) {
322
+ let { element, node } = target, { getDocument } = useDocuments(), [status, setStatus] = useState("loading"), [value, setValue] = useState(""), [inherited, setInherited] = useState(!1), [box, setBox] = useState(null), [typo] = useState(() => textStyle(element)), initial = useRef(""), inheritedStart = useRef(""), multiline = useRef(!1), rootRef = useRef(null), fieldRef = useRef(null);
323
+ useEffect(() => {
324
+ let previous = element.style.visibility;
325
+ return element.style.visibility = "hidden", () => {
326
+ element.style.visibility = previous;
327
+ };
328
+ }, [element]), useEffect(() => {
329
+ let frame = 0, tick = () => {
330
+ let r = element.getBoundingClientRect(), next = {
331
+ top: r.top,
332
+ left: r.left,
333
+ width: r.width,
334
+ height: r.height
335
+ };
336
+ setBox((prev) => sameBox(prev, next) ? prev : next), frame = requestAnimationFrame(tick);
337
+ };
338
+ return tick(), () => cancelAnimationFrame(frame);
339
+ }, [element]), useEffect(() => {
340
+ let cancelled = !1;
341
+ return getDocument(node.id).getSnapshot().then((doc) => {
342
+ if (cancelled) return;
343
+ let stored = doc ? getAtPath(parse(node.path), doc) : void 0, list = inheritedListFor(node.path), text = typeof stored == "string" && stored !== "" ? stored : inheritedValueFor(node.path) ?? (list ? inheritedListValue(list, node.path) : null) ?? vercelStegaClean(element.textContent ?? "").trim();
344
+ initial.current = typeof stored == "string" ? stored : "", inheritedStart.current = text, multiline.current = text.includes("\n"), setInherited(typeof stored != "string" || stored === ""), setValue(text), setStatus("editing");
345
+ }).catch(() => {
346
+ cancelled || inlineEdit.close();
347
+ }), () => {
348
+ cancelled = !0;
349
+ };
350
+ }, [
351
+ getDocument,
352
+ node.id,
353
+ node.path,
354
+ element
355
+ ]), useEffect(() => {
356
+ if (status !== "editing") return;
357
+ let field = fieldRef.current;
358
+ if (!field) return;
359
+ let focusField = () => {
360
+ field.focus({ preventScroll: !0 }), field.setSelectionRange(field.value.length, field.value.length);
361
+ };
362
+ focusField();
363
+ let until = performance.now() + 1500, onBlur = () => {
364
+ performance.now() < until && window.setTimeout(focusField, 0);
365
+ };
366
+ window.addEventListener("blur", onBlur);
367
+ let retry = window.setTimeout(focusField, 300);
368
+ return () => {
369
+ window.removeEventListener("blur", onBlur), window.clearTimeout(retry);
370
+ };
371
+ }, [status]), useLayoutEffect(() => {
372
+ let field = fieldRef.current;
373
+ field && (field.style.height = "auto", field.style.height = `${field.scrollHeight}px`);
374
+ }, [
375
+ value,
376
+ box?.width,
377
+ status
378
+ ]);
379
+ let save = useCallback(() => {
380
+ let next = multiline.current ? value : value.replace(/\s*\n\s*/g, " ");
381
+ if (next === initial.current || inherited && next.trim() === inheritedStart.current.trim()) {
382
+ inlineEdit.close();
383
+ return;
384
+ }
385
+ let list = inherited ? inheritedListFor(node.path) : null, items = list ? materializeInheritedList(list, node.path, next) : null, doc = getDocument(node.id);
386
+ list && items ? doc.patch([at(list.path, set(items))]) : isSpanTextPath(node.path) ? doc.patch([at(node.path, set(next))]) : doc.patch([at(node.path, next.trim() === "" ? unset() : set(next))]), setStatus("saving");
387
+ }, [
388
+ value,
389
+ inherited,
390
+ getDocument,
391
+ node.id,
392
+ node.path
393
+ ]);
394
+ useEffect(() => {
395
+ if (status !== "saving") return;
396
+ let expected = value.replace(/\s+/g, " ").trim(), started = performance.now(), timer = window.setInterval(() => {
397
+ (vercelStegaClean(element.textContent ?? "").replace(/\s+/g, " ").trim().includes(expected) || expected === "" || performance.now() - started > 6e3) && inlineEdit.close();
398
+ }, 150);
399
+ return () => window.clearInterval(timer);
400
+ }, [
401
+ status,
402
+ value,
403
+ element
404
+ ]), useEffect(() => {
405
+ if (status !== "editing") return;
406
+ let onPointerDown = (event) => {
407
+ event.target instanceof Node && rootRef.current?.contains(event.target) || save();
408
+ };
409
+ return window.addEventListener("pointerdown", onPointerDown, { capture: !0 }), () => window.removeEventListener("pointerdown", onPointerDown, { capture: !0 });
410
+ }, [status, save]);
411
+ let onKeyDown = (event) => {
412
+ event.key === "Escape" ? (event.preventDefault(), inlineEdit.close()) : event.key === "Enter" && !(event.shiftKey && multiline.current) && (event.preventDefault(), save());
413
+ };
414
+ if (!box) return null;
415
+ let below = box.top + box.height + 56 < window.innerHeight, place = below ? {
416
+ top: "100%",
417
+ marginTop: 12
418
+ } : {
419
+ bottom: "100%",
420
+ marginBottom: 12
421
+ };
422
+ return /* @__PURE__ */ jsxs("div", {
423
+ ref: rootRef,
424
+ "data-sanity-overlay-element": !0,
425
+ style: {
426
+ position: "fixed",
427
+ zIndex: 2147483e3,
428
+ top: box.top,
429
+ left: box.left,
430
+ width: box.width,
431
+ minHeight: box.height
432
+ },
433
+ children: [
434
+ /* @__PURE__ */ jsx("textarea", {
435
+ ref: fieldRef,
436
+ value,
437
+ rows: 1,
438
+ spellCheck: !0,
439
+ readOnly: status !== "editing",
440
+ "aria-label": labels.fieldLabel,
441
+ onChange: (e) => setValue(e.target.value),
442
+ onKeyDown,
443
+ style: {
444
+ ...typo,
445
+ display: "block",
446
+ width: "100%",
447
+ minHeight: box.height,
448
+ margin: 0,
449
+ padding: 0,
450
+ border: 0,
451
+ borderRadius: 2,
452
+ resize: "none",
453
+ overflow: "hidden",
454
+ background: "transparent",
455
+ caretColor: ACCENT,
456
+ outline: `2px solid ${ACCENT}`,
457
+ outlineOffset: 4,
458
+ opacity: status === "loading" ? 0 : 1
459
+ }
460
+ }),
461
+ /* @__PURE__ */ jsx("div", {
462
+ style: {
463
+ ...CHIP_STYLE,
464
+ ...place
465
+ },
466
+ children: status === "saving" ? /* @__PURE__ */ jsx("span", {
467
+ style: { padding: "6px 10px" },
468
+ children: labels.saved
469
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("button", {
470
+ type: "button",
471
+ onClick: save,
472
+ disabled: status !== "editing",
473
+ style: {
474
+ ...BUTTON_STYLE,
475
+ background: ACCENT,
476
+ color: "#fff"
477
+ },
478
+ children: [labels.save, /* @__PURE__ */ jsx("kbd", {
479
+ style: KBD_STYLE,
480
+ children: "↵"
481
+ })]
482
+ }), /* @__PURE__ */ jsxs("button", {
483
+ type: "button",
484
+ onClick: () => inlineEdit.close(),
485
+ style: {
486
+ ...BUTTON_STYLE,
487
+ background: "transparent",
488
+ color: "rgba(255,255,255,0.85)"
489
+ },
490
+ children: [labels.cancel, /* @__PURE__ */ jsx("kbd", {
491
+ style: KBD_STYLE,
492
+ children: "Esc"
493
+ })]
494
+ })] })
495
+ }),
496
+ inherited && status === "editing" && /* @__PURE__ */ jsx("p", {
497
+ style: {
498
+ position: "absolute",
499
+ left: 0,
500
+ ...below ? {
501
+ top: "100%",
502
+ marginTop: 56
503
+ } : {
504
+ bottom: "100%",
505
+ marginBottom: 56
506
+ },
507
+ width: "max-content",
508
+ maxWidth: "min(28rem, 90vw)",
509
+ padding: "8px 12px",
510
+ borderRadius: 6,
511
+ background: "#fff",
512
+ color: "#1b1d21",
513
+ boxShadow: "0 8px 24px rgba(0,0,0,0.18)",
514
+ font: "12px/1.35 var(--ncf-edit-font, ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif)",
515
+ fontStyle: "normal",
516
+ textTransform: "none",
517
+ letterSpacing: "normal"
518
+ },
519
+ children: labels.inheritedNote
520
+ })
521
+ ]
522
+ });
523
+ }
524
+ /**
525
+ * Monté par l'overlay de Sanity au survol d'un texte modifiable sur place : crayon
526
+ * en haut à droite du cadre, et inscription comme cible du prochain clic
527
+ * (`InlineTextEditor` écoute le clic avant Sanity).
528
+ */
529
+ function InlineTextOverlay({ element, node }) {
530
+ return useEffect(() => {
531
+ if (element instanceof HTMLElement) return inlineEdit.setHovered({
532
+ element,
533
+ node
534
+ }), () => inlineEdit.clearHovered(element);
535
+ }, [element, node]), /* @__PURE__ */ jsx("span", {
536
+ "aria-hidden": !0,
537
+ style: {
538
+ pointerEvents: "none",
539
+ position: "absolute",
540
+ top: -12,
541
+ right: -12,
542
+ display: "flex",
543
+ width: 24,
544
+ height: 24,
545
+ alignItems: "center",
546
+ justifyContent: "center",
547
+ borderRadius: 999,
548
+ background: ACCENT,
549
+ color: "#fff",
550
+ boxShadow: "0 4px 12px rgba(0,0,0,0.2)"
551
+ },
552
+ children: /* @__PURE__ */ jsxs("svg", {
553
+ viewBox: "0 0 16 16",
554
+ width: "12",
555
+ height: "12",
556
+ fill: "none",
557
+ stroke: "currentColor",
558
+ strokeWidth: "1.6",
559
+ strokeLinecap: "round",
560
+ strokeLinejoin: "round",
561
+ children: [/* @__PURE__ */ jsx("path", { d: "M10.5 2.5l3 3L6 13H3v-3l7.5-7.5z" }), /* @__PURE__ */ jsx("path", { d: "M9 4l3 3" })]
562
+ })
563
+ });
564
+ }
565
+ /**
566
+ * ÉDITION SUR PLACE dans l'aperçu (Presentation), à monter à côté de
567
+ * `<VisualEditing/>` en mode brouillon :
568
+ *
569
+ * ```tsx
570
+ * <VisualEditing refresh={useNcfPreviewRefresh()} components={ncfOverlayComponents} />
571
+ * <NcfPreviewEditing labels={messages.previewEditing} />
572
+ * ```
573
+ *
574
+ * - texte (champ chaîne, ligne d'un titre en texte riche) : crayon au survol, au
575
+ * clic un champ de saisie à sa place exacte ; enregistré dans le brouillon ;
576
+ * - image : « Replace this image » au survol, au clic le Studio ouvre la
577
+ * médiathèque (pont monté par le plugin du kit) ;
578
+ * - « Mode édition / Mode visite » : en visite, un clic suit les liens.
579
+ */
580
+ const ncfOverlayComponents = (context) => {
581
+ if (isEditMode() && isInlineEditablePath(context.type, context.node.path, context.element)) return InlineTextOverlay;
582
+ }, EDIT_CSS = `html[${PREVIEW_EDIT_ATTRIBUTE}] a::after, html[${PREVIEW_EDIT_ATTRIBUTE}] a::before { pointer-events: none !important; }`;
583
+ function NcfPreviewEditing({ labels, editMode = "toggle" }) {
584
+ let text = {
585
+ ...DEFAULT_PREVIEW_EDITING_LABELS,
586
+ ...labels
587
+ }, custom = typeof editMode == "function" ? editMode : null, customRef = useRef(custom);
588
+ customRef.current = custom;
589
+ let hasCustom = custom !== null;
590
+ return useOverlayRectRefresh(), useEffect(() => {
591
+ setEditModeResolver(hasCustom ? () => customRef.current?.() ?? !1 : null);
592
+ let root = document.documentElement, sync = () => {
593
+ let want = isEditMode();
594
+ want && !root.hasAttribute("data-ncf-preview-edit") ? root.setAttribute(PREVIEW_EDIT_ATTRIBUTE, "") : !want && root.hasAttribute("data-ncf-preview-edit") && root.removeAttribute(PREVIEW_EDIT_ATTRIBUTE);
595
+ };
596
+ sync();
597
+ let observer = new MutationObserver(sync);
598
+ return observer.observe(root, { attributes: !0 }), () => {
599
+ observer.disconnect(), root.removeAttribute(PREVIEW_EDIT_ATTRIBUTE), setEditModeResolver(null);
600
+ };
601
+ }, [hasCustom]), /* @__PURE__ */ jsxs(Fragment, { children: [
602
+ /* @__PURE__ */ jsx("style", { children: EDIT_CSS }),
603
+ /* @__PURE__ */ jsx(InlineTextEditor, { labels: text }),
604
+ /* @__PURE__ */ jsx(ImageReplaceLayer, { label: text.replaceImage }),
605
+ !hasCustom && /* @__PURE__ */ jsx(EditModeToggle, { labels: text })
606
+ ] });
607
+ }
608
+ /** Interrupteur « Edit mode / Browse mode » : affiché dans l'aperçu du Studio seulement. */
609
+ function EditModeToggle({ labels }) {
610
+ let [embedded, setEmbedded] = useState(!1), [edit, setEdit] = useState(!0);
611
+ if (useEffect(() => {
612
+ let inFrame = !0;
613
+ try {
614
+ inFrame = window.self !== window.top;
615
+ } catch {
616
+ inFrame = !0;
617
+ }
618
+ setEmbedded(inFrame);
619
+ let stored = null;
620
+ try {
621
+ stored = window.localStorage.getItem(EDIT_MODE_STORAGE_KEY);
622
+ } catch {
623
+ stored = null;
624
+ }
625
+ let next = stored !== "browse";
626
+ return setEdit(next), document.documentElement.setAttribute(EDIT_MODE_ATTRIBUTE, next ? "edit" : "browse"), () => document.documentElement.removeAttribute(EDIT_MODE_ATTRIBUTE);
627
+ }, []), !embedded) return null;
628
+ let toggle = () => {
629
+ let next = !edit;
630
+ setEdit(next), document.documentElement.setAttribute(EDIT_MODE_ATTRIBUTE, next ? "edit" : "browse");
631
+ try {
632
+ window.localStorage.setItem(EDIT_MODE_STORAGE_KEY, next ? "edit" : "browse");
633
+ } catch {}
634
+ };
635
+ return /* @__PURE__ */ jsxs("button", {
636
+ type: "button",
637
+ role: "switch",
638
+ "aria-checked": edit,
639
+ "aria-label": labels.modeLabel,
640
+ onClick: toggle,
641
+ "data-sanity-overlay-element": !0,
642
+ style: {
643
+ position: "fixed",
644
+ left: 16,
645
+ bottom: 16,
646
+ zIndex: 2147482500,
647
+ display: "flex",
648
+ alignItems: "center",
649
+ gap: 8,
650
+ padding: "8px 14px 8px 10px",
651
+ border: 0,
652
+ borderRadius: 999,
653
+ background: CHIP,
654
+ color: "#fff",
655
+ boxShadow: "0 8px 24px rgba(0,0,0,0.25)",
656
+ font: `500 12px/1 ${FONT}`,
657
+ cursor: "pointer"
658
+ },
659
+ children: [/* @__PURE__ */ jsx("span", {
660
+ "aria-hidden": !0,
661
+ style: {
662
+ width: 8,
663
+ height: 8,
664
+ borderRadius: 999,
665
+ background: edit ? "#3ecf8e" : "rgba(255,255,255,0.45)"
666
+ }
667
+ }), edit ? labels.editMode : labels.browseMode]
668
+ });
669
+ }
670
+ /**
671
+ * Cadres de Sanity à la bonne place. L'overlay mémorise la position de chaque
672
+ * élément et ne la remesure qu'au redimensionnement : une page qui se décale
673
+ * après le chargement (photos différées, effets liés au défilement) laissait les
674
+ * cadres à l'ancienne place. On demande la remesure quand la hauteur de la page
675
+ * change, quand une image finit de charger et à la fin d'un défilement, par le
676
+ * signal que Sanity écoute déjà : un événement « scroll » sur <body> (il ne
677
+ * remonte pas jusqu'à la fenêtre : aucun effet de défilement ne le reçoit).
678
+ */
679
+ function useOverlayRectRefresh() {
680
+ useEffect(() => {
681
+ let frame = 0, timer = 0, refresh = () => {
682
+ cancelAnimationFrame(frame), frame = requestAnimationFrame(() => document.body.dispatchEvent(new Event("scroll")));
683
+ }, onScroll = () => {
684
+ window.clearTimeout(timer), timer = window.setTimeout(refresh, 120);
685
+ }, ro = new ResizeObserver(refresh);
686
+ return ro.observe(document.body), window.addEventListener("scroll", onScroll, { passive: !0 }), document.addEventListener("load", refresh, !0), refresh(), () => {
687
+ ro.disconnect(), cancelAnimationFrame(frame), window.clearTimeout(timer), window.removeEventListener("scroll", onScroll), document.removeEventListener("load", refresh, !0);
688
+ };
689
+ }, []);
690
+ }
691
+ export { DEFAULT_PREVIEW_EDITING_LABELS, NcfPreviewEditing, ncfOverlayComponents };
692
+
693
+ //# sourceMappingURL=web-editing.js.map