@nocode-factory/sanity-kit 2.61.0 → 2.61.1-rc.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.
@@ -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)";
@@ -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"),
@@ -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 ?? "";
@@ -395,6 +401,40 @@ function inheritedListFor(path) {
395
401
  }
396
402
  return null;
397
403
  }
404
+ /** Origine du Studio qui affiche l'aperçu. */
405
+ function studioOrigin() {
406
+ let ancestor = window.location.ancestorOrigins?.[0];
407
+ if (ancestor) return ancestor;
408
+ try {
409
+ return document.referrer ? new URL(document.referrer).origin : null;
410
+ } catch {
411
+ return null;
412
+ }
413
+ }
414
+ /**
415
+ * Valeur BRUTE d'un champ des valeurs par défaut, lue par le Studio (le document des
416
+ * valeurs par défaut n'est pas un document de la page : l'aperçu ne peut pas le lire
417
+ * lui-même). undefined si le Studio ne répond pas (4 s) ou ne trouve rien.
418
+ */
419
+ function readDefaults(id, path) {
420
+ let origin = studioOrigin();
421
+ if (!origin || window.parent === window) return Promise.resolve(void 0);
422
+ let requestId = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
423
+ return new Promise((done) => {
424
+ let timer = window.setTimeout(() => finish(void 0), 4e3), onMessage = (event) => {
425
+ let d = event.data;
426
+ event.origin === origin && event.source === window.parent && d?.type === "ncf-kit/read-defaults-result" && d.requestId === requestId && finish(d.found ? d.value : void 0);
427
+ }, finish = (value) => {
428
+ window.clearTimeout(timer), window.removeEventListener("message", onMessage), done(value);
429
+ };
430
+ window.addEventListener("message", onMessage), window.parent.postMessage({
431
+ type: READ_DEFAULTS_MESSAGE,
432
+ requestId,
433
+ id,
434
+ path
435
+ }, origin);
436
+ });
437
+ }
398
438
  /** Valeur héritée de toute forme : entrée qui couvre ce chemin (source brute des valeurs par défaut). */
399
439
  function inheritedSourceFor(path) {
400
440
  let entries = [];
@@ -490,7 +530,7 @@ const sameBox = (a, b) => !!a && a.top === b.top && a.left === b.left && a.width
490
530
  opacity: .7
491
531
  };
492
532
  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);
533
+ 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), [breaks, setBreaks] = useState(!1), rootRef = useRef(null), fieldRef = useRef(null);
494
534
  useEffect(() => {
495
535
  let previous = element.style.visibility;
496
536
  return element.style.visibility = "hidden", () => {
@@ -513,7 +553,7 @@ function EditorSession({ target, labels }) {
513
553
  if (cancelled) return;
514
554
  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
555
  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;
556
+ 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
557
  if (raw !== void 0) {
518
558
  rawInherited.current = {
519
559
  path: covering.entry.path,
@@ -531,7 +571,7 @@ function EditorSession({ target, labels }) {
531
571
  return;
532
572
  }
533
573
  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");
574
+ 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
575
  }).catch(() => {
536
576
  cancelled || inlineEdit.close();
537
577
  }), () => {
@@ -579,6 +619,10 @@ function EditorSession({ target, labels }) {
579
619
  return;
580
620
  }
581
621
  let list = inherited ? inheritedListFor(node.path) : null, items = list ? materializeInheritedList(list, node.path, next) : null;
622
+ if (inherited && !items && inheritedSourceFor(node.path)) {
623
+ inlineEdit.close();
624
+ return;
625
+ }
582
626
  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
627
  }, [
584
628
  value,
@@ -662,32 +706,48 @@ function EditorSession({ target, labels }) {
662
706
  children: status === "saving" ? /* @__PURE__ */ jsx("span", {
663
707
  style: { padding: "6px 10px" },
664
708
  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
- })] })
709
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [
710
+ /* @__PURE__ */ jsxs("button", {
711
+ type: "button",
712
+ onClick: save,
713
+ disabled: status !== "editing",
714
+ style: {
715
+ ...BUTTON_STYLE,
716
+ background: ACCENT,
717
+ color: "#fff"
718
+ },
719
+ children: [labels.save, /* @__PURE__ */ jsx("kbd", {
720
+ style: KBD_STYLE,
721
+ children: "↵"
722
+ })]
723
+ }),
724
+ breaks && /* @__PURE__ */ jsxs("span", {
725
+ style: {
726
+ display: "flex",
727
+ alignItems: "center",
728
+ gap: 6,
729
+ padding: "7px 8px",
730
+ color: "rgba(255,255,255,0.7)"
731
+ },
732
+ children: [labels.newLine, /* @__PURE__ */ jsx("kbd", {
733
+ style: KBD_STYLE,
734
+ children: "⇧ ↵"
735
+ })]
736
+ }),
737
+ /* @__PURE__ */ jsxs("button", {
738
+ type: "button",
739
+ onClick: () => inlineEdit.close(),
740
+ style: {
741
+ ...BUTTON_STYLE,
742
+ background: "transparent",
743
+ color: "rgba(255,255,255,0.85)"
744
+ },
745
+ children: [labels.cancel, /* @__PURE__ */ jsx("kbd", {
746
+ style: KBD_STYLE,
747
+ children: "Esc"
748
+ })]
749
+ })
750
+ ] })
691
751
  }),
692
752
  inherited && status === "editing" && /* @__PURE__ */ jsx("p", {
693
753
  style: {