@nocode-factory/sanity-kit 2.54.0 → 2.58.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 (38) hide show
  1. package/README.md +61 -6
  2. package/bin/item-types.mjs +131 -0
  3. package/bin/ncf-kit.mjs +97 -0
  4. package/dist/index.d.ts +48 -4
  5. package/dist/index.js +7222 -6916
  6. package/dist/index.js.map +1 -1
  7. package/dist/inherited-DZvM35P6.js +101 -0
  8. package/dist/inherited-DZvM35P6.js.map +1 -0
  9. package/dist/protocol-Bl7Yj2Ro.js +31 -0
  10. package/dist/protocol-Bl7Yj2Ro.js.map +1 -0
  11. package/dist/web-edit.d.ts +192 -0
  12. package/dist/web-edit.js +144 -0
  13. package/dist/web-edit.js.map +1 -0
  14. package/dist/web-editing.d.ts +51 -0
  15. package/dist/web-editing.js +693 -0
  16. package/dist/web-editing.js.map +1 -0
  17. package/package.json +22 -2
  18. package/scripts/use-client.mjs +1 -1
  19. package/src/form/AssetSourceBrowser.tsx +68 -39
  20. package/src/hooks/useCollection.ts +19 -3
  21. package/src/index.ts +3 -2
  22. package/src/lib/collectionQuery.ts +10 -2
  23. package/src/structure/collections.tsx +35 -5
  24. package/src/tools/collections/CollectionTable.tsx +295 -89
  25. package/src/tools/collections/CollectionToolbar.tsx +53 -4
  26. package/src/ui/PreviewEditBridge.tsx +74 -0
  27. package/src/version.ts +1 -1
  28. package/src/web/edit/ImageReplaceLayer.tsx +174 -0
  29. package/src/web/edit/InlineTextEditor.tsx +365 -0
  30. package/src/web/edit/InlineTextOverlay.tsx +43 -0
  31. package/src/web/edit/PreviewEditing.tsx +191 -0
  32. package/src/web/edit/index.ts +18 -0
  33. package/src/web/edit/inherited.ts +174 -0
  34. package/src/web/edit/labels.ts +37 -0
  35. package/src/web/edit/protocol.ts +47 -0
  36. package/src/web/edit/store.ts +98 -0
  37. package/src/web/edit/targets.ts +186 -0
  38. package/src/web/editing.ts +18 -0
