@nocode-factory/sanity-kit 2.65.0-rc.7 → 2.66.0-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.
- package/CHANGELOG.md +53 -69
- package/bin/ncf-kit.mjs +18 -134
- package/dist/index.d.ts +1 -1
- package/dist/index.js +200 -592
- package/dist/index.js.map +1 -1
- package/dist/web-edit.d.ts +13 -1
- package/dist/web-edit.js +38 -7
- package/dist/web-edit.js.map +1 -1
- package/dist/web-editing.d.ts +2 -0
- package/dist/web-editing.js +138 -17
- package/dist/web-editing.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/PropagatePublish.tsx +10 -54
- package/src/form/TranslationTodoInput.tsx +1 -5
- package/src/lib/aiTranslate.ts +11 -72
- package/src/lib/propagate.ts +1 -29
- package/src/lib/translateDocument.ts +35 -142
- package/src/tools/pages/LanguagesSync.tsx +111 -255
- package/src/version.ts +1 -1
- package/src/web/edit/InlineTextEditor.tsx +156 -14
- package/src/web/edit/InlineTextOverlay.tsx +1 -1
- package/src/web/edit/index.ts +2 -2
- package/src/web/edit/labels.ts +3 -0
- package/src/web/edit/store.ts +30 -0
- package/src/web/edit/targets.ts +38 -1
- package/bin/translation-audit.mjs +0 -41
- package/src/lib/linkedTranslations.ts +0 -51
package/dist/web-edit.d.ts
CHANGED
|
@@ -121,6 +121,18 @@ type ImageEditValue = {
|
|
|
121
121
|
sourcePath: string;
|
|
122
122
|
};
|
|
123
123
|
} | null | undefined;
|
|
124
|
+
type NumberEditAttributes = {
|
|
125
|
+
'data-sanity'?: string;
|
|
126
|
+
'data-edit-number'?: string;
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Attributs à poser sur l'élément qui affiche un chiffre (champ nombre `field` de
|
|
130
|
+
* `value`, élément de liste ou section) : crayon au survol, édition sur place au clic.
|
|
131
|
+
* Vide pour les visiteurs. Ex. : `<span {...numberEditAttributes(item, 'value')}>`.
|
|
132
|
+
* L'élément ne doit contenir QUE le chiffre (préfixe et suffixe à côté, dans leurs
|
|
133
|
+
* propres éléments), sinon ils s'effacent avec lui pendant l'édition.
|
|
134
|
+
*/
|
|
135
|
+
export declare function numberEditAttributes(value: unknown, field: string): NumberEditAttributes;
|
|
124
136
|
type ImageEditOptions = {
|
|
125
137
|
/** Adresse du Studio (celle de `stega.studioUrl`). */
|
|
126
138
|
studioUrl: string;
|
|
@@ -225,5 +237,5 @@ export declare function replaceImagePatch(path: string, assetId: string): ({
|
|
|
225
237
|
setIfMissing?: undefined;
|
|
226
238
|
set?: undefined;
|
|
227
239
|
})[];
|
|
228
|
-
export type { ImageEditAttributes, ImageEditOptions, ImageEditValue, InheritedEdit, ReplaceImageRequest };
|
|
240
|
+
export type { ImageEditAttributes, ImageEditOptions, ImageEditValue, InheritedEdit, NumberEditAttributes, ReplaceImageRequest };
|
|
229
241
|
//# sourceMappingURL=web-edit.d.ts.map
|
package/dist/web-edit.js
CHANGED
|
@@ -21,6 +21,33 @@ function mark(value, id, type, path, extra) {
|
|
|
21
21
|
path: inList ? path.replace(/\[[^\]]+\]$/, "") : path
|
|
22
22
|
}).toString(), value._editPath = path, value._editDoc = id.replace(/^drafts\./, ""), value._editType = type;
|
|
23
23
|
}
|
|
24
|
+
function markNumbers(value, id, type, path, baseUrl) {
|
|
25
|
+
let numbers = {};
|
|
26
|
+
for (let [k, v] of Object.entries(value)) !k.startsWith("_") && typeof v == "number" && Number.isFinite(v) && (numbers[k] = createDataAttribute({
|
|
27
|
+
baseUrl,
|
|
28
|
+
id,
|
|
29
|
+
type,
|
|
30
|
+
path: `${path}.${k}`
|
|
31
|
+
}).toString());
|
|
32
|
+
Object.keys(numbers).length && (value._editNumbers = {
|
|
33
|
+
...value._editNumbers,
|
|
34
|
+
...numbers
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Attributs à poser sur l'élément qui affiche un chiffre (champ nombre `field` de
|
|
39
|
+
* `value`, élément de liste ou section) : crayon au survol, édition sur place au clic.
|
|
40
|
+
* Vide pour les visiteurs. Ex. : `<span {...numberEditAttributes(item, 'value')}>`.
|
|
41
|
+
* L'élément ne doit contenir QUE le chiffre (préfixe et suffixe à côté, dans leurs
|
|
42
|
+
* propres éléments), sinon ils s'effacent avec lui pendant l'édition.
|
|
43
|
+
*/
|
|
44
|
+
function numberEditAttributes(value, field) {
|
|
45
|
+
let target = value && typeof value == "object" ? value._editNumbers?.[field] : void 0;
|
|
46
|
+
return target ? {
|
|
47
|
+
"data-sanity": target,
|
|
48
|
+
"data-edit-number": field
|
|
49
|
+
} : {};
|
|
50
|
+
}
|
|
24
51
|
/**
|
|
25
52
|
* Marque chaque image du résultat d'une requête en brouillon. Une image venue du
|
|
26
53
|
* document des valeurs par défaut n'est pas marquée ici (un clic modifierait
|
|
@@ -162,7 +189,8 @@ function retagDeep(value, path, page, inherited, options) {
|
|
|
162
189
|
let copy = { ...value };
|
|
163
190
|
return mark(copy, page.id, page.type, path, { baseUrl: options.studioUrl }), copy._editInherited = inherited, copy;
|
|
164
191
|
}
|
|
165
|
-
|
|
192
|
+
let copy = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, k.startsWith("_") ? v : retagDeep(v, `${path}.${k}`, page, inherited, options)]));
|
|
193
|
+
return markNumbers(copy, page.id, page.type, path, options.studioUrl), copy;
|
|
166
194
|
}
|
|
167
195
|
/**
|
|
168
196
|
* Chemin EXACT des images qui appartiennent à la page, recalculé avec les clés
|
|
@@ -179,11 +207,14 @@ function rekeyOwnImageTargets(section, source, key, options) {
|
|
|
179
207
|
});
|
|
180
208
|
return;
|
|
181
209
|
}
|
|
182
|
-
if (value
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
210
|
+
if (!value || typeof value != "object") return;
|
|
211
|
+
if (isImageValue(value) && value._editDoc) {
|
|
212
|
+
value._editDoc === pageId && mark(value, pageId, source.type, path, { baseUrl: options.studioUrl });
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
let id = value._id;
|
|
216
|
+
if (typeof id != "string" || id.replace(/^drafts\./, "") === pageId) {
|
|
217
|
+
markNumbers(value, pageId, source.type, path, options.studioUrl);
|
|
187
218
|
for (let [k, child] of Object.entries(value)) k.startsWith("_") || visit(child, `${path}.${k}`);
|
|
188
219
|
}
|
|
189
220
|
};
|
|
@@ -207,6 +238,6 @@ function imageAlt(image, alt) {
|
|
|
207
238
|
let value = alt ?? image?.alt ?? "";
|
|
208
239
|
return image?._editTarget ? vercelStegaClean(value) : value;
|
|
209
240
|
}
|
|
210
|
-
export { REPLACE_IMAGE_MESSAGE, annotateImageEditTargets, imageAlt, imageEditAttributes, inheritedEditScriptProps, inheritedListValue, isReplaceImageRequest, materializeInheritedList, rekeyOwnImageTargets, replaceImagePatch, retagInheritedList, withPreviewEditTargets };
|
|
241
|
+
export { REPLACE_IMAGE_MESSAGE, annotateImageEditTargets, imageAlt, imageEditAttributes, inheritedEditScriptProps, inheritedListValue, isReplaceImageRequest, materializeInheritedList, numberEditAttributes, rekeyOwnImageTargets, replaceImagePatch, retagInheritedList, withPreviewEditTargets };
|
|
211
242
|
|
|
212
243
|
//# sourceMappingURL=web-edit.js.map
|
package/dist/web-edit.js.map
CHANGED
|
@@ -1 +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 {retag, retagInheritedList, type InheritedEdit} from './inherited'\nimport {vercelStegaDecode} from '@vercel/stega'\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 /** Image héritée DANS une valeur par défaut (liste...) : champ à recopier d'abord. */\n _editInherited?: {path: string; sourceId: string; sourcePath: string}\n} | null | undefined\n\ntype Marked = {asset: {_ref: string}; _editTarget?: string; _editPath?: string; _editDoc?: string; _editType?: string; _editInherited?: {path: string; sourceId: string; sourcePath: string}; _editDefaults?: {id: string; path: 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) 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 // Image des valeurs par défaut : pas de repère (il modifierait TOUTES les pages), mais\n // sa source brute, pour la recopier dans la page au remplacement.\n if (info.type === defaultsType) {\n value._editDefaults = {id: info.id.replace(/^drafts\\./, ''), path: imagePath}\n return\n }\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 const entryPath = `${base}.${path.join('.')}`\n if (typeof out === 'string') {\n collected.push({path: entryPath, value: vercelStegaClean(out)})\n return out\n }\n if (!out || typeof out !== 'object') return out\n // Image héritée seule : elle vise le champ de l'instance (choisir crée l'image de la page).\n if (isImageValue(out)) {\n const copy = {...out}\n markInherited(copy, entryPath)\n return copy\n }\n // Valeur héritée de N'IMPORTE QUELLE forme (liste, objet) : chaque texte et chaque image\n // vise son chemin EXACT dans la page ; à la première modification, la valeur brute des\n // valeurs par défaut est recopiée dans la page (source lue dans les marqueurs).\n const raw = defaultsSourceOf(value, path[path.length - 1] as string)\n if (raw) {\n collected.push({path: entryPath, source: raw})\n return retagDeep(out, entryPath, {...source, id: pageId}, {path: entryPath, sourceId: raw.id, sourcePath: raw.path}, options)\n }\n // Sans source repérable : l'ancienne règle (listes simples seulement).\n if (Array.isArray(out) && path.length === 1) return retagInheritedList(out, entryPath, source, collected)\n markInherited(out, entryPath)\n return out\n }\n}\n\n/** Champ des valeurs par défaut d'où vient une valeur héritée : lu dans un texte (stega) ou une image. */\nfunction defaultsSourceOf(value: unknown, field: string): {id: string; path: string} | null {\n let found: {id: string; full: string} | null = null\n const visit = (v: unknown) => {\n if (found || v === null || v === undefined) return\n if (typeof v === 'string') {\n const info = vercelStegaDecode(v) as {href?: string} | undefined\n if (!info?.href) return\n const href = decodeURIComponent(info.href)\n const id = /[;/]id=([^;?&]+)/.exec(href)?.[1]\n const full = /;path=([^;?&]+)/.exec(href)?.[1]\n if (id && full) found = {id: id.replace(/^drafts\\./, ''), full}\n return\n }\n if (Array.isArray(v)) return v.forEach(visit)\n if (typeof v === 'object') {\n const d = (v as Marked)._editDefaults\n if (d) found = {id: d.id, full: d.path}\n else for (const [k, x] of Object.entries(v)) if (!k.startsWith('_')) visit(x)\n }\n }\n visit(value)\n if (!found) return null\n const {id, full} = found as {id: string; full: string}\n // Chemin du champ dans le document des valeurs par défaut : jusqu'au segment `field`.\n const m = new RegExp(`^(.*?(?:^|\\\\.)${field.replace(/[^\\w]/g, '')})(?=[.[]|$)`).exec(full)\n return m?.[1] ? {id, path: m[1]} : null\n}\n\n/** Réétiquette chaque texte et marque chaque image d'une valeur héritée, à son chemin exact. */\nfunction retagDeep(value: unknown, path: string, page: {id: string; type: string}, inherited: {path: string; sourceId: string; sourcePath: string}, options: ImageEditOptions): unknown {\n if (typeof value === 'string') return retag(value, page, path)\n if (Array.isArray(value))\n return value.map((item, index) => {\n const k = item && typeof item === 'object' ? (item as {_key?: unknown})._key : undefined\n return retagDeep(item, typeof k === 'string' ? `${path}[_key==\"${k}\"]` : `${path}[${index}]`, page, inherited, options)\n })\n if (!value || typeof value !== 'object') return value\n if (isImageValue(value)) {\n const copy: Marked = {...value}\n mark(copy, page.id, page.type, path, {baseUrl: options.studioUrl})\n copy._editInherited = inherited\n return copy\n }\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, k.startsWith('_') ? v : retagDeep(v, `${path}.${k}`, page, inherited, options)]))\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; 'data-edit-inherited'?: 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 {\n 'data-sanity': image._editTarget,\n 'data-edit-image': image._editPath,\n 'data-edit-doc': image._editDoc,\n 'data-edit-type': image._editType,\n ...(image._editInherited ? {'data-edit-inherited': JSON.stringify(image._editInherited)} : {}),\n }\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":";;;;AAwCA,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,CAAC;EAC/H,IAAI,CAAC,MAAM;EACX,IAAM,OAAO,OAAO,KAAK,QAAS,WAAW,KAAK,OAAO,WAAW,SAAS,KAAK,IAAa,GACzF,YAAY,KAAK,QAAQ,kBAAkB,EAAE;EAC/C,IAAC,aAAa,cAAc,MAGhC;OAAI,KAAK,SAAS,cAAc;IAC9B,MAAM,gBAAgB;KAAC,IAAI,KAAK,GAAG,QAAQ,aAAa,EAAE;KAAG,MAAM;IAAS;IAC5E;GACF;GACA,KAAK,OAAO,KAAK,IAAI,KAAK,MAAM,WAAW;IACzC,SAAS,KAAK;IACd,WAAW,KA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KAAK,IAAI;AACxD"}
|
|
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 {retag, retagInheritedList, type InheritedEdit} from './inherited'\nimport {vercelStegaDecode} from '@vercel/stega'\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 /** Image héritée DANS une valeur par défaut (liste...) : champ à recopier d'abord. */\n _editInherited?: {path: string; sourceId: string; sourcePath: string}\n} | null | undefined\n\ntype Marked = {asset: {_ref: string}; _editTarget?: string; _editPath?: string; _editDoc?: string; _editType?: string; _editInherited?: {path: string; sourceId: string; sourcePath: string}; _editDefaults?: {id: string; path: 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\n/**\n * CHIFFRES (kit >= 2.66.0) : un champ NOMBRE ne peut pas porter de stega (caractères\n * invisibles), il était donc invisible pour l'édition sur place. Dans l'aperçu, l'objet\n * qui le contient (élément de liste, section) reçoit `_editNumbers` : pour chaque champ\n * nombre, son repère Sanity (document + chemin exact). Le composant le pose avec\n * `numberEditAttributes(objet, 'champ')` sur l'élément qui affiche le chiffre.\n */\ntype WithNumbers = {_editNumbers?: Record<string, string>}\nfunction markNumbers(value: Record<string, unknown>, id: string, type: string, path: string, baseUrl: string) {\n const numbers: Record<string, string> = {}\n for (const [k, v] of Object.entries(value))\n if (!k.startsWith('_') && typeof v === 'number' && Number.isFinite(v)) numbers[k] = createDataAttribute({baseUrl, id, type, path: `${path}.${k}`}).toString()\n if (Object.keys(numbers).length) (value as WithNumbers)._editNumbers = {...(value as WithNumbers)._editNumbers, ...numbers}\n}\n\nexport type NumberEditAttributes = {'data-sanity'?: string; 'data-edit-number'?: string}\n\n/**\n * Attributs à poser sur l'élément qui affiche un chiffre (champ nombre `field` de\n * `value`, élément de liste ou section) : crayon au survol, édition sur place au clic.\n * Vide pour les visiteurs. Ex. : `<span {...numberEditAttributes(item, 'value')}>`.\n * L'élément ne doit contenir QUE le chiffre (préfixe et suffixe à côté, dans leurs\n * propres éléments), sinon ils s'effacent avec lui pendant l'édition.\n */\nexport function numberEditAttributes(value: unknown, field: string): NumberEditAttributes {\n const target = value && typeof value === 'object' ? (value as WithNumbers)._editNumbers?.[field] : undefined\n return target ? {'data-sanity': target, 'data-edit-number': field} : {}\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) 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 // Image des valeurs par défaut : pas de repère (il modifierait TOUTES les pages), mais\n // sa source brute, pour la recopier dans la page au remplacement.\n if (info.type === defaultsType) {\n value._editDefaults = {id: info.id.replace(/^drafts\\./, ''), path: imagePath}\n return\n }\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 const entryPath = `${base}.${path.join('.')}`\n if (typeof out === 'string') {\n collected.push({path: entryPath, value: vercelStegaClean(out)})\n return out\n }\n if (!out || typeof out !== 'object') return out\n // Image héritée seule : elle vise le champ de l'instance (choisir crée l'image de la page).\n if (isImageValue(out)) {\n const copy = {...out}\n markInherited(copy, entryPath)\n return copy\n }\n // Valeur héritée de N'IMPORTE QUELLE forme (liste, objet) : chaque texte et chaque image\n // vise son chemin EXACT dans la page ; à la première modification, la valeur brute des\n // valeurs par défaut est recopiée dans la page (source lue dans les marqueurs).\n const raw = defaultsSourceOf(value, path[path.length - 1] as string)\n if (raw) {\n collected.push({path: entryPath, source: raw})\n return retagDeep(out, entryPath, {...source, id: pageId}, {path: entryPath, sourceId: raw.id, sourcePath: raw.path}, options)\n }\n // Sans source repérable : l'ancienne règle (listes simples seulement).\n if (Array.isArray(out) && path.length === 1) return retagInheritedList(out, entryPath, source, collected)\n markInherited(out, entryPath)\n return out\n }\n}\n\n/** Champ des valeurs par défaut d'où vient une valeur héritée : lu dans un texte (stega) ou une image. */\nfunction defaultsSourceOf(value: unknown, field: string): {id: string; path: string} | null {\n let found: {id: string; full: string} | null = null\n const visit = (v: unknown) => {\n if (found || v === null || v === undefined) return\n if (typeof v === 'string') {\n const info = vercelStegaDecode(v) as {href?: string} | undefined\n if (!info?.href) return\n const href = decodeURIComponent(info.href)\n const id = /[;/]id=([^;?&]+)/.exec(href)?.[1]\n const full = /;path=([^;?&]+)/.exec(href)?.[1]\n if (id && full) found = {id: id.replace(/^drafts\\./, ''), full}\n return\n }\n if (Array.isArray(v)) return v.forEach(visit)\n if (typeof v === 'object') {\n const d = (v as Marked)._editDefaults\n if (d) found = {id: d.id, full: d.path}\n else for (const [k, x] of Object.entries(v)) if (!k.startsWith('_')) visit(x)\n }\n }\n visit(value)\n if (!found) return null\n const {id, full} = found as {id: string; full: string}\n // Chemin du champ dans le document des valeurs par défaut : jusqu'au segment `field`.\n const m = new RegExp(`^(.*?(?:^|\\\\.)${field.replace(/[^\\w]/g, '')})(?=[.[]|$)`).exec(full)\n return m?.[1] ? {id, path: m[1]} : null\n}\n\n/** Réétiquette chaque texte et marque chaque image d'une valeur héritée, à son chemin exact. */\nfunction retagDeep(value: unknown, path: string, page: {id: string; type: string}, inherited: {path: string; sourceId: string; sourcePath: string}, options: ImageEditOptions): unknown {\n if (typeof value === 'string') return retag(value, page, path)\n if (Array.isArray(value))\n return value.map((item, index) => {\n const k = item && typeof item === 'object' ? (item as {_key?: unknown})._key : undefined\n return retagDeep(item, typeof k === 'string' ? `${path}[_key==\"${k}\"]` : `${path}[${index}]`, page, inherited, options)\n })\n if (!value || typeof value !== 'object') return value\n if (isImageValue(value)) {\n const copy: Marked = {...value}\n mark(copy, page.id, page.type, path, {baseUrl: options.studioUrl})\n copy._editInherited = inherited\n return copy\n }\n const copy = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, k.startsWith('_') ? v : retagDeep(v, `${path}.${k}`, page, inherited, options)]))\n // Chiffres hérités : visent leur chemin dans la PAGE (la valeur par défaut est recopiée\n // dans la page à la première modification, comme pour les textes).\n markNumbers(copy, page.id, page.type, path, options.studioUrl)\n return copy\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 // Document lié (témoignage, carte...) : ses chiffres ne sont pas ceux de la page.\n const id = (value as {_id?: unknown})._id\n if (typeof id === 'string' && id.replace(/^drafts\\./, '') !== pageId) return\n markNumbers(value as Record<string, unknown>, pageId, source.type, path, options.studioUrl)\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; 'data-edit-inherited'?: 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 {\n 'data-sanity': image._editTarget,\n 'data-edit-image': image._editPath,\n 'data-edit-doc': image._editDoc,\n 'data-edit-type': image._editType,\n ...(image._editInherited ? {'data-edit-inherited': JSON.stringify(image._editInherited)} : {}),\n }\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":";;;;AAwCA,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;AAUA,SAAS,YAAY,OAAgC,IAAY,MAAc,MAAc,SAAiB;CAC5G,IAAM,UAAkC,CAAC;CACzC,KAAK,IAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,KAAK,GACvC,AAAI,CAAC,EAAE,W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sB;CACpE,IAAM,QAAQ,OAAO,OAAO,OAAO;CACnC,OAAO,OAAO,cAAc,iBAAiB,KAAK,IAAI;AACxD"}
|
package/dist/web-editing.d.ts
CHANGED
|
@@ -23,6 +23,8 @@ type PreviewEditingLabels = {
|
|
|
23
23
|
/** Contrôle automatique : « {n} à vérifier » (éléments non modifiables sur place). */
|
|
24
24
|
auditIssues: string;
|
|
25
25
|
auditHelp: string;
|
|
26
|
+
/** Chiffre (champ nombre) : saisie qui n'est pas un nombre, rien n'est enregistré. */
|
|
27
|
+
numberExpected: string;
|
|
26
28
|
};
|
|
27
29
|
export declare const DEFAULT_PREVIEW_EDITING_LABELS: PreviewEditingLabels;
|
|
28
30
|
/**
|
package/dist/web-editing.js
CHANGED
|
@@ -19,7 +19,8 @@ const DEFAULT_PREVIEW_EDITING_LABELS = {
|
|
|
19
19
|
modeLabel: "Preview mode: edit or browse",
|
|
20
20
|
newLine: "New line",
|
|
21
21
|
auditIssues: "{n} to check",
|
|
22
|
-
auditHelp: "Elements of this page that cannot be edited in place (click to outline them in red)"
|
|
22
|
+
auditHelp: "Elements of this page that cannot be edited in place (click to outline them in red)",
|
|
23
|
+
numberExpected: "Number expected (e.g. 98.5): nothing saved."
|
|
23
24
|
}, 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)";
|
|
24
25
|
let hovered = null, editing = null;
|
|
25
26
|
const listeners = /* @__PURE__ */ new Set(), emit = () => listeners.forEach((l) => l()), inlineEdit = {
|
|
@@ -65,10 +66,26 @@ function stegaRuns(text) {
|
|
|
65
66
|
* un slug (une adresse se change dans le panneau, qui crée la 301).
|
|
66
67
|
*/
|
|
67
68
|
function isInlineEditablePath(type, path, element) {
|
|
68
|
-
return !(type !== "string" || /(^|\.)alt$/.test(path) || element.matches("img, picture, video, svg, canvas, iframe") || !element.textContent?.trim() || /\.children\[[^\]]+\]\.text$/.test(path) && stegaRuns(element.textContent ?? "") !== 1 || /(^|\.)slug\.current$/.test(path) || path.endsWith(".current"));
|
|
69
|
+
return type === "number" ? element.hasAttribute("data-edit-number") : !(type !== "string" || /(^|\.)alt$/.test(path) || element.matches("img, picture, video, svg, canvas, iframe") || !element.textContent?.trim() || /\.children\[[^\]]+\]\.text$/.test(path) && stegaRuns(element.textContent ?? "") !== 1 || /(^|\.)slug\.current$/.test(path) || path.endsWith(".current"));
|
|
69
70
|
}
|
|
70
71
|
/** Chemin d'un morceau de texte riche (jamais retiré, seulement vidé). */
|
|
71
72
|
const isSpanTextPath = (path) => /\.children\[[^\]]+\]\.text$/.test(path);
|
|
73
|
+
/**
|
|
74
|
+
* Saisie d'un chiffre : « 98,5 », « 98.5 », « 1 200 » (espaces, espaces insécables) ;
|
|
75
|
+
* vide = retour à la valeur par défaut (null) ; autre chose = NaN (rien n'est enregistré).
|
|
76
|
+
*/
|
|
77
|
+
function parseNumberInput(text, locale) {
|
|
78
|
+
let parts = locale ? new Intl.NumberFormat(locale).formatToParts(12345.6) : [], group = parts.find((p) => p.type === "group")?.value, decimal = parts.find((p) => p.type === "decimal")?.value, clean = text.replace(/[\s\u00a0\u202f]/g, "");
|
|
79
|
+
return group && !/\s/.test(group) && group !== decimal && (clean = clean.split(group).join("")), clean = decimal && decimal !== "." ? clean.split(decimal).join(".") : clean.replace(",", "."), clean === "" ? null : /^-?\d+(\.\d+)?$/.test(clean) ? Number(clean) : NaN;
|
|
80
|
+
}
|
|
81
|
+
/** Chiffre affiché dans la saisie au format de la langue de la page (« 98,5 », « 1 200 »). */
|
|
82
|
+
function formatNumberInput(value, locale) {
|
|
83
|
+
try {
|
|
84
|
+
return new Intl.NumberFormat(locale, { maximumFractionDigits: 20 }).format(value);
|
|
85
|
+
} catch {
|
|
86
|
+
return String(value);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
72
89
|
function sanityImageUrl(img) {
|
|
73
90
|
let src = img.currentSrc || img.src || "";
|
|
74
91
|
if (src.includes("cdn.sanity.io")) return !0;
|
|
@@ -331,7 +348,7 @@ function InlineTextEditor({ labels }) {
|
|
|
331
348
|
return useEffect(() => {
|
|
332
349
|
let onClick = (event) => {
|
|
333
350
|
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || !isEditMode()) return;
|
|
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] : []);
|
|
351
|
+
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 && own.kind !== "number" ? paragraphGroup(own) : null) ?? own ?? paragraphGroupAt(event.target), area = hovered?.parts ?? (hovered ? [hovered.element] : []);
|
|
335
352
|
hovered && clicked && area.some((el) => el.contains(clicked)) && inlineEdit.getEditing()?.element !== hovered.element && (event.preventDefault(), inlineEdit.open(hovered));
|
|
336
353
|
};
|
|
337
354
|
return window.addEventListener("click", onClick, { capture: !0 }), () => window.removeEventListener("click", onClick, { capture: !0 });
|
|
@@ -508,6 +525,24 @@ function textStyle(element) {
|
|
|
508
525
|
for (let prop of TYPO_PROPS) style[prop.replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = cs.getPropertyValue(prop);
|
|
509
526
|
return style;
|
|
510
527
|
}
|
|
528
|
+
/** Texte en cours d'édition : seul le texte s'efface, fonds, bordures et images restent. */
|
|
529
|
+
const EDITING_ATTR = "data-ncf-inline-editing", EDITING_CSS = `[${EDITING_ATTR}],[${EDITING_ATTR}] *{color:transparent!important;-webkit-text-fill-color:transparent!important;text-shadow:none!important;text-decoration-color:transparent!important}`;
|
|
530
|
+
function ensureEditingStyle() {
|
|
531
|
+
if (document.getElementById("ncf-inline-editing-style")) return;
|
|
532
|
+
let style = document.createElement("style");
|
|
533
|
+
style.id = "ncf-inline-editing-style", style.textContent = EDITING_CSS, document.head.appendChild(style);
|
|
534
|
+
}
|
|
535
|
+
/** Padding de l'élément édité (un seul élément ; un bloc de paragraphes n'en a pas). */
|
|
536
|
+
function paddingOf(parts) {
|
|
537
|
+
if (parts.length !== 1) return "0";
|
|
538
|
+
let cs = getComputedStyle(parts[0]);
|
|
539
|
+
return `${cs.paddingTop} ${cs.paddingRight} ${cs.paddingBottom} ${cs.paddingLeft}`;
|
|
540
|
+
}
|
|
541
|
+
/** Couleur lisible pour la saisie : celle du texte, sauf si elle est transparente (texte en dégradé). */
|
|
542
|
+
function readableColor(color) {
|
|
543
|
+
let m = color?.match(/rgba?\(([^)]+)\)/), alpha = m ? Number(m[1].split(",")[3] ?? 1) : 1;
|
|
544
|
+
return !color || color === "transparent" || alpha === 0 ? "#1b1d21" : color;
|
|
545
|
+
}
|
|
511
546
|
const sameBox = (a, b) => !!a && a.top === b.top && a.left === b.left && a.width === b.width && a.height === b.height, CHIP_STYLE = {
|
|
512
547
|
position: "absolute",
|
|
513
548
|
left: 0,
|
|
@@ -538,16 +573,19 @@ const sameBox = (a, b) => !!a && a.top === b.top && a.left === b.left && a.width
|
|
|
538
573
|
opacity: .7
|
|
539
574
|
};
|
|
540
575
|
function EditorSession({ target, labels }) {
|
|
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);
|
|
576
|
+
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])), [padding] = useState(() => paddingOf(parts)), initial = useRef(""), inheritedStart = useRef(""), rawInherited = useRef(null), multiline = useRef(!1), [breaks, setBreaks] = useState(!1), isNumber = target.kind === "number", [invalid, setInvalid] = useState(!1), [locale] = useState(() => element.closest("[lang]")?.getAttribute("lang") || document.documentElement.lang || void 0), rootRef = useRef(null), fieldRef = useRef(null);
|
|
542
577
|
useEffect(() => {
|
|
543
|
-
|
|
544
|
-
for (let el of parts) el.
|
|
578
|
+
ensureEditingStyle();
|
|
579
|
+
for (let el of parts) el.setAttribute(EDITING_ATTR, "");
|
|
545
580
|
return () => {
|
|
546
|
-
|
|
547
|
-
el.style.visibility = previous[i] ?? "";
|
|
548
|
-
});
|
|
581
|
+
for (let el of parts) el.removeAttribute(EDITING_ATTR);
|
|
549
582
|
};
|
|
550
583
|
}, [element]), useEffect(() => {
|
|
584
|
+
let onKey = (event) => {
|
|
585
|
+
event.key === "Escape" && (event.preventDefault(), event.stopPropagation(), inlineEdit.close());
|
|
586
|
+
};
|
|
587
|
+
return window.addEventListener("keydown", onKey, { capture: !0 }), () => window.removeEventListener("keydown", onKey, { capture: !0 });
|
|
588
|
+
}, []), useEffect(() => {
|
|
551
589
|
let frame = 0, tick = () => {
|
|
552
590
|
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
591
|
top,
|
|
@@ -562,7 +600,29 @@ function EditorSession({ target, labels }) {
|
|
|
562
600
|
let cancelled = !1;
|
|
563
601
|
return getDocument(node.id).getSnapshot().then(async (doc) => {
|
|
564
602
|
if (cancelled) return;
|
|
565
|
-
let stored = doc ? getAtPath(parse(node.path), doc) : void 0
|
|
603
|
+
let stored = doc ? getAtPath(parse(node.path), doc) : void 0;
|
|
604
|
+
if (isNumber) {
|
|
605
|
+
let start = typeof stored == "number" ? formatNumberInput(stored, locale) : "";
|
|
606
|
+
if (typeof stored != "number") {
|
|
607
|
+
let covering = inheritedSourceFor(node.path);
|
|
608
|
+
if (covering) {
|
|
609
|
+
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;
|
|
610
|
+
if (raw !== void 0) {
|
|
611
|
+
rawInherited.current = {
|
|
612
|
+
path: covering.entry.path,
|
|
613
|
+
raw,
|
|
614
|
+
rest: covering.rest
|
|
615
|
+
};
|
|
616
|
+
let v = readAt(raw, parsePath(covering.rest) ?? []);
|
|
617
|
+
typeof v == "number" && (start = formatNumberInput(v, locale));
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
if (cancelled) return;
|
|
622
|
+
initial.current = typeof stored == "number" ? formatNumberInput(stored, locale) : "", inheritedStart.current = start, multiline.current = !1, setBreaks(!1), setInherited(typeof stored != "number"), setValue(start), setStatus("editing");
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
let list = inheritedListFor(node.path), covering = typeof stored == "string" && stored !== "" ? null : inheritedSourceFor(node.path), fromSource = null;
|
|
566
626
|
if (covering) {
|
|
567
627
|
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;
|
|
568
628
|
if (raw !== void 0) {
|
|
@@ -599,7 +659,7 @@ function EditorSession({ target, labels }) {
|
|
|
599
659
|
let field = fieldRef.current;
|
|
600
660
|
if (!field) return;
|
|
601
661
|
let focusField = () => {
|
|
602
|
-
field.focus({ preventScroll: !0 }), field.setSelectionRange(field.value.length, field.value.length);
|
|
662
|
+
field.focus({ preventScroll: !0 }), isNumber ? field.select() : field.setSelectionRange(field.value.length, field.value.length);
|
|
603
663
|
};
|
|
604
664
|
focusField();
|
|
605
665
|
let until = performance.now() + 1500, onBlur = () => {
|
|
@@ -619,6 +679,28 @@ function EditorSession({ target, labels }) {
|
|
|
619
679
|
status
|
|
620
680
|
]);
|
|
621
681
|
let save = useCallback(() => {
|
|
682
|
+
if (isNumber) {
|
|
683
|
+
let parsed = parseNumberInput(value, locale);
|
|
684
|
+
if (Number.isNaN(parsed)) {
|
|
685
|
+
setInvalid(!0);
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
if (parsed === (initial.current === "" ? null : parseNumberInput(initial.current, locale)) || inherited && parsed !== null && parsed === parseNumberInput(inheritedStart.current, locale)) {
|
|
689
|
+
inlineEdit.close();
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
let doc = getDocument(node.id);
|
|
693
|
+
if (inherited && rawInherited.current) {
|
|
694
|
+
if (parsed === null) {
|
|
695
|
+
inlineEdit.close();
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
let copy = writeAt(rawInherited.current.raw, parsePath(rawInherited.current.rest) ?? [], parsed);
|
|
699
|
+
doc.patch([at(rawInherited.current.path, set(copy))]);
|
|
700
|
+
} else doc.patch([at(node.path, parsed === null ? unset() : set(parsed))]);
|
|
701
|
+
setStatus("saving");
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
622
704
|
let next = multiline.current ? value : value.replace(/\s*\n\s*/g, " ");
|
|
623
705
|
if (next === initial.current || inherited && next.trim() === inheritedStart.current.trim()) {
|
|
624
706
|
inlineEdit.close();
|
|
@@ -648,10 +730,15 @@ function EditorSession({ target, labels }) {
|
|
|
648
730
|
inherited,
|
|
649
731
|
getDocument,
|
|
650
732
|
node.id,
|
|
651
|
-
node.path
|
|
733
|
+
node.path,
|
|
734
|
+
isNumber
|
|
652
735
|
]);
|
|
653
736
|
useEffect(() => {
|
|
654
737
|
if (status !== "saving") return;
|
|
738
|
+
if (isNumber) {
|
|
739
|
+
let done = window.setTimeout(() => inlineEdit.close(), 700);
|
|
740
|
+
return () => window.clearTimeout(done);
|
|
741
|
+
}
|
|
655
742
|
let expected = value.replace(/\s+/g, " ").trim(), started = performance.now(), timer = window.setInterval(() => {
|
|
656
743
|
(vercelStegaClean(parts.map((el) => el.textContent ?? "").join(" ")).replace(/\s+/g, " ").trim().includes(expected) || expected === "" || performance.now() - started > 6e3) && inlineEdit.close();
|
|
657
744
|
}, 150);
|
|
@@ -697,15 +784,22 @@ function EditorSession({ target, labels }) {
|
|
|
697
784
|
spellCheck: !0,
|
|
698
785
|
readOnly: status !== "editing",
|
|
699
786
|
"aria-label": labels.fieldLabel,
|
|
700
|
-
onChange: (e) =>
|
|
787
|
+
onChange: (e) => {
|
|
788
|
+
setValue(e.target.value), invalid && setInvalid(!1);
|
|
789
|
+
},
|
|
790
|
+
inputMode: isNumber ? "decimal" : void 0,
|
|
791
|
+
wrap: isNumber ? "off" : void 0,
|
|
701
792
|
onKeyDown,
|
|
702
793
|
style: {
|
|
703
794
|
...typo,
|
|
795
|
+
color: readableColor(typo.color),
|
|
704
796
|
display: "block",
|
|
705
|
-
width: "100%",
|
|
797
|
+
width: isNumber ? `max(100%, ${value.length + 2}ch)` : "100%",
|
|
798
|
+
whiteSpace: isNumber ? "nowrap" : void 0,
|
|
706
799
|
minHeight: box.height,
|
|
707
800
|
margin: 0,
|
|
708
|
-
padding
|
|
801
|
+
padding,
|
|
802
|
+
boxSizing: "border-box",
|
|
709
803
|
border: 0,
|
|
710
804
|
borderRadius: 2,
|
|
711
805
|
resize: "none",
|
|
@@ -768,7 +862,33 @@ function EditorSession({ target, labels }) {
|
|
|
768
862
|
})
|
|
769
863
|
] })
|
|
770
864
|
}),
|
|
771
|
-
|
|
865
|
+
isNumber && invalid && status === "editing" && /* @__PURE__ */ jsx("p", {
|
|
866
|
+
role: "alert",
|
|
867
|
+
style: {
|
|
868
|
+
position: "absolute",
|
|
869
|
+
left: 0,
|
|
870
|
+
...below ? {
|
|
871
|
+
top: "100%",
|
|
872
|
+
marginTop: 56
|
|
873
|
+
} : {
|
|
874
|
+
bottom: "100%",
|
|
875
|
+
marginBottom: 56
|
|
876
|
+
},
|
|
877
|
+
width: "max-content",
|
|
878
|
+
maxWidth: "min(28rem, 90vw)",
|
|
879
|
+
padding: "8px 12px",
|
|
880
|
+
borderRadius: 6,
|
|
881
|
+
background: "#fff",
|
|
882
|
+
color: "#b42318",
|
|
883
|
+
boxShadow: "0 8px 24px rgba(0,0,0,0.18)",
|
|
884
|
+
font: "12px/1.35 var(--ncf-edit-font, ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif)",
|
|
885
|
+
fontStyle: "normal",
|
|
886
|
+
textTransform: "none",
|
|
887
|
+
letterSpacing: "normal"
|
|
888
|
+
},
|
|
889
|
+
children: labels.numberExpected
|
|
890
|
+
}),
|
|
891
|
+
inherited && status === "editing" && !invalid && /* @__PURE__ */ jsx("p", {
|
|
772
892
|
style: {
|
|
773
893
|
position: "absolute",
|
|
774
894
|
left: 0,
|
|
@@ -805,7 +925,8 @@ function InlineTextOverlay({ element, node }) {
|
|
|
805
925
|
return useEffect(() => {
|
|
806
926
|
if (element instanceof HTMLElement) return inlineEdit.setHovered({
|
|
807
927
|
element,
|
|
808
|
-
node
|
|
928
|
+
node,
|
|
929
|
+
...element.hasAttribute("data-edit-number") ? { kind: "number" } : {}
|
|
809
930
|
}), () => inlineEdit.clearHovered(element);
|
|
810
931
|
}, [element, node]), /* @__PURE__ */ jsx("span", {
|
|
811
932
|
"aria-hidden": !0,
|