@nocode-factory/sanity-kit 2.35.0 → 2.37.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
@@ -1384,7 +1384,7 @@ function explainGrantError(error) {
1384
1384
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1385
1385
  * le vérifie.
1386
1386
  */
1387
- const KIT_VERSION = "2.35.0";
1387
+ const KIT_VERSION = "2.37.0";
1388
1388
  /**
1389
1389
  * Signale ce Studio au service du kit, une fois par montage.
1390
1390
  *
@@ -1727,7 +1727,7 @@ function useKitUpdate() {
1727
1727
  !controller.signal.aborted && body?.version && setLatest(body.version);
1728
1728
  }).catch(() => {}), () => controller.abort();
1729
1729
  }, []);
1730
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.35.0") > 0);
1730
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.37.0") > 0);
1731
1731
  return {
1732
1732
  current: KIT_VERSION,
1733
1733
  latest,
@@ -2960,22 +2960,22 @@ async function localizeReferences(client, value, language) {
2960
2960
  for (let row of rows ?? []) row?.from && row.to && row.to !== row.from && map.set(row.from, row.to);
2961
2961
  return map.size ? replaceRefs(value, map) : value;
2962
2962
  }
2963
- const isObj$1 = (v) => typeof v == "object" && !!v && !Array.isArray(v);
2963
+ const isObj$3 = (v) => typeof v == "object" && !!v && !Array.isArray(v);
2964
2964
  /** Textes d'une valeur, dans l'ordre. */
2965
2965
  function collectTexts$1(value) {
2966
2966
  if (typeof value == "string") return [value];
2967
2967
  if (!Array.isArray(value)) return [];
2968
2968
  let out = [];
2969
2969
  for (let item of value) if (typeof item == "string") out.push(item);
2970
- 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);
2970
+ else if (isObj$3(item) && Array.isArray(item.children)) for (let child of item.children) isObj$3(child) && typeof child.text == "string" && out.push(child.text);
2971
2971
  return out;
2972
2972
  }
2973
2973
  /** La même valeur avec ses textes remplacés (dans l'ordre de `collectTexts`). */
