@nocode-factory/sanity-kit 2.18.0 → 2.20.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/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, Container, Flex, Grid, Select, Spinner, Stack, Tab, TabList, TabPanel, Text, TextArea, TextInput } from "@sanity/ui";
8
+ import { Badge, Box, Button, Card, Checkbox, Container, 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";
@@ -36,6 +36,7 @@ import { RefreshIcon } from "@sanity/icons/Refresh";
36
36
  import { RestoreIcon } from "@sanity/icons/Restore";
37
37
  import { UndoIcon } from "@sanity/icons/Undo";
38
38
  import { Tooltip } from "@sanity/ui/tooltip";
39
+ import { EyeClosedIcon } from "@sanity/icons/EyeClosed";
39
40
  const DEFAULT_PAGE_BUILDER_FIELD = "sections", DEFAULT_SLUG_FIELD = "slug", DEFAULT_TITLE_FIELD = "title", DEFAULT_NOINDEX_FIELDS = ["seo.noindex", "noindex"], DEFAULT_I18N = {
40
41
  field: "language",
41
42
  defaultLocale: "fr",
@@ -291,7 +292,42 @@ function useKitContext() {
291
292
  if (!value) throw Error("useKitContext doit être appelé dans un outil du plugin @nocode-factory/sanity-kit.");
292
293
  return value;
293
294
  }
294
- const useKitConfig = () => useKitContext().config, BOARD_LAYOUT_TYPE = "ncfBoardLayout", BOARD_LAYOUT_ID = "ncfBoardLayout", BOARD_NODE_TYPE = "ncfBoardNode", SECTION_NODE_TYPE = "ncfSectionNode", NODE_FIELD_TYPE = "ncfNodeField", COLUMN_TYPE = "ncfColumn", COLUMN_OPTION_TYPE = "ncfColumnOption", ANNOTATION_TYPE = "ncfAnnotation", NCF_HIDDEN_TYPES = [BOARD_LAYOUT_TYPE], boardNodeType = defineType({
295
+ const useKitConfig = () => useKitContext().config, TRANSLATION_TODO_TYPE = "ncfTranslationTodo", translationTodoId = (documentId) => `ncfTodo.${documentId.replace(/^drafts\./, "")}`, translationTodoType = defineType({
296
+ name: TRANSLATION_TODO_TYPE,
297
+ title: "À traduire (NCF)",
298
+ type: "document",
299
+ fields: [
300
+ defineField({
301
+ name: "documentId",
302
+ title: "Traduction",
303
+ type: "string",
304
+ readOnly: !0
305
+ }),
306
+ defineField({
307
+ name: "sourceId",
308
+ title: "Version principale",
309
+ type: "string",
310
+ readOnly: !0
311
+ }),
312
+ defineField({
313
+ name: "sourceLanguage",
314
+ title: "Langue principale",
315
+ type: "string",
316
+ readOnly: !0
317
+ }),
318
+ defineField({
319
+ name: "paths",
320
+ title: "Champs à traduire",
321
+ type: "array",
322
+ of: [{ type: "string" }],
323
+ readOnly: !0
324
+ })
325
+ ],
326
+ preview: {
327
+ select: { title: "documentId" },
328
+ prepare: ({ title }) => ({ title: `À traduire : ${title}` })
329
+ }
330
+ }), BOARD_LAYOUT_TYPE = "ncfBoardLayout", BOARD_LAYOUT_ID = "ncfBoardLayout", BOARD_NODE_TYPE = "ncfBoardNode", SECTION_NODE_TYPE = "ncfSectionNode", NODE_FIELD_TYPE = "ncfNodeField", COLUMN_TYPE = "ncfColumn", COLUMN_OPTION_TYPE = "ncfColumnOption", ANNOTATION_TYPE = "ncfAnnotation", NCF_HIDDEN_TYPES = [BOARD_LAYOUT_TYPE, TRANSLATION_TODO_TYPE], boardNodeType = defineType({
295
331
  name: BOARD_NODE_TYPE,
296
332
  title: "Position d'une page",
297
333
  type: "object",
@@ -565,6 +601,7 @@ const useKitConfig = () => useKitContext().config, BOARD_LAYOUT_TYPE = "ncfBoard
565
601
  ],
566
602
  preview: { prepare: () => ({ title: "Disposition du board (NCF)" }) }
567
603
  }),
604
+ translationTodoType,
568
605
  boardNodeType,
569
606
  sectionNodeType,
570
607
  nodeFieldType,
@@ -685,9 +722,9 @@ const STATUS_LABELS = {
685
722
  help: "En ligne, avec des modifications non publiées"
686
723
  },
687
724
  draft: {
688
- label: "Brouillon",
725
+ label: "Non publiée",
689
726
  tone: "default",
690
- help: "Jamais publiée : absente du site"
727
+ help: "Absente du site : jamais publiée, ou retirée du site (contenu conservé en brouillon)"
691
728
  }
692
729
  };
693
730
  /**
@@ -1380,7 +1417,7 @@ function explainGrantError(error) {
1380
1417
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1381
1418
  * le vérifie.
1382
1419
  */
1383
- const KIT_VERSION = "2.18.0";
1420
+ const KIT_VERSION = "2.20.0";
1384
1421
  /**
1385
1422
  * Signale ce Studio au service du kit, une fois par montage.
1386
1423
  *
@@ -1707,7 +1744,7 @@ function useKitUpdate() {
1707
1744
  !controller.signal.aborted && body?.version && setLatest(body.version);
1708
1745
  }).catch(() => {}), () => controller.abort();
1709
1746
  }, []);
1710
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.18.0") > 0);
1747
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.20.0") > 0);
1711
1748
  return {
1712
1749
  current: KIT_VERSION,
1713
1750
  latest,
@@ -6740,7 +6777,7 @@ function flatten(value, prefix = "", out = /* @__PURE__ */ new Map()) {
6740
6777
  }
6741
6778
  return prefix && out.set(prefix, value), out;
6742
6779
  }
