@nocode-factory/sanity-kit 2.61.0 → 2.61.1-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,6 +33,17 @@ function replaceImagePatch(path, assetId) {
33
33
  { unset: [`${path}.crop`, `${path}.hotspot`] }
34
34
  ];
35
35
  }
36
+ /**
37
+ * Lecture d'une valeur BRUTE des valeurs par défaut (recopie d'une liste héritée à la
38
+ * première modification d'un texte) : l'aperçu la demande au Studio, qui la lit dans le
39
+ * document (brouillon s'il existe) et répond à la seule fenêtre qui a demandé.
40
+ */
41
+ const READ_DEFAULTS_MESSAGE = "ncf-kit/read-defaults", READ_DEFAULTS_RESULT = "ncf-kit/read-defaults-result";
42
+ function isReadDefaultsRequest(data) {
43
+ if (!data || typeof data != "object") return !1;
44
+ let d = data;
45
+ return d.type === "ncf-kit/read-defaults" && typeof d.requestId == "string" && typeof d.id == "string" && /^[\w.-]+$/.test(d.id) && typeof d.path == "string" && SAFE_PATH.test(d.path);
46
+ }
36
47
  const isPrimitive = (v) => typeof v == "string" || typeof v == "number" || typeof v == "boolean";
37
48
  function isSimpleList(value) {
38
49
  return Array.isArray(value) && value.length > 0 && value.every((item) => item && typeof item == "object" && !Array.isArray(item) && typeof item._key == "string" && item._type !== "block" && Object.entries(item).every(([k, v]) => k.startsWith("_") ? k === "_key" || k === "_type" : isPrimitive(v)));
@@ -179,6 +190,6 @@ function coveringEntry(entries, path) {
179
190
  rest: path.slice(entry.path.length)
180
191
  } : null;
181
192
  }
182
- export { parsePath as a, retagInheritedList as c, isReplaceImageRequest as d, replaceImagePatch as f, materializeInheritedList as i, writeAt as l, inheritedEditScriptProps as n, readAt as o, inheritedListValue as r, retag as s, coveringEntry as t, REPLACE_IMAGE_MESSAGE as u };
193
+ export { parsePath as a, retagInheritedList as c, READ_DEFAULTS_RESULT as d, REPLACE_IMAGE_MESSAGE as f, replaceImagePatch as h, materializeInheritedList as i, writeAt as l, isReplaceImageRequest as m, inheritedEditScriptProps as n, readAt as o, isReadDefaultsRequest as p, inheritedListValue as r, retag as s, coveringEntry as t, READ_DEFAULTS_MESSAGE as u };
183
194
 