2974
2974
  function replaceTexts(value, texts) {
2975
2975
  let i = 0, next = () => texts[i++] ?? "";
2976
- return typeof value == "string" ? next() : Array.isArray(value) ? value.map((item) => typeof item == "string" ? next() : isObj$1(item) && Array.isArray(item.children) ? {
2976
+ return typeof value == "string" ? next() : Array.isArray(value) ? value.map((item) => typeof item == "string" ? next() : isObj$3(item) && Array.isArray(item.children) ? {
2977
2977
  ...item,
2978
- children: item.children.map((child) => isObj$1(child) && typeof child.text == "string" ? {
2978
+ children: item.children.map((child) => isObj$3(child) && typeof child.text == "string" ? {
2979
2979
  ...child,
2980
2980
  text: next()
2981
2981
  } : child)
@@ -2988,14 +2988,14 @@ function parsePathKey(path) {
2988
2988
  return out;
2989
2989
  }
2990
2990
  function itemOf(list, key) {
2991
- return list.find((i) => isObj$1(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : void 0);
2991
+ return list.find((i) => isObj$3(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : void 0);
2992
2992
  }
2993
2993
  /** Valeur d'un document au chemin `sections[a].title`. */
2994
2994
  function valueAtKey(doc, path) {
2995
2995
  let cur = doc;
2996
2996
  for (let seg of parsePathKey(path)) {
2997
2997
  if (cur == null) return;
2998
- cur = "field" in seg ? isObj$1(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0;
2998
+ cur = "field" in seg ? isObj$3(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0;
2999
2999
  }
3000
3000
  return cur;
3001
3001
  }
@@ -3004,10 +3004,10 @@ function setAtKey(doc, path, value) {
3004
3004
  let segs = parsePathKey(path), cur = doc;
3005
3005
  for (let n = 0; n < segs.length - 1; n++) {
3006
3006
  let seg = segs[n];
3007
- 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;
3007
+ if (cur = "field" in seg ? isObj$3(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0, cur == null) return !1;
3008
3008
  }
3009
3009
  let last = segs[segs.length - 1];
3010
- return !last || !("field" in last) || !isObj$1(cur) ? !1 : (cur[last.field] = value, !0);
3010
+ return !last || !("field" in last) || !isObj$3(cur) ? !1 : (cur[last.field] = value, !0);
3011
3011
  }
3012
3012
  const MESSAGES = {
3013
3013
  daily_limit: "Daily AI translation limit reached for this project.",
@@ -3059,7 +3059,7 @@ const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
3059
3059
  "datetime",
3060
3060
  "number",
3061
3061
  "boolean"
3062
- ]), 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");
3062
+ ]), SKIP_KEYS = /* @__PURE__ */ new Set(["language", "slug"]), isObj$2 = (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$2(i) && typeof i._key == "string");
3063
3063
  function typeNames(t) {
3064
3064
  let out = [];
3065
3065
  for (let c = t; c; c = c.type) c.name && out.push(c.name);
@@ -3078,7 +3078,7 @@ function kindOf(t, value) {
3078
3078
  }
3079
3079
  return t.jsonType === "object" ? "object" : t.jsonType === "string" ? t.options?.list?.length ? "value" : "text" : "value";
3080
3080
  }
3081
- return keyed$1(value) ? "list" : isObj(value) ? "object" : "value";
3081
+ return keyed$1(value) ? "list" : isObj$2(value) ? "object" : "value";
3082
3082
  }
3083
3083
  function fieldType(t, name) {
3084
3084
  for (let c = t; c; c = c.type) {
@@ -3095,8 +3095,8 @@ function itemType(t, item) {
3095
3095
  function collectTexts(value, t, path, acc) {
3096
3096
  let kind = kindOf(t, value);
3097
3097
  if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
3098
- else if (kind === "object" && isObj(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
3099
- else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
3098
+ else if (kind === "object" && isObj$2(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
3099
+ else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj$2(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
3100
3100
  }
3101
3101
  const ABSENT$1 = Symbol("absent");
3102
3102
  function merge(target, before, after, t, path, acc) {
@@ -3105,8 +3105,8 @@ function merge(target, before, after, t, path, acc) {
3105
3105
  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);
3106
3106
  if (kind === "value") return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
3107
3107
  if (kind === "object") {
3108
- if (!isObj(after)) return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
3109
- let base = isObj(target) ? { ...target } : { _type: after._type }, b = isObj(before) ? before : {};
3108
+ if (!isObj$2(after)) return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
3109
+ let base = isObj$2(target) ? { ...target } : { _type: after._type }, b = isObj$2(before) ? before : {};
3110
3110
  for (let k of /* @__PURE__ */ new Set([...Object.keys(b), ...Object.keys(after)])) {
3111
3111
  if (k.startsWith("_") || SKIP_KEYS.has(k)) continue;
3112
3112
  let v = merge(base[k], b[k], after[k], fieldType(t, k), path ? `${path}.${k}` : k, acc);
@@ -3114,7 +3114,7 @@ function merge(target, before, after, t, path, acc) {
3114
3114
  }
3115
3115
  return base;
3116
3116
  }
3117
- 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 = [];
3117
+ let tgt = Array.isArray(target) ? target.filter(isObj$2) : [], bef = Array.isArray(before) ? before.filter(isObj$2) : [], aft = Array.isArray(after) ? after.filter(isObj$2) : [], byKey = (list) => new Map(list.map((i) => [i._key, i])), tMap = byKey(tgt), bMap = byKey(bef), aMap = byKey(aft), result = [];
3118
3118
  for (let item of aft) {
3119
3119
  let key = item._key, it = itemType(t, item);
3120
3120
  if (tMap.has(key)) {
@@ -3148,7 +3148,7 @@ function propagate(target, before, after, documentType) {
3148
3148
  return {
3149
3149
  document: {
3150
3150
  ...target ?? {},
3151
- ...isObj(merged) ? merged : {}
3151
+ ...isObj$2(merged) ? merged : {}
3152
3152
  },
3153
3153
  ...acc
3154
3154
  };
@@ -8628,23 +8628,56 @@ function OverrideDot(props) {
8628
8628
  * leurs liens vers elle disparaîtront du site. Une référence FORTE (non `weak`)
8629
8629
  * empêche Sanity de dépublier : le message l'explique au lieu d'une erreur brute.
8630
8630
  */
8631
- const RemoveFromSiteAction = (props) => {
8632
- let client = useKitClient(), [open, setOpen] = useState(!1), [referrers, setReferrers] = useState(null), [busy, setBusy] = useState(!1), [error, setError] = useState(null);
8633
- if (useEffect(() => {
8634
- 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([])));
8631
+ const RemoveFromSiteAction = createRemoveFromSite();
8632
+ /**
8633
+ * Variante multilingue : sur la version PRINCIPALE d'un document traduit (page ou
8634
+ * fiche de collection), la fenêtre propose aussi de retirer du site ses autres
8635
+ * langues publiées (cochées par défaut), en une seule opération.
8636
+ */
8637
+ function createRemoveFromSite(config, masterLocale) {
8638
+ let i18n = config?.i18n, master = masterLocale ?? i18n?.defaultLocale, Action = (props) => useRemoveFromSite(props, i18n?.field, master);
8639
+ return Action.action = "unpublish", Action;
8640
+ }
8641
+ function useRemoveFromSite(props, field, master) {
8642
+ let client = useKitClient(), current = props.draft ?? props.published, isMaster = !!field && !!master && current?.[field] === master, [versions, setVersions] = useState([]), [open, setOpen] = useState(!1), [referrers, setReferrers] = useState(null), [busy, setBusy] = useState(!1), [error, setError] = useState(null);
8643
+ useEffect(() => {
8644
+ if (!open || !isMaster) return;
8645
+ let alive = !0;
8646
+ return translationsOf(client, props.id).then(async (list) => {
8647
+ let others = list.filter((t) => t.id !== props.id), live = new Set(await client.fetch("*[_id in $ids]._id", { ids: others.map((t) => t.id) }));
8648
+ alive && setVersions(others.filter((t) => live.has(t.id)).map((t) => ({
8649
+ ...t,
8650
+ selected: !0
8651
+ })));
8652
+ }).catch(() => alive && setVersions([])), () => {
8653
+ alive = !1;
8654
+ };
8635
8655
  }, [
8636
8656
  open,
8657
+ isMaster,
8637
8658
  client,
8638
8659
  props.id
8660
+ ]);
8661
+ let ids = [props.id, ...versions.filter((v) => v.selected).map((v) => v.id)];
8662
+ if (useEffect(() => {
8663
+ open && (setReferrers(null), client.fetch("*[references($ids) && !(_id in path(\"drafts.**\")) && !(_id in $ids) && _type != \"translation.metadata\"]{_id, _type, \"title\": coalesce(title, name, _id)}", { ids }).then(setReferrers).catch(() => setReferrers([])));
8664
+ }, [
8665
+ open,
8666
+ client,
8667
+ ids.join(",")
8639
8668
  ]), !props.published) return null;
8640
8669
  let confirm = async () => {
8641
8670
  setBusy(!0), setError(null);
8642
8671
  try {
8643
- let { _rev, _updatedAt, ...published } = props.published, tx = client.transaction();
8644
- props.draft || tx.createIfNotExists({
8645
- ...published,
8646
- _id: `drafts.${props.id}`
8647
- }), tx.delete(props.id), await tx.commit(), setOpen(!1), props.onComplete();
8672
+ let tx = client.transaction(), docs = await client.fetch("*[_id in $ids]", { ids }), drafts = new Set(await client.fetch("*[_id in $drafts]._id", { drafts: ids.map((id) => `drafts.${id}`) }));
8673
+ for (let doc of docs) {
8674
+ let { _rev, _updatedAt, ...published } = doc, id = String(doc._id);
8675
+ drafts.has(`drafts.${id}`) || tx.createIfNotExists({
8676
+ ...published,
8677
+ _id: `drafts.${id}`
8678
+ }), tx.delete(id);
8679
+ }
8680
+ await tx.commit(), setOpen(!1), props.onComplete();
8648
8681
  } catch (cause) {
8649
8682
  let message = cause instanceof Error ? cause.message : String(cause);
8650
8683
  setError(/referenc/i.test(message) ? "Sanity refused: a published document points to this page with a strong reference. Remove or change that link, then try again." : `Removal failed, nothing was changed. (${message.slice(0, 140)})`);
@@ -8671,16 +8704,44 @@ const RemoveFromSiteAction = (props) => {
8671
8704
  children: [
8672
8705
  /* @__PURE__ */ jsx(Text, {
8673
8706
  size: 1,
8674
- children: "The page leaves the site (production and staging \"Published\"). All its content stays in the draft: to put it back online, publish it."
8707
+ children: "It leaves the site (production and staging \"Published\"). All its content stays in the draft: to put it back online, publish it."
8708
+ }),
8709
+ versions.length > 0 && /* @__PURE__ */ jsxs(Stack, {
8710
+ gap: 2,
8711
+ children: [/* @__PURE__ */ jsx(Text, {
8712
+ size: 1,
8713
+ weight: "semibold",
8714
+ children: "Also remove the other languages from the site:"
8715
+ }), versions.map((v, index) => /* @__PURE__ */ jsx(Card, {
8716
+ padding: 2,
8717
+ radius: 2,
8718
+ border: !0,
8719
+ children: /* @__PURE__ */ jsxs(Flex, {
8720
+ as: "label",
8721
+ gap: 3,
8722
+ align: "center",
8723
+ children: [/* @__PURE__ */ jsx(Checkbox, {
8724
+ checked: v.selected,
8725
+ disabled: busy,
8726
+ onChange: () => setVersions(versions.map((x, i) => i === index ? {
8727
+ ...x,
8728
+ selected: !x.selected
8729
+ } : x))
8730
+ }), /* @__PURE__ */ jsx(Text, {
8731
+ size: 1,
8732
+ children: v.language.toUpperCase()
8733
+ })]
8734
+ })
8735
+ }, v.id))]
8675
8736
  }),
8676
8737
  referrers === null ? /* @__PURE__ */ jsx(Text, {
8677
8738
  size: 1,
8678
8739
  muted: !0,
8679
- children: "Looking for links to this page…"
8740
+ children: "Looking for links…"
8680
8741
  }) : referrers.length > 0 ? /* @__PURE__ */ jsxs(Text, {
8681
8742
  size: 1,
8682
8743
  children: [
8683
- "These published documents point to it; their links to this page will disappear from the site:",
8744
+ "These published documents point to it; their links will disappear from the site:",
8684
8745
  " ",
8685
8746
  referrers.map((r) => r.title || r._id).join(", "),
8686
8747
  "."
@@ -8688,7 +8749,7 @@ const RemoveFromSiteAction = (props) => {
8688
8749
  }) : /* @__PURE__ */ jsx(Text, {
8689
8750
  size: 1,
8690
8751
  muted: !0,
8691
- children: "No published document points to this page."
8752
+ children: "No published document points to it."
8692
8753
  }),
8693
8754
  error && /* @__PURE__ */ jsx(Text, {
8694
8755
  size: 1,
@@ -8699,8 +8760,7 @@ const RemoveFromSiteAction = (props) => {
8699
8760
  })
8700
8761
  }
8701
8762
  };
8702
- };
8703
- RemoveFromSiteAction.action = "unpublish";
8763
+ }
8704
8764
  /**
8705
8765
  * Sous le champ Slug d'une page (types de pages du kit) : l'adresse COMPLÈTE de la
8706
8766
  * page sur le site en ligne, avec « Copier » et « Ouvrir ». Le slug seul ne dit pas
@@ -9325,6 +9385,184 @@ function summary(r) {
9325
9385
  let parts = [];
9326
9386
  return r.added && parts.push(`${r.added} item${r.added > 1 ? "s" : ""} added`), r.removed && parts.push(`${r.removed} removed`), r.moved && parts.push("order updated"), r.copied.length && parts.push(`${r.copied.length} value${r.copied.length > 1 ? "s" : ""} copied (images, links, options…)`), r.toTranslate.length && parts.push(`${r.toTranslate.length} text${r.toTranslate.length > 1 ? "s" : ""} to translate`), parts.join(" · ");
9327
9387
  }
9388
+ /** Identifiants publiés + brouillons d'une liste de documents. */
9389
+ const withDrafts = (ids) => ids.flatMap((id) => [id, `drafts.${id}`]);
9390
+ /**
9391
+ * Supprimer la version PRINCIPALE d'un document traduit (page, fiche de collection,
9392
+ * réglage par langue) : la fenêtre propose de supprimer aussi ses autres langues
9393
+ * (cochées par défaut), en une fois. Bloqué, avec la liste, si un autre document y
9394
+ * fait encore référence (comme la suppression native de Sanity). Les liens de
9395
+ * traduction sont nettoyés. Sans traduction, ou depuis une autre langue : la
9396
+ * suppression native, inchangée.
9397
+ */
9398
+ function withTranslationDelete(Delete, config, masterLocale) {
9399
+ let i18n = config.i18n, master = masterLocale ?? i18n?.defaultLocale, Wrapped = (props) => {
9400
+ let base = Delete(props), client = useKitClient(), [versions, setVersions] = useState(null), current = props.draft ?? props.published;
9401
+ useEffect(() => {
9402
+ if (!i18n || current?.[i18n.field] !== master) return;
9403
+ let alive = !0;
9404
+ return translationsOf(client, props.id).then((list) => alive && setVersions(list.filter((t) => t.id !== props.id).map((t) => ({
9405
+ ...t,
9406
+ selected: !0
9407
+ })))).catch(() => alive && setVersions([])), () => {
9408
+ alive = !1;
9409
+ };
9410
+ }, [
9411
+ client,
9412
+ props.id,
9413
+ current?.[i18n?.field ?? "language"]
9414
+ ]);
9415
+ let [open, setOpen] = useState(!1);
9416
+ return !base || !i18n || current?.[i18n.field] !== master || !versions?.length ? base : {
9417
+ ...base,
9418
+ onHandle: () => setOpen(!0),
9419
+ dialog: open ? {
9420
+ type: "dialog",
9421
+ header: "Delete this document",
9422
+ width: "medium",
9423
+ onClose: () => setOpen(!1),
9424
+ content: /* @__PURE__ */ jsx(DeleteDialog, {
9425
+ id: props.id,
9426
+ language: String(current?.[i18n.field] ?? ""),
9427
+ versions,
9428
+ onDone: () => {
9429
+ setOpen(!1), props.onComplete();
9430
+ }
9431
+ })
9432
+ } : base.dialog
9433
+ };
9434
+ };
9435
+ return Wrapped;
9436
+ }
9437
+ function DeleteDialog(props) {
9438
+ let { id, language, onDone } = props, client = useKitClient(), toast = useToast(), [versions, setVersions] = useState(props.versions), [referrers, setReferrers] = useState(null), [busy, setBusy] = useState(!1), [error, setError] = useState(null), ids = [id, ...versions.filter((v) => v.selected).map((v) => v.id)], key = ids.join(",");
9439
+ useEffect(() => {
9440
+ setReferrers(null);
9441
+ let all = withDrafts(ids);
9442
+ client.fetch("*[references($ids) && !(_id in $all) && _type != \"translation.metadata\"]{_id, _type, \"title\": coalesce(title, name, heading, _id)}", {
9443
+ ids,
9444
+ all
9445
+ }).then(setReferrers).catch(() => setReferrers([]));
9446
+ }, [client, key]);
9447
+ let remove = async () => {
9448
+ setBusy(!0), setError(null);
9449
+ try {
9450
+ let tx = client.transaction();
9451
+ for (let docId of withDrafts(ids)) tx.delete(docId);
9452
+ let meta = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0]{_id, translations}", { id });
9453
+ if (meta) {
9454
+ let gone = (meta.translations ?? []).filter((t) => ids.includes(t.value?._ref ?? ""));
9455
+ (meta.translations ?? []).length - gone.length > 1 ? tx.patch(meta._id, (p) => p.unset(gone.map((t) => `translations[_key == "${t._key}"]`))) : tx.delete(meta._id);
9456
+ }
9457
+ await tx.commit({ visibility: "async" }), toast.push({
9458
+ status: "success",
9459
+ title: `Deleted: ${[language, ...versions.filter((v) => v.selected).map((v) => v.language)].map((l) => l.toUpperCase()).join(", ")}`,
9460
+ duration: 6e3
9461
+ }), onDone();
9462
+ } catch (cause) {
9463
+ setError(`Failed. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 160)})`), setBusy(!1);
9464
+ }
9465
+ }, blocked = !!referrers?.length;
9466
+ return /* @__PURE__ */ jsxs(Stack, {
9467
+ gap: 4,
9468
+ padding: 4,
9469
+ children: [
9470
+ /* @__PURE__ */ jsxs(Text, {
9471
+ size: 1,
9472
+ children: [
9473
+ "The ",
9474
+ language.toUpperCase(),
9475
+ " version will be deleted for good (published and draft). Delete the other language versions too?"
9476
+ ]
9477
+ }),
9478
+ /* @__PURE__ */ jsx(Stack, {
9479
+ gap: 2,
9480
+ children: versions.map((v, index) => /* @__PURE__ */ jsx(Card, {
9481
+ padding: 3,
9482
+ radius: 2,
9483
+ border: !0,
9484
+ children: /* @__PURE__ */ jsxs(Flex, {
9485
+ as: "label",
9486
+ gap: 3,
9487
+ align: "center",
9488
+ children: [/* @__PURE__ */ jsx(Checkbox, {
9489
+ checked: v.selected,
9490
+ disabled: busy,
9491
+ onChange: () => setVersions(versions.map((x, i) => i === index ? {
9492
+ ...x,
9493
+ selected: !x.selected
9494
+ } : x))
9495
+ }), /* @__PURE__ */ jsx(Text, {
9496
+ size: 1,
9497
+ weight: "semibold",
9498
+ children: v.language.toUpperCase()
9499
+ })]
9500
+ })
9501
+ }, v.id))
9502
+ }),
9503
+ referrers === null ? /* @__PURE__ */ jsx(Flex, {
9504
+ justify: "center",
9505
+ children: /* @__PURE__ */ jsx(Spinner, { muted: !0 })
9506
+ }) : blocked ? /* @__PURE__ */ jsx(Card, {
9507
+ tone: "critical",
9508
+ padding: 3,
9509
+ radius: 2,
9510
+ children: /* @__PURE__ */ jsxs(Stack, {
9511
+ gap: 2,
9512
+ children: [
9513
+ /* @__PURE__ */ jsx(Text, {
9514
+ size: 1,
9515
+ children: "Still referenced by these documents: remove the references first."
9516
+ }),
9517
+ referrers.slice(0, 8).map((r) => /* @__PURE__ */ jsxs(Text, {
9518
+ size: 1,
9519
+ muted: !0,
9520
+ children: [
9521
+ r.title,
9522
+ " (",
9523
+ r._type,
9524
+ ")"
9525
+ ]
9526
+ }, r._id)),
9527
+ referrers.length > 8 && /* @__PURE__ */ jsxs(Text, {
9528
+ size: 1,
9529
+ muted: !0,
9530
+ children: [
9531
+ "…and ",
9532
+ referrers.length - 8,
9533
+ " more"
9534
+ ]
9535
+ })
9536
+ ]
9537
+ })
9538
+ }) : null,
9539
+ error && /* @__PURE__ */ jsx(Card, {
9540
+ tone: "critical",
9541
+ padding: 3,
9542
+ radius: 2,
9543
+ children: /* @__PURE__ */ jsx(Text, {
9544
+ size: 1,
9545
+ children: error
9546
+ })
9547
+ }),
9548
+ /* @__PURE__ */ jsxs(Flex, {
9549
+ justify: "flex-end",
9550
+ gap: 2,
9551
+ children: [/* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Button, {
9552
+ text: "Cancel",
9553
+ mode: "ghost",
9554
+ onClick: onDone,
9555
+ disabled: busy
9556
+ }) }), /* @__PURE__ */ jsx(Button, {
9557
+ text: busy ? "Deleting…" : `Delete ${ids.length > 1 ? `${ids.length} versions` : `${language.toUpperCase()} only`}`,
9558
+ tone: "critical",
9559
+ onClick: () => void remove(),
9560
+ disabled: busy || referrers === null || blocked
9561
+ })]
9562
+ })
9563
+ ]
9564
+ });
9565
+ }
9328
9566
  /**
9329
9567
  * `pageTypes` déduits du registre du starter, pour ne pas redire au kit ce que
9330
9568
  * le site sait déjà : l'accueil (chemin fixe `/`) et chaque collection avec
@@ -9420,6 +9658,120 @@ function withMoreTool(tools, names = DEFAULT_MORE_TOOLS) {
9420
9658
  };
9421
9659
  return [...tools.filter((tool) => !names.includes(tool.name)), more];
9422
9660
  }
9661
+ const isObj$1 = (v) => {
9662
+ if (!v || typeof v != "object" || Array.isArray(v) || "$$typeof" in v) return !1;
9663
+ let proto = Object.getPrototypeOf(v);
9664
+ return proto === Object.prototype || proto === null;
9665
+ };
9666
+ /**
9667
+ * RÈGLE D'OR DU MULTILINGUE : une référence ne propose que des documents de la
9668
+ * MÊME langue que le document en cours (un article EN ne voit que les catégories EN,
9669
+ * une page FR que les pages FR). Les documents sans langue (logos, régions, assets…)
9670
+ * restent proposés. Un document commun à toutes les langues (Navigation…) vise la
9671
+ * langue principale.
9672
+ *
9673
+ * Pose ce filtre sur TOUS les champs de référence des types donnés (champs, listes,
9674
+ * objets imbriqués, annotations du texte riche), combiné avec un filtre déjà présent.
9675
+ * À appliquer aux types du projet :
9676
+ *
9677
+ * ```ts
9678
+ * schema: {types: withSameLanguageReferences(schemaTypes, ncfOptions)}
9679
+ * ```
9680
+ */
9681
+ function withSameLanguageReferences(types, options) {
9682
+ let i18n = options.i18n;
9683
+ if (!i18n) return types;
9684
+ let field = i18n.field ?? "language", fallback = i18n.defaultLocale ?? i18n.locales?.[0], condition = `(!defined(${field}) || ${field} == $ncfLanguage)`, languageOf = (document) => typeof document?.[field] == "string" && document[field] || fallback, wrap = (opts) => {
9685
+ let previous = opts?.filter, previousParams = opts?.filterParams ?? {}, filter = async (context) => {
9686
+ let base = typeof previous == "function" ? await previous(context) ?? {} : typeof previous == "string" ? {
9687
+ filter: previous,
9688
+ params: previousParams
9689
+ } : {};
9690
+ return {
9691
+ filter: base.filter ? `(${base.filter}) && ${condition}` : condition,
9692
+ params: {
9693
+ ...base.params ?? {},
9694
+ ncfLanguage: languageOf(context.document)
9695
+ }
9696
+ };
9697
+ }, { filterParams: _ignored, ...rest } = opts ?? {};
9698
+ return {
9699
+ ...rest,
9700
+ filter
9701
+ };
9702
+ }, visit = (node) => {
9703
+ if (Array.isArray(node)) return node.map(visit);
9704
+ if (!isObj$1(node)) return node;
9705
+ let out = {};
9706
+ for (let [key, value] of Object.entries(node)) out[key] = key === "options" || key === "initialValue" || key === "validation" ? value : visit(value);
9707
+ return node.type === "reference" && Array.isArray(node.to) && (out.options = wrap(node.options)), out;
9708
+ };
9709
+ return types.map((t) => visit(t));
9710
+ }
9711
+ const isObj = (v) => !!v && typeof v == "object" && !Array.isArray(v), bare = (id) => id.replace(/^drafts\./, "");
9712
+ /** Références d'une valeur, avec leur chemin de patch (`a.b[_key=="x"].c`). */
9713
+ function refs(value, path, out) {
9714
+ if (Array.isArray(value)) {
9715
+ value.forEach((item, i) => refs(item, `${path}[${isObj(item) && typeof item._key == "string" ? `_key=="${item._key}"` : i}]`, out));
9716
+ return;
9717
+ }
9718
+ if (isObj(value)) {
9719
+ typeof value._ref == "string" && !/^(image|file)-/.test(value._ref) && out.push({
9720
+ path: `${path}._ref`,
9721
+ ref: value._ref
9722
+ });
9723
+ for (let [k, v] of Object.entries(value)) k.startsWith("_") || refs(v, path ? `${path}.${k}` : k, out);
9724
+ }
9725
+ }
9726
+ /**
9727
+ * RÈGLE D'OR DU MULTILINGUE, côté données : chaque référence d'un document vise un
9728
+ * document de SA langue (document sans langue : la langue principale). Une
9729
+ * référence croisée est repointée vers la traduction de la bonne langue (liens de
9730
+ * traduction) ; sans traduction, elle est signalée et laissée. Publiés et
9731
+ * brouillons. `apply: false` : simulation.
9732
+ *
9733
+ * ```ts
9734
+ * // studio/scripts/references-same-language.ts (sanity exec --with-user-token)
9735
+ * const report = await fixCrossLanguageReferences(getCliClient(...), {defaultLocale: 'fr', apply})
9736
+ * ```
9737
+ */
9738
+ async function fixCrossLanguageReferences(client, options) {
9739
+ let field = options.field ?? "language", c = client.withConfig({ perspective: "raw" }), docs = await c.fetch("*[!(_type match \"system.*\") && !(_type match \"sanity.*\") && !(_type match \"ncf.*\") && _type != \"translation.metadata\"]"), language = /* @__PURE__ */ new Map();
9740
+ for (let d of docs) typeof d[field] == "string" && language.set(bare(String(d._id)), String(d[field]));
9741
+ let metas = await c.fetch("*[_type == \"translation.metadata\"]{translations}"), equivalent = /* @__PURE__ */ new Map();
9742
+ for (let m of metas) {
9743
+ let group = /* @__PURE__ */ new Map();
9744
+ for (let t of m.translations ?? []) t.value?._ref && group.set(t.language ?? t._key ?? "", t.value._ref);
9745
+ for (let id of group.values()) equivalent.set(id, group);
9746
+ }
9747
+ let report = {
9748
+ fixed: [],
9749
+ missing: []
9750
+ };
9751
+ for (let d of docs) {
9752
+ let own = typeof d[field] == "string" ? String(d[field]) : options.defaultLocale, found = [];
9753
+ for (let [k, v] of Object.entries(d)) k.startsWith("_") || refs(v, k, found);
9754
+ let set = {};
9755
+ for (let { path, ref } of found) {
9756
+ let target = language.get(bare(ref));
9757
+ if (!target || target === own) continue;
9758
+ let to = equivalent.get(bare(ref))?.get(own);
9759
+ to ? (set[path] = to, report.fixed.push({
9760
+ documentId: String(d._id),
9761
+ path,
9762
+ from: ref,
9763
+ to
9764
+ })) : report.missing.push({
9765
+ documentId: String(d._id),
9766
+ path,
9767
+ ref,
9768
+ language: own
9769
+ });
9770
+ }
9771
+ options.apply && Object.keys(set).length && await c.patch(String(d._id)).ifRevisionId(String(d._rev)).set(set).commit({ visibility: "async" });
9772
+ }
9773
+ return report;
9774
+ }
9423
9775
  /**
9424
9776
  * Bascule brouillons / en ligne, posée dans l'aperçu lui-même.
9425
9777
  *
@@ -9966,7 +10318,7 @@ const ncfKit = definePlugin((options) => {
9966
10318
  },
9967
10319
  document: {
9968
10320
  newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
9969
- actions: (prev, context) => config.pageTypeNames.includes(context.schemaType) ? prev.map((action) => action.action === "unpublish" ? RemoveFromSiteAction : action.action === "publish" && config.i18n ? withPropagation(action, config, void 0, { allowCreate: !0 }) : action) : context.schemaType === config.componentPreview.defaultsType && config.i18n ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action) : config.i18n && !isKitType(context.schemaType) && hasLanguageField(context.schema.get(context.schemaType), config.i18n.field) ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, void 0, { allowCreate: !0 }) : action) : prev
10321
+ actions: (prev, context) => config.pageTypeNames.includes(context.schemaType) ? prev.map((action) => action.action === "unpublish" ? config.i18n ? createRemoveFromSite(config) : RemoveFromSiteAction : action.action === "publish" && config.i18n ? withPropagation(action, config, void 0, { allowCreate: !0 }) : action.action === "delete" && config.i18n ? withTranslationDelete(action, config) : action) : context.schemaType === config.componentPreview.defaultsType && config.i18n ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action.action === "delete" ? withTranslationDelete(action, config, config.i18n?.defaultsSourceLocale) : action) : config.i18n && !isKitType(context.schemaType) && hasLanguageField(context.schema.get(context.schemaType), config.i18n.field) ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, void 0, { allowCreate: !0 }) : action.action === "delete" ? withTranslationDelete(action, config) : action.action === "unpublish" ? createRemoveFromSite(config) : action) : prev
9970
10322
  },
9971
10323
  studio: { components: { toolMenu: createPreviewLauncher(config, issues) } },
9972
10324
  form: { components: { input: createKitInput(config) } }
@@ -9977,6 +10329,6 @@ function hasLanguageField(schemaType, field) {
9977
10329
  let fields = schemaType?.fields;
9978
10330
  return Array.isArray(fields) && fields.some((f) => f?.name === field);
9979
10331
  }
9980
- export { ANNOTATION_TYPE, ActorName, BOARD_LAYOUT_ID, BOARD_LAYOUT_TYPE, BRAIN_NODE_SIZE, BoardLayoutProvider, COLUMN_TYPE, CONTENT_SCAN_LIMIT, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, CUSTOM_ENVIRONMENT_ID, DATA_PREFIX, DEFAULT_BOARD_TAGS, DEFAULT_COMPONENT_DEFAULTS_TYPE, DEFAULT_COMPONENT_PREVIEW, DEFAULT_I18N, DEFAULT_INTERNAL_FIELDS, DEFAULT_MORE_TOOLS, DEFAULT_PAGE_BUILDER_FIELD, DEFAULT_SLUG_FIELD, DEFAULT_TITLE_FIELD, KIT_API_VERSION, KIT_VERSION, NCF_COMPONENTS_TOOL, NCF_DESIGN_SYSTEM_TOOL, NCF_HIDDEN_TYPES, NCF_HISTORY_TOOL, NCF_MORE_TOOL, NCF_PAGES_TOOL, NCF_TOOL_NAMES, NODE_FIELD_TYPE, NODE_HEIGHT, NODE_WIDTH, NcfKitUpdate, NcfPreviewHeader, NcfPreviewLauncher, PERSPECTIVES, PROJECTION, SECTION_NODE_TYPE, STATUS_COLORS, STATUS_LABELS, SharePreview, UNSET_LABEL, addColumn, addColumnOption, announce, applySavedPositions, baseId, blockName, blockTypesFromSchema, buildContentsQuery, buildLinkGraph, buildPageRows, buildPagesQuery, collectLinks, collectOccurrences, colorForRow, colorFromString, columnId, compareVersions, componentDefaultsMainDocument, componentDefaultsMainDocuments, createPreviewLauncher, customEnvironment, defaultNodeSize, defaultsFieldName, defineComponentDefaults, depth, deriveDocumentColumns, diffDocuments, diffWords, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterRows, flatten, formatDocumentValue, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, ncfAllowedOrigins, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, segments, slugKey, sortRows, summarize, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useBoardLayout, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withMoreTool };
10332
+ export { ANNOTATION_TYPE, ActorName, BOARD_LAYOUT_ID, BOARD_LAYOUT_TYPE, BRAIN_NODE_SIZE, BoardLayoutProvider, COLUMN_TYPE, CONTENT_SCAN_LIMIT, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, CUSTOM_ENVIRONMENT_ID, DATA_PREFIX, DEFAULT_BOARD_TAGS, DEFAULT_COMPONENT_DEFAULTS_TYPE, DEFAULT_COMPONENT_PREVIEW, DEFAULT_I18N, DEFAULT_INTERNAL_FIELDS, DEFAULT_MORE_TOOLS, DEFAULT_PAGE_BUILDER_FIELD, DEFAULT_SLUG_FIELD, DEFAULT_TITLE_FIELD, KIT_API_VERSION, KIT_VERSION, NCF_COMPONENTS_TOOL, NCF_DESIGN_SYSTEM_TOOL, NCF_HIDDEN_TYPES, NCF_HISTORY_TOOL, NCF_MORE_TOOL, NCF_PAGES_TOOL, NCF_TOOL_NAMES, NODE_FIELD_TYPE, NODE_HEIGHT, NODE_WIDTH, NcfKitUpdate, NcfPreviewHeader, NcfPreviewLauncher, PERSPECTIVES, PROJECTION, SECTION_NODE_TYPE, STATUS_COLORS, STATUS_LABELS, SharePreview, UNSET_LABEL, addColumn, addColumnOption, announce, applySavedPositions, baseId, blockName, blockTypesFromSchema, buildContentsQuery, buildLinkGraph, buildPageRows, buildPagesQuery, collectLinks, collectOccurrences, colorForRow, colorFromString, columnId, compareVersions, componentDefaultsMainDocument, componentDefaultsMainDocuments, createPreviewLauncher, customEnvironment, defaultNodeSize, defaultsFieldName, defineComponentDefaults, depth, deriveDocumentColumns, diffDocuments, diffWords, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterRows, fixCrossLanguageReferences, flatten, formatDocumentValue, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, ncfAllowedOrigins, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, segments, slugKey, sortRows, summarize, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useBoardLayout, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withMoreTool, withSameLanguageReferences };
9981
10333
 
9982
10334
  //# sourceMappingURL=index.js.map