@nocode-factory/sanity-kit 2.29.2 → 2.30.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.
- package/bin/ncf-kit.mjs +176 -0
- package/dist/index.d.ts +14 -1
- package/dist/index.js +753 -278
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/PropagatePublish.tsx +63 -64
- package/src/form/TranslationTodoInput.tsx +2 -0
- package/src/lib/translateDocument.ts +202 -0
- package/src/lib/translationTrace.ts +55 -0
- package/src/schema/translationTodo.ts +10 -0
- package/src/tools/pages/LanguagesSync.tsx +262 -0
- package/src/tools/pages/PagesTool.tsx +5 -0
- package/src/version.ts +1 -1
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { ClockIcon } from "@sanity/icons/Clock";
|
|
|
5
5
|
import { ComponentIcon } from "@sanity/icons/Component";
|
|
6
6
|
import { DocumentsIcon } from "@sanity/icons/Documents";
|
|
7
7
|
import { ColorWheelIcon } from "@sanity/icons/ColorWheel";
|
|
8
|
-
import { Badge, Box, Button, Card, Checkbox, Container, Flex, Grid, Select, Spinner, Stack, Tab, TabList, TabPanel, Text, TextArea, TextInput } from "@sanity/ui";
|
|
8
|
+
import { Badge, Box, Button, Card, Checkbox, Container, Dialog, Flex, Grid, Select, Spinner, Stack, Tab, TabList, TabPanel, Text, TextArea, TextInput } from "@sanity/ui";
|
|
9
9
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
10
10
|
import { IntentLink, useRouter } from "sanity/router";
|
|
11
11
|
import { EyeOpenIcon } from "@sanity/icons/EyeOpen";
|
|
@@ -20,6 +20,7 @@ import { EarthGlobeIcon } from "@sanity/icons/EarthGlobe";
|
|
|
20
20
|
import { ProjectsIcon } from "@sanity/icons/Projects";
|
|
21
21
|
import { CircleIcon } from "@sanity/icons/Circle";
|
|
22
22
|
import { ShareIcon } from "@sanity/icons/Share";
|
|
23
|
+
import { TranslateIcon } from "@sanity/icons/Translate";
|
|
23
24
|
import { ChevronDownIcon } from "@sanity/icons/ChevronDown";
|
|
24
25
|
import { ChevronRightIcon } from "@sanity/icons/ChevronRight";
|
|
25
26
|
import { ChevronUpIcon } from "@sanity/icons/ChevronUp";
|
|
@@ -267,6 +268,23 @@ const useKitConfig = () => useKitContext().config, TRANSLATION_TODO_TYPE = "ncfT
|
|
|
267
268
|
type: "array",
|
|
268
269
|
of: [{ type: "string" }],
|
|
269
270
|
readOnly: !0
|
|
271
|
+
}),
|
|
272
|
+
defineField({
|
|
273
|
+
name: "machine",
|
|
274
|
+
title: "Texts written by AI",
|
|
275
|
+
type: "array",
|
|
276
|
+
readOnly: !0,
|
|
277
|
+
of: [{
|
|
278
|
+
type: "object",
|
|
279
|
+
name: "ncfMachineText",
|
|
280
|
+
fields: [{
|
|
281
|
+
name: "path",
|
|
282
|
+
type: "string"
|
|
283
|
+
}, {
|
|
284
|
+
name: "hash",
|
|
285
|
+
type: "string"
|
|
286
|
+
}]
|
|
287
|
+
}]
|
|
270
288
|
})
|
|
271
289
|
],
|
|
272
290
|
preview: {
|
|
@@ -1363,7 +1381,7 @@ function explainGrantError(error) {
|
|
|
1363
1381
|
* quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
|
|
1364
1382
|
* le vérifie.
|
|
1365
1383
|
*/
|
|
1366
|
-
const KIT_VERSION = "2.
|
|
1384
|
+
const KIT_VERSION = "2.30.0";
|
|
1367
1385
|
/**
|
|
1368
1386
|
* Signale ce Studio au service du kit, une fois par montage.
|
|
1369
1387
|
*
|
|
@@ -1706,7 +1724,7 @@ function useKitUpdate() {
|
|
|
1706
1724
|
!controller.signal.aborted && body?.version && setLatest(body.version);
|
|
1707
1725
|
}).catch(() => {}), () => controller.abort();
|
|
1708
1726
|
}, []);
|
|
1709
|
-
let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.
|
|
1727
|
+
let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.30.0") > 0);
|
|
1710
1728
|
return {
|
|
1711
1729
|
current: KIT_VERSION,
|
|
1712
1730
|
latest,
|
|
@@ -2899,9 +2917,651 @@ function SharePreview() {
|
|
|
2899
2917
|
})
|
|
2900
2918
|
]
|
|
2901
2919
|
})
|
|
2902
|
-
] })
|
|
2920
|
+
] })
|
|
2921
|
+
})
|
|
2922
|
+
}) : null;
|
|
2923
|
+
}
|
|
2924
|
+
const isObj$1 = (v) => typeof v == "object" && !!v && !Array.isArray(v);
|
|
2925
|
+
/** Textes d'une valeur, dans l'ordre. */
|
|
2926
|
+
function collectTexts$1(value) {
|
|
2927
|
+
if (typeof value == "string") return [value];
|
|
2928
|
+
if (!Array.isArray(value)) return [];
|
|
2929
|
+
let out = [];
|
|
2930
|
+
for (let item of value) if (typeof item == "string") out.push(item);
|
|
2931
|
+
else if (isObj$1(item) && Array.isArray(item.children)) for (let child of item.children) isObj$1(child) && typeof child.text == "string" && out.push(child.text);
|
|
2932
|
+
return out;
|
|
2933
|
+
}
|
|
2934
|
+
/** La même valeur avec ses textes remplacés (dans l'ordre de `collectTexts`). */
|
|
2935
|
+
function replaceTexts(value, texts) {
|
|
2936
|
+
let i = 0, next = () => texts[i++] ?? "";
|
|
2937
|
+
return typeof value == "string" ? next() : Array.isArray(value) ? value.map((item) => typeof item == "string" ? next() : isObj$1(item) && Array.isArray(item.children) ? {
|
|
2938
|
+
...item,
|
|
2939
|
+
children: item.children.map((child) => isObj$1(child) && typeof child.text == "string" ? {
|
|
2940
|
+
...child,
|
|
2941
|
+
text: next()
|
|
2942
|
+
} : child)
|
|
2943
|
+
} : item) : value;
|
|
2944
|
+
}
|
|
2945
|
+
/** `sections[a].title` → segments (`[x]` : clé d'élément de liste, ou rang). */
|
|
2946
|
+
function parsePathKey(path) {
|
|
2947
|
+
let out = [];
|
|
2948
|
+
for (let m of path.matchAll(/([^.[\]]+)|\[([^\]]+)\]/g)) out.push(m[1] === void 0 ? { item: m[2] } : { field: m[1] });
|
|
2949
|
+
return out;
|
|
2950
|
+
}
|
|
2951
|
+
function itemOf(list, key) {
|
|
2952
|
+
return list.find((i) => isObj$1(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : void 0);
|
|
2953
|
+
}
|
|
2954
|
+
/** Valeur d'un document au chemin `sections[a].title`. */
|
|
2955
|
+
function valueAtKey(doc, path) {
|
|
2956
|
+
let cur = doc;
|
|
2957
|
+
for (let seg of parsePathKey(path)) {
|
|
2958
|
+
if (cur == null) return;
|
|
2959
|
+
cur = "field" in seg ? isObj$1(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0;
|
|
2960
|
+
}
|
|
2961
|
+
return cur;
|
|
2962
|
+
}
|
|
2963
|
+
/** Écrit `value` au chemin dans `doc` (modifié sur place). Faux si le chemin n'existe pas. */
|
|
2964
|
+
function setAtKey(doc, path, value) {
|
|
2965
|
+
let segs = parsePathKey(path), cur = doc;
|
|
2966
|
+
for (let n = 0; n < segs.length - 1; n++) {
|
|
2967
|
+
let seg = segs[n];
|
|
2968
|
+
if (cur = "field" in seg ? isObj$1(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0, cur == null) return !1;
|
|
2969
|
+
}
|
|
2970
|
+
let last = segs[segs.length - 1];
|
|
2971
|
+
return !last || !("field" in last) || !isObj$1(cur) ? !1 : (cur[last.field] = value, !0);
|
|
2972
|
+
}
|
|
2973
|
+
const MESSAGES = {
|
|
2974
|
+
daily_limit: "Daily AI translation limit reached for this project.",
|
|
2975
|
+
project_inactive: "This project is not active in the NCF kit.",
|
|
2976
|
+
bad_key: "This project is not registered in the NCF kit (npx ncf-kit setup).",
|
|
2977
|
+
not_configured: "AI translation is not configured on the NCF kit service.",
|
|
2978
|
+
too_long: "Text too long to translate at once."
|
|
2979
|
+
};
|
|
2980
|
+
async function call(service, from, to, texts) {
|
|
2981
|
+
let response = await fetch(`${service.endpoint}/translate`, {
|
|
2982
|
+
method: "POST",
|
|
2983
|
+
headers: { "content-type": "application/json" },
|
|
2984
|
+
body: JSON.stringify({
|
|
2985
|
+
key: service.projectKey,
|
|
2986
|
+
from,
|
|
2987
|
+
to,
|
|
2988
|
+
texts
|
|
2989
|
+
})
|
|
2990
|
+
}), body = await response.json().catch(() => ({}));
|
|
2991
|
+
if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length) throw Error(MESSAGES[body.error ?? ""] ?? `AI translation failed (${body.error ?? response.status}).`);
|
|
2992
|
+
return body.texts;
|
|
2993
|
+
}
|
|
2994
|
+
/**
|
|
2995
|
+
* Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to` :
|
|
2996
|
+
* mêmes valeurs, textes traduits. Découpe en lots si besoin.
|
|
2997
|
+
*/
|
|
2998
|
+
async function translateValues(service, from, to, values) {
|
|
2999
|
+
let perValue = values.map((v) => collectTexts$1(v)), all = perValue.flat(), translated = [], batch = [], size = 0, flush = async () => {
|
|
3000
|
+
batch.length && (translated.push(...await call(service, from, to, batch)), batch = [], size = 0);
|
|
3001
|
+
};
|
|
3002
|
+
for (let text of all) (batch.length >= 250 || size + text.length > 3e4) && await flush(), batch.push(text), size += text.length;
|
|
3003
|
+
await flush();
|
|
3004
|
+
let offset = 0;
|
|
3005
|
+
return values.map((value, n) => {
|
|
3006
|
+
let count = perValue[n].length, slice = translated.slice(offset, offset + count);
|
|
3007
|
+
return offset += count, count ? replaceTexts(value, slice) : value;
|
|
3008
|
+
});
|
|
3009
|
+
}
|
|
3010
|
+
const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
|
|
3011
|
+
"image",
|
|
3012
|
+
"file",
|
|
3013
|
+
"reference",
|
|
3014
|
+
"crossDatasetReference",
|
|
3015
|
+
"slug",
|
|
3016
|
+
"geopoint",
|
|
3017
|
+
"url",
|
|
3018
|
+
"email",
|
|
3019
|
+
"date",
|
|
3020
|
+
"datetime",
|
|
3021
|
+
"number",
|
|
3022
|
+
"boolean"
|
|
3023
|
+
]), SKIP_KEYS = /* @__PURE__ */ new Set(["language", "slug"]), isObj = (v) => typeof v == "object" && !!v && !Array.isArray(v), same$2 = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null), keyed$1 = (v) => Array.isArray(v) && v.length > 0 && v.every((i) => isObj(i) && typeof i._key == "string");
|
|
3024
|
+
function typeNames(t) {
|
|
3025
|
+
let out = [];
|
|
3026
|
+
for (let c = t; c; c = c.type) c.name && out.push(c.name);
|
|
3027
|
+
return out;
|
|
3028
|
+
}
|
|
3029
|
+
/** Nature d'un champ d'après son schéma (et sa valeur, faute de schéma). */
|
|
3030
|
+
function kindOf(t, value) {
|
|
3031
|
+
if (t) {
|
|
3032
|
+
if (typeNames(t).some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return "value";
|
|
3033
|
+
if (t.jsonType === "array") {
|
|
3034
|
+
let of = t.of ?? [];
|
|
3035
|
+
if (of.some((m) => typeNames(m).includes("block"))) return "text";
|
|
3036
|
+
if (of.some((m) => m.jsonType === "object" || typeNames(m).includes("object"))) return "list";
|
|
3037
|
+
let prim = of[0];
|
|
3038
|
+
return prim && prim.jsonType === "string" && !prim.options?.list?.length ? "text" : "value";
|
|
3039
|
+
}
|
|
3040
|
+
return t.jsonType === "object" ? "object" : t.jsonType === "string" ? t.options?.list?.length ? "value" : "text" : "value";
|
|
3041
|
+
}
|
|
3042
|
+
return keyed$1(value) ? "list" : isObj(value) ? "object" : "value";
|
|
3043
|
+
}
|
|
3044
|
+
function fieldType(t, name) {
|
|
3045
|
+
for (let c = t; c; c = c.type) {
|
|
3046
|
+
let f = c.fields?.find((x) => x.name === name);
|
|
3047
|
+
if (f) return f.type;
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
function itemType(t, item) {
|
|
3051
|
+
let of;
|
|
3052
|
+
for (let c = t; c && !of; c = c.type) of = c.of;
|
|
3053
|
+
if (of?.length) return of.find((m) => typeNames(m).includes(item._type)) ?? (of.length === 1 ? of[0] : void 0);
|
|
3054
|
+
}
|
|
3055
|
+
/** Tous les textes d'un élément ajouté : à traduire. */
|
|
3056
|
+
function collectTexts(value, t, path, acc) {
|
|
3057
|
+
let kind = kindOf(t, value);
|
|
3058
|
+
if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
|
|
3059
|
+
else if (kind === "object" && isObj(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
|
|
3060
|
+
else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
|
|
3061
|
+
}
|
|
3062
|
+
const ABSENT$1 = Symbol("absent");
|
|
3063
|
+
function merge(target, before, after, t, path, acc) {
|
|
3064
|
+
if (same$2(before, after)) return target === void 0 ? ABSENT$1 : target;
|
|
3065
|
+
let kind = kindOf(t, after ?? before);
|
|
3066
|
+
if (kind === "text") return after == null || after === "" ? (target != null && target !== "" && acc.toTranslate.push(path), target === void 0 ? ABSENT$1 : target) : (acc.toTranslate.push(path), target == null || target === "" || same$2(target, before) ? after : target);
|
|
3067
|
+
if (kind === "value") return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
|
|
3068
|
+
if (kind === "object") {
|
|
3069
|
+
if (!isObj(after)) return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
|
|
3070
|
+
let base = isObj(target) ? { ...target } : { _type: after._type }, b = isObj(before) ? before : {};
|
|
3071
|
+
for (let k of /* @__PURE__ */ new Set([...Object.keys(b), ...Object.keys(after)])) {
|
|
3072
|
+
if (k.startsWith("_") || SKIP_KEYS.has(k)) continue;
|
|
3073
|
+
let v = merge(base[k], b[k], after[k], fieldType(t, k), path ? `${path}.${k}` : k, acc);
|
|
3074
|
+
v === ABSENT$1 ? delete base[k] : base[k] = v;
|
|
3075
|
+
}
|
|
3076
|
+
return base;
|
|
3077
|
+
}
|
|
3078
|
+
let tgt = Array.isArray(target) ? target.filter(isObj) : [], bef = Array.isArray(before) ? before.filter(isObj) : [], aft = Array.isArray(after) ? after.filter(isObj) : [], byKey = (list) => new Map(list.map((i) => [i._key, i])), tMap = byKey(tgt), bMap = byKey(bef), aMap = byKey(aft), result = [];
|
|
3079
|
+
for (let item of aft) {
|
|
3080
|
+
let key = item._key, it = itemType(t, item);
|
|
3081
|
+
if (tMap.has(key)) {
|
|
3082
|
+
let merged = merge(tMap.get(key), bMap.get(key), item, it, `${path}[${key}]`, acc);
|
|
3083
|
+
result.push(merged === ABSENT$1 ? item : merged);
|
|
3084
|
+
} else result.push(structuredClone(item)), acc.added++, collectTexts(item, it, `${path}[${key}]`, acc);
|
|
3085
|
+
}
|
|
3086
|
+
for (let key of bMap.keys()) !aMap.has(key) && tMap.has(key) && acc.removed++;
|
|
3087
|
+
tgt.forEach((item, index) => {
|
|
3088
|
+
let key = item._key;
|
|
3089
|
+
if (bMap.has(key) || aMap.has(key)) return;
|
|
3090
|
+
let prev = tgt.slice(0, index).reverse().find((p) => result.some((r) => r._key === p._key)), at = prev ? result.findIndex((r) => r._key === prev._key) + 1 : 0;
|
|
3091
|
+
result.splice(at, 0, item);
|
|
3092
|
+
});
|
|
3093
|
+
let common = (list) => list.map((i) => i._key).filter((k) => tMap.has(k) && aMap.has(k));
|
|
3094
|
+
return same$2(common(tgt), common(aft)) || (acc.moved = !0), result;
|
|
3095
|
+
}
|
|
3096
|
+
/**
|
|
3097
|
+
* Applique la modification `before` → `after` (version principale) à `target`
|
|
3098
|
+
* (brouillon ou version publiée de la traduction). `documentType` : schéma du
|
|
3099
|
+
* document, pour distinguer textes et valeurs.
|
|
3100
|
+
*/
|
|
3101
|
+
function propagate(target, before, after, documentType) {
|
|
3102
|
+
let acc = {
|
|
3103
|
+
toTranslate: [],
|
|
3104
|
+
copied: [],
|
|
3105
|
+
added: 0,
|
|
3106
|
+
removed: 0,
|
|
3107
|
+
moved: !1
|
|
3108
|
+
}, merged = merge(target ?? {}, before ?? {}, after, documentType, "", acc);
|
|
3109
|
+
return {
|
|
3110
|
+
document: {
|
|
3111
|
+
...target ?? {},
|
|
3112
|
+
...isObj(merged) ? merged : {}
|
|
3113
|
+
},
|
|
3114
|
+
...acc
|
|
3115
|
+
};
|
|
3116
|
+
}
|
|
3117
|
+
/** La propagation changerait-elle quelque chose ? */
|
|
3118
|
+
function hasChanges(r) {
|
|
3119
|
+
return r.toTranslate.length > 0 || r.copied.length > 0 || r.added > 0 || r.removed > 0 || r.moved;
|
|
3120
|
+
}
|
|
3121
|
+
/** Slug d'URL depuis un titre : sans accents, minuscules, tirets. */
|
|
3122
|
+
function slugify(input, maxLength = 96) {
|
|
3123
|
+
return input.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxLength).replace(/-+$/g, "");
|
|
3124
|
+
}
|
|
3125
|
+
/**
|
|
3126
|
+
* Trace des textes écrits par l'IA dans une traduction (champ `machine` du document
|
|
3127
|
+
* `ncfTodo.<id>`). Sert à ne JAMAIS écraser un texte modifié à la main dans une
|
|
3128
|
+
* langue : à la propagation, un texte dont l'empreinte diffère de celle que l'IA a
|
|
3129
|
+
* écrite est un texte édité, gardé sauf demande explicite.
|
|
3130
|
+
*/
|
|
3131
|
+
/** Empreinte courte et stable d'une valeur (FNV-1a 32 bits sur son JSON). */
|
|
3132
|
+
function hashValue(value) {
|
|
3133
|
+
let text = JSON.stringify(value ?? null), h = 2166136261;
|
|
3134
|
+
for (let i = 0; i < text.length; i++) h ^= text.charCodeAt(i), h = Math.imul(h, 16777619);
|
|
3135
|
+
return (h >>> 0).toString(36);
|
|
3136
|
+
}
|
|
3137
|
+
async function readTrace(client, documentId) {
|
|
3138
|
+
let list = await client.fetch("*[_id == $id][0].machine", { id: translationTodoId(documentId) });
|
|
3139
|
+
return new Map((list ?? []).filter((e) => e.path && e.hash).map((e) => [e.path, e.hash]));
|
|
3140
|
+
}
|
|
3141
|
+
/** Enregistre les textes que l'IA vient d'écrire (fusion avec la trace existante). */
|
|
3142
|
+
async function recordTrace(client, documentId, entries, meta) {
|
|
3143
|
+
if (!entries.length) return;
|
|
3144
|
+
let id = translationTodoId(documentId), trace = await readTrace(client, documentId);
|
|
3145
|
+
for (let e of entries) trace.set(e.path, hashValue(e.value));
|
|
3146
|
+
let machine = [...trace].map(([path, hash]) => ({
|
|
3147
|
+
_key: `k${hashValue(path)}`,
|
|
3148
|
+
_type: "ncfMachineText",
|
|
3149
|
+
path,
|
|
3150
|
+
hash
|
|
3151
|
+
}));
|
|
3152
|
+
await client.transaction().createIfNotExists({
|
|
3153
|
+
_id: id,
|
|
3154
|
+
_type: TRANSLATION_TODO_TYPE,
|
|
3155
|
+
documentId: documentId.replace(/^drafts\./, ""),
|
|
3156
|
+
...meta,
|
|
3157
|
+
paths: []
|
|
3158
|
+
}).patch(id, (p) => p.set({ machine })).commit();
|
|
3159
|
+
}
|
|
3160
|
+
/**
|
|
3161
|
+
* Un texte de traduction peut-il être remplacé par une nouvelle traduction ?
|
|
3162
|
+
* Oui s'il est vide, s'il est encore le texte source (jamais traduit) ou s'il est
|
|
3163
|
+
* exactement ce que l'IA avait écrit. Non s'il a été modifié à la main.
|
|
3164
|
+
*/
|
|
3165
|
+
function isReplaceable(current, source, path, trace, isEmpty) {
|
|
3166
|
+
return isEmpty(current) || JSON.stringify(current) === JSON.stringify(source) ? !0 : trace.get(path) === hashValue(current);
|
|
3167
|
+
}
|
|
3168
|
+
/**
|
|
3169
|
+
* Versions traduites d'un document (création), partagé par la fenêtre de
|
|
3170
|
+
* publication (« Create the other language versions? ») et la synchronisation
|
|
3171
|
+
* des langues (onglet Pages > Languages) : même résultat dans les deux cas.
|
|
3172
|
+
*/
|
|
3173
|
+
const randomId = () => typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
|
|
3174
|
+
/**
|
|
3175
|
+
* Identifiant de la nouvelle version. Document à identifiant lisible (singleton,
|
|
3176
|
+
* `homePage`, `homePage-fr`, `componentDefaults`) : `<base>-<langue>`, la
|
|
3177
|
+
* convention des Studios NCF (structure par langue). Sinon : identifiant aléatoire.
|
|
3178
|
+
*/
|
|
3179
|
+
function translationIdFor(sourceId, sourceLanguage, language) {
|
|
3180
|
+
return /^[A-Za-z][A-Za-z0-9_]*(-[a-z]{2}(-[A-Za-z]{2})?)?$/.test(sourceId) ? `${sourceId.endsWith(`-${sourceLanguage}`) ? sourceId.slice(0, -sourceLanguage.length - 1) : sourceId}-${language}` : randomId();
|
|
3181
|
+
}
|
|
3182
|
+
/** Traductions reliées d'un document (translation.metadata). */
|
|
3183
|
+
async function translationsOf(client, id) {
|
|
3184
|
+
return (await client.fetch("*[_type == \"translation.metadata\" && references($id)][0].translations[]{language, \"key\": _key, \"id\": value._ref}", { id }) ?? []).map((t) => ({
|
|
3185
|
+
language: t.language ?? t.key ?? "",
|
|
3186
|
+
id: t.id ?? ""
|
|
3187
|
+
})).filter((t) => t.language && t.id);
|
|
3188
|
+
}
|
|
3189
|
+
/** Relie des versions au document source (translation.metadata de document-internationalization). */
|
|
3190
|
+
async function linkTranslations(client, sourceId, sourceLanguage, type, created) {
|
|
3191
|
+
if (!created.length) return;
|
|
3192
|
+
let item = (language, ref) => ({
|
|
3193
|
+
_key: language,
|
|
3194
|
+
_type: "internationalizedArrayReferenceValue",
|
|
3195
|
+
language,
|
|
3196
|
+
value: {
|
|
3197
|
+
_type: "reference",
|
|
3198
|
+
_ref: ref,
|
|
3199
|
+
_weak: !0,
|
|
3200
|
+
_strengthenOnPublish: { type }
|
|
3201
|
+
}
|
|
3202
|
+
}), meta = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0]{_id, \"keys\": translations[]._key}", { id: sourceId });
|
|
3203
|
+
if (meta) {
|
|
3204
|
+
let fresh = created.filter((c) => !(meta.keys ?? []).includes(c.language));
|
|
3205
|
+
if (!fresh.length) return;
|
|
3206
|
+
await client.patch(meta._id).setIfMissing({ translations: [] }).append("translations", fresh.map((c) => item(c.language, c.id))).commit();
|
|
3207
|
+
} else await client.create({
|
|
3208
|
+
_id: randomId(),
|
|
3209
|
+
_type: "translation.metadata",
|
|
3210
|
+
schemaTypes: [type],
|
|
3211
|
+
translations: [item(sourceLanguage, sourceId), ...created.map((c) => item(c.language, c.id))]
|
|
3212
|
+
});
|
|
3213
|
+
}
|
|
3214
|
+
/**
|
|
3215
|
+
* Crée la version `language` de `source` : même structure et mêmes valeurs, textes
|
|
3216
|
+
* traduits par l'IA si `ai` (service du kit), slug traduit et unique, publiée si
|
|
3217
|
+
* tout est traduit (sinon brouillon et textes « To translate »). Relie la version.
|
|
3218
|
+
*/
|
|
3219
|
+
async function createTranslatedVersion(opts) {
|
|
3220
|
+
let { client, config, type, schemaType, source, sourceId, sourceLanguage, language, ai } = opts, field = config.i18n?.field ?? "language", result = propagate({}, {}, source, schemaType), { _id, _rev, _createdAt, _updatedAt, ...doc } = structuredClone(result.document), id = translationIdFor(sourceId, sourceLanguage, language), remaining = result.toTranslate, aiError = null, written = [];
|
|
3221
|
+
if (ai && config.history && remaining.length) try {
|
|
3222
|
+
let toSend = remaining.map((path) => valueAtKey(source, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), translated = await translateValues(config.history, sourceLanguage, language, toSend.map((v) => v ?? ""));
|
|
3223
|
+
remaining = remaining.filter((path, n) => {
|
|
3224
|
+
let value = toSend[n] === void 0 ? void 0 : translated[n], ok = setAtKey(doc, path, value);
|
|
3225
|
+
return ok && value !== void 0 && written.push({
|
|
3226
|
+
path,
|
|
3227
|
+
value
|
|
3228
|
+
}), !ok;
|
|
3229
|
+
});
|
|
3230
|
+
} catch (cause) {
|
|
3231
|
+
aiError = cause instanceof Error ? cause.message : String(cause);
|
|
3232
|
+
}
|
|
3233
|
+
doc[field] = language;
|
|
3234
|
+
let pageType = config.pageTypes.find((t) => t.type === type), slugField = pageType?.slugField ?? (source.slug?.current ? "slug" : null);
|
|
3235
|
+
if (slugField && source[slugField]?.current) {
|
|
3236
|
+
let titleField = pageType?.titleField ?? "title", base = slugify(typeof doc[titleField] == "string" ? doc[titleField] : "") || String(source[slugField].current), slug = base;
|
|
3237
|
+
for (let n = 2; await client.fetch(`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**"))]) > 0`, {
|
|
3238
|
+
type,
|
|
3239
|
+
slug,
|
|
3240
|
+
language
|
|
3241
|
+
}); n++) slug = `${base}-${n}`;
|
|
3242
|
+
doc[slugField] = {
|
|
3243
|
+
_type: "slug",
|
|
3244
|
+
current: slug
|
|
3245
|
+
};
|
|
3246
|
+
}
|
|
3247
|
+
let published = ai && !remaining.length && !aiError;
|
|
3248
|
+
return await client.createOrReplace({
|
|
3249
|
+
...doc,
|
|
3250
|
+
_id: published ? id : `drafts.${id}`,
|
|
3251
|
+
_type: type
|
|
3252
|
+
}), remaining.length && await client.createOrReplace({
|
|
3253
|
+
_id: translationTodoId(id),
|
|
3254
|
+
_type: TRANSLATION_TODO_TYPE,
|
|
3255
|
+
documentId: id,
|
|
3256
|
+
sourceId,
|
|
3257
|
+
sourceLanguage,
|
|
3258
|
+
paths: remaining
|
|
3259
|
+
}), await recordTrace(client, id, written, {
|
|
3260
|
+
sourceId,
|
|
3261
|
+
sourceLanguage
|
|
3262
|
+
}), await linkTranslations(client, sourceId, sourceLanguage, type, [{
|
|
3263
|
+
language,
|
|
3264
|
+
id
|
|
3265
|
+
}]), {
|
|
3266
|
+
id,
|
|
3267
|
+
published,
|
|
3268
|
+
aiError
|
|
3269
|
+
};
|
|
3270
|
+
}
|
|
3271
|
+
/**
|
|
3272
|
+
* Complète la version `target` (valeurs par défaut des composants d'une langue)
|
|
3273
|
+
* depuis `source` : un bloc absent est recopié, un texte vide ou resté identique au
|
|
3274
|
+
* texte source est traduit. Les textes déjà traduits ne sont jamais touchés.
|
|
3275
|
+
* Rend le document complété et le nombre de textes traduits.
|
|
3276
|
+
*/
|
|
3277
|
+
async function fillTranslation(opts) {
|
|
3278
|
+
let { config, schemaType, source, sourceLanguage, language } = opts, document = structuredClone(opts.target);
|
|
3279
|
+
for (let [key, value] of Object.entries(source)) key.startsWith("_") || key === (config.i18n?.field ?? "language") || (document[key] === void 0 || document[key] === null) && (document[key] = structuredClone(value));
|
|
3280
|
+
let paths = untranslatedPaths(source, document, schemaType);
|
|
3281
|
+
if (!paths.length || !config.history) return {
|
|
3282
|
+
document,
|
|
3283
|
+
translated: 0,
|
|
3284
|
+
written: []
|
|
3285
|
+
};
|
|
3286
|
+
let translated = await translateValues(config.history, sourceLanguage, language, paths.map((p) => valueAtKey(source, p))), written = [];
|
|
3287
|
+
return paths.forEach((p, n) => {
|
|
3288
|
+
setAtKey(document, p, translated[n]) && written.push({
|
|
3289
|
+
path: p,
|
|
3290
|
+
value: translated[n]
|
|
3291
|
+
});
|
|
3292
|
+
}), {
|
|
3293
|
+
document,
|
|
3294
|
+
translated: written.length,
|
|
3295
|
+
written
|
|
3296
|
+
};
|
|
3297
|
+
}
|
|
3298
|
+
/**
|
|
3299
|
+
* Textes de `source` absents ou non traduits dans `target` (vides, ou identiques au
|
|
3300
|
+
* texte source). Un texte déjà traduit, même à la main, n'y figure jamais.
|
|
3301
|
+
*/
|
|
3302
|
+
function untranslatedPaths(source, target, schemaType) {
|
|
3303
|
+
return propagate({}, {}, source, schemaType).toTranslate.filter((path) => {
|
|
3304
|
+
let src = valueAtKey(source, path);
|
|
3305
|
+
if (!collectTexts$1(src).some((t) => t.trim())) return !1;
|
|
3306
|
+
let cur = target ? valueAtKey(target, path) : void 0;
|
|
3307
|
+
return !collectTexts$1(cur).some((t) => t.trim()) || JSON.stringify(cur) === JSON.stringify(src);
|
|
3308
|
+
});
|
|
3309
|
+
}
|
|
3310
|
+
const EXCLUDED = [
|
|
3311
|
+
"translation.metadata",
|
|
3312
|
+
BOARD_LAYOUT_TYPE,
|
|
3313
|
+
TRANSLATION_TODO_TYPE
|
|
3314
|
+
];
|
|
3315
|
+
/**
|
|
3316
|
+
* Langues du site : met chaque langue au niveau de la langue principale, en UN clic
|
|
3317
|
+
* explicite (jamais tout seul). Utile à l'ajout d'une langue (« de » : toutes les
|
|
3318
|
+
* pages en allemand) et après l'ajout d'un composant (valeurs par défaut traduites
|
|
3319
|
+
* dans chaque langue).
|
|
3320
|
+
* - Documents : chaque document publié de la langue principale sans version dans
|
|
3321
|
+
* une langue reçoit sa version, traduite par l'IA, publiée et reliée.
|
|
3322
|
+
* - Valeurs par défaut des composants : langue source (anglais en général), puis
|
|
3323
|
+
* chaque langue ; un document absent est créé ; seuls les textes vides ou restés
|
|
3324
|
+
* identiques au texte source sont traduits (jamais un texte traduit à la main).
|
|
3325
|
+
*/
|
|
3326
|
+
function LanguagesSync() {
|
|
3327
|
+
let config = useKitConfig(), client = useKitClient(), schema = useSchema(), [open, setOpen] = useState(!1), [plan, setPlan] = useState(null), [busy, setBusy] = useState(!1), [progress, setProgress] = useState(null), [report, setReport] = useState(null), i18n = config.i18n, field = i18n?.field ?? "language", defaultsType = config.componentPreview.defaultsType, typeOf = (name) => schema.get(name), analyse = useCallback(async () => {
|
|
3328
|
+
if (!i18n) return;
|
|
3329
|
+
setPlan(null), setReport(null);
|
|
3330
|
+
let main = i18n.defaultLocale, sources = await client.fetch(`*[defined(${field}) && ${field} == $main && !(_id in path("drafts.**")) && !(_type in $excluded)]{_id, _type}`, {
|
|
3331
|
+
main,
|
|
3332
|
+
excluded: [...EXCLUDED, defaultsType]
|
|
3333
|
+
}), metas = await client.fetch("*[_type == \"translation.metadata\"]{\"refs\": translations[]{\"lang\": coalesce(language, _key), \"id\": value._ref}}"), langsOf = /* @__PURE__ */ new Map();
|
|
3334
|
+
for (let m of metas) {
|
|
3335
|
+
let langs = new Set((m.refs ?? []).map((r) => r.lang ?? ""));
|
|
3336
|
+
for (let r of m.refs ?? []) r.id && langsOf.set(r.id, langs);
|
|
3337
|
+
}
|
|
3338
|
+
let missing = i18n.locales.filter((l) => l !== main).map((language) => ({
|
|
3339
|
+
language,
|
|
3340
|
+
docs: sources.filter((d) => !langsOf.get(d._id)?.has(language))
|
|
3341
|
+
})), defaultsDocs = await client.fetch("*[_type == $type && !(_id in path(\"drafts.**\"))]", { type: defaultsType }), byLang = (lang) => defaultsDocs.find((d) => d[field] === lang) ?? null, sourceLang = byLang(i18n.defaultsSourceLocale) ? i18n.defaultsSourceLocale : main, sourceDoc = byLang(sourceLang), mainDoc = byLang(main), defaults = [];
|
|
3342
|
+
if (sourceDoc && mainDoc && sourceLang !== main) {
|
|
3343
|
+
let texts = untranslatedPaths(mainDoc, sourceDoc, typeOf(defaultsType)).length;
|
|
3344
|
+
texts && defaults.push({
|
|
3345
|
+
language: sourceLang,
|
|
3346
|
+
exists: !0,
|
|
3347
|
+
texts,
|
|
3348
|
+
from: main
|
|
3349
|
+
});
|
|
3350
|
+
}
|
|
3351
|
+
if (sourceDoc) for (let language of i18n.locales.filter((l) => l !== sourceLang)) {
|
|
3352
|
+
let doc = byLang(language);
|
|
3353
|
+
defaults.push({
|
|
3354
|
+
language,
|
|
3355
|
+
exists: !!doc,
|
|
3356
|
+
texts: untranslatedPaths(sourceDoc, doc, typeOf(defaultsType)).length,
|
|
3357
|
+
from: sourceLang
|
|
3358
|
+
});
|
|
3359
|
+
}
|
|
3360
|
+
setPlan({
|
|
3361
|
+
missing,
|
|
3362
|
+
defaults
|
|
3363
|
+
});
|
|
3364
|
+
}, [
|
|
3365
|
+
client,
|
|
3366
|
+
defaultsType,
|
|
3367
|
+
field,
|
|
3368
|
+
i18n
|
|
3369
|
+
]), run = async () => {
|
|
3370
|
+
if (!plan || !i18n) return;
|
|
3371
|
+
setBusy(!0);
|
|
3372
|
+
let lines = [];
|
|
3373
|
+
try {
|
|
3374
|
+
let total = plan.missing.reduce((n, m) => n + m.docs.length, 0), n = 0;
|
|
3375
|
+
for (let m of plan.missing) {
|
|
3376
|
+
let ok = 0, drafts = 0;
|
|
3377
|
+
for (let d of m.docs) {
|
|
3378
|
+
n++, setProgress(`Documents ${n}/${total} (${m.language.toUpperCase()})`);
|
|
3379
|
+
let source = await client.getDocument(d._id);
|
|
3380
|
+
if (source) try {
|
|
3381
|
+
(await createTranslatedVersion({
|
|
3382
|
+
client,
|
|
3383
|
+
config,
|
|
3384
|
+
type: d._type,
|
|
3385
|
+
schemaType: typeOf(d._type),
|
|
3386
|
+
source,
|
|
3387
|
+
sourceId: d._id,
|
|
3388
|
+
sourceLanguage: i18n.defaultLocale,
|
|
3389
|
+
language: m.language,
|
|
3390
|
+
ai: !0
|
|
3391
|
+
})).published ? ok++ : drafts++;
|
|
3392
|
+
} catch (cause) {
|
|
3393
|
+
lines.push(`${m.language.toUpperCase()} ${d._id}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
3394
|
+
}
|
|
3395
|
+
}
|
|
3396
|
+
m.docs.length && lines.unshift(`${m.language.toUpperCase()}: ${ok} published${drafts ? `, ${drafts} saved as drafts (texts to translate)` : ""}`);
|
|
3397
|
+
}
|
|
3398
|
+
for (let d of plan.defaults) {
|
|
3399
|
+
if (d.exists && !d.texts) continue;
|
|
3400
|
+
let src = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
|
|
3401
|
+
type: defaultsType,
|
|
3402
|
+
lang: d.from
|
|
3403
|
+
});
|
|
3404
|
+
if (!src) continue;
|
|
3405
|
+
let sourceLang = d.from;
|
|
3406
|
+
if (setProgress(`Component defaults (${d.language.toUpperCase()})`), !d.exists) {
|
|
3407
|
+
await createTranslatedVersion({
|
|
3408
|
+
client,
|
|
3409
|
+
config,
|
|
3410
|
+
type: defaultsType,
|
|
3411
|
+
schemaType: typeOf(defaultsType),
|
|
3412
|
+
source: src,
|
|
3413
|
+
sourceId: String(src._id),
|
|
3414
|
+
sourceLanguage: sourceLang,
|
|
3415
|
+
language: d.language,
|
|
3416
|
+
ai: !0
|
|
3417
|
+
}), lines.push(`Component defaults ${d.language.toUpperCase()}: created`);
|
|
3418
|
+
continue;
|
|
3419
|
+
}
|
|
3420
|
+
let target = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
|
|
3421
|
+
type: defaultsType,
|
|
3422
|
+
lang: d.language
|
|
3423
|
+
});
|
|
3424
|
+
if (!target) continue;
|
|
3425
|
+
let filled = await fillTranslation({
|
|
3426
|
+
config,
|
|
3427
|
+
schemaType: typeOf(defaultsType),
|
|
3428
|
+
source: src,
|
|
3429
|
+
target,
|
|
3430
|
+
sourceLanguage: sourceLang,
|
|
3431
|
+
language: d.language
|
|
3432
|
+
}), { _rev, _updatedAt, _createdAt, ...doc } = filled.document, tx = client.transaction().createOrReplace(doc), draft = await client.getDocument(`drafts.${String(target._id)}`);
|
|
3433
|
+
if (draft) {
|
|
3434
|
+
let { _rev: r2, _updatedAt: u2, _createdAt: c2, ...dd } = (await fillTranslation({
|
|
3435
|
+
config,
|
|
3436
|
+
schemaType: typeOf(defaultsType),
|
|
3437
|
+
source: src,
|
|
3438
|
+
target: draft,
|
|
3439
|
+
sourceLanguage: sourceLang,
|
|
3440
|
+
language: d.language
|
|
3441
|
+
})).document;
|
|
3442
|
+
tx.createOrReplace(dd);
|
|
3443
|
+
}
|
|
3444
|
+
await tx.commit(), await recordTrace(client, String(target._id), filled.written, {
|
|
3445
|
+
sourceId: String(src._id),
|
|
3446
|
+
sourceLanguage: sourceLang
|
|
3447
|
+
}), lines.push(`Component defaults ${d.language.toUpperCase()}: ${filled.translated} text${filled.translated > 1 ? "s" : ""} translated`);
|
|
3448
|
+
}
|
|
3449
|
+
} catch (cause) {
|
|
3450
|
+
lines.push(`Stopped: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
3451
|
+
} finally {
|
|
3452
|
+
setBusy(!1), setProgress(null), setReport(lines.length ? lines : ["Everything was already up to date."]), analyse();
|
|
3453
|
+
}
|
|
3454
|
+
};
|
|
3455
|
+
if (!i18n || !config.history) return null;
|
|
3456
|
+
let pendingDocs = plan?.missing.reduce((n, m) => n + m.docs.length, 0) ?? 0, pendingDefaults = plan?.defaults.filter((d) => !d.exists || d.texts).length ?? 0;
|
|
3457
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
|
|
3458
|
+
icon: TranslateIcon,
|
|
3459
|
+
text: "Languages",
|
|
3460
|
+
mode: "ghost",
|
|
3461
|
+
fontSize: 1,
|
|
3462
|
+
padding: 2,
|
|
3463
|
+
onClick: () => {
|
|
3464
|
+
setOpen(!0), analyse();
|
|
3465
|
+
}
|
|
3466
|
+
}), open && /* @__PURE__ */ jsx(Dialog, {
|
|
3467
|
+
id: "ncf-languages",
|
|
3468
|
+
header: "Languages",
|
|
3469
|
+
width: 1,
|
|
3470
|
+
onClose: () => !busy && setOpen(!1),
|
|
3471
|
+
children: /* @__PURE__ */ jsxs(Stack, {
|
|
3472
|
+
gap: 4,
|
|
3473
|
+
padding: 4,
|
|
3474
|
+
children: [
|
|
3475
|
+
/* @__PURE__ */ jsxs(Text, {
|
|
3476
|
+
size: 1,
|
|
3477
|
+
muted: !0,
|
|
3478
|
+
children: [
|
|
3479
|
+
"Brings every language to the level of the main language (",
|
|
3480
|
+
i18n.defaultLocale.toUpperCase(),
|
|
3481
|
+
"): missing pages and documents are created, translated with AI and published; component defaults are translated from",
|
|
3482
|
+
" ",
|
|
3483
|
+
i18n.defaultsSourceLocale.toUpperCase(),
|
|
3484
|
+
". Texts already translated (even by hand) are never changed."
|
|
3485
|
+
]
|
|
3486
|
+
}),
|
|
3487
|
+
plan ? /* @__PURE__ */ jsxs(Stack, {
|
|
3488
|
+
gap: 3,
|
|
3489
|
+
children: [plan.missing.map((m) => /* @__PURE__ */ jsx(Card, {
|
|
3490
|
+
padding: 3,
|
|
3491
|
+
radius: 2,
|
|
3492
|
+
border: !0,
|
|
3493
|
+
tone: m.docs.length ? "caution" : "positive",
|
|
3494
|
+
children: /* @__PURE__ */ jsxs(Text, {
|
|
3495
|
+
size: 1,
|
|
3496
|
+
children: [
|
|
3497
|
+
m.language.toUpperCase(),
|
|
3498
|
+
": ",
|
|
3499
|
+
m.docs.length ? `${m.docs.length} document${m.docs.length > 1 ? "s" : ""} without a version` : "all documents have a version"
|
|
3500
|
+
]
|
|
3501
|
+
})
|
|
3502
|
+
}, m.language)), plan.defaults.map((d) => /* @__PURE__ */ jsx(Card, {
|
|
3503
|
+
padding: 3,
|
|
3504
|
+
radius: 2,
|
|
3505
|
+
border: !0,
|
|
3506
|
+
tone: !d.exists || d.texts ? "caution" : "positive",
|
|
3507
|
+
children: /* @__PURE__ */ jsxs(Text, {
|
|
3508
|
+
size: 1,
|
|
3509
|
+
children: [
|
|
3510
|
+
"Component defaults ",
|
|
3511
|
+
d.language.toUpperCase(),
|
|
3512
|
+
":",
|
|
3513
|
+
" ",
|
|
3514
|
+
d.exists ? d.texts ? `${d.texts} text${d.texts > 1 ? "s" : ""} to translate` : "translated" : "missing (will be created)"
|
|
3515
|
+
]
|
|
3516
|
+
})
|
|
3517
|
+
}, `d-${d.language}`))]
|
|
3518
|
+
}) : /* @__PURE__ */ jsxs(Flex, {
|
|
3519
|
+
align: "center",
|
|
3520
|
+
gap: 2,
|
|
3521
|
+
children: [/* @__PURE__ */ jsx(Spinner, { muted: !0 }), /* @__PURE__ */ jsx(Text, {
|
|
3522
|
+
size: 1,
|
|
3523
|
+
muted: !0,
|
|
3524
|
+
children: "Checking…"
|
|
3525
|
+
})]
|
|
3526
|
+
}),
|
|
3527
|
+
progress && /* @__PURE__ */ jsxs(Flex, {
|
|
3528
|
+
align: "center",
|
|
3529
|
+
gap: 2,
|
|
3530
|
+
children: [/* @__PURE__ */ jsx(Spinner, { muted: !0 }), /* @__PURE__ */ jsx(Text, {
|
|
3531
|
+
size: 1,
|
|
3532
|
+
children: progress
|
|
3533
|
+
})]
|
|
3534
|
+
}),
|
|
3535
|
+
report && /* @__PURE__ */ jsx(Card, {
|
|
3536
|
+
padding: 3,
|
|
3537
|
+
radius: 2,
|
|
3538
|
+
tone: "primary",
|
|
3539
|
+
children: /* @__PURE__ */ jsx(Stack, {
|
|
3540
|
+
gap: 2,
|
|
3541
|
+
children: report.map((line, i) => /* @__PURE__ */ jsx(Text, {
|
|
3542
|
+
size: 1,
|
|
3543
|
+
children: line
|
|
3544
|
+
}, i))
|
|
3545
|
+
})
|
|
3546
|
+
}),
|
|
3547
|
+
/* @__PURE__ */ jsxs(Flex, {
|
|
3548
|
+
justify: "flex-end",
|
|
3549
|
+
gap: 2,
|
|
3550
|
+
children: [/* @__PURE__ */ jsx(Button, {
|
|
3551
|
+
text: "Close",
|
|
3552
|
+
mode: "ghost",
|
|
3553
|
+
disabled: busy,
|
|
3554
|
+
onClick: () => setOpen(!1)
|
|
3555
|
+
}), /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Button, {
|
|
3556
|
+
tone: "primary",
|
|
3557
|
+
text: busy ? "Working…" : "Translate with AI and publish",
|
|
3558
|
+
disabled: busy || !plan || !pendingDocs && !pendingDefaults,
|
|
3559
|
+
onClick: () => void run()
|
|
3560
|
+
}) })]
|
|
3561
|
+
})
|
|
3562
|
+
]
|
|
2903
3563
|
})
|
|
2904
|
-
})
|
|
3564
|
+
})] });
|
|
2905
3565
|
}
|
|
2906
3566
|
/**
|
|
2907
3567
|
* Nombre de champs « À traduire » par page (id publié), tenu à jour en direct.
|
|
@@ -5551,6 +6211,13 @@ function PagesTool() {
|
|
|
5551
6211
|
},
|
|
5552
6212
|
children: /* @__PURE__ */ jsx(SharePreview, {})
|
|
5553
6213
|
}),
|
|
6214
|
+
/* @__PURE__ */ jsx(Box, {
|
|
6215
|
+
style: {
|
|
6216
|
+
flex: "none",
|
|
6217
|
+
paddingBottom: 2
|
|
6218
|
+
},
|
|
6219
|
+
children: /* @__PURE__ */ jsx(LanguagesSync, {})
|
|
6220
|
+
}),
|
|
5554
6221
|
view === "list" && /* @__PURE__ */ jsx(Box, {
|
|
5555
6222
|
style: {
|
|
5556
6223
|
flex: "none",
|
|
@@ -6788,7 +7455,7 @@ function flatten(value, prefix = "", out = /* @__PURE__ */ new Map()) {
|
|
|
6788
7455
|
}
|
|
6789
7456
|
return prefix && out.set(prefix, value), out;
|
|
6790
7457
|
}
|
|
6791
|
-
const same$
|
|
7458
|
+
const same$1 = (a, b) => a === b || Number.isNaN(a) && Number.isNaN(b) || JSON.stringify(a) === JSON.stringify(b);
|
|
6792
7459
|
/**
|
|
6793
7460
|
* Modifications entre deux états, triées par chemin.
|
|
6794
7461
|
*
|
|
@@ -6801,7 +7468,7 @@ function diffDocuments(before, after) {
|
|
|
6801
7468
|
for (let path of paths) {
|
|
6802
7469
|
let had = left.has(path), has = right.has(path), valueBefore = left.get(path), valueAfter = right.get(path);
|
|
6803
7470
|
if (had && has) {
|
|
6804
|
-
same$
|
|
7471
|
+
same$1(valueBefore, valueAfter) || changes.push({
|
|
6805
7472
|
path,
|
|
6806
7473
|
kind: "changed",
|
|
6807
7474
|
before: valueBefore,
|
|
@@ -6884,27 +7551,27 @@ const isTextChange = (before, after) => typeof before == "string" && typeof afte
|
|
|
6884
7551
|
"_createdAt",
|
|
6885
7552
|
"_id",
|
|
6886
7553
|
"_type"
|
|
6887
|
-
]), isObject = (v) => typeof v == "object" && !!v && !Array.isArray(v), same
|
|
7554
|
+
]), isObject = (v) => typeof v == "object" && !!v && !Array.isArray(v), same = (a, b) => JSON.stringify(a) === JSON.stringify(b), keyed = (v) => Array.isArray(v) && v.every((item) => isObject(item) && typeof item._key == "string"), ABSENT = Symbol("absent");
|
|
6888
7555
|
function revert(current, before, after, path, out) {
|
|
6889
|
-
if (same
|
|
6890
|
-
if (same
|
|
7556
|
+
if (same(before, after)) return current;
|
|
7557
|
+
if (same(current, after)) return out.reverted++, before;
|
|
6891
7558
|
if (isObject(current) && isObject(before) && isObject(after)) {
|
|
6892
7559
|
let result = { ...current };
|
|
6893
7560
|
for (let key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) {
|
|
6894
7561
|
if (SYSTEM_KEYS.has(key)) continue;
|
|
6895
|
-
let v = revert(key in current ? current[key] : ABSENT
|
|
6896
|
-
v === ABSENT
|
|
7562
|
+
let v = revert(key in current ? current[key] : ABSENT, key in before ? before[key] : ABSENT, key in after ? after[key] : ABSENT, path ? `${path}.${key}` : key, out);
|
|
7563
|
+
v === ABSENT ? delete result[key] : result[key] = v;
|
|
6897
7564
|
}
|
|
6898
7565
|
return result;
|
|
6899
7566
|
}
|
|
6900
|
-
if (keyed
|
|
7567
|
+
if (keyed(current) && keyed(before) && keyed(after)) {
|
|
6901
7568
|
let result = [...current], at = (list, key) => list.findIndex((item) => item._key === key);
|
|
6902
7569
|
for (let key of /* @__PURE__ */ new Set([...before.map((i) => i._key), ...after.map((i) => i._key)])) {
|
|
6903
7570
|
let b = before[at(before, key)], a = after[at(after, key)], index = at(result, key), label = `${path}[${key}]`;
|
|
6904
7571
|
if (index >= 0) {
|
|
6905
|
-
let v = revert(result[index], b ?? ABSENT
|
|
6906
|
-
v === ABSENT
|
|
6907
|
-
} else b && !a ? (result.splice(Math.min(at(before, key), result.length), 0, b), out.reverted++) : b && a && !same
|
|
7572
|
+
let v = revert(result[index], b ?? ABSENT, a ?? ABSENT, label, out);
|
|
7573
|
+
v === ABSENT ? result.splice(index, 1) : result[index] = v;
|
|
7574
|
+
} else b && !a ? (result.splice(Math.min(at(before, key), result.length), 0, b), out.reverted++) : b && a && !same(a, b) && out.conflicts.push(label);
|
|
6908
7575
|
}
|
|
6909
7576
|
return result;
|
|
6910
7577
|
}
|
|
@@ -7593,92 +8260,6 @@ function DesignSystemTool() {
|
|
|
7593
8260
|
})
|
|
7594
8261
|
});
|
|
7595
8262
|
}
|
|
7596
|
-
const isObj$1 = (v) => typeof v == "object" && !!v && !Array.isArray(v);
|
|
7597
|
-
/** Textes d'une valeur, dans l'ordre. */
|
|
7598
|
-
function collectTexts$1(value) {
|
|
7599
|
-
if (typeof value == "string") return [value];
|
|
7600
|
-
if (!Array.isArray(value)) return [];
|
|
7601
|
-
let out = [];
|
|
7602
|
-
for (let item of value) if (typeof item == "string") out.push(item);
|
|
7603
|
-
else if (isObj$1(item) && Array.isArray(item.children)) for (let child of item.children) isObj$1(child) && typeof child.text == "string" && out.push(child.text);
|
|
7604
|
-
return out;
|
|
7605
|
-
}
|
|
7606
|
-
/** La même valeur avec ses textes remplacés (dans l'ordre de `collectTexts`). */
|
|
7607
|
-
function replaceTexts(value, texts) {
|
|
7608
|
-
let i = 0, next = () => texts[i++] ?? "";
|
|
7609
|
-
return typeof value == "string" ? next() : Array.isArray(value) ? value.map((item) => typeof item == "string" ? next() : isObj$1(item) && Array.isArray(item.children) ? {
|
|
7610
|
-
...item,
|
|
7611
|
-
children: item.children.map((child) => isObj$1(child) && typeof child.text == "string" ? {
|
|
7612
|
-
...child,
|
|
7613
|
-
text: next()
|
|
7614
|
-
} : child)
|
|
7615
|
-
} : item) : value;
|
|
7616
|
-
}
|
|
7617
|
-
/** `sections[a].title` → segments (`[x]` : clé d'élément de liste, ou rang). */
|
|
7618
|
-
function parsePathKey(path) {
|
|
7619
|
-
let out = [];
|
|
7620
|
-
for (let m of path.matchAll(/([^.[\]]+)|\[([^\]]+)\]/g)) out.push(m[1] === void 0 ? { item: m[2] } : { field: m[1] });
|
|
7621
|
-
return out;
|
|
7622
|
-
}
|
|
7623
|
-
function itemOf(list, key) {
|
|
7624
|
-
return list.find((i) => isObj$1(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : void 0);
|
|
7625
|
-
}
|
|
7626
|
-
/** Valeur d'un document au chemin `sections[a].title`. */
|
|
7627
|
-
function valueAtKey(doc, path) {
|
|
7628
|
-
let cur = doc;
|
|
7629
|
-
for (let seg of parsePathKey(path)) {
|
|
7630
|
-
if (cur == null) return;
|
|
7631
|
-
cur = "field" in seg ? isObj$1(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0;
|
|
7632
|
-
}
|
|
7633
|
-
return cur;
|
|
7634
|
-
}
|
|
7635
|
-
/** Écrit `value` au chemin dans `doc` (modifié sur place). Faux si le chemin n'existe pas. */
|
|
7636
|
-
function setAtKey(doc, path, value) {
|
|
7637
|
-
let segs = parsePathKey(path), cur = doc;
|
|
7638
|
-
for (let n = 0; n < segs.length - 1; n++) {
|
|
7639
|
-
let seg = segs[n];
|
|
7640
|
-
if (cur = "field" in seg ? isObj$1(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0, cur == null) return !1;
|
|
7641
|
-
}
|
|
7642
|
-
let last = segs[segs.length - 1];
|
|
7643
|
-
return !last || !("field" in last) || !isObj$1(cur) ? !1 : (cur[last.field] = value, !0);
|
|
7644
|
-
}
|
|
7645
|
-
const MESSAGES = {
|
|
7646
|
-
daily_limit: "Daily AI translation limit reached for this project.",
|
|
7647
|
-
project_inactive: "This project is not active in the NCF kit.",
|
|
7648
|
-
bad_key: "This project is not registered in the NCF kit (npx ncf-kit setup).",
|
|
7649
|
-
not_configured: "AI translation is not configured on the NCF kit service.",
|
|
7650
|
-
too_long: "Text too long to translate at once."
|
|
7651
|
-
};
|
|
7652
|
-
async function call(service, from, to, texts) {
|
|
7653
|
-
let response = await fetch(`${service.endpoint}/translate`, {
|
|
7654
|
-
method: "POST",
|
|
7655
|
-
headers: { "content-type": "application/json" },
|
|
7656
|
-
body: JSON.stringify({
|
|
7657
|
-
key: service.projectKey,
|
|
7658
|
-
from,
|
|
7659
|
-
to,
|
|
7660
|
-
texts
|
|
7661
|
-
})
|
|
7662
|
-
}), body = await response.json().catch(() => ({}));
|
|
7663
|
-
if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length) throw Error(MESSAGES[body.error ?? ""] ?? `AI translation failed (${body.error ?? response.status}).`);
|
|
7664
|
-
return body.texts;
|
|
7665
|
-
}
|
|
7666
|
-
/**
|
|
7667
|
-
* Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to` :
|
|
7668
|
-
* mêmes valeurs, textes traduits. Découpe en lots si besoin.
|
|
7669
|
-
*/
|
|
7670
|
-
async function translateValues(service, from, to, values) {
|
|
7671
|
-
let perValue = values.map((v) => collectTexts$1(v)), all = perValue.flat(), translated = [], batch = [], size = 0, flush = async () => {
|
|
7672
|
-
batch.length && (translated.push(...await call(service, from, to, batch)), batch = [], size = 0);
|
|
7673
|
-
};
|
|
7674
|
-
for (let text of all) (batch.length >= 250 || size + text.length > 3e4) && await flush(), batch.push(text), size += text.length;
|
|
7675
|
-
await flush();
|
|
7676
|
-
let offset = 0;
|
|
7677
|
-
return values.map((value, n) => {
|
|
7678
|
-
let count = perValue[n].length, slice = translated.slice(offset, offset + count);
|
|
7679
|
-
return offset += count, count ? replaceTexts(value, slice) : value;
|
|
7680
|
-
});
|
|
7681
|
-
}
|
|
7682
8263
|
const store$1 = /* @__PURE__ */ new Map();
|
|
7683
8264
|
function entryFor$1(client, type, languageField, language) {
|
|
7684
8265
|
let { projectId, dataset } = client.config(), key = `${projectId}:${dataset}:${type}:${language ?? ""}`, entry = store$1.get(key);
|
|
@@ -8212,7 +8793,13 @@ function withTranslationTodo(Inner, config) {
|
|
|
8212
8793
|
if (!collectTexts$1(value).some((t) => t.trim())) props.onChange(unset());
|
|
8213
8794
|
else {
|
|
8214
8795
|
let [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value]);
|
|
8215
|
-
props.onChange(set(translated))
|
|
8796
|
+
props.onChange(set(translated)), id && await recordTrace(client, id, [{
|
|
8797
|
+
path: key,
|
|
8798
|
+
value: translated
|
|
8799
|
+
}], {
|
|
8800
|
+
sourceId: todo.sourceId,
|
|
8801
|
+
sourceLanguage: todo.sourceLanguage
|
|
8802
|
+
});
|
|
8216
8803
|
}
|
|
8217
8804
|
await client.patch(todo._id).set({ paths: (todo.paths ?? []).filter((p) => p !== key) }).commit();
|
|
8218
8805
|
} catch (cause) {
|
|
@@ -8415,121 +9002,6 @@ function withLanguageMismatch(Inner, config) {
|
|
|
8415
9002
|
}
|
|
8416
9003
|
return LanguageMismatch;
|
|
8417
9004
|
}
|
|
8418
|
-
const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
|
|
8419
|
-
"image",
|
|
8420
|
-
"file",
|
|
8421
|
-
"reference",
|
|
8422
|
-
"crossDatasetReference",
|
|
8423
|
-
"slug",
|
|
8424
|
-
"geopoint",
|
|
8425
|
-
"url",
|
|
8426
|
-
"email",
|
|
8427
|
-
"date",
|
|
8428
|
-
"datetime",
|
|
8429
|
-
"number",
|
|
8430
|
-
"boolean"
|
|
8431
|
-
]), SKIP_KEYS = /* @__PURE__ */ new Set(["language", "slug"]), isObj = (v) => typeof v == "object" && !!v && !Array.isArray(v), same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null), keyed = (v) => Array.isArray(v) && v.length > 0 && v.every((i) => isObj(i) && typeof i._key == "string");
|
|
8432
|
-
function typeNames(t) {
|
|
8433
|
-
let out = [];
|
|
8434
|
-
for (let c = t; c; c = c.type) c.name && out.push(c.name);
|
|
8435
|
-
return out;
|
|
8436
|
-
}
|
|
8437
|
-
/** Nature d'un champ d'après son schéma (et sa valeur, faute de schéma). */
|
|
8438
|
-
function kindOf(t, value) {
|
|
8439
|
-
if (t) {
|
|
8440
|
-
if (typeNames(t).some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return "value";
|
|
8441
|
-
if (t.jsonType === "array") {
|
|
8442
|
-
let of = t.of ?? [];
|
|
8443
|
-
if (of.some((m) => typeNames(m).includes("block"))) return "text";
|
|
8444
|
-
if (of.some((m) => m.jsonType === "object" || typeNames(m).includes("object"))) return "list";
|
|
8445
|
-
let prim = of[0];
|
|
8446
|
-
return prim && prim.jsonType === "string" && !prim.options?.list?.length ? "text" : "value";
|
|
8447
|
-
}
|
|
8448
|
-
return t.jsonType === "object" ? "object" : t.jsonType === "string" ? t.options?.list?.length ? "value" : "text" : "value";
|
|
8449
|
-
}
|
|
8450
|
-
return keyed(value) ? "list" : isObj(value) ? "object" : "value";
|
|
8451
|
-
}
|
|
8452
|
-
function fieldType(t, name) {
|
|
8453
|
-
for (let c = t; c; c = c.type) {
|
|
8454
|
-
let f = c.fields?.find((x) => x.name === name);
|
|
8455
|
-
if (f) return f.type;
|
|
8456
|
-
}
|
|
8457
|
-
}
|
|
8458
|
-
function itemType(t, item) {
|
|
8459
|
-
let of;
|
|
8460
|
-
for (let c = t; c && !of; c = c.type) of = c.of;
|
|
8461
|
-
if (of?.length) return of.find((m) => typeNames(m).includes(item._type)) ?? (of.length === 1 ? of[0] : void 0);
|
|
8462
|
-
}
|
|
8463
|
-
/** Tous les textes d'un élément ajouté : à traduire. */
|
|
8464
|
-
function collectTexts(value, t, path, acc) {
|
|
8465
|
-
let kind = kindOf(t, value);
|
|
8466
|
-
if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
|
|
8467
|
-
else if (kind === "object" && isObj(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
|
|
8468
|
-
else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
|
|
8469
|
-
}
|
|
8470
|
-
const ABSENT = Symbol("absent");
|
|
8471
|
-
function merge(target, before, after, t, path, acc) {
|
|
8472
|
-
if (same(before, after)) return target === void 0 ? ABSENT : target;
|
|
8473
|
-
let kind = kindOf(t, after ?? before);
|
|
8474
|
-
if (kind === "text") return after == null || after === "" ? (target != null && target !== "" && acc.toTranslate.push(path), target === void 0 ? ABSENT : target) : (acc.toTranslate.push(path), target == null || target === "" || same(target, before) ? after : target);
|
|
8475
|
-
if (kind === "value") return acc.copied.push(path), after === void 0 ? ABSENT : after;
|
|
8476
|
-
if (kind === "object") {
|
|
8477
|
-
if (!isObj(after)) return acc.copied.push(path), after === void 0 ? ABSENT : after;
|
|
8478
|
-
let base = isObj(target) ? { ...target } : { _type: after._type }, b = isObj(before) ? before : {};
|
|
8479
|
-
for (let k of /* @__PURE__ */ new Set([...Object.keys(b), ...Object.keys(after)])) {
|
|
8480
|
-
if (k.startsWith("_") || SKIP_KEYS.has(k)) continue;
|
|
8481
|
-
let v = merge(base[k], b[k], after[k], fieldType(t, k), path ? `${path}.${k}` : k, acc);
|
|
8482
|
-
v === ABSENT ? delete base[k] : base[k] = v;
|
|
8483
|
-
}
|
|
8484
|
-
return base;
|
|
8485
|
-
}
|
|
8486
|
-
let tgt = Array.isArray(target) ? target.filter(isObj) : [], bef = Array.isArray(before) ? before.filter(isObj) : [], aft = Array.isArray(after) ? after.filter(isObj) : [], byKey = (list) => new Map(list.map((i) => [i._key, i])), tMap = byKey(tgt), bMap = byKey(bef), aMap = byKey(aft), result = [];
|
|
8487
|
-
for (let item of aft) {
|
|
8488
|
-
let key = item._key, it = itemType(t, item);
|
|
8489
|
-
if (tMap.has(key)) {
|
|
8490
|
-
let merged = merge(tMap.get(key), bMap.get(key), item, it, `${path}[${key}]`, acc);
|
|
8491
|
-
result.push(merged === ABSENT ? item : merged);
|
|
8492
|
-
} else result.push(structuredClone(item)), acc.added++, collectTexts(item, it, `${path}[${key}]`, acc);
|
|
8493
|
-
}
|
|
8494
|
-
for (let key of bMap.keys()) !aMap.has(key) && tMap.has(key) && acc.removed++;
|
|
8495
|
-
tgt.forEach((item, index) => {
|
|
8496
|
-
let key = item._key;
|
|
8497
|
-
if (bMap.has(key) || aMap.has(key)) return;
|
|
8498
|
-
let prev = tgt.slice(0, index).reverse().find((p) => result.some((r) => r._key === p._key)), at = prev ? result.findIndex((r) => r._key === prev._key) + 1 : 0;
|
|
8499
|
-
result.splice(at, 0, item);
|
|
8500
|
-
});
|
|
8501
|
-
let common = (list) => list.map((i) => i._key).filter((k) => tMap.has(k) && aMap.has(k));
|
|
8502
|
-
return same(common(tgt), common(aft)) || (acc.moved = !0), result;
|
|
8503
|
-
}
|
|
8504
|
-
/**
|
|
8505
|
-
* Applique la modification `before` → `after` (version principale) à `target`
|
|
8506
|
-
* (brouillon ou version publiée de la traduction). `documentType` : schéma du
|
|
8507
|
-
* document, pour distinguer textes et valeurs.
|
|
8508
|
-
*/
|
|
8509
|
-
function propagate(target, before, after, documentType) {
|
|
8510
|
-
let acc = {
|
|
8511
|
-
toTranslate: [],
|
|
8512
|
-
copied: [],
|
|
8513
|
-
added: 0,
|
|
8514
|
-
removed: 0,
|
|
8515
|
-
moved: !1
|
|
8516
|
-
}, merged = merge(target ?? {}, before ?? {}, after, documentType, "", acc);
|
|
8517
|
-
return {
|
|
8518
|
-
document: {
|
|
8519
|
-
...target ?? {},
|
|
8520
|
-
...isObj(merged) ? merged : {}
|
|
8521
|
-
},
|
|
8522
|
-
...acc
|
|
8523
|
-
};
|
|
8524
|
-
}
|
|
8525
|
-
/** La propagation changerait-elle quelque chose ? */
|
|
8526
|
-
function hasChanges(r) {
|
|
8527
|
-
return r.toTranslate.length > 0 || r.copied.length > 0 || r.added > 0 || r.removed > 0 || r.moved;
|
|
8528
|
-
}
|
|
8529
|
-
/** Slug d'URL depuis un titre : sans accents, minuscules, tirets. */
|
|
8530
|
-
function slugify(input, maxLength = 96) {
|
|
8531
|
-
return input.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxLength).replace(/-+$/g, "");
|
|
8532
|
-
}
|
|
8533
9005
|
/**
|
|
8534
9006
|
* Publier la version PRINCIPALE d'une page :
|
|
8535
9007
|
* - page déjà publiée qui a des traductions : « Propagate to other languages? »
|
|
@@ -8570,7 +9042,8 @@ function withPropagation(Publish, config, masterLocale, options = {}) {
|
|
|
8570
9042
|
language,
|
|
8571
9043
|
id: null,
|
|
8572
9044
|
result,
|
|
8573
|
-
selected: !0
|
|
9045
|
+
selected: !0,
|
|
9046
|
+
edited: []
|
|
8574
9047
|
}))
|
|
8575
9048
|
});
|
|
8576
9049
|
}).catch(() => {});
|
|
@@ -8598,24 +9071,22 @@ function withPropagation(Publish, config, masterLocale, options = {}) {
|
|
|
8598
9071
|
};
|
|
8599
9072
|
return Wrapped.action = Publish.action, Wrapped;
|
|
8600
9073
|
}
|
|
8601
|
-
async function translationsOf(client, id) {
|
|
8602
|
-
return (await client.fetch("*[_type == \"translation.metadata\" && references($id)][0].translations[]{language, \"key\": _key, \"id\": value._ref}", { id }) ?? []).map((t) => ({
|
|
8603
|
-
language: t.language ?? t.key ?? "",
|
|
8604
|
-
id: t.id ?? ""
|
|
8605
|
-
})).filter((t) => t.language && t.id);
|
|
8606
|
-
}
|
|
8607
9074
|
async function findTargets(client, id, source, before, after, documentType) {
|
|
8608
9075
|
let list = [];
|
|
8609
9076
|
for (let t of await translationsOf(client, id)) {
|
|
8610
9077
|
if (t.id === id || t.language === source) continue;
|
|
8611
9078
|
let target = await client.getDocument(`drafts.${t.id}`) ?? await client.getDocument(t.id) ?? null;
|
|
8612
9079
|
if (!target) continue;
|
|
8613
|
-
let result = propagate(target, before, after, documentType)
|
|
9080
|
+
let result = propagate(target, before, after, documentType), trace = await readTrace(client, t.id), edited = result.toTranslate.filter((path) => {
|
|
9081
|
+
let src = valueAtKey(after, path);
|
|
9082
|
+
return collectTexts$1(src).some((x) => x.trim()) ? !isReplaceable(valueAtKey(result.document, path), src, path, trace, (v) => !collectTexts$1(v).some((x) => x.trim())) : !1;
|
|
9083
|
+
});
|
|
8614
9084
|
list.push({
|
|
8615
9085
|
language: t.language,
|
|
8616
9086
|
id: t.id,
|
|
8617
9087
|
result,
|
|
8618
|
-
selected: hasChanges(result)
|
|
9088
|
+
selected: hasChanges(result),
|
|
9089
|
+
edited
|
|
8619
9090
|
});
|
|
8620
9091
|
}
|
|
8621
9092
|
return list;
|
|
@@ -8624,59 +9095,45 @@ async function findMissing(client, id, source, locales) {
|
|
|
8624
9095
|
let existing = new Set((await translationsOf(client, id)).map((t) => t.language));
|
|
8625
9096
|
return locales.filter((l) => l !== source && !existing.has(l));
|
|
8626
9097
|
}
|
|
8627
|
-
const randomId = () => typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
|
|
8628
|
-
/** Relie les nouvelles versions à la page (translation.metadata de document-internationalization). */
|
|
8629
|
-
async function linkTranslations(client, sourceId, sourceLanguage, type, created) {
|
|
8630
|
-
if (!created.length) return;
|
|
8631
|
-
let item = (language, ref) => ({
|
|
8632
|
-
_key: language,
|
|
8633
|
-
_type: "internationalizedArrayReferenceValue",
|
|
8634
|
-
language,
|
|
8635
|
-
value: {
|
|
8636
|
-
_type: "reference",
|
|
8637
|
-
_ref: ref,
|
|
8638
|
-
_weak: !0,
|
|
8639
|
-
_strengthenOnPublish: { type }
|
|
8640
|
-
}
|
|
8641
|
-
}), meta = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0]{_id}", { id: sourceId });
|
|
8642
|
-
meta ? await client.patch(meta._id).setIfMissing({ translations: [] }).append("translations", created.map((c) => item(c.language, c.id))).commit() : await client.create({
|
|
8643
|
-
_id: randomId(),
|
|
8644
|
-
_type: "translation.metadata",
|
|
8645
|
-
schemaTypes: [type],
|
|
8646
|
-
translations: [item(sourceLanguage, sourceId), ...created.map((c) => item(c.language, c.id))]
|
|
8647
|
-
});
|
|
8648
|
-
}
|
|
8649
9098
|
function PropagateDialog(props) {
|
|
8650
|
-
let { config, id, type, mode, after, onDone } = props, client = useKitClient(), field = config.i18n?.field ?? "language", source = String(after[field] ?? ""),
|
|
9099
|
+
let { config, id, type, mode, after, onDone } = props, client = useKitClient(), schema = useSchema(), field = config.i18n?.field ?? "language", source = String(after[field] ?? ""), [targets, setTargets] = useState(props.targets), [busy, setBusy] = useState(!1), toast = useToast(), [error, setError] = useState(null), [ai, setAi] = useState(!!config.history), [overwrite, setOverwrite] = useState(!1), editedCount = targets.reduce((n, t) => n + (t.selected ? t.edited.length : 0), 0), hasTexts = targets.some((t) => t.result.toTranslate.length), apply = async () => {
|
|
8651
9100
|
setBusy(!0), setError(null);
|
|
8652
9101
|
try {
|
|
8653
|
-
let published = [], drafted = [],
|
|
9102
|
+
let published = [], drafted = [], aiError = null;
|
|
8654
9103
|
for (let t of targets) {
|
|
8655
9104
|
if (!t.selected) continue;
|
|
8656
|
-
let { _id, _rev, _createdAt, _updatedAt, ...doc } = structuredClone(t.result.document), targetId = t.id ?? randomId(), remaining = t.result.toTranslate, translatedOk = !remaining.length;
|
|
8657
|
-
if (ai && config.history && remaining.length) try {
|
|
8658
|
-
let toSend = remaining.map((path) => valueAtKey(after, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), translated = await translateValues(config.history, source, t.language, toSend.map((v) => v ?? ""));
|
|
8659
|
-
remaining = remaining.filter((path, n) => !setAtKey(doc, path, toSend[n] === void 0 ? void 0 : translated[n])), translatedOk = !remaining.length;
|
|
8660
|
-
} catch (cause) {
|
|
8661
|
-
aiError = cause instanceof Error ? cause.message : String(cause);
|
|
8662
|
-
}
|
|
8663
9105
|
if (mode === "create") {
|
|
8664
|
-
|
|
8665
|
-
|
|
8666
|
-
|
|
8667
|
-
|
|
8668
|
-
|
|
8669
|
-
|
|
8670
|
-
|
|
8671
|
-
|
|
8672
|
-
|
|
8673
|
-
|
|
8674
|
-
|
|
8675
|
-
|
|
8676
|
-
|
|
9106
|
+
let created = await createTranslatedVersion({
|
|
9107
|
+
client,
|
|
9108
|
+
config,
|
|
9109
|
+
type,
|
|
9110
|
+
schemaType: schema.get(type),
|
|
9111
|
+
source: after,
|
|
9112
|
+
sourceId: id,
|
|
9113
|
+
sourceLanguage: source,
|
|
9114
|
+
language: t.language,
|
|
9115
|
+
ai
|
|
9116
|
+
});
|
|
9117
|
+
created.aiError && (aiError = created.aiError), (created.published ? published : drafted).push(t.language.toUpperCase());
|
|
9118
|
+
continue;
|
|
9119
|
+
}
|
|
9120
|
+
let { _id, _rev, _createdAt, _updatedAt, ...doc } = structuredClone(t.result.document), targetId = t.id, kept = overwrite ? [] : t.edited, remaining = t.result.toTranslate, failed = !1, written = [];
|
|
9121
|
+
if (ai && config.history && remaining.length) {
|
|
9122
|
+
let toDo = remaining.filter((p) => !kept.includes(p));
|
|
9123
|
+
try {
|
|
9124
|
+
let toSend = toDo.map((path) => valueAtKey(after, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), translated = await translateValues(config.history, source, t.language, toSend.map((v) => v ?? "")), done = /* @__PURE__ */ new Set();
|
|
9125
|
+
toDo.forEach((path, n) => {
|
|
9126
|
+
let value = toSend[n] === void 0 ? void 0 : translated[n];
|
|
9127
|
+
setAtKey(doc, path, value) && (done.add(path), value !== void 0 && written.push({
|
|
9128
|
+
path,
|
|
9129
|
+
value
|
|
9130
|
+
}));
|
|
9131
|
+
}), remaining = remaining.filter((p) => !done.has(p));
|
|
9132
|
+
} catch (cause) {
|
|
9133
|
+
failed = !0, aiError = cause instanceof Error ? cause.message : String(cause);
|
|
8677
9134
|
}
|
|
8678
9135
|
}
|
|
8679
|
-
let publish = ai &&
|
|
9136
|
+
let publish = ai && !failed && remaining.every((p) => kept.includes(p)), tx = client.transaction();
|
|
8680
9137
|
publish ? (tx.createOrReplace({
|
|
8681
9138
|
...doc,
|
|
8682
9139
|
_id: targetId,
|
|
@@ -8694,12 +9151,12 @@ function PropagateDialog(props) {
|
|
|
8694
9151
|
sourceId: id,
|
|
8695
9152
|
sourceLanguage: source,
|
|
8696
9153
|
paths
|
|
8697
|
-
}),
|
|
8698
|
-
|
|
8699
|
-
|
|
9154
|
+
}), await recordTrace(client, targetId, written, {
|
|
9155
|
+
sourceId: id,
|
|
9156
|
+
sourceLanguage: source
|
|
8700
9157
|
}), (publish ? published : drafted).push(t.language.toUpperCase());
|
|
8701
9158
|
}
|
|
8702
|
-
|
|
9159
|
+
toast.push({
|
|
8703
9160
|
status: aiError ? "warning" : "success",
|
|
8704
9161
|
title: [published.length ? `Published: ${published.join(", ")}` : "", drafted.length ? `Drafts: ${drafted.join(", ")}` : ""].filter(Boolean).join(" · "),
|
|
8705
9162
|
description: aiError ? `AI translation failed (${aiError}): saved as drafts, texts marked "To translate".` : drafted.length ? "Translate the fields marked \"To translate\", then publish each language." : "Translated with AI and published.",
|
|
@@ -8735,6 +9192,24 @@ function PropagateDialog(props) {
|
|
|
8735
9192
|
children: "Translate with AI and publish"
|
|
8736
9193
|
})]
|
|
8737
9194
|
}),
|
|
9195
|
+
mode === "update" && editedCount > 0 && /* @__PURE__ */ jsxs(Flex, {
|
|
9196
|
+
as: "label",
|
|
9197
|
+
align: "center",
|
|
9198
|
+
gap: 2,
|
|
9199
|
+
children: [/* @__PURE__ */ jsx(Checkbox, {
|
|
9200
|
+
checked: overwrite,
|
|
9201
|
+
onChange: () => setOverwrite(!overwrite)
|
|
9202
|
+
}), /* @__PURE__ */ jsxs(Text, {
|
|
9203
|
+
size: 1,
|
|
9204
|
+
children: [
|
|
9205
|
+
"Overwrite ",
|
|
9206
|
+
editedCount,
|
|
9207
|
+
" text",
|
|
9208
|
+
editedCount > 1 ? "s" : "",
|
|
9209
|
+
" edited by hand in other languages (kept otherwise, marked \"To translate\")"
|
|
9210
|
+
]
|
|
9211
|
+
})]
|
|
9212
|
+
}),
|
|
8738
9213
|
/* @__PURE__ */ jsx(Stack, {
|
|
8739
9214
|
gap: 3,
|
|
8740
9215
|
children: targets.map((t, index) => /* @__PURE__ */ jsx(Card, {
|
|
@@ -8759,10 +9234,10 @@ function PropagateDialog(props) {
|
|
|
8759
9234
|
size: 1,
|
|
8760
9235
|
weight: "semibold",
|
|
8761
9236
|
children: t.language.toUpperCase()
|
|
8762
|
-
}), /* @__PURE__ */
|
|
9237
|
+
}), /* @__PURE__ */ jsxs(Text, {
|
|
8763
9238
|
size: 1,
|
|
8764
9239
|
muted: !0,
|
|
8765
|
-
children: mode === "create" ? `New version (${t.result.toTranslate.length} texts)` : summary(t.result)
|
|
9240
|
+
children: [mode === "create" ? `New version (${t.result.toTranslate.length} texts)` : summary(t.result), t.edited.length ? ` · ${t.edited.length} edited by hand` : ""]
|
|
8766
9241
|
})]
|
|
8767
9242
|
})
|
|
8768
9243
|
})]
|