184
- //# sourceMappingURL=inherited-BveIuNhM.js.map
195
+ //# sourceMappingURL=inherited-BJxEcInY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inherited-BJxEcInY.js","names":[],"sources":["../src/web/edit/protocol.ts","../src/web/edit/inherited.ts"],"sourcesContent":["/**\n * Message « remplacer cette image » envoyé par l'aperçu (Presentation) au Studio.\n *\n * Partagé par le front (`NcfPreviewEditing`, couche des images) et le Studio\n * (pont monté par le plugin, qui ouvre la médiathèque). Module pur : ni React,\n * ni `sanity`, importable des deux côtés.\n */\nexport const REPLACE_IMAGE_MESSAGE = 'ncf-kit/replace-image'\n\nexport type ReplaceImageRequest = {\n type: typeof REPLACE_IMAGE_MESSAGE\n /** Document à modifier (sans préfixe `drafts.`). */\n documentId: string\n /** Type du document, quand le front le connaît ; sinon le Studio le lit. */\n documentType: string | null\n /** Chemin EXACT du champ image (`sections[_key==\"a\"].items[_key==\"b\"].image`). */\n path: string\n /**\n * Image DANS une valeur héritée des valeurs par défaut (liste...) que la page n'a pas\n * encore : le champ `path` de la page reçoit d'abord la valeur brute du champ\n * `sourcePath` du document `sourceId` (recopie, comme « Edit default items »).\n */\n inherited?: {path: string; sourceId: string; sourcePath: string} | null\n}\n\n/** Chemin de champ Sanity sûr : lettres, chiffres, clés entre guillemets, rien d'autre. */\nconst SAFE_PATH = /^[A-Za-z0-9_\\-.[\\]=\"]+$/\n\n/** Le message reçu est-il une demande de remplacement bien formée ? */\nexport function isReplaceImageRequest(data: unknown): data is ReplaceImageRequest {\n if (!data || typeof data !== 'object') return false\n const d = data as Record<string, unknown>\n return (\n d.type === REPLACE_IMAGE_MESSAGE &&\n typeof d.documentId === 'string' &&\n d.documentId.length > 0 &&\n typeof d.path === 'string' &&\n SAFE_PATH.test(d.path) &&\n (d.documentType === null || d.documentType === undefined || typeof d.documentType === 'string') &&\n (d.inherited === null || d.inherited === undefined || isInherited(d.inherited))\n )\n}\n\nfunction isInherited(v: unknown): v is NonNullable<ReplaceImageRequest['inherited']> {\n if (!v || typeof v !== 'object') return false\n const i = v as Record<string, unknown>\n return typeof i.path === 'string' && SAFE_PATH.test(i.path) && typeof i.sourcePath === 'string' && SAFE_PATH.test(i.sourcePath) && typeof i.sourceId === 'string' && /^[\\w.-]+$/.test(i.sourceId)\n}\n\n/**\n * Patch du remplacement : l'image choisie remplace celle du champ. Cadrage et\n * point focal sont retirés : calés sur l'ancienne photo, ils seraient faux.\n */\nexport function replaceImagePatch(path: string, assetId: string) {\n return [\n {setIfMissing: {[path]: {_type: 'image'}}},\n {set: {[`${path}.asset`]: {_type: 'reference', _ref: assetId}}},\n {unset: [`${path}.crop`, `${path}.hotspot`]},\n ]\n}\n\n/**\n * Lecture d'une valeur BRUTE des valeurs par défaut (recopie d'une liste héritée à la\n * première modification d'un texte) : l'aperçu la demande au Studio, qui la lit dans le\n * document (brouillon s'il existe) et répond à la seule fenêtre qui a demandé.\n */\nexport const READ_DEFAULTS_MESSAGE = 'ncf-kit/read-defaults'\nexport const READ_DEFAULTS_RESULT = 'ncf-kit/read-defaults-result'\n\nexport type ReadDefaultsRequest = {type: typeof READ_DEFAULTS_MESSAGE; requestId: string; id: string; path: string}\nexport type ReadDefaultsResult = {type: typeof READ_DEFAULTS_RESULT; requestId: string; value: unknown; found: boolean}\n\nexport function isReadDefaultsRequest(data: unknown): data is ReadDefaultsRequest {\n if (!data || typeof data !== 'object') return false\n const d = data as Record<string, unknown>\n return d.type === READ_DEFAULTS_MESSAGE && typeof d.requestId === 'string' && typeof d.id === 'string' && /^[\\w.-]+$/.test(d.id) && typeof d.path === 'string' && SAFE_PATH.test(d.path)\n}\n","import {vercelStegaClean, vercelStegaCombine, vercelStegaDecode} from '@vercel/stega'\nimport {createEditUrl} from '@sanity/client/csm'\n\n/**\n * ÉDITION DANS L'APERÇU, valeurs HÉRITÉES des valeurs par défaut du composant\n * (champ vide dans la page : le site affiche la valeur par défaut).\n *\n * `reattributeTo` fait déjà pointer chaque texte hérité vers le champ de\n * l'INSTANCE (et non vers le document des valeurs par défaut). Ici, deux cas que\n * Sanity ne sait pas éditer sur place :\n *\n * - **Texte hérité** (`value`) : l'éditeur doit partir de la valeur par défaut\n * EXACTE, jamais du texte affiché que le composant met en forme (guillemets\n * ajoutés, retours à la ligne rendus en espaces).\n * - **Liste héritée** (`items`) : liste SIMPLE (textes, nombres, cases) ou TEXTE\n * RICHE sans lien (titre en lignes, italique). La page n'a pas encore ses\n * éléments, Sanity n'y active aucun composant. Chaque texte vise sa ligne exacte\n * (`…titleLines[_key==\"k\"].text`, `…title[_key==\"b\"].children[_key==\"s\"].text`) ;\n * à l'enregistrement, la liste par défaut est RECOPIÉE dans la page avec la\n * ligne modifiée, en un seul patch du brouillon (comme « Edit default items »).\n * La valeur par défaut du composant ne change jamais.\n *\n * Une liste avec liens, images ou références reste gérée dans le panneau : la\n * recopier depuis l'aperçu risquerait d'abîmer les données.\n *\n * Ces entrées sont jointes à la page en mode brouillon seulement\n * (`<script type=\"application/json\" data-ncf-inherited-…>`, voir\n * `inheritedEditScriptProps`).\n */\nexport type InheritedEdit =\n | {path: string; items: Record<string, unknown>[]}\n | {path: string; value: string}\n /**\n * Valeur héritée de N'IMPORTE QUELLE forme (liste avec images, liens, texte riche,\n * objet) : sa source BRUTE est le champ du document des valeurs par défaut\n * (`source.id`, `source.path`), relu tel qu'enregistré au moment de la recopie (jamais\n * la version projetée par la requête du site, qui peut porter des champs vides ou\n * résolus). Même recopie que « Edit default items » du kit.\n */\n | {path: string; source: {id: string; path: string}}\n\ntype Source = {id: string; type: string}\n\nconst isPrimitive = (v: unknown) => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'\n\nfunction isSimpleList(value: unknown): value is Record<string, unknown>[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every(\n (item) =>\n item &&\n typeof item === 'object' &&\n !Array.isArray(item) &&\n typeof (item as {_key?: unknown})._key === 'string' &&\n (item as {_type?: unknown})._type !== 'block' &&\n Object.entries(item as Record<string, unknown>).every(([k, v]) => (k.startsWith('_') ? k === '_key' || k === '_type' : isPrimitive(v))),\n )\n )\n}\n\ntype Block = {_key: string; _type: 'block'; children: {_key: string; _type: 'span'; text: string}[]; markDefs?: unknown[]}\nfunction isPlainBlocks(value: unknown): value is Block[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every(\n (b) =>\n b?._type === 'block' &&\n typeof b._key === 'string' &&\n !b.markDefs?.length &&\n Array.isArray(b.children) &&\n b.children.every(\n (c: {_type?: unknown; _key?: unknown; text?: unknown}) => c?._type === 'span' && typeof c._key === 'string' && typeof c.text === 'string',\n ),\n )\n )\n}\n\n/** Réétiquette un texte (stega) vers un autre chemin du document de la page. */\nexport function retag(text: string, source: Source, path: string): string {\n const info = vercelStegaDecode(text) as {origin?: string; href?: string} | undefined\n if (!info?.href) return text\n const url = new URL(info.href, 'https://studio.invalid')\n const baseUrl = url.searchParams.get('baseUrl')\n if (!baseUrl) return text\n const href = createEditUrl({\n baseUrl,\n workspace: url.searchParams.get('workspace') ?? undefined,\n tool: url.searchParams.get('tool') ?? undefined,\n id: `drafts.${source.id.replace(/^drafts\\./, '')}`,\n type: source.type,\n path,\n })\n return vercelStegaCombine(vercelStegaClean(text), {origin: info.origin ?? 'sanity.io', href})\n}\n\n/**\n * Liste héritée (déjà réétiquetée par `reattributeTo`) : renvoie la liste avec\n * chaque texte pointé vers sa ligne et inscrit la liste par défaut (textes\n * nettoyés) dans `collected`. Toute autre valeur est rendue telle quelle.\n */\nexport function retagInheritedList(value: unknown, listPath: string, source: Source, collected: InheritedEdit[]): unknown {\n if (isPlainBlocks(value)) {\n collected.push({path: listPath, items: vercelStegaClean(value) as Record<string, unknown>[]})\n return value.map((b) => ({\n ...b,\n children: b.children.map((c) => ({...c, text: retag(c.text, source, `${listPath}[_key==\"${b._key}\"].children[_key==\"${c._key}\"].text`)})),\n }))\n }\n if (!isSimpleList(value)) return value\n collected.push({\n path: listPath,\n items: value.map((item) => Object.fromEntries(Object.entries(item).map(([k, v]) => [k, typeof v === 'string' ? vercelStegaClean(v) : v]))),\n })\n return value.map((item) =>\n Object.fromEntries(\n Object.entries(item).map(([k, v]) => [k, typeof v === 'string' && !k.startsWith('_') ? retag(v, source, `${listPath}[_key==\"${item._key as string}\"].${k}`) : v]),\n ),\n )\n}\n\n/** Attributs du `<script>` qui joint une entrée héritée à la page (mode brouillon). */\nexport function inheritedEditScriptProps(entry: InheritedEdit) {\n return {\n type: 'application/json',\n ...('items' in entry ? {'data-ncf-inherited-list': entry.path} : 'source' in entry ? {'data-ncf-inherited-source': entry.path} : {'data-ncf-inherited-value': entry.path}),\n dangerouslySetInnerHTML: {__html: JSON.stringify('items' in entry ? entry.items : 'source' in entry ? entry.source : entry.value).replace(/</g, '\\\\u003c')},\n }\n}\n\n/* ------------------------------------------------------------------------- */\n/* Côté éditeur : lecture et recopie (pur, testé) */\n/* ------------------------------------------------------------------------- */\n\ntype Step = {key: string} | {field: string}\n\n/** Étapes d'un chemin RELATIF à la liste : `[_key==\"b\"].children[_key==\"s\"].text`. */\nfunction steps(listPath: string, path: string): Step[] | null {\n if (!path.startsWith(`${listPath}[`)) return null\n const rest = path.slice(listPath.length)\n const out: Step[] = []\n let consumed = 0\n for (const m of rest.matchAll(/\\[_key==\"([^\"]+)\"\\]|\\.(\\w+)/g)) {\n if (m.index !== consumed) return null\n consumed += m[0].length\n out.push(m[1] ? {key: m[1]} : {field: m[2] as string})\n }\n return consumed === rest.length && out.length > 0 && 'key' in out[0]! ? out : null\n}\n\n/** Texte exact d'une ligne de liste héritée, ou null. */\nexport function inheritedListValue(list: {path: string; items: Record<string, unknown>[]}, path: string): string | null {\n const s = steps(list.path, path)\n if (!s) return null\n let value: unknown = list.items\n for (const step of s) {\n if ('key' in step) value = Array.isArray(value) ? value.find((v) => v?._key === step.key) : undefined\n else value = value && typeof value === 'object' ? (value as Record<string, unknown>)[step.field] : undefined\n }\n return typeof value === 'string' ? value : null\n}\n\n/** Liste par défaut recopiée avec la ligne `path` remplacée par `next`, ou null. */\nexport function materializeInheritedList(list: {path: string; items: Record<string, unknown>[]}, path: string, next: string): Record<string, unknown>[] | null {\n const s = steps(list.path, path)\n if (!s) return null\n const write = (value: unknown, i: number): unknown => {\n if (i === s.length) return next\n const step = s[i]!\n if ('key' in step) {\n if (!Array.isArray(value) || !value.some((v) => v?._key === step.key)) throw new Error('absent')\n return value.map((v) => (v?._key === step.key ? write(v, i + 1) : v))\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('absent')\n const obj = value as Record<string, unknown>\n return {...obj, [step.field]: write(obj[step.field], i + 1)}\n }\n try {\n return write(list.items, 0) as Record<string, unknown>[]\n } catch {\n return null\n }\n}\n\n/* ------------------------------------------------------------------------- */\n/* Chemins Sanity : lecture et écriture dans une valeur brute (pur, testé) */\n/* ------------------------------------------------------------------------- */\n\nexport type PathStep = {key: string} | {index: number} | {field: string}\n\n/** `sections[_key==\"a\"].items[2].title` → étapes ; null si le chemin est illisible. */\nexport function parsePath(path: string): PathStep[] | null {\n const out: PathStep[] = []\n let consumed = 0\n for (const m of path.matchAll(/\\[_key==\"([^\"]+)\"\\]|\\[(\\d+)\\]|\\.?([A-Za-z_][\\w-]*)/g)) {\n if (m.index !== consumed) return null\n consumed += m[0].length\n out.push(m[1] !== undefined ? {key: m[1]} : m[2] !== undefined ? {index: Number(m[2])} : {field: m[3] as string})\n }\n return consumed === path.length && out.length ? out : null\n}\n\n/** Valeur au chemin (étapes), ou undefined. */\nexport function readAt(root: unknown, steps: PathStep[]): unknown {\n let value = root\n for (const step of steps) {\n if ('key' in step) value = Array.isArray(value) ? value.find((v) => v?._key === step.key) : undefined\n else if ('index' in step) value = Array.isArray(value) ? value[step.index] : undefined\n else value = value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>)[step.field] : undefined\n if (value === undefined) return undefined\n }\n return value\n}\n\n/** Copie de `root` avec `next` écrit au chemin ; null si un élément du chemin manque. */\nexport function writeAt(root: unknown, steps: PathStep[], next: unknown): unknown {\n const write = (value: unknown, i: number): unknown => {\n if (i === steps.length) return next\n const step = steps[i]!\n if ('key' in step || 'index' in step) {\n if (!Array.isArray(value)) throw new Error('absent')\n const at = 'key' in step ? value.findIndex((v) => v?._key === step.key) : step.index\n if (at < 0 || at >= value.length) throw new Error('absent')\n return value.map((v, j) => (j === at ? write(v, i + 1) : v))\n }\n if (value !== undefined && (typeof value !== 'object' || value === null || Array.isArray(value))) throw new Error('absent')\n if (value === undefined && i < steps.length - 1 && !('field' in steps[i + 1]!)) throw new Error('absent')\n const obj = (value ?? {}) as Record<string, unknown>\n return {...obj, [step.field]: write(obj[step.field], i + 1)}\n }\n try {\n return write(root, 0)\n } catch {\n return null\n }\n}\n\n/**\n * Entrée héritée qui couvre `path` (le chemin d'un texte ou d'une image dans la page) :\n * son chemin est un préfixe exact (suivi de `[` ou `.`). Renvoie aussi le reste du chemin.\n */\nexport function coveringEntry<T extends {path: string}>(entries: T[], path: string): {entry: T; rest: string} | null {\n const entry = entries.filter((e) => path.startsWith(`${e.path}[`) || path.startsWith(`${e.path}.`)).sort((a, b) => b.path.length - a.path.length)[0]\n return entry ? {entry, rest: path.slice(entry.path.length)} : null\n}\n"],"mappings":";;;;;;;;;AAOA,MAAa,wBAAwB,yBAmB/B,YAAY;;AAGlB,SAAgB,sBAAsB,MAA4C;CAChF,IAAI,CAAC,QAAQ,OAAO,QAAS,UAAU,OAAO;CAC9C,IAAM,IAAI;CACV,OACE,EAAE,SAAA,2BACF,OAAO,EAAE,cAAe,YACxB,EAAE,WAAW,SAAS,KACtB,OAAO,EAAE,QAAS,YAClB,UAAU,KAAK,EAAE,IAAI,MACpB,EAAE,iBAAiB,QAAQ,EAAE,iBAAiB,KAAA,KAAa,OAAO,EAAE,gBAAiB,cACrF,EAAE,cAAc,QAAQ,EAAE,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A,MAAc,OAAO,SAAU,aAAY,SAAkB,MAAM,QAAQ,KAAK,MAC1F,UAAU,KAAA,KAAa,IAAI,MAAM,SAAS,KAAK,EAAE,WAAW,MAAM,IAAI,KAAM,MAAU,MAAM,QAAQ;EACxG,IAAM,MAAO,SAAS,CAAC;EACvB,OAAO;GAAC,GAAG;IAAM,KAAK,QAAQ,MAAM,IAAI,KAAK,QAAQ,IAAI,CAAC;EAAC;CAC7D;CACA,IAAI;EACF,OAAO,MAAM,MAAM,CAAC;CACtB,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,SAAgB,cAAwC,SAAc,MAA+C;CACnH,IAAM,QAAQ,QAAQ,QAAQ,MAAM,KAAK,WAAW,GAAG,EAAE,KAAK,EAAE,KAAK,KAAK,WAAW,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,KAAK,SAAS,EAAE,KAAK,MAAM,CAAC,CAAC;CAClJ,OAAO,QAAQ;EAAC;EAAO,MAAM,KAAK,MAAM,MAAM,KAAK,MAAM;CAAC,IAAI;AAChE"}
package/dist/web-edit.js CHANGED
@@ -1,4 +1,4 @@
1
- import { c as retagInheritedList, d as isReplaceImageRequest, f as replaceImagePatch, i as materializeInheritedList, n as inheritedEditScriptProps, r as inheritedListValue, s as retag, u as REPLACE_IMAGE_MESSAGE } from "./inherited-BveIuNhM.js";
1
+ import { c as retagInheritedList, f as REPLACE_IMAGE_MESSAGE, h as replaceImagePatch, i as materializeInheritedList, m as isReplaceImageRequest, n as inheritedEditScriptProps, r as inheritedListValue, s as retag } from "./inherited-BJxEcInY.js";
2
2
  import { vercelStegaClean, vercelStegaDecode } from "@vercel/stega";