@@ -0,0 +1,101 @@
1
+ import { createEditUrl } from "@sanity/client/csm";
2
+ import { vercelStegaClean, vercelStegaCombine, vercelStegaDecode } from "@vercel/stega";
3
+ const isPrimitive = (v) => typeof v == "string" || typeof v == "number" || typeof v == "boolean";
4
+ function isSimpleList(value) {
5
+ 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)));
6
+ }
7
+ function isPlainBlocks(value) {
8
+ return Array.isArray(value) && value.length > 0 && value.every((b) => b?._type === "block" && typeof b._key == "string" && !b.markDefs?.length && Array.isArray(b.children) && b.children.every((c) => c?._type === "span" && typeof c._key == "string" && typeof c.text == "string"));
9
+ }
10
+ /** Réétiquette un texte (stega) vers un autre chemin du document de la page. */
11
+ function retag(text, source, path) {
12
+ let info = vercelStegaDecode(text);
13
+ if (!info?.href) return text;
14
+ let url = new URL(info.href, "https://studio.invalid"), baseUrl = url.searchParams.get("baseUrl");
15
+ if (!baseUrl) return text;
16
+ let href = createEditUrl({
17
+ baseUrl,
18
+ workspace: url.searchParams.get("workspace") ?? void 0,
19
+ tool: url.searchParams.get("tool") ?? void 0,
20
+ id: `drafts.${source.id.replace(/^drafts\./, "")}`,
21
+ type: source.type,
22
+ path
23
+ });
24
+ return vercelStegaCombine(vercelStegaClean(text), {
25
+ origin: info.origin ?? "sanity.io",
26
+ href
27
+ });
28
+ }
29
+ /**
30
+ * Liste héritée (déjà réétiquetée par `reattributeTo`) : renvoie la liste avec
31
+ * chaque texte pointé vers sa ligne et inscrit la liste par défaut (textes
32
+ * nettoyés) dans `collected`. Toute autre valeur est rendue telle quelle.
33
+ */
34
+ function retagInheritedList(value, listPath, source, collected) {
35
+ return isPlainBlocks(value) ? (collected.push({
36
+ path: listPath,
37
+ items: vercelStegaClean(value)
38
+ }), value.map((b) => ({
39
+ ...b,
40
+ children: b.children.map((c) => ({
41
+ ...c,
42
+ text: retag(c.text, source, `${listPath}[_key=="${b._key}"].children[_key=="${c._key}"].text`)
43
+ }))
44
+ }))) : isSimpleList(value) ? (collected.push({
45
+ path: listPath,
46
+ items: value.map((item) => Object.fromEntries(Object.entries(item).map(([k, v]) => [k, typeof v == "string" ? vercelStegaClean(v) : v])))
47
+ }), value.map((item) => Object.fromEntries(Object.entries(item).map(([k, v]) => [k, typeof v == "string" && !k.startsWith("_") ? retag(v, source, `${listPath}[_key=="${item._key}"].${k}`) : v])))) : value;
48
+ }
49
+ /** Attributs du `<script>` qui joint une entrée héritée à la page (mode brouillon). */
50
+ function inheritedEditScriptProps(entry) {
51
+ return {
52
+ type: "application/json",
53
+ ..."items" in entry ? { "data-ncf-inherited-list": entry.path } : { "data-ncf-inherited-value": entry.path },
54
+ dangerouslySetInnerHTML: { __html: JSON.stringify("items" in entry ? entry.items : entry.value).replace(/</g, "\\u003c") }
55
+ };
56
+ }
57
+ /** Étapes d'un chemin RELATIF à la liste : `[_key=="b"].children[_key=="s"].text`. */
58
+ function steps(listPath, path) {
59
+ if (!path.startsWith(`${listPath}[`)) return null;
60
+ let rest = path.slice(listPath.length), out = [], consumed = 0;
61
+ for (let m of rest.matchAll(/\[_key=="([^"]+)"\]|\.(\w+)/g)) {
62
+ if (m.index !== consumed) return null;
63
+ consumed += m[0].length, out.push(m[1] ? { key: m[1] } : { field: m[2] });
64
+ }
65
+ return consumed === rest.length && out.length > 0 && "key" in out[0] ? out : null;
66
+ }
67
+ /** Texte exact d'une ligne de liste héritée, ou null. */
68
+ function inheritedListValue(list, path) {
69
+ let s = steps(list.path, path);
70
+ if (!s) return null;
71
+ let value = list.items;
72
+ for (let step of s) value = "key" in step ? Array.isArray(value) ? value.find((v) => v?._key === step.key) : void 0 : value && typeof value == "object" ? value[step.field] : void 0;
73
+ return typeof value == "string" ? value : null;
74
+ }
75
+ /** Liste par défaut recopiée avec la ligne `path` remplacée par `next`, ou null. */
76
+ function materializeInheritedList(list, path, next) {
77
+ let s = steps(list.path, path);
78
+ if (!s) return null;
79
+ let write = (value, i) => {
80
+ if (i === s.length) return next;
81
+ let step = s[i];
82
+ if ("key" in step) {
83
+ if (!Array.isArray(value) || !value.some((v) => v?._key === step.key)) throw Error("absent");
84
+ return value.map((v) => v?._key === step.key ? write(v, i + 1) : v);
85
+ }
86
+ if (!value || typeof value != "object" || Array.isArray(value)) throw Error("absent");
87
+ let obj = value;
88
+ return {
89
+ ...obj,
90
+ [step.field]: write(obj[step.field], i + 1)
91
+ };
92
+ };
93
+ try {
94
+ return write(list.items, 0);
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+ export { retagInheritedList as i, inheritedListValue as n, materializeInheritedList as r, inheritedEditScriptProps as t };
100
+
101
+ //# sourceMappingURL=inherited-DZvM35P6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inherited-DZvM35P6.js","names":[],"sources":["../src/web/edit/inherited.ts"],"sourcesContent":["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 = {path: string; items: Record<string, unknown>[]} | {path: string; value: 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. */\nfunction 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} : {'data-ncf-inherited-value': entry.path}),\n dangerouslySetInnerHTML: {__html: JSON.stringify('items' in entry ? entry.items : 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"],"mappings":";;AAiCA,MAAM,eAAe,MAAe,OAAO,KAAM,YAAY,OAAO,KAAM,YAAY,OAAO,KAAM;AAEnG,SAAS,aAAa,OAAoD;CACxE,OACE,MAAM,QAAQ,KAAK,KACnB,MAAM,SAAS,KACf,MAAM,OACH,SACC,QACA,OAAO,QAAS,YAChB,CAAC,MAAM,QAAQ,IAAI,KACnB,OAAQ,KAA0B,QAAS,YAC1C,KAA2B,UAAU,WACtC,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3
+ *
4
+ * Partagé par le front (`NcfPreviewEditing`, couche des images) et le Studio
5
+ * (pont monté par le plugin, qui ouvre la médiathèque). Module pur : ni React,
6
+ * ni `sanity`, importable des deux côtés.
7
+ */
8
+ const REPLACE_IMAGE_MESSAGE = "ncf-kit/replace-image", SAFE_PATH = /^[A-Za-z0-9_\-.[\]="]+$/;
9
+ /** Le message reçu est-il une demande de remplacement bien formée ? */
10
+ function isReplaceImageRequest(data) {
11
+ if (!data || typeof data != "object") return !1;
12
+ let d = data;
13
+ return d.type === "ncf-kit/replace-image" && typeof d.documentId == "string" && d.documentId.length > 0 && typeof d.path == "string" && SAFE_PATH.test(d.path) && (d.documentType === null || d.documentType === void 0 || typeof d.documentType == "string");
14
+ }
15
+ /**
16
+ * Patch du remplacement : l'image choisie remplace celle du champ. Cadrage et
17
+ * point focal sont retirés : calés sur l'ancienne photo, ils seraient faux.
18
+ */
19
+ function replaceImagePatch(path, assetId) {
20
+ return [
21
+ { setIfMissing: { [path]: { _type: "image" } } },
22
+ { set: { [`${path}.asset`]: {
23
+ _type: "reference",
24
+ _ref: assetId
25
+ } } },
26
+ { unset: [`${path}.crop`, `${path}.hotspot`] }
27
+ ];
28
+ }
29
+ export { isReplaceImageRequest as n, replaceImagePatch as r, REPLACE_IMAGE_MESSAGE as t };
30
+
31
+ //# sourceMappingURL=protocol-Bl7Yj2Ro.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol-Bl7Yj2Ro.js","names":[],"sources":["../src/web/edit/protocol.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\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 )\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"],"mappings":";;;;;;;AAOA,MAAa,wBAAwB,yBAa/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;AAE1F;;;;;AAMA,SAAgB,kBAAkB,MAAc,SAAiB;CAC/D,OAAO;EACL,EAAC,cAAc,GAAE,OAAO,EAAC,OAAO,QAAO,EAAC,EAAC;EACzC,EAAC,KAAK,GAAE,GAAG,KAAK,UAAU;GAAC,OAAO;GAAa,MAAM;EAAO,EAAC,EAAC;EAC9D,EAAC,OAAO,CAAC,GAAG,KAAK,QAAQ,GAAG,KAAK,SAAS,EAAC;CAC7C;AACF"}
@@ -0,0 +1,192 @@
1
+ import { ContentSourceMap } from "@sanity/client/csm";
2
+ /**
3
+ * ÉDITION DANS L'APERÇU, valeurs HÉRITÉES des valeurs par défaut du composant
4
+ * (champ vide dans la page : le site affiche la valeur par défaut).
5
+ *
6
+ * `reattributeTo` fait déjà pointer chaque texte hérité vers le champ de
7
+ * l'INSTANCE (et non vers le document des valeurs par défaut). Ici, deux cas que
8
+ * Sanity ne sait pas éditer sur place :
9
+ *
10
+ * - **Texte hérité** (`value`) : l'éditeur doit partir de la valeur par défaut
11
+ * EXACTE, jamais du texte affiché que le composant met en forme (guillemets
12
+ * ajoutés, retours à la ligne rendus en espaces).
13
+ * - **Liste héritée** (`items`) : liste SIMPLE (textes, nombres, cases) ou TEXTE
14
+ * RICHE sans lien (titre en lignes, italique). La page n'a pas encore ses
15
+ * éléments, Sanity n'y active aucun composant. Chaque texte vise sa ligne exacte
16
+ * (`…titleLines[_key=="k"].text`, `…title[_key=="b"].children[_key=="s"].text`) ;
17
+ * à l'enregistrement, la liste par défaut est RECOPIÉE dans la page avec la
18
+ * ligne modifiée, en un seul patch du brouillon (comme « Edit default items »).
19
+ * La valeur par défaut du composant ne change jamais.
20
+ *
21
+ * Une liste avec liens, images ou références reste gérée dans le panneau : la
22
+ * recopier depuis l'aperçu risquerait d'abîmer les données.
23
+ *
24
+ * Ces entrées sont jointes à la page en mode brouillon seulement
25
+ * (`<script type="application/json" data-ncf-inherited-…>`, voir
26
+ * `inheritedEditScriptProps`).
27
+ */
28
+ type InheritedEdit = {
29
+ path: string;
30
+ items: Record<string, unknown>[];
31
+ } | {
32
+ path: string;
33
+ value: string;
34
+ };
35
+ type Source$1 = {
36
+ id: string;
37
+ type: string;
38
+ };
39
+ /**
40
+ * Liste héritée (déjà réétiquetée par `reattributeTo`) : renvoie la liste avec
41
+ * chaque texte pointé vers sa ligne et inscrit la liste par défaut (textes
42
+ * nettoyés) dans `collected`. Toute autre valeur est rendue telle quelle.
43
+ */
44
+ export declare function retagInheritedList(value: unknown, listPath: string, source: Source$1, collected: InheritedEdit[]): unknown;
45
+ /** Attributs du `<script>` qui joint une entrée héritée à la page (mode brouillon). */
46
+ export declare function inheritedEditScriptProps(entry: InheritedEdit): {
47
+ dangerouslySetInnerHTML: {
48
+ __html: string;
49
+ };
50
+ 'data-ncf-inherited-list': string;
51
+ type: string;
52
+ } | {
53
+ dangerouslySetInnerHTML: {
54
+ __html: string;
55
+ };
56
+ 'data-ncf-inherited-value': string;
57
+ type: string;
58
+ };
59
+ /** Texte exact d'une ligne de liste héritée, ou null. */
60
+ export declare function inheritedListValue(list: {
61
+ path: string;
62
+ items: Record<string, unknown>[];
63
+ }, path: string): string | null;
64
+ /** Liste par défaut recopiée avec la ligne `path` remplacée par `next`, ou null. */
65
+ export declare function materializeInheritedList(list: {
66
+ path: string;
67
+ items: Record<string, unknown>[];
68
+ }, path: string, next: string): Record<string, unknown>[] | null;
69
+ /**
70
+ * ÉDITION DANS L'APERÇU, IMAGES (mode brouillon seulement) : chaque image est
71
+ * cliquable dans Presentation, alt rempli ou non, et porte son document et son
72
+ * chemin EXACTS pour la pastille « Replace this image » (`NcfPreviewEditing`).
73
+ *
74
+ * Sanity ne repère d'ordinaire une image que par son alt (texte encodé en stega) :
75
+ * une image sans alt n'avait aucun overlay. Ici, la carte des sources (Content
76
+ * Source Map, renvoyée par `sanityFetch` en brouillon) donne pour chaque image son
77
+ * document et son champ ; on les attache à la valeur (`_editTarget`, `_editPath`,
78
+ * `_editDoc`, `_editType`), que le composant pose avec `imageEditAttributes`.
79
+ *
80
+ * Câblage d'un projet (starter) :
81
+ * - `annotateImageEditTargets(data, sourceMap, {studioUrl})` sur le résultat de
82
+ * `sanityFetch` en brouillon ;
83
+ * - `withPreviewEditTargets(reattributeTo(source, key), source, key, collected, {studioUrl})`
84
+ * comme rappel d'héritage de `applyDefaults` ;
85
+ * - `rekeyOwnImageTargets(section, source, key, {studioUrl})` sur chaque section ;
86
+ * - `imageEditAttributes(image)` / `imageAlt(image)` sur chaque image affichée.
87
+ */
88
+ type ImageEditValue = {
89
+ asset?: {
90
+ _ref?: string;
91
+ };
92
+ alt?: string;
93
+ _editTarget?: string;
94
+ _editPath?: string;
95
+ _editDoc?: string;
96
+ _editType?: string;
97
+ } | null | undefined;
98
+ type ImageEditOptions = {
99
+ /** Adresse du Studio (celle de `stega.studioUrl`). */
100
+ studioUrl: string;
101
+ /** Type du document des valeurs par défaut des composants (jamais marqué). */
102
+ defaultsType?: string;
103
+ };
104
+ /**
105
+ * Marque chaque image du résultat d'une requête en brouillon. Une image venue du
106
+ * document des valeurs par défaut n'est pas marquée ici (un clic modifierait
107
+ * l'image de TOUTES les pages) : `withPreviewEditTargets` la fait viser l'instance.
108
+ */
109
+ export declare function annotateImageEditTargets<T>(data: T, sourceMap: ContentSourceMap | null | undefined, options: ImageEditOptions): T;
110
+ type OnInherit = (value: unknown, path: string[]) => unknown;
111
+ type Source = {
112
+ id: string;
113
+ type: string;
114
+ path: string;
115
+ single?: boolean;
116
+ };
117
+ /**
118
+ * Rappel d'héritage pour `applyDefaults` (en aperçu), autour de `reattributeTo` :
119
+ * - image héritée : vise le champ image de L'INSTANCE (choisir une image crée une
120
+ * image propre à la page, la valeur par défaut ne change pas) ;
121
+ * - texte hérité : sa valeur par défaut exacte est jointe (`collected`) ;
122
+ * - liste simple ou texte riche hérité : modifiable ligne à ligne (voir `inherited.ts`).
123
+ * `collected` est à rendre par la section avec `inheritedEditScriptProps`.
124
+ */
125
+ export declare function withPreviewEditTargets(onInherit: OnInherit, source: Source, key: string | undefined, collected: InheritedEdit[], options: ImageEditOptions): OnInherit;
126
+ /**
127
+ * Chemin EXACT des images qui appartiennent à la page, recalculé avec les clés
128
+ * `_key` de la section. La carte des sources donne parfois un rang au lieu de la
129
+ * clé (`images:0`) : Sanity ne retrouve alors pas le champ. Une image d'un AUTRE
130
+ * document (carte liée, témoignage...) garde son repère.
131
+ */
132
+ export declare function rekeyOwnImageTargets<T>(section: T, source: Source, key: string | undefined, options: ImageEditOptions): T;
133
+ type ImageEditAttributes = {
134
+ 'data-sanity'?: string;
135
+ 'data-edit-image'?: string;
136
+ 'data-edit-doc'?: string;
137
+ 'data-edit-type'?: string;
138
+ };
139
+ /** Attributs à poser sur le cadre d'une image marquée ; vide pour les visiteurs. */
140
+ export declare function imageEditAttributes(image: ImageEditValue): ImageEditAttributes;
141
+ /**
142
+ * Alt d'une image marquée : nettoyé de ses marqueurs (sinon Sanity la prendrait
143
+ * pour un texte et le clic ouvrirait l'alt au lieu de l'image).
144
+ */
145
+ export declare function imageAlt(image: ImageEditValue, alt?: string): string;
146
+ /**
147
+ * Message « remplacer cette image » envoyé par l'aperçu (Presentation) au Studio.
148
+ *
149
+ * Partagé par le front (`NcfPreviewEditing`, couche des images) et le Studio
150
+ * (pont monté par le plugin, qui ouvre la médiathèque). Module pur : ni React,
151
+ * ni `sanity`, importable des deux côtés.
152
+ */
153
+ export declare const REPLACE_IMAGE_MESSAGE = "ncf-kit/replace-image";
154
+ type ReplaceImageRequest = {
155
+ type: typeof REPLACE_IMAGE_MESSAGE;
156
+ /** Document à modifier (sans préfixe `drafts.`). */
157
+ documentId: string;
158
+ /** Type du document, quand le front le connaît ; sinon le Studio le lit. */
159
+ documentType: string | null;
160
+ /** Chemin EXACT du champ image (`sections[_key=="a"].items[_key=="b"].image`). */
161
+ path: string;
162
+ };
163
+ /** Le message reçu est-il une demande de remplacement bien formée ? */
164
+ export declare function isReplaceImageRequest(data: unknown): data is ReplaceImageRequest;
165
+ /**
166
+ * Patch du remplacement : l'image choisie remplace celle du champ. Cadrage et
167
+ * point focal sont retirés : calés sur l'ancienne photo, ils seraient faux.
168
+ */
169
+ export declare function replaceImagePatch(path: string, assetId: string): ({
170
+ setIfMissing: {
171
+ [path]: {
172
+ _type: string;
173
+ };
174
+ };
175
+ set?: undefined;
176
+ unset?: undefined;
177
+ } | {
178
+ set: {
179
+ [x: string]: {
180
+ _type: string;
181
+ _ref: string;
182
+ };
183
+ };
184
+ setIfMissing?: undefined;
185
+ unset?: undefined;
186
+ } | {
187
+ unset: string[];
188
+ setIfMissing?: undefined;
189
+ set?: undefined;
190
+ })[];
191
+ export type { ImageEditAttributes, ImageEditOptions, ImageEditValue, InheritedEdit, ReplaceImageRequest };
192
+ //# sourceMappingURL=web-edit.d.ts.map
@@ -0,0 +1,144 @@
1
+ import { n as isReplaceImageRequest, r as replaceImagePatch, t as REPLACE_IMAGE_MESSAGE } from "./protocol-Bl7Yj2Ro.js";
2
+ import { i as retagInheritedList, n as inheritedListValue, r as materializeInheritedList, t as inheritedEditScriptProps } from "./inherited-DZvM35P6.js";
3
+ import { resolveEditInfo, studioPath } from "@sanity/client/csm";
4
+ import { vercelStegaClean } from "@vercel/stega";
5
+ import { createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
6
+ function isImageValue(value) {
7
+ if (!value || typeof value != "object" || Array.isArray(value)) return !1;
8
+ let ref = value.asset?._ref;
9
+ return typeof ref == "string" && ref.startsWith("image-");
10
+ }
11
+ /**
12
+ * Pose le repère Sanity et le chemin exact. Image élément de liste
13
+ * (`…images[_key=="i3"]`) : Sanity n'active pas un repère placé dans un élément de
14
+ * liste d'images ; le repère vise la liste, le chemin exact reste dans `_editPath`.
15
+ */
16
+ function mark(value, id, type, path, extra) {
17
+ let inList = /\[[^\]]+\]$/.test(path);
18
+ value._editTarget = createDataAttribute({
19
+ ...extra,
20
+ id,
21
+ type,
22
+ path: inList ? path.replace(/\[[^\]]+\]$/, "") : path
23
+ }).toString(), value._editPath = path, value._editDoc = id.replace(/^drafts\./, ""), value._editType = type;
24
+ }
25
+ /**
26
+ * Marque chaque image du résultat d'une requête en brouillon. Une image venue du
27
+ * document des valeurs par défaut n'est pas marquée ici (un clic modifierait
28
+ * l'image de TOUTES les pages) : `withPreviewEditTargets` la fait viser l'instance.
29
+ */
30
+ function annotateImageEditTargets(data, sourceMap, options) {
31
+ if (!sourceMap) return data;
32
+ let defaultsType = options.defaultsType ?? "componentDefaults", fromSourceMap = (value, path) => {
33
+ let info = resolveEditInfo({
34
+ studioUrl: options.studioUrl,
35
+ resultSourceMap: sourceMap,
36
+ resultPath: [
37
+ ...path,
38
+ "asset",
39
+ "_ref"
40
+ ]
41
+ });
42
+ if (!info || info.type === defaultsType) return;
43
+ let full = typeof info.path == "string" ? info.path : studioPath.toString(info.path), imagePath = full.replace(/\.asset\._ref$/, "");
44
+ imagePath && imagePath !== full && mark(value, info.id, info.type, imagePath, {
45
+ baseUrl: info.baseUrl,
46
+ workspace: info.workspace,
47
+ tool: info.tool,
48
+ projectId: info.projectId,
49
+ dataset: info.dataset
50
+ });
51
+ }, visit = (value, path) => {
52
+ if (Array.isArray(value)) {
53
+ value.forEach((item, index) => {
54
+ let key = item && typeof item == "object" && typeof item._key == "string" ? item._key : null, segment = key ? {
55
+ _key: key,
56
+ _index: index
57
+ } : index;
58
+ visit(item, [...path, segment]);
59
+ });
60
+ return;
61
+ }
62
+ if (value && typeof value == "object") {
63
+ isImageValue(value) && !value._editTarget && fromSourceMap(value, path);
64
+ for (let [key, child] of Object.entries(value)) key.startsWith("_edit") || visit(child, [...path, key]);
65
+ }
66
+ };
67
+ return visit(data, []), data;
68
+ }
69
+ const sectionBase = (source, key) => key && !source.single ? `${source.path}[_key=="${key}"]` : source.path;
70
+ /**
71
+ * Rappel d'héritage pour `applyDefaults` (en aperçu), autour de `reattributeTo` :
72
+ * - image héritée : vise le champ image de L'INSTANCE (choisir une image crée une
73
+ * image propre à la page, la valeur par défaut ne change pas) ;
74
+ * - texte hérité : sa valeur par défaut exacte est jointe (`collected`) ;
75
+ * - liste simple ou texte riche hérité : modifiable ligne à ligne (voir `inherited.ts`).
76
+ * `collected` est à rendre par la section avec `inheritedEditScriptProps`.
77
+ */
78
+ function withPreviewEditTargets(onInherit, source, key, collected, options) {
79
+ let base = sectionBase(source, key), pageId = source.id.replace(/^drafts\./, ""), markInherited = (value, path) => {
80
+ if (!Array.isArray(value) && value && typeof value == "object") {
81
+ if (isImageValue(value)) {
82
+ mark(value, pageId, source.type, path, { baseUrl: options.studioUrl });
83
+ return;
84
+ }
85
+ for (let [k, child] of Object.entries(value)) k.startsWith("_") || markInherited(child, `${path}.${k}`);
86
+ }
87
+ };
88
+ return (value, path) => {
89
+ let out = onInherit(value, path);
90
+ if (out && typeof out == "object" && !Array.isArray(out)) {
91
+ let copy = isImageValue(out) ? { ...out } : out;
92
+ return markInherited(copy, `${base}.${path.join(".")}`), copy;
93
+ }
94
+ return typeof out == "string" && collected.push({
95
+ path: `${base}.${path.join(".")}`,
96
+ value: vercelStegaClean(out)
97
+ }), Array.isArray(out) && path.length === 1 ? retagInheritedList(out, `${base}.${path[0]}`, source, collected) : out;
98
+ };
99
+ }
100
+ /**
101
+ * Chemin EXACT des images qui appartiennent à la page, recalculé avec les clés
102
+ * `_key` de la section. La carte des sources donne parfois un rang au lieu de la
103
+ * clé (`images:0`) : Sanity ne retrouve alors pas le champ. Une image d'un AUTRE
104
+ * document (carte liée, témoignage...) garde son repère.
105
+ */
106
+ function rekeyOwnImageTargets(section, source, key, options) {
107
+ let pageId = source.id.replace(/^drafts\./, ""), visit = (value, path) => {
108
+ if (Array.isArray(value)) {
109
+ value.forEach((item, index) => {
110
+ let k = item && typeof item == "object" ? item._key : void 0;
111
+ visit(item, typeof k == "string" ? `${path}[_key=="${k}"]` : `${path}[${index}]`);
112
+ });
113
+ return;
114
+ }
115
+ if (value && typeof value == "object") {
116
+ if (isImageValue(value) && value._editDoc) {
117
+ value._editDoc === pageId && mark(value, pageId, source.type, path, { baseUrl: options.studioUrl });
118
+ return;
119
+ }
120
+ for (let [k, child] of Object.entries(value)) k.startsWith("_") || visit(child, `${path}.${k}`);
121
+ }
122
+ };
123
+ return visit(section, sectionBase(source, key)), section;
124
+ }
125
+ /** Attributs à poser sur le cadre d'une image marquée ; vide pour les visiteurs. */
126
+ function imageEditAttributes(image) {
127
+ return !image?._editTarget || !image._editPath || !image._editDoc || !image._editType ? {} : {
128
+ "data-sanity": image._editTarget,
129
+ "data-edit-image": image._editPath,
130
+ "data-edit-doc": image._editDoc,
131
+ "data-edit-type": image._editType
132
+ };
133
+ }
134
+ /**
135
+ * Alt d'une image marquée : nettoyé de ses marqueurs (sinon Sanity la prendrait
136
+ * pour un texte et le clic ouvrirait l'alt au lieu de l'image).
137
+ */
138
+ function imageAlt(image, alt) {
139
+ let value = alt ?? image?.alt ?? "";
140
+ return image?._editTarget ? vercelStegaClean(value) : value;
141
+ }
142
+ export { REPLACE_IMAGE_MESSAGE, annotateImageEditTargets, imageAlt, imageEditAttributes, inheritedEditScriptProps, inheritedListValue, isReplaceImageRequest, materializeInheritedList, rekeyOwnImageTargets, replaceImagePatch, retagInheritedList, withPreviewEditTargets };
143
+
144
+ //# sourceMappingURL=web-edit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-edit.js","names":[],"sources":["../src/web/edit/targets.ts"],"sourcesContent":["import {createDataAttribute} from '@sanity/visual-editing/create-data-attribute'\nimport {resolveEditInfo, studioPath, type ContentSourceMap, type ContentSourceMapParsedPath} from '@sanity/client/csm'\nimport {vercelStegaClean} from '@vercel/stega'\nimport {retagInheritedList, type InheritedEdit} from './inherited'\n\n/**\n * ÉDITION DANS L'APERÇU, IMAGES (mode brouillon seulement) : chaque image est\n * cliquable dans Presentation, alt rempli ou non, et porte son document et son\n * chemin EXACTS pour la pastille « Replace this image » (`NcfPreviewEditing`).\n *\n * Sanity ne repère d'ordinaire une image que par son alt (texte encodé en stega) :\n * une image sans alt n'avait aucun overlay. Ici, la carte des sources (Content\n * Source Map, renvoyée par `sanityFetch` en brouillon) donne pour chaque image son\n * document et son champ ; on les attache à la valeur (`_editTarget`, `_editPath`,\n * `_editDoc`, `_editType`), que le composant pose avec `imageEditAttributes`.\n *\n * Câblage d'un projet (starter) :\n * - `annotateImageEditTargets(data, sourceMap, {studioUrl})` sur le résultat de\n * `sanityFetch` en brouillon ;\n * - `withPreviewEditTargets(reattributeTo(source, key), source, key, collected, {studioUrl})`\n * comme rappel d'héritage de `applyDefaults` ;\n * - `rekeyOwnImageTargets(section, source, key, {studioUrl})` sur chaque section ;\n * - `imageEditAttributes(image)` / `imageAlt(image)` sur chaque image affichée.\n */\n\nexport type ImageEditValue = {\n asset?: {_ref?: string}\n alt?: string\n _editTarget?: string\n _editPath?: string\n _editDoc?: string\n _editType?: string\n} | null | undefined\n\ntype Marked = {asset: {_ref: string}; _editTarget?: string; _editPath?: string; _editDoc?: string; _editType?: string}\ntype Segment = ContentSourceMapParsedPath[number]\n\nfunction isImageValue(value: unknown): value is Marked {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const ref = (value as {asset?: {_ref?: unknown}}).asset?._ref\n return typeof ref === 'string' && ref.startsWith('image-')\n}\n\n/**\n * Pose le repère Sanity et le chemin exact. Image élément de liste\n * (`…images[_key==\"i3\"]`) : Sanity n'active pas un repère placé dans un élément de\n * liste d'images ; le repère vise la liste, le chemin exact reste dans `_editPath`.\n */\nfunction mark(value: Marked, id: string, type: string, path: string, extra: Record<string, string | undefined> & {baseUrl: string}) {\n const inList = /\\[[^\\]]+\\]$/.test(path)\n value._editTarget = createDataAttribute({...extra, id, type, path: inList ? path.replace(/\\[[^\\]]+\\]$/, '') : path}).toString()\n value._editPath = path\n value._editDoc = id.replace(/^drafts\\./, '')\n value._editType = type\n}\n\nexport type ImageEditOptions = {\n /** Adresse du Studio (celle de `stega.studioUrl`). */\n studioUrl: string\n /** Type du document des valeurs par défaut des composants (jamais marqué). */\n defaultsType?: string\n}\n\n/**\n * Marque chaque image du résultat d'une requête en brouillon. Une image venue du\n * document des valeurs par défaut n'est pas marquée ici (un clic modifierait\n * l'image de TOUTES les pages) : `withPreviewEditTargets` la fait viser l'instance.\n */\nexport function annotateImageEditTargets<T>(data: T, sourceMap: ContentSourceMap | null | undefined, options: ImageEditOptions): T {\n if (!sourceMap) return data\n const defaultsType = options.defaultsType ?? 'componentDefaults'\n const fromSourceMap = (value: Marked, path: ContentSourceMapParsedPath) => {\n const info = resolveEditInfo({studioUrl: options.studioUrl, resultSourceMap: sourceMap, resultPath: [...path, 'asset', '_ref']})\n if (!info || info.type === defaultsType) return\n const full = typeof info.path === 'string' ? info.path : studioPath.toString(info.path as never)\n const imagePath = full.replace(/\\.asset\\._ref$/, '')\n if (!imagePath || imagePath === full) return\n mark(value, info.id, info.type, imagePath, {\n baseUrl: info.baseUrl,\n workspace: info.workspace,\n tool: info.tool,\n projectId: info.projectId,\n dataset: info.dataset,\n })\n }\n const visit = (value: unknown, path: ContentSourceMapParsedPath) => {\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n const key = item && typeof item === 'object' && typeof (item as {_key?: unknown})._key === 'string' ? (item as {_key: string})._key : null\n const segment: Segment = key ? {_key: key, _index: index} : index\n visit(item, [...path, segment])\n })\n return\n }\n if (!value || typeof value !== 'object') return\n if (isImageValue(value) && !value._editTarget) fromSourceMap(value, path)\n for (const [key, child] of Object.entries(value)) {\n if (key.startsWith('_edit')) continue\n visit(child, [...path, key])\n }\n }\n visit(data, [])\n return data\n}\n\ntype OnInherit = (value: unknown, path: string[]) => unknown\ntype Source = {id: string; type: string; path: string; single?: boolean}\n\nconst sectionBase = (source: Source, key: string | undefined) => (key && !source.single ? `${source.path}[_key==\"${key}\"]` : source.path)\n\n/**\n * Rappel d'héritage pour `applyDefaults` (en aperçu), autour de `reattributeTo` :\n * - image héritée : vise le champ image de L'INSTANCE (choisir une image crée une\n * image propre à la page, la valeur par défaut ne change pas) ;\n * - texte hérité : sa valeur par défaut exacte est jointe (`collected`) ;\n * - liste simple ou texte riche hérité : modifiable ligne à ligne (voir `inherited.ts`).\n * `collected` est à rendre par la section avec `inheritedEditScriptProps`.\n */\nexport function withPreviewEditTargets(onInherit: OnInherit, source: Source, key: string | undefined, collected: InheritedEdit[], options: ImageEditOptions): OnInherit {\n const base = sectionBase(source, key)\n const pageId = source.id.replace(/^drafts\\./, '')\n const markInherited = (value: unknown, path: string) => {\n if (Array.isArray(value) || !value || typeof value !== 'object') return\n if (isImageValue(value)) {\n mark(value, pageId, source.type, path, {baseUrl: options.studioUrl})\n return\n }\n for (const [k, child] of Object.entries(value)) if (!k.startsWith('_')) markInherited(child, `${path}.${k}`)\n }\n return (value, path) => {\n const out = onInherit(value, path)\n if (out && typeof out === 'object' && !Array.isArray(out)) {\n const copy = isImageValue(out) ? {...out} : out\n markInherited(copy, `${base}.${path.join('.')}`)\n return copy\n }\n if (typeof out === 'string') collected.push({path: `${base}.${path.join('.')}`, value: vercelStegaClean(out)})\n // Liste héritée directement par un champ de la section (le parent existe dans la page).\n if (Array.isArray(out) && path.length === 1) return retagInheritedList(out, `${base}.${path[0]}`, source, collected)\n return out\n }\n}\n\n/**\n * Chemin EXACT des images qui appartiennent à la page, recalculé avec les clés\n * `_key` de la section. La carte des sources donne parfois un rang au lieu de la\n * clé (`images:0`) : Sanity ne retrouve alors pas le champ. Une image d'un AUTRE\n * document (carte liée, témoignage...) garde son repère.\n */\nexport function rekeyOwnImageTargets<T>(section: T, source: Source, key: string | undefined, options: ImageEditOptions): T {\n const pageId = source.id.replace(/^drafts\\./, '')\n const visit = (value: unknown, path: string) => {\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n const k = item && typeof item === 'object' ? (item as {_key?: unknown})._key : undefined\n visit(item, typeof k === 'string' ? `${path}[_key==\"${k}\"]` : `${path}[${index}]`)\n })\n return\n }\n if (!value || typeof value !== 'object') return\n if (isImageValue(value) && value._editDoc) {\n if (value._editDoc === pageId) mark(value, pageId, source.type, path, {baseUrl: options.studioUrl})\n return\n }\n for (const [k, child] of Object.entries(value)) if (!k.startsWith('_')) visit(child, `${path}.${k}`)\n }\n visit(section, sectionBase(source, key))\n return section\n}\n\nexport type ImageEditAttributes = {'data-sanity'?: string; 'data-edit-image'?: string; 'data-edit-doc'?: string; 'data-edit-type'?: string}\n\n/** Attributs à poser sur le cadre d'une image marquée ; vide pour les visiteurs. */\nexport function imageEditAttributes(image: ImageEditValue): ImageEditAttributes {\n if (!image?._editTarget || !image._editPath || !image._editDoc || !image._editType) return {}\n return {'data-sanity': image._editTarget, 'data-edit-image': image._editPath, 'data-edit-doc': image._editDoc, 'data-edit-type': image._editType}\n}\n\n/**\n * Alt d'une image marquée : nettoyé de ses marqueurs (sinon Sanity la prendrait\n * pour un texte et le clic ouvrirait l'alt au lieu de l'image).\n */\nexport function imageAlt(image: ImageEditValue, alt?: string): string {\n const value = alt ?? image?.alt ?? ''\n return image?._editTarget ? vercelStegaClean(value) : value\n}\n"],"mappings":";;;;;AAqCA,SAAS,aAAa,OAAiC;CACrD,IAAI,CAAC,SAAS,OAAO,SAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO;CACxE,IAAM,MAAO,MAAqC,OAAO;CACzD,OAAO,OAAO,OAAQ,YAAY,IAAI,WAAW,QAAQ;AAC3D;;;;;;AAOA,SAAS,KAAK,OAAe,IAAY,MAAc,MAAc,OAA+D;CAClI,IAAM,SAAS,cAAc,KAAK,IAAI;CAItC,AAHA,MAAM,cAAc,oBAAoB;EAAC,GAAG;EAAO;EAAI;EAAM,MAAM,SAAS,KAAK,QAAQ,eAAe,EAAE,IAAI;CAAI,CAAC,CAAC,CAAC,SAAS,GAC9H,MAAM,YAAY,MAClB,MAAM,WAAW,GAAG,QAAQ,aAAa,EAAE,GAC3C,MAAM,YAAY;AACpB;;;;;;AAcA,SAAgB,yBAA4B,MAAS,WAAgD,SAA8B;CACjI,IAAI,CAAC,WAAW,OAAO;CACvB,IAAM,eAAe,QAAQ,gBAAgB,qBACvC,iBAAiB,OAAe,SAAqC;EACzE,IAAM,OAAO,gBAAgB;GAAC,WAAW,QAAQ;GAAW,iBAAiB;GAAW,YAAY;IAAC,GAAG;IAAM;IAAS;GAAM;EAAC,C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,aAAa,KAAK,KAAK,MAAM,UAAU;IACzC,AAAI,MAAM,aAAa,UAAQ,KAAK,OAAO,QAAQ,OAAO,MAAM,MAAM,EAAC,SAAS,QAAQ,UAAS,CAAC;IAClG;GACF;GACA,KAAK,IAAM,CAAC,GAAG,UAAU,OAAO,QAAQ,KAAK,GAAG,AAAK,EAAE,WAAW,GAAG,KAAG,MAAM,OAAO,GAAG,KAAK,GAAG,GAAG;EADnG;CAEF;CAEA,OADA,MAAM,SAAS,YAAY,QAAQ,GAAG,CAAC,GAChC;AACT;;AAKA,SAAgB,oBAAoB,OAA4C;CAE9E,OADI,CAAC,OAAO,eAAe,CAAC,MAAM,aAAa,CAAC,MAAM,YAAY,CAAC,MAAM,YAAkB,CAAC,IACrF;EAAC,eAAe,MAAM;EAAa,mBAAmB,MAAM;EAAW,iBAAiB,MAAM;EAAU,kBAAkB,MAAM;CAAS;AAClJ;;;;;AAMA,SAAgB,SAAS,OAAuB,KAAsB;CACpE,IAAM,QAAQ,OAAO,OAAO,OAAO;CACnC,OAAO,OAAO,cAAc,iBAAiB,KAAK,IAAI;AACxD"}
@@ -0,0 +1,51 @@
1
+ import { OverlayComponentResolver } from "@sanity/visual-editing";
2
+ /**
3
+ * Libellés de l'édition sur place. Anglais par défaut (interface du kit) ; un
4
+ * projet passe les siens (fichier de textes de sa langue) à `NcfPreviewEditing`.
5
+ */
6
+ type PreviewEditingLabels = {
7
+ /** Nom accessible du champ de saisie. */
8
+ fieldLabel: string;
9
+ save: string;
10
+ cancel: string;
11
+ /** Affiché le temps que l'aperçu montre la nouvelle valeur. */
12
+ saved: string;
13
+ /** Sous un texte hérité des valeurs par défaut du composant. */
14
+ inheritedNote: string;
15
+ /** Pastille au survol d'une image. */
16
+ replaceImage: string;
17
+ /** Interrupteur du kit (mode `toggle`). */
18
+ editMode: string;
19
+ browseMode: string;
20
+ modeLabel: string;
21
+ };
22
+ export declare const DEFAULT_PREVIEW_EDITING_LABELS: PreviewEditingLabels;
23
+ /**
24
+ * ÉDITION SUR PLACE dans l'aperçu (Presentation), à monter à côté de
25
+ * `<VisualEditing/>` en mode brouillon :
26
+ *
27
+ * ```tsx
28
+ * <VisualEditing refresh={useNcfPreviewRefresh()} components={ncfOverlayComponents} />
29
+ * <NcfPreviewEditing labels={messages.previewEditing} />
30
+ * ```
31
+ *
32
+ * - texte (champ chaîne, ligne d'un titre en texte riche) : crayon au survol, au
33
+ * clic un champ de saisie à sa place exacte ; enregistré dans le brouillon ;
34
+ * - image : « Replace this image » au survol, au clic le Studio ouvre la
35
+ * médiathèque (pont monté par le plugin du kit) ;
36
+ * - « Mode édition / Mode visite » : en visite, un clic suit les liens.
37
+ */
38
+ export declare const ncfOverlayComponents: OverlayComponentResolver;
39
+ type NcfPreviewEditingProps = {
40
+ /** Libellés (anglais par défaut) : passer ceux de la langue du projet. */
41
+ labels?: Partial<PreviewEditingLabels>;
42
+ /**
43
+ * `'toggle'` (défaut) : interrupteur « Edit mode / Browse mode » du kit, en bas
44
+ * à gauche de l'aperçu, mémorisé. Une fonction : le projet décide (ex. son propre
45
+ * interrupteur d'animations) ; le kit n'affiche alors rien.
46
+ */
47
+ editMode?: 'toggle' | (() => boolean);
48
+ };
49
+ export declare function NcfPreviewEditing({ labels, editMode }: NcfPreviewEditingProps): import("react").JSX.Element;
50
+ export type { NcfPreviewEditingProps, PreviewEditingLabels };
51
+ //# sourceMappingURL=web-editing.d.ts.map