6743
- const same$1 = (a, b) => a === b || Number.isNaN(a) && Number.isNaN(b) || JSON.stringify(a) === JSON.stringify(b);
6780
+ const same$2 = (a, b) => a === b || Number.isNaN(a) && Number.isNaN(b) || JSON.stringify(a) === JSON.stringify(b);
6744
6781
  /**
6745
6782
  * Modifications entre deux états, triées par chemin.
6746
6783
  *
@@ -6753,7 +6790,7 @@ function diffDocuments(before, after) {
6753
6790
  for (let path of paths) {
6754
6791
  let had = left.has(path), has = right.has(path), valueBefore = left.get(path), valueAfter = right.get(path);
6755
6792
  if (had && has) {
6756
- same$1(valueBefore, valueAfter) || changes.push({
6793
+ same$2(valueBefore, valueAfter) || changes.push({
6757
6794
  path,
6758
6795
  kind: "changed",
6759
6796
  before: valueBefore,
@@ -6836,27 +6873,27 @@ const isTextChange = (before, after) => typeof before == "string" && typeof afte
6836
6873
  "_createdAt",
6837
6874
  "_id",
6838
6875
  "_type"
6839
- ]), 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");
6876
+ ]), isObject = (v) => typeof v == "object" && !!v && !Array.isArray(v), same$1 = (a, b) => JSON.stringify(a) === JSON.stringify(b), keyed$1 = (v) => Array.isArray(v) && v.every((item) => isObject(item) && typeof item._key == "string"), ABSENT$1 = Symbol("absent");
6840
6877
  function revert(current, before, after, path, out) {
6841
- if (same(before, after)) return current;
6842
- if (same(current, after)) return out.reverted++, before;
6878
+ if (same$1(before, after)) return current;
6879
+ if (same$1(current, after)) return out.reverted++, before;
6843
6880
  if (isObject(current) && isObject(before) && isObject(after)) {
6844
6881
  let result = { ...current };
6845
6882
  for (let key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) {
6846
6883
  if (SYSTEM_KEYS.has(key)) continue;
6847
- 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);
6848
- v === ABSENT ? delete result[key] : result[key] = v;
6884
+ let v = revert(key in current ? current[key] : ABSENT$1, key in before ? before[key] : ABSENT$1, key in after ? after[key] : ABSENT$1, path ? `${path}.${key}` : key, out);
6885
+ v === ABSENT$1 ? delete result[key] : result[key] = v;
6849
6886
  }
6850
6887
  return result;
6851
6888
  }
6852
- if (keyed(current) && keyed(before) && keyed(after)) {
6889
+ if (keyed$1(current) && keyed$1(before) && keyed$1(after)) {
6853
6890
  let result = [...current], at = (list, key) => list.findIndex((item) => item._key === key);
6854
6891
  for (let key of /* @__PURE__ */ new Set([...before.map((i) => i._key), ...after.map((i) => i._key)])) {
6855
6892
  let b = before[at(before, key)], a = after[at(after, key)], index = at(result, key), label = `${path}[${key}]`;
6856
6893
  if (index >= 0) {
6857
- let v = revert(result[index], b ?? ABSENT, a ?? ABSENT, label, out);
6858
- v === ABSENT ? result.splice(index, 1) : result[index] = v;
6859
- } 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);
6894
+ let v = revert(result[index], b ?? ABSENT$1, a ?? ABSENT$1, label, out);
6895
+ v === ABSENT$1 ? result.splice(index, 1) : result[index] = v;
6896
+ } else b && !a ? (result.splice(Math.min(at(before, key), result.length), 0, b), out.reverted++) : b && a && !same$1(a, b) && out.conflicts.push(label);
6860
6897
  }
6861
6898
  return result;
6862
6899
  }
@@ -7545,14 +7582,14 @@ function DesignSystemTool() {
7545
7582
  })
7546
7583
  });
7547
7584
  }
7548
- const store = /* @__PURE__ */ new Map();
7549
- function entryFor(client, type, languageField, language) {
7550
- let { projectId, dataset } = client.config(), key = `${projectId}:${dataset}:${type}:${language ?? ""}`, entry = store.get(key);
7585
+ const store$1 = /* @__PURE__ */ new Map();
7586
+ function entryFor$1(client, type, languageField, language) {
7587
+ let { projectId, dataset } = client.config(), key = `${projectId}:${dataset}:${type}:${language ?? ""}`, entry = store$1.get(key);
7551
7588
  entry || (entry = {
7552
7589
  value: null,
7553
7590
  listeners: /* @__PURE__ */ new Set(),
7554
7591
  stop: null
7555
- }, store.set(key, entry));
7592
+ }, store$1.set(key, entry));
7556
7593
  let e = entry;
7557
7594
  if (!e.stop) {
7558
7595
  let filter = `_type == $type && ($language == null || !defined(${languageField}) || ${languageField} == $language)`, params = {
@@ -7571,7 +7608,7 @@ function entryFor(client, type, languageField, language) {
7571
7608
  return [key, e];
7572
7609
  }
7573
7610
  function useComponentDefaults(client, type, languageField, language) {
7574
- let [, entry] = entryFor(client, type, languageField, language), value = useSyncExternalStore((listener) => (entry.listeners.add(listener), () => {
7611
+ let [, entry] = entryFor$1(client, type, languageField, language), value = useSyncExternalStore((listener) => (entry.listeners.add(listener), () => {
7575
7612
  entry.listeners.delete(listener);
7576
7613
  }), () => entry.value);
7577
7614
  return useEffect(() => () => {
@@ -7805,6 +7842,90 @@ function OverrideDot(props) {
7805
7842
  });
7806
7843
  }
7807
7844
  /**
7845
+ * « Retirer du site » : dépublication native de Sanity, rendue visible et expliquée.
7846
+ * La version EN LIGNE est supprimée, tout le contenu reste dans le BROUILLON (rien
7847
+ * n'est perdu) : la page disparaît du site (404 en production et en préproduction
7848
+ * « En ligne », purge par le webhook), l'onglet Pages l'affiche « Non publiée », et
7849
+ * on la remet en ligne en publiant le brouillon.
7850
+ *
7851
+ * Avant de confirmer, la liste des documents publiés qui pointent vers la page :
7852
+ * leurs liens vers elle disparaîtront du site. Une référence FORTE (non `weak`)
7853
+ * empêche Sanity de dépublier : le message l'explique au lieu d'une erreur brute.
7854
+ */
7855
+ const RemoveFromSiteAction = (props) => {
7856
+ let client = useKitClient(), [open, setOpen] = useState(!1), [referrers, setReferrers] = useState(null), [busy, setBusy] = useState(!1), [error, setError] = useState(null);
7857
+ if (useEffect(() => {
7858
+ open && (setReferrers(null), client.fetch("*[references($id) && !(_id in path(\"drafts.**\")) && _type != \"translation.metadata\"]{_id, _type, \"title\": coalesce(title, name, _id)}", { id: props.id }).then(setReferrers).catch(() => setReferrers([])));
7859
+ }, [
7860
+ open,
7861
+ client,
7862
+ props.id
7863
+ ]), !props.published) return null;
7864
+ let confirm = async () => {
7865
+ setBusy(!0), setError(null);
7866
+ try {
7867
+ let { _rev, _updatedAt, ...published } = props.published, tx = client.transaction();
7868
+ props.draft || tx.createIfNotExists({
7869
+ ...published,
7870
+ _id: `drafts.${props.id}`
7871
+ }), tx.delete(props.id), await tx.commit(), setOpen(!1), props.onComplete();
7872
+ } catch (cause) {
7873
+ let message = cause instanceof Error ? cause.message : String(cause);
7874
+ setError(/referenc/i.test(message) ? "Sanity refuse : un document publié pointe vers cette page par une référence forte. Retirez ou modifiez ce lien, puis recommencez." : `Le retrait a échoué, rien n'a changé. (${message.slice(0, 140)})`);
7875
+ } finally {
7876
+ setBusy(!1);
7877
+ }
7878
+ };
7879
+ return {
7880
+ label: "Retirer du site",
7881
+ title: "Dépublier : la page quitte le site, son contenu reste en brouillon",
7882
+ icon: EyeClosedIcon,
7883
+ tone: "critical",
7884
+ disabled: busy,
7885
+ onHandle: () => setOpen(!0),
7886
+ dialog: open && {
7887
+ type: "confirm",
7888
+ tone: "critical",
7889
+ onCancel: () => {
7890
+ setOpen(!1), props.onComplete();
7891
+ },
7892
+ onConfirm: () => void confirm(),
7893
+ message: /* @__PURE__ */ jsxs(Stack, {
7894
+ gap: 3,
7895
+ children: [
7896
+ /* @__PURE__ */ jsx(Text, {
7897
+ size: 1,
7898
+ children: "La page quitte le site (production et préproduction « En ligne »). Tout son contenu reste dans le brouillon : pour la remettre en ligne, publiez-le."
7899
+ }),
7900
+ referrers === null ? /* @__PURE__ */ jsx(Text, {
7901
+ size: 1,
7902
+ muted: !0,
7903
+ children: "Recherche des liens vers cette page…"
7904
+ }) : referrers.length > 0 ? /* @__PURE__ */ jsxs(Text, {
7905
+ size: 1,
7906
+ children: [
7907
+ "Ces documents publiés pointent vers elle ; leurs liens vers cette page disparaîtront du site :",
7908
+ " ",
7909
+ referrers.map((r) => r.title || r._id).join(", "),
7910
+ "."
7911
+ ]
7912
+ }) : /* @__PURE__ */ jsx(Text, {
7913
+ size: 1,
7914
+ muted: !0,
7915
+ children: "Aucun document publié ne pointe vers cette page."
7916
+ }),
7917
+ error && /* @__PURE__ */ jsx(Text, {
7918
+ size: 1,
7919
+ weight: "semibold",
7920
+ children: error
7921
+ })
7922
+ ]
7923
+ })
7924
+ }
7925
+ };
7926
+ };
7927
+ RemoveFromSiteAction.action = "unpublish";
7928
+ /**
7808
7929
  * Sous le champ Slug d'une page (types de pages du kit) : l'adresse COMPLÈTE de la
7809
7930
  * page sur le site en ligne, avec « Copier » et « Ouvrir ». Le slug seul ne dit pas
7810
7931
  * où la page vivra (préfixe de collection, langue) ; l'adresse se met à jour à
@@ -7877,6 +7998,413 @@ function isSlugInput(props) {
7877
7998
  }
7878
7999
  return !1;
7879
8000
  }
8001
+ const store = /* @__PURE__ */ new Map();
8002
+ function entryFor(client, documentId) {
8003
+ let { projectId, dataset } = client.config(), id = translationTodoId(documentId), key = `${projectId}:${dataset}:${id}`, entry = store.get(key);
8004
+ entry || (entry = {
8005
+ value: null,
8006
+ listeners: /* @__PURE__ */ new Set(),
8007
+ stop: null
8008
+ }, store.set(key, entry));
8009
+ let e = entry;
8010
+ if (!e.stop) {
8011
+ let load = () => client.fetch("*[_id == $id][0]{_id, sourceLanguage, paths}", { id }).then((value) => {
8012
+ e.value = value, e.listeners.forEach((l) => l());
8013
+ }).catch(() => {});
8014
+ load();
8015
+ let sub = client.listen("*[_id == $id]", { id }, {
8016
+ visibility: "query",
8017
+ includeResult: !1
8018
+ }).subscribe({ next: () => void load() });
8019
+ e.stop = () => sub.unsubscribe();
8020
+ }
8021
+ return e;
8022
+ }
8023
+ function useTranslationTodo(client, documentId) {
8024
+ let entry = documentId ? entryFor(client, documentId) : null, value = useSyncExternalStore((listener) => entry ? (entry.listeners.add(listener), () => {
8025
+ entry.listeners.delete(listener);
8026
+ }) : () => {}, () => entry?.value ?? null);
8027
+ return useEffect(() => () => {
8028
+ entry && entry.listeners.size === 0 && entry.stop && (entry.stop(), entry.stop = null);
8029
+ }, [entry]), value;
8030
+ }
8031
+ /** Chemin lisible d'un champ du formulaire, au format de la propagation (`sections[a].title`). */
8032
+ function fieldPathKey(path) {
8033
+ let out = "";
8034
+ for (let seg of path) typeof seg == "string" ? out += out ? `.${seg}` : seg : seg && typeof seg == "object" && "_key" in seg ? out += `[${String(seg._key)}]` : typeof seg == "number" && (out += `[${seg}]`);
8035
+ return out;
8036
+ }
8037
+ /**
8038
+ * Sous un champ d'une traduction modifié dans la version principale (propagation) :
8039
+ * « À traduire », avec « Marquer comme traduit » qui le retire de la liste.
8040
+ */
8041
+ function withTranslationTodo(Inner, config) {
8042
+ function TranslationTodoInput(props) {
8043
+ let id = useFormValue(["_id"]), client = useKitClient(), todo = useTranslationTodo(client, config.i18n ? id : void 0), [busy, setBusy] = useState(!1), key = fieldPathKey(props.path), inner = createElement(Inner, props);
8044
+ if (!todo?.paths?.includes(key)) return inner;
8045
+ let done = () => {
8046
+ setBusy(!0), client.patch(todo._id).set({ paths: (todo.paths ?? []).filter((p) => p !== key) }).commit().finally(() => setBusy(!1));
8047
+ };
8048
+ return /* @__PURE__ */ jsxs(Stack, {
8049
+ gap: 2,
8050
+ children: [inner, /* @__PURE__ */ jsx(Card, {
8051
+ tone: "caution",
8052
+ padding: 2,
8053
+ radius: 2,
8054
+ border: !0,
8055
+ children: /* @__PURE__ */ jsxs(Flex, {
8056
+ align: "center",
8057
+ gap: 2,
8058
+ children: [/* @__PURE__ */ jsxs(Text, {
8059
+ size: 1,
8060
+ style: { flex: 1 },
8061
+ children: [
8062
+ "À traduire : modifié dans la version ",
8063
+ (todo.sourceLanguage ?? "").toUpperCase(),
8064
+ "."
8065
+ ]
8066
+ }), /* @__PURE__ */ jsx(Button, {
8067
+ mode: "ghost",
8068
+ fontSize: 1,
8069
+ padding: 2,
8070
+ text: "Marquer comme traduit",
8071
+ disabled: busy,
8072
+ onClick: done
8073
+ })]
8074
+ })
8075
+ })]
8076
+ });
8077
+ }
8078
+ return TranslationTodoInput;
8079
+ }
8080
+ const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
8081
+ "image",
8082
+ "file",
8083
+ "reference",
8084
+ "crossDatasetReference",
8085
+ "slug",
8086
+ "geopoint",
8087
+ "url",
8088
+ "email",
8089
+ "date",
8090
+ "datetime",
8091
+ "number",
8092
+ "boolean"
8093
+ ]), 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");
8094
+ function typeNames(t) {
8095
+ let out = [];
8096
+ for (let c = t; c; c = c.type) c.name && out.push(c.name);
8097
+ return out;
8098
+ }
8099
+ /** Nature d'un champ d'après son schéma (et sa valeur, faute de schéma). */
8100
+ function kindOf(t, value) {
8101
+ if (t) {
8102
+ if (typeNames(t).some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return "value";
8103
+ if (t.jsonType === "array") {
8104
+ let of = t.of ?? [];
8105
+ if (of.some((m) => typeNames(m).includes("block"))) return "text";
8106
+ if (of.some((m) => m.jsonType === "object" || typeNames(m).includes("object"))) return "list";
8107
+ let prim = of[0];
8108
+ return prim && prim.jsonType === "string" && !prim.options?.list?.length ? "text" : "value";
8109
+ }
8110
+ return t.jsonType === "object" ? "object" : t.jsonType === "string" ? t.options?.list?.length ? "value" : "text" : "value";
8111
+ }
8112
+ return keyed(value) ? "list" : isObj(value) ? "object" : "value";
8113
+ }
8114
+ function fieldType(t, name) {
8115
+ for (let c = t; c; c = c.type) {
8116
+ let f = c.fields?.find((x) => x.name === name);
8117
+ if (f) return f.type;
8118
+ }
8119
+ }
8120
+ function itemType(t, item) {
8121
+ let of;
8122
+ for (let c = t; c && !of; c = c.type) of = c.of;
8123
+ if (of?.length) return of.find((m) => typeNames(m).includes(item._type)) ?? (of.length === 1 ? of[0] : void 0);
8124
+ }
8125
+ /** Tous les textes d'un élément ajouté : à traduire. */
8126
+ function collectTexts(value, t, path, acc) {
8127
+ let kind = kindOf(t, value);
8128
+ if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
8129
+ else if (kind === "object" && isObj(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
8130
+ else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
8131
+ }
8132
+ const ABSENT = Symbol("absent");
8133
+ function merge(target, before, after, t, path, acc) {
8134
+ if (same(before, after)) return target === void 0 ? ABSENT : target;
8135
+ let kind = kindOf(t, after ?? before);
8136
+ 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);
8137
+ if (kind === "value") return acc.copied.push(path), after === void 0 ? ABSENT : after;
8138
+ if (kind === "object") {
8139
+ if (!isObj(after)) return acc.copied.push(path), after === void 0 ? ABSENT : after;
8140
+ let base = isObj(target) ? { ...target } : { _type: after._type }, b = isObj(before) ? before : {};
8141
+ for (let k of /* @__PURE__ */ new Set([...Object.keys(b), ...Object.keys(after)])) {
8142
+ if (k.startsWith("_") || SKIP_KEYS.has(k)) continue;
8143
+ let v = merge(base[k], b[k], after[k], fieldType(t, k), path ? `${path}.${k}` : k, acc);
8144
+ v === ABSENT ? delete base[k] : base[k] = v;
8145
+ }
8146
+ return base;
8147
+ }
8148
+ 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 = [];
8149
+ for (let item of aft) {
8150
+ let key = item._key, it = itemType(t, item);
8151
+ if (tMap.has(key)) {
8152
+ let merged = merge(tMap.get(key), bMap.get(key), item, it, `${path}[${key}]`, acc);
8153
+ result.push(merged === ABSENT ? item : merged);
8154
+ } else result.push(structuredClone(item)), acc.added++, collectTexts(item, it, `${path}[${key}]`, acc);
8155
+ }
8156
+ for (let key of bMap.keys()) !aMap.has(key) && tMap.has(key) && acc.removed++;
8157
+ tgt.forEach((item, index) => {
8158
+ let key = item._key;
8159
+ if (bMap.has(key) || aMap.has(key)) return;
8160
+ 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;
8161
+ result.splice(at, 0, item);
8162
+ });
8163
+ let common = (list) => list.map((i) => i._key).filter((k) => tMap.has(k) && aMap.has(k));
8164
+ return same(common(tgt), common(aft)) || (acc.moved = !0), result;
8165
+ }
8166
+ /**
8167
+ * Applique la modification `before` → `after` (version principale) à `target`
8168
+ * (brouillon ou version publiée de la traduction). `documentType` : schéma du
8169
+ * document, pour distinguer textes et valeurs.
8170
+ */
8171
+ function propagate(target, before, after, documentType) {
8172
+ let acc = {
8173
+ toTranslate: [],
8174
+ copied: [],
8175
+ added: 0,
8176
+ removed: 0,
8177
+ moved: !1
8178
+ }, merged = merge(target ?? {}, before ?? {}, after, documentType, "", acc);
8179
+ return {
8180
+ document: {
8181
+ ...target ?? {},
8182
+ ...isObj(merged) ? merged : {}
8183
+ },
8184
+ ...acc
8185
+ };
8186
+ }
8187
+ /** La propagation changerait-elle quelque chose ? */
8188
+ function hasChanges(r) {
8189
+ return r.toTranslate.length > 0 || r.copied.length > 0 || r.added > 0 || r.removed > 0 || r.moved;
8190
+ }
8191
+ /**
8192
+ * Publier la version PRINCIPALE d'une page qui a des traductions : la publication
8193
+ * part normalement, puis « Propager aux autres langues ? » propose d'appliquer aux
8194
+ * BROUILLONS des traductions la structure (sections ajoutées, supprimées, déplacées)
8195
+ * et les valeurs non textuelles (images, liens, options…). Les textes traduits ne
8196
+ * sont jamais écrasés : les textes modifiés sont marqués « à traduire ». Rien n'est
8197
+ * publié dans les autres langues : on relit, on traduit, on publie.
8198
+ */
8199
+ function withPropagation(Publish, config) {
8200
+ let i18n = config.i18n, Wrapped = (props) => {
8201
+ let base = Publish(props), [run, setRun] = useState(null), current = props.draft ?? props.published;
8202
+ return !base || !i18n || current?.[i18n.field] !== i18n.defaultLocale ? base : {
8203
+ ...base,
8204
+ onHandle: () => {
8205
+ let before = props.published, after = props.draft;
8206
+ base.onHandle?.(), before && after && setRun({
8207
+ before,
8208
+ after
8209
+ });
8210
+ },
8211
+ dialog: run ? {
8212
+ type: "dialog",
8213
+ header: "Propager aux autres langues ?",
8214
+ width: "medium",
8215
+ onClose: () => {
8216
+ setRun(null), props.onComplete();
8217
+ },
8218
+ content: /* @__PURE__ */ jsx(PropagateDialog, {
8219
+ config,
8220
+ id: props.id,
8221
+ type: props.type,
8222
+ before: run.before,
8223
+ after: run.after,
8224
+ onDone: () => {
8225
+ setRun(null), props.onComplete();
8226
+ }
8227
+ })
8228
+ } : base.dialog
8229
+ };
8230
+ };
8231
+ return Wrapped.action = Publish.action, Wrapped;
8232
+ }
8233
+ function PropagateDialog(props) {
8234
+ let { config, id, type, before, after, onDone } = props, client = useKitClient(), schema = useSchema(), field = config.i18n?.field ?? "language", source = String(after[field] ?? ""), [targets, setTargets] = useState(null), [busy, setBusy] = useState(!1), [done, setDone] = useState(null), [error, setError] = useState(null);
8235
+ useEffect(() => {
8236
+ let documentType = schema.get(type);
8237
+ (async () => {
8238
+ let translations = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0].translations[]{language, \"id\": value._ref}", { id }), list = [];
8239
+ for (let t of translations ?? []) {
8240
+ if (!t?.id || t.id === id || t.language === source) continue;
8241
+ let target = await client.getDocument(`drafts.${t.id}`) ?? await client.getDocument(t.id) ?? null;
8242
+ if (!target) continue;
8243
+ let result = propagate(target, before, after, documentType);
8244
+ list.push({
8245
+ language: t.language,
8246
+ id: t.id,
8247
+ result,
8248
+ selected: hasChanges(result)
8249
+ });
8250
+ }
8251
+ setTargets(list);
8252
+ })().catch(() => setTargets([]));
8253
+ }, [
8254
+ client,
8255
+ schema,
8256
+ id,
8257
+ type,
8258
+ before,
8259
+ after,
8260
+ source
8261
+ ]);
8262
+ let apply = async () => {
8263
+ setBusy(!0), setError(null);
8264
+ try {
8265
+ let applied = [];
8266
+ for (let t of targets ?? []) {
8267
+ if (!t.selected) continue;
8268
+ let { _rev, _createdAt, _updatedAt, ...doc } = t.result.document;
8269
+ if (await client.createOrReplace({
8270
+ ...doc,
8271
+ _id: `drafts.${t.id}`,
8272
+ _type: type
8273
+ }), t.result.toTranslate.length) {
8274
+ let todoId = translationTodoId(t.id), existing = await client.fetch("*[_id == $todoId][0].paths", { todoId });
8275
+ await client.createOrReplace({
8276
+ _id: todoId,
8277
+ _type: TRANSLATION_TODO_TYPE,
8278
+ documentId: t.id,
8279
+ sourceId: id,
8280
+ sourceLanguage: source,
8281
+ paths: [.../* @__PURE__ */ new Set([...existing ?? [], ...t.result.toTranslate])]
8282
+ });
8283
+ }
8284
+ applied.push(t.language.toUpperCase());
8285
+ }
8286
+ setDone(applied);
8287
+ } catch (cause) {
8288
+ setError(`La propagation a échoué, rien n'a été publié. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 140)})`);
8289
+ } finally {
8290
+ setBusy(!1);
8291
+ }
8292
+ };
8293
+ return done ? /* @__PURE__ */ jsxs(Stack, {
8294
+ gap: 4,
8295
+ padding: 4,
8296
+ children: [/* @__PURE__ */ jsx(Text, {
8297
+ size: 1,
8298
+ children: done.length ? `Brouillons mis à jour : ${done.join(", ")}. Relisez, traduisez les champs marqués « À traduire », puis publiez chaque langue.` : "Rien n’a été propagé."
8299
+ }), /* @__PURE__ */ jsx(Flex, {
8300
+ justify: "flex-end",
8301
+ children: /* @__PURE__ */ jsx(Button, {
8302
+ text: "Fermer",
8303
+ mode: "ghost",
8304
+ onClick: onDone
8305
+ })
8306
+ })]
8307
+ }) : targets ? targets.some((t) => hasChanges(t.result)) ? /* @__PURE__ */ jsxs(Stack, {
8308
+ gap: 4,
8309
+ padding: 4,
8310
+ children: [
8311
+ /* @__PURE__ */ jsxs(Text, {
8312
+ size: 1,
8313
+ children: [
8314
+ "La version ",
8315
+ source.toUpperCase(),
8316
+ " est publiée. Appliquer ses changements aux brouillons des autres langues ? Les textes traduits ne sont jamais écrasés : les textes modifiés sont marqués « À traduire ». Rien n’est publié."
8317
+ ]
8318
+ }),
8319
+ /* @__PURE__ */ jsx(Stack, {
8320
+ gap: 3,
8321
+ children: targets.map((t, index) => /* @__PURE__ */ jsx(Card, {
8322
+ padding: 3,
8323
+ radius: 2,
8324
+ border: !0,
8325
+ children: /* @__PURE__ */ jsxs(Flex, {
8326
+ gap: 3,
8327
+ align: "flex-start",
8328
+ children: [/* @__PURE__ */ jsx(Checkbox, {
8329
+ checked: t.selected,
8330
+ disabled: !hasChanges(t.result),
8331
+ onChange: () => setTargets(targets.map((x, i) => i === index ? {
8332
+ ...x,
8333
+ selected: !x.selected
8334
+ } : x))
8335
+ }), /* @__PURE__ */ jsx(Box, {
8336
+ flex: 1,
8337
+ children: /* @__PURE__ */ jsxs(Stack, {
8338
+ gap: 2,
8339
+ children: [/* @__PURE__ */ jsx(Text, {
8340
+ size: 1,
8341
+ weight: "semibold",
8342
+ children: t.language.toUpperCase()
8343
+ }), /* @__PURE__ */ jsx(Text, {
8344
+ size: 1,
8345
+ muted: !0,
8346
+ children: summary(t.result)
8347
+ })]
8348
+ })
8349
+ })]
8350
+ })
8351
+ }, t.id))
8352
+ }),
8353
+ error && /* @__PURE__ */ jsx(Card, {
8354
+ tone: "critical",
8355
+ padding: 3,
8356
+ radius: 2,
8357
+ children: /* @__PURE__ */ jsx(Text, {
8358
+ size: 1,
8359
+ children: error
8360
+ })
8361
+ }),
8362
+ /* @__PURE__ */ jsxs(Flex, {
8363
+ justify: "flex-end",
8364
+ gap: 2,
8365
+ children: [/* @__PURE__ */ jsx(Button, {
8366
+ text: "Ignorer",
8367
+ mode: "ghost",
8368
+ onClick: onDone,
8369
+ disabled: busy
8370
+ }), /* @__PURE__ */ jsx(Button, {
8371
+ text: busy ? "Propagation…" : "Propager",
8372
+ tone: "primary",
8373
+ onClick: () => void apply(),
8374
+ disabled: busy || !targets.some((t) => t.selected)
8375
+ })]
8376
+ })
8377
+ ]
8378
+ }) : /* @__PURE__ */ jsxs(Stack, {
8379
+ gap: 4,
8380
+ padding: 4,
8381
+ children: [/* @__PURE__ */ jsx(Text, {
8382
+ size: 1,
8383
+ children: "Aucune traduction à mettre à jour."
8384
+ }), /* @__PURE__ */ jsx(Flex, {
8385
+ justify: "flex-end",
8386
+ children: /* @__PURE__ */ jsx(Button, {
8387
+ text: "Fermer",
8388
+ mode: "ghost",
8389
+ onClick: onDone
8390
+ })
8391
+ })]
8392
+ }) : /* @__PURE__ */ jsxs(Flex, {
8393
+ align: "center",
8394
+ gap: 3,
8395
+ padding: 4,
8396
+ children: [/* @__PURE__ */ jsx(Spinner, { muted: !0 }), /* @__PURE__ */ jsx(Text, {
8397
+ size: 1,
8398
+ muted: !0,
8399
+ children: "Comparaison avec les traductions…"
8400
+ })]
8401
+ });
8402
+ }
8403
+ function summary(r) {
8404
+ if (!hasChanges(r)) return "Déjà à jour.";
8405
+ let parts = [];
8406
+ return r.added && parts.push(`${r.added} élément${r.added > 1 ? "s" : ""} ajouté${r.added > 1 ? "s" : ""}`), r.removed && parts.push(`${r.removed} supprimé${r.removed > 1 ? "s" : ""}`), r.moved && parts.push("ordre mis à jour"), r.copied.length && parts.push(`${r.copied.length} valeur${r.copied.length > 1 ? "s" : ""} recopiée${r.copied.length > 1 ? "s" : ""} (images, liens, options…)`), r.toTranslate.length && parts.push(`${r.toTranslate.length} texte${r.toTranslate.length > 1 ? "s" : ""} à traduire`), parts.join(" · ");
8407
+ }
7880
8408
  /**
7881
8409
  * `pageTypes` déduits du registre du starter, pour ne pas redire au kit ce que
7882
8410
  * le site sait déjà : l'accueil (chemin fixe `/`) et chaque collection avec
@@ -8063,7 +8591,7 @@ function createKitInput(config) {
8063
8591
  function KitInput(props) {
8064
8592
  return isSlugInput(props) ? createElement(SlugUrl, props) : createElement(Override, props);
8065
8593
  }
8066
- return KitInput;
8594
+ return config.i18n ? withTranslationTodo(KitInput, config) : KitInput;
8067
8595
  }
8068
8596
  const ncfKit = definePlugin((options) => {
8069
8597
  let config = resolveConfig(options), issues = validateConfig(config);
@@ -8135,7 +8663,10 @@ const ncfKit = definePlugin((options) => {
8135
8663
  types: kitSchemaTypes,
8136
8664
  templates: (prev) => prev.filter((template) => !isKitType(template.schemaType))
8137
8665
  },
8138
- document: { newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE) },
8666
+ document: {
8667
+ newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
8668
+ actions: (prev, context) => config.pageTypeNames.includes(context.schemaType) ? prev.map((action) => action.action === "unpublish" ? RemoveFromSiteAction : action.action === "publish" && config.i18n ? withPropagation(action, config) : action) : prev
8669
+ },
8139
8670
  studio: { components: { toolMenu: createPreviewLauncher(config, issues) } },
8140
8671
  form: { components: { input: createKitInput(config) } }
8141
8672
  };