3
3
  import { resolveEditInfo, studioPath } from "@sanity/client/csm";
4
4
  import { createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
@@ -18,6 +18,8 @@ type PreviewEditingLabels = {
18
18
  editMode: string;
19
19
  browseMode: string;
20
20
  modeLabel: string;
21
+ /** Indication sous un texte à plusieurs lignes : Maj + Entrée = retour à la ligne. */
22
+ newLine: string;
21
23
  /** Contrôle automatique : « {n} à vérifier » (éléments non modifiables sur place). */
22
24
  auditIssues: string;
23
25
  auditHelp: string;
@@ -1,5 +1,5 @@
1
1
  'use client'
2
- import { a as parsePath, i as materializeInheritedList, l as writeAt, o as readAt, r as inheritedListValue, t as coveringEntry, u as REPLACE_IMAGE_MESSAGE } from "./inherited-BveIuNhM.js";
2
+ import { a as parsePath, f as REPLACE_IMAGE_MESSAGE, i as materializeInheritedList, l as writeAt, o as readAt, r as inheritedListValue, t as coveringEntry, u as READ_DEFAULTS_MESSAGE } from "./inherited-BJxEcInY.js";
3
3
  import { useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
  import { VERCEL_STEGA_REGEX, vercelStegaClean, vercelStegaDecode } from "@vercel/stega";
@@ -17,6 +17,7 @@ const DEFAULT_PREVIEW_EDITING_LABELS = {
17
17
  editMode: "Edit mode",
18
18
  browseMode: "Browse mode",
19
19
  modeLabel: "Preview mode: edit or browse",
20
+ newLine: "New line",
20
21
  auditIssues: "{n} to check",
21
22
  auditHelp: "Elements of this page that cannot be edited in place (click to outline them in red)"
22
23
  }, 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)";
@@ -87,7 +88,7 @@ function inheritedPaths() {
87
88
  function auditEditability(root = document.body) {
88
89
  let issues = [];
89
90
  for (let img of root.querySelectorAll("img")) {
90
- if (!sanityImageUrl(img) || img.closest("[data-edit-image]") || img.closest("[data-sanity-overlay-element]")) continue;
91
+ if (!sanityImageUrl(img) || img.closest("[data-edit-image], [data-edit-skip], [data-sanity-overlay-element]")) continue;
91
92
  let box = img.getBoundingClientRect();
92
93
  box.width < 24 || box.height < 24 || issues.push({
93
94
  element: img,
@@ -96,7 +97,7 @@ function auditEditability(root = document.body) {
96
97
  }
97
98
  let lists = inheritedPaths();
98
99
  if (lists.size) {
99
- let walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
100
+ let walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { acceptNode: (n) => n.parentElement?.closest("script, style, noscript, template, [data-sanity-overlay-element]") ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT });
100
101
  for (let n = walker.nextNode(); n; n = walker.nextNode()) {
101
102
  let text = n.textContent ?? "";
102
103
  if (!VERCEL_STEGA_REGEX.test(text)) continue;
@@ -178,7 +179,7 @@ function EditAudit({ labels }) {
178
179
  }), labels.auditIssues.replace("{n}", String(issues.length))]
179
180
  }) : null;
180
181
  }
181
- function studioOrigin() {
182
+ function studioOrigin$1() {
182
183
  let ancestor = window.location.ancestorOrigins?.[0];
183
184
  if (ancestor) return ancestor;
184
185
  try {
@@ -241,7 +242,7 @@ function ImageReplaceLayer({ label }) {
241
242
  event.relatedTarget || setTarget(null);
242
243
  }, onClick = (event) => {
243
244
  if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || !isEditMode()) return;
244
- let el = imageAt(event.clientX, event.clientY), origin = studioOrigin();
245
+ let el = imageAt(event.clientX, event.clientY), origin = studioOrigin$1();
245
246
  el && origin && (event.preventDefault(), setTarget(null), window.parent.postMessage({
246
247
  type: REPLACE_IMAGE_MESSAGE,
247
248
  documentId: el.getAttribute("data-edit-doc"),
@@ -330,8 +331,8 @@ function InlineTextEditor({ labels }) {
330
331
  return useEffect(() => {
331
332
  let onClick = (event) => {
332
333
  if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || !isEditMode()) return;
333
- let direct = inlineEdit.getHovered() ?? inheritedListTarget(event.target), hovered = (direct && paragraphGroup(direct)) ?? direct ?? paragraphGroupAt(event.target);
334
- hovered && event.target instanceof Node && hovered.element.contains(event.target) && inlineEdit.getEditing()?.element !== hovered.element && (event.preventDefault(), inlineEdit.open(hovered));
334
+ let direct = inlineEdit.getHovered() ?? inheritedListTarget(event.target), clicked = event.target instanceof Node ? event.target : null, own = direct && clicked && direct.element.contains(clicked) ? direct : null, hovered = (own && paragraphGroup(own)) ?? own ?? paragraphGroupAt(event.target), area = hovered?.parts ?? (hovered ? [hovered.element] : []);
335
+ hovered && clicked && area.some((el) => el.contains(clicked)) && inlineEdit.getEditing()?.element !== hovered.element && (event.preventDefault(), inlineEdit.open(hovered));
335
336
  };
336
337
  return window.addEventListener("click", onClick, { capture: !0 }), () => window.removeEventListener("click", onClick, { capture: !0 });
337
338
  }, []), target ? createPortal(/* @__PURE__ */ jsx(EditorSession, {
@@ -340,6 +341,11 @@ function InlineTextEditor({ labels }) {
340
341
  }, `${target.node.id}:${target.node.path}`), document.body) : null;
341
342
  }
342
343
  const BLOCK = "p, li, blockquote, h1, h2, h3, h4, h5, h6";
344
+ /** L'élément (ou le premier qui porte du texte) affiche-t-il les retours à la ligne ? */
345
+ function keepsLineBreaks(element) {
346
+ let host = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, { acceptNode: (n) => n.textContent?.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP }).nextNode()?.parentElement ?? element;
347
+ return /^(pre|pre-wrap|pre-line|break-spaces)$/.test(getComputedStyle(host).whiteSpace) || /^(pre|pre-wrap|pre-line|break-spaces)$/.test(getComputedStyle(element).whiteSpace);
348
+ }
343
349
  /** Un seul texte marqué (stega) dans l'élément ? Renvoie son nœud Sanity. */
344
350
  function singleStegaNode(el) {
345
351
  let text = el.textContent ?? "";
@@ -354,27 +360,35 @@ function singleStegaNode(el) {
354
360
  };
355
361
  }
356
362
  /**
357
- * Bloc de paragraphes d'un même champ : le parent direct qui contient au moins deux
358
- * blocs (p, li...) et UN SEUL texte marqué (celui du champ, à la fin du dernier bloc).
363
+ * Bloc de paragraphes d'un même champ : les paragraphes CONSÉCUTIFS de même balise autour
364
+ * de celui-ci (un bouton ou un titre voisin ne compte pas), avec UN SEUL texte marqué,
365
+ * dans le dernier (les marqueurs sont à la fin du texte du champ).
359
366
  */
360
367
  function groupOf(block) {
361
368
  let parent = block.parentElement;
362
369
  if (!parent || parent === document.body) return null;
363
- let blocks = Array.from(parent.children).filter((c) => c.matches(BLOCK));
364
- if (blocks.length < 2 || !blocks.includes(block) || blocks.some((b) => b.tagName !== block.tagName)) return null;
365
- let last = blocks[blocks.length - 1];
366
- if (stegaRuns(last.textContent ?? "") !== 1) return null;
367
- let node = singleStegaNode(parent), expect = vercelStegaClean(block.textContent ?? "").replace(/\s+/g, " ").trim();
368
- return node && parent instanceof HTMLElement ? {
369
- element: parent,
370
+ let siblings = Array.from(parent.children), at = siblings.indexOf(block), first = at, last = at;
371
+ for (; first > 0 && siblings[first - 1].tagName === block.tagName;) first--;
372
+ for (; last < siblings.length - 1 && siblings[last + 1].tagName === block.tagName;) last++;
373
+ let run = siblings.slice(first, last + 1);
374
+ if (run.length < 2) return null;
375
+ let withStega = run.filter((b) => stegaRuns(b.textContent ?? "") > 0), end = run[run.length - 1];
376
+ if (withStega.length !== 1 || withStega[0] !== end || stegaRuns(end.textContent ?? "") !== 1) return null;
377
+ let node = singleStegaNode(end);
378
+ return node ? {
379
+ element: end,
370
380
  node,
371
- expect
381
+ expect: vercelStegaClean(block.textContent ?? "").replace(/\s+/g, " ").trim(),
382
+ parts: run
372
383
  } : null;
373
384
  }
374
385
  /** Cible déjà trouvée (dernier paragraphe) : élargie au bloc entier quand c'en est un. */
375
386
  function paragraphGroup(target) {
376
387
  let block = target.element.matches(BLOCK) ? target.element : target.element.closest(BLOCK), group = block ? groupOf(block) : null;
377
- return group && group.node.path === target.node.path ? group : null;
388
+ return group && group.node.path === target.node.path ? {
389
+ ...group,
390
+ expect: void 0
391
+ } : null;
378
392
  }
379
393
  /** Clic sur un paragraphe SANS marqueur (pas le dernier) : le bloc dont il fait partie. */
380
394
  function paragraphGroupAt(target) {
@@ -395,6 +409,40 @@ function inheritedListFor(path) {
395
409
  }
396
410
  return null;
397
411
  }
412
+ /** Origine du Studio qui affiche l'aperçu. */
413
+ function studioOrigin() {
414
+ let ancestor = window.location.ancestorOrigins?.[0];
415
+ if (ancestor) return ancestor;
416
+ try {
417
+ return document.referrer ? new URL(document.referrer).origin : null;
418
+ } catch {
419
+ return null;
420
+ }
421
+ }
422
+ /**
423
+ * Valeur BRUTE d'un champ des valeurs par défaut, lue par le Studio (le document des
424
+ * valeurs par défaut n'est pas un document de la page : l'aperçu ne peut pas le lire
425
+ * lui-même). undefined si le Studio ne répond pas (4 s) ou ne trouve rien.
426
+ */
427
+ function readDefaults(id, path) {
428
+ let origin = studioOrigin();
429
+ if (!origin || window.parent === window) return Promise.resolve(void 0);
430
+ let requestId = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
431
+ return new Promise((done) => {
432
+ let timer = window.setTimeout(() => finish(void 0), 4e3), onMessage = (event) => {
433
+ let d = event.data;
434
+ event.origin === origin && event.source === window.parent && d?.type === "ncf-kit/read-defaults-result" && d.requestId === requestId && finish(d.found ? d.value : void 0);
435
+ }, finish = (value) => {
436
+ window.clearTimeout(timer), window.removeEventListener("message", onMessage), done(value);
437
+ };
438
+ window.addEventListener("message", onMessage), window.parent.postMessage({
439
+ type: READ_DEFAULTS_MESSAGE,
440
+ requestId,
441
+ id,
442
+ path
443
+ }, origin);
444
+ });
445
+ }
398
446
  /** Valeur héritée de toute forme : entrée qui couvre ce chemin (source brute des valeurs par défaut). */
399
447
  function inheritedSourceFor(path) {
400
448
  let entries = [];
@@ -490,19 +538,22 @@ const sameBox = (a, b) => !!a && a.top === b.top && a.left === b.left && a.width
490
538
  opacity: .7
491
539
  };
492
540
  function EditorSession({ target, labels }) {
493
- 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(""), rawInherited = useRef(null), multiline = useRef(!1), rootRef = useRef(null), fieldRef = useRef(null);
541
+ let { element, node } = target, { getDocument } = useDocuments(), [status, setStatus] = useState("loading"), [value, setValue] = useState(""), [inherited, setInherited] = useState(!1), [box, setBox] = useState(null), parts = target.parts?.length ? target.parts : [element], [typo] = useState(() => textStyle(parts[0])), initial = useRef(""), inheritedStart = useRef(""), rawInherited = useRef(null), multiline = useRef(!1), [breaks, setBreaks] = useState(!1), rootRef = useRef(null), fieldRef = useRef(null);
494
542
  useEffect(() => {
495
- let previous = element.style.visibility;
496
- return element.style.visibility = "hidden", () => {
497
- element.style.visibility = previous;
543
+ let previous = parts.map((el) => el.style.visibility);
544
+ for (let el of parts) el.style.visibility = "hidden";
545
+ return () => {
546
+ parts.forEach((el, i) => {
547
+ el.style.visibility = previous[i] ?? "";
548
+ });
498
549
  };
499
550
  }, [element]), useEffect(() => {
500
551
  let frame = 0, tick = () => {
501
- let r = element.getBoundingClientRect(), next = {
502
- top: r.top,
503
- left: r.left,
504
- width: r.width,
505
- height: r.height
552
+ let rects = parts.map((el) => el.getBoundingClientRect()), top = Math.min(...rects.map((r) => r.top)), left = Math.min(...rects.map((r) => r.left)), right = Math.max(...rects.map((r) => r.right)), bottom = Math.max(...rects.map((r) => r.bottom)), next = {
553
+ top,
554
+ left,
555
+ width: right - left,
556
+ height: bottom - top
506
557
  };
507
558
  setBox((prev) => sameBox(prev, next) ? prev : next), frame = requestAnimationFrame(tick);
508
559
  };
@@ -513,7 +564,7 @@ function EditorSession({ target, labels }) {
513
564
  if (cancelled) return;
514
565
  let stored = doc ? getAtPath(parse(node.path), doc) : void 0, list = inheritedListFor(node.path), covering = typeof stored == "string" && stored !== "" ? null : inheritedSourceFor(node.path), fromSource = null;
515
566
  if (covering) {
516
- let own = doc ? readAt(doc, parsePath(covering.entry.path) ?? []) : void 0, defaults = own === void 0 || Array.isArray(own) && own.length === 0 ? await getDocument(covering.entry.source.id).getSnapshot().catch(() => null) : null, raw = defaults ? readAt(defaults, parsePath(covering.entry.source.path) ?? []) : void 0;
567
+ let own = doc ? readAt(doc, parsePath(covering.entry.path) ?? []) : void 0, raw = own === void 0 || Array.isArray(own) && own.length === 0 ? await readDefaults(covering.entry.source.id, covering.entry.source.path).catch(() => void 0) : void 0;
517
568
  if (raw !== void 0) {
518
569
  rawInherited.current = {
519
570
  path: covering.entry.path,
@@ -525,13 +576,13 @@ function EditorSession({ target, labels }) {
525
576
  }
526
577
  }
527
578
  if (cancelled) return;
528
- let resolved = typeof stored == "string" && stored !== "" ? stored : fromSource ?? inheritedValueFor(node.path) ?? (list ? inheritedListValue(list, node.path) : null) ?? vercelStegaClean(element.textContent ?? "").trim();
579
+ let resolved = typeof stored == "string" && stored !== "" ? stored : fromSource ?? inheritedValueFor(node.path) ?? (list ? inheritedListValue(list, node.path) : null) ?? vercelStegaClean(parts.map((el) => el.textContent ?? "").join("\n\n")).trim();
529
580
  if (target.expect && !resolved.replace(/\s+/g, " ").includes(target.expect)) {
530
581
  inlineEdit.close();
531
582
  return;
532
583
  }
533
584
  let text = resolved;
534
- initial.current = typeof stored == "string" ? stored : "", inheritedStart.current = text, multiline.current = text.includes("\n"), setInherited(typeof stored != "string" || stored === ""), setValue(text), setStatus("editing");
585
+ initial.current = typeof stored == "string" ? stored : "", inheritedStart.current = text, multiline.current = text.includes("\n") || !!target.expect || keepsLineBreaks(element), setBreaks(multiline.current), setInherited(typeof stored != "string" || stored === ""), setValue(text), setStatus("editing");
535
586
  }).catch(() => {
536
587
  cancelled || inlineEdit.close();
537
588
  }), () => {
@@ -574,11 +625,23 @@ function EditorSession({ target, labels }) {
574
625
  return;
575
626
  }
576
627
  let doc = getDocument(node.id), copy = inherited && rawInherited.current ? writeAt(rawInherited.current.raw, parsePath(rawInherited.current.rest) ?? [], next) : null;
628
+ if (copy !== null && JSON.stringify(copy) === JSON.stringify(rawInherited.current?.raw)) {
629
+ inlineEdit.close();
630
+ return;
631
+ }
577
632
  if (copy !== null && rawInherited.current) {
578
633
  doc.patch([at(rawInherited.current.path, set(copy))]), setStatus("saving");
579
634
  return;
580
635
  }
581
636
  let list = inherited ? inheritedListFor(node.path) : null, items = list ? materializeInheritedList(list, node.path, next) : null;
637
+ if (inherited && !items && inheritedSourceFor(node.path)) {
638
+ inlineEdit.close();
639
+ return;
640
+ }
641
+ if (list && items && JSON.stringify(items) === JSON.stringify(list.items)) {
642
+ inlineEdit.close();
643
+ return;
644
+ }
582
645
  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");
583
646
  }, [
584
647
  value,
@@ -590,7 +653,7 @@ function EditorSession({ target, labels }) {
590
653
  useEffect(() => {
591
654
  if (status !== "saving") return;
592
655
  let expected = value.replace(/\s+/g, " ").trim(), started = performance.now(), timer = window.setInterval(() => {
593
- (vercelStegaClean(element.textContent ?? "").replace(/\s+/g, " ").trim().includes(expected) || expected === "" || performance.now() - started > 6e3) && inlineEdit.close();
656
+ (vercelStegaClean(parts.map((el) => el.textContent ?? "").join(" ")).replace(/\s+/g, " ").trim().includes(expected) || expected === "" || performance.now() - started > 6e3) && inlineEdit.close();
594
657
  }, 150);
595
658
  return () => window.clearInterval(timer);
596
659
  }, [
@@ -662,32 +725,48 @@ function EditorSession({ target, labels }) {
662
725
  children: status === "saving" ? /* @__PURE__ */ jsx("span", {
663
726
  style: { padding: "6px 10px" },
664
727
  children: labels.saved
665
- }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("button", {
666
- type: "button",
667
- onClick: save,
668
- disabled: status !== "editing",
669
- style: {
670
- ...BUTTON_STYLE,
671
- background: ACCENT,
672
- color: "#fff"
673
- },
674
- children: [labels.save, /* @__PURE__ */ jsx("kbd", {
675
- style: KBD_STYLE,
676
- children: "↵"
677
- })]
678
- }), /* @__PURE__ */ jsxs("button", {
679
- type: "button",
680
- onClick: () => inlineEdit.close(),
681
- style: {
682
- ...BUTTON_STYLE,
683
- background: "transparent",
684
- color: "rgba(255,255,255,0.85)"
685
- },
686
- children: [labels.cancel, /* @__PURE__ */ jsx("kbd", {
687
- style: KBD_STYLE,
688
- children: "Esc"
689
- })]
690
- })] })
728
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [
729
+ /* @__PURE__ */ jsxs("button", {
730
+ type: "button",
731
+ onClick: save,
732
+ disabled: status !== "editing",
733
+ style: {
734
+ ...BUTTON_STYLE,
735
+ background: ACCENT,
736
+ color: "#fff"
737
+ },
738
+ children: [labels.save, /* @__PURE__ */ jsx("kbd", {
739
+ style: KBD_STYLE,
740
+ children: "↵"
741
+ })]
742
+ }),
743
+ breaks && /* @__PURE__ */ jsxs("span", {
744
+ style: {
745
+ display: "flex",
746
+ alignItems: "center",
747
+ gap: 6,
748
+ padding: "7px 8px",
749
+ color: "rgba(255,255,255,0.7)"
750
+ },
751
+ children: [labels.newLine, /* @__PURE__ */ jsx("kbd", {
752
+ style: KBD_STYLE,
753
+ children: "⇧ ↵"
754
+ })]
755
+ }),
756
+ /* @__PURE__ */ jsxs("button", {
757
+ type: "button",
758
+ onClick: () => inlineEdit.close(),
759
+ style: {
760
+ ...BUTTON_STYLE,
761
+ background: "transparent",
762
+ color: "rgba(255,255,255,0.85)"
763
+ },
764
+ children: [labels.cancel, /* @__PURE__ */ jsx("kbd", {
765
+ style: KBD_STYLE,
766
+ children: "Esc"
767
+ })]
768
+ })
769
+ ] })
691
770
  }),
692
771
  inherited && status === "editing" && /* @__PURE__ */ jsx("p", {
693
772
  style: {