@nocode-factory/sanity-kit 2.28.0 → 2.29.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.d.ts CHANGED
@@ -1348,7 +1348,7 @@ export declare function ActorName(props: {
1348
1348
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1349
1349
  * le vérifie.
1350
1350
  */
1351
- export declare const KIT_VERSION = "2.28.0";
1351
+ export declare const KIT_VERSION = "2.29.0";
1352
1352
  /**
1353
1353
  * Données de la page proposées comme colonnes.
1354
1354
  *
package/dist/index.js CHANGED
@@ -1420,7 +1420,7 @@ function explainGrantError(error) {
1420
1420
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1421
1421
  * le vérifie.
1422
1422
  */
1423
- const KIT_VERSION = "2.28.0";
1423
+ const KIT_VERSION = "2.29.0";
1424
1424
  /**
1425
1425
  * Signale ce Studio au service du kit, une fois par montage.
1426
1426
  *
@@ -1763,7 +1763,7 @@ function useKitUpdate() {
1763
1763
  !controller.signal.aborted && body?.version && setLatest(body.version);
1764
1764
  }).catch(() => {}), () => controller.abort();
1765
1765
  }, []);
1766
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.28.0") > 0);
1766
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.29.0") > 0);
1767
1767
  return {
1768
1768
  current: KIT_VERSION,
1769
1769
  latest,
@@ -8250,7 +8250,7 @@ function withTranslationTodo(Inner, config) {
8250
8250
  return client.getDocument(sourceId).then((doc) => {
8251
8251
  if (!alive) return;
8252
8252
  let text = collectTexts$1(valueAtKey(doc, key)).join("").trim();
8253
- setMaster(text || null);
8253
+ setMaster(text || "(empty: follows the component default)");
8254
8254
  }).catch(() => alive && setMaster(null)), () => {
8255
8255
  alive = !1;
8256
8256
  };
@@ -8266,9 +8266,12 @@ function withTranslationTodo(Inner, config) {
8266
8266
  setBusy(!0), setError(null);
8267
8267
  try {
8268
8268
  let value = valueAtKey(await client.getDocument(todo.sourceId) ?? await client.getDocument(`drafts.${todo.sourceId}`), key);
8269
- if (value === void 0) throw Error("Source text not found.");
8270
- let [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value]);
8271
- props.onChange(set(translated)), await client.patch(todo._id).set({ paths: (todo.paths ?? []).filter((p) => p !== key) }).commit();
8269
+ if (!collectTexts$1(value).some((t) => t.trim())) props.onChange(unset());
8270
+ else {
8271
+ let [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value]);
8272
+ props.onChange(set(translated));
8273
+ }
8274
+ await client.patch(todo._id).set({ paths: (todo.paths ?? []).filter((p) => p !== key) }).commit();
8272
8275
  } catch (cause) {
8273
8276
  setError(cause instanceof Error ? cause.message : String(cause));
8274
8277
  } finally {
@@ -8580,37 +8583,58 @@ function propagate(target, before, after, documentType) {
8580
8583
  function hasChanges(r) {
8581
8584
  return r.toTranslate.length > 0 || r.copied.length > 0 || r.added > 0 || r.removed > 0 || r.moved;
8582
8585
  }
8583
- /**
8584
- * Publier la version PRINCIPALE d'une page qui a des traductions : la publication
8585
- * part normalement, puis « Propager aux autres langues ? » propose d'appliquer aux
8586
- * BROUILLONS des traductions la structure (sections ajoutées, supprimées, déplacées)
8587
- * et les valeurs non textuelles (images, liens, options…). Les textes traduits ne
8588
- * sont jamais écrasés à la main : les textes modifiés sont traduits par l'IA
8589
- * (« Translate with AI », service du kit, coché par défaut) ou marqués « à
8590
- * traduire ». Rien n'est publié dans les autres langues : on relit, on publie.
8586
+ /** Slug d'URL depuis un titre : sans accents, minuscules, tirets. */
8587
+ function slugify(input, maxLength = 96) {
8588
+ return input.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxLength).replace(/-+$/g, "");
8589
+ }
8590
+ /**
8591
+ * Publier la version PRINCIPALE d'une page :
8592
+ * - page déjà publiée qui a des traductions : « Propagate to other languages? »
8593
+ * applique la structure (sections ajoutées, supprimées, déplacées) et les valeurs
8594
+ * non textuelles (images, liens, options…) ;
8595
+ * - PREMIÈRE publication : « Create the other language versions? » crée la page dans
8596
+ * chaque langue cochée, reliée à ses traductions (hreflang, bascule de langue).
8597
+ * Avec « Translate with AI » (service du kit, coché par défaut) : textes traduits
8598
+ * par l'IA et versions PUBLIÉES directement (aucun clic de plus). Sans, ou si l'IA
8599
+ * échoue : brouillons, textes marqués « To translate ». Une modification d'une autre
8600
+ * langue ne remonte jamais à la version principale.
8591
8601
  * `masterLocale` : langue source (défaut : langue principale du site ; les valeurs
8592
- * par défaut des composants ont la leur, `i18n.defaultsSourceLocale`).
8602
+ * par défaut des composants ont la leur, `i18n.defaultsSourceLocale`). `allowCreate` :
8603
+ * propose la création des autres versions (types de pages seulement).
8593
8604
  */
8594
- function withPropagation(Publish, config, masterLocale) {
8605
+ function withPropagation(Publish, config, masterLocale, options = {}) {
8595
8606
  let i18n = config.i18n, master = masterLocale ?? i18n?.defaultLocale, Wrapped = (props) => {
8596
8607
  let base = Publish(props), client = useKitClient(), schema = useSchema(), [run, setRun] = useState(null), current = props.draft ?? props.published;
8597
8608
  return !base || !i18n || current?.[i18n.field] !== master ? base : {
8598
8609
  ...base,
8599
8610
  onHandle: () => {
8600
8611
  let before = props.published, after = props.draft;
8601
- if (base.onHandle?.(), !before || !after) return;
8602
- let documentType = schema.get(props.type);
8603
- findTargets(client, props.id, String(after[i18n.field] ?? ""), before, after, documentType).then((targets) => {
8612
+ if (base.onHandle?.(), !after) return;
8613
+ let documentType = schema.get(props.type), source = String(after[i18n.field] ?? "");
8614
+ before ? findTargets(client, props.id, source, before, after, documentType).then((targets) => {
8604
8615
  targets.some((t) => hasChanges(t.result)) && setRun({
8605
- before,
8616
+ mode: "update",
8606
8617
  after,
8607
8618
  targets
8608
8619
  });
8620
+ }).catch(() => {}) : options.allowCreate && findMissing(client, props.id, source, i18n.locales).then((missing) => {
8621
+ if (!missing.length) return;
8622
+ let result = propagate({}, {}, after, documentType);
8623
+ setRun({
8624
+ mode: "create",
8625
+ after,
8626
+ targets: missing.map((language) => ({
8627
+ language,
8628
+ id: null,
8629
+ result,
8630
+ selected: !0
8631
+ }))
8632
+ });
8609
8633
  }).catch(() => {});
8610
8634
  },
8611
8635
  dialog: run ? {
8612
8636
  type: "dialog",
8613
- header: "Propagate to other languages?",
8637
+ header: run.mode === "create" ? "Create the other language versions?" : "Propagate to other languages?",
8614
8638
  width: "medium",
8615
8639
  onClose: () => {
8616
8640
  setRun(null), props.onComplete();
@@ -8619,7 +8643,7 @@ function withPropagation(Publish, config, masterLocale) {
8619
8643
  config,
8620
8644
  id: props.id,
8621
8645
  type: props.type,
8622
- before: run.before,
8646
+ mode: run.mode,
8623
8647
  after: run.after,
8624
8648
  targets: run.targets,
8625
8649
  onDone: () => {
@@ -8631,10 +8655,16 @@ function withPropagation(Publish, config, masterLocale) {
8631
8655
  };
8632
8656
  return Wrapped.action = Publish.action, Wrapped;
8633
8657
  }
8658
+ async function translationsOf(client, id) {
8659
+ return (await client.fetch("*[_type == \"translation.metadata\" && references($id)][0].translations[]{language, \"key\": _key, \"id\": value._ref}", { id }) ?? []).map((t) => ({
8660
+ language: t.language ?? t.key ?? "",
8661
+ id: t.id ?? ""
8662
+ })).filter((t) => t.language && t.id);
8663
+ }
8634
8664
  async function findTargets(client, id, source, before, after, documentType) {
8635
- let translations = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0].translations[]{language, \"id\": value._ref}", { id }), list = [];
8636
- for (let t of translations ?? []) {
8637
- if (!t?.id || t.id === id || t.language === source) continue;
8665
+ let list = [];
8666
+ for (let t of await translationsOf(client, id)) {
8667
+ if (t.id === id || t.language === source) continue;
8638
8668
  let target = await client.getDocument(`drafts.${t.id}`) ?? await client.getDocument(t.id) ?? null;
8639
8669
  if (!target) continue;
8640
8670
  let result = propagate(target, before, after, documentType);
@@ -8647,45 +8677,93 @@ async function findTargets(client, id, source, before, after, documentType) {
8647
8677
  }
8648
8678
  return list;
8649
8679
  }
8680
+ async function findMissing(client, id, source, locales) {
8681
+ let existing = new Set((await translationsOf(client, id)).map((t) => t.language));
8682
+ return locales.filter((l) => l !== source && !existing.has(l));
8683
+ }
8684
+ const randomId = () => typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
8685
+ /** Relie les nouvelles versions à la page (translation.metadata de document-internationalization). */
8686
+ async function linkTranslations(client, sourceId, sourceLanguage, type, created) {
8687
+ if (!created.length) return;
8688
+ let item = (language, ref) => ({
8689
+ _key: language,
8690
+ _type: "internationalizedArrayReferenceValue",
8691
+ language,
8692
+ value: {
8693
+ _type: "reference",
8694
+ _ref: ref,
8695
+ _weak: !0,
8696
+ _strengthenOnPublish: { type }
8697
+ }
8698
+ }), meta = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0]{_id}", { id: sourceId });
8699
+ meta ? await client.patch(meta._id).setIfMissing({ translations: [] }).append("translations", created.map((c) => item(c.language, c.id))).commit() : await client.create({
8700
+ _id: randomId(),
8701
+ _type: "translation.metadata",
8702
+ schemaTypes: [type],
8703
+ translations: [item(sourceLanguage, sourceId), ...created.map((c) => item(c.language, c.id))]
8704
+ });
8705
+ }
8650
8706
  function PropagateDialog(props) {
8651
- let { config, id, type, after, onDone } = props, client = useKitClient(), 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), apply = async () => {
8707
+ let { config, id, type, mode, after, onDone } = props, client = useKitClient(), field = config.i18n?.field ?? "language", source = String(after[field] ?? ""), pageType = config.pageTypes.find((t) => t.type === type), [targets, setTargets] = useState(props.targets), [busy, setBusy] = useState(!1), toast = useToast(), [error, setError] = useState(null), [ai, setAi] = useState(!!config.history), hasTexts = targets.some((t) => t.result.toTranslate.length), apply = async () => {
8652
8708
  setBusy(!0), setError(null);
8653
8709
  try {
8654
- let applied = [], translatedCount = 0, aiError = null;
8710
+ let published = [], drafted = [], created = [], aiError = null;
8655
8711
  for (let t of targets) {
8656
8712
  if (!t.selected) continue;
8657
- let { _rev, _createdAt, _updatedAt, ...doc } = t.result.document, remaining = t.result.toTranslate;
8713
+ let { _id, _rev, _createdAt, _updatedAt, ...doc } = structuredClone(t.result.document), targetId = t.id ?? randomId(), remaining = t.result.toTranslate, translatedOk = !remaining.length;
8658
8714
  if (ai && config.history && remaining.length) try {
8659
- let values = remaining.map((path) => valueAtKey(after, path)), translated = await translateValues(config.history, source, t.language, values);
8660
- remaining = remaining.filter((path, n) => values[n] === void 0 || !setAtKey(doc, path, translated[n])), translatedCount += t.result.toTranslate.length - remaining.length;
8715
+ 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 ?? ""));
8716
+ remaining = remaining.filter((path, n) => !setAtKey(doc, path, toSend[n] === void 0 ? void 0 : translated[n])), translatedOk = !remaining.length;
8661
8717
  } catch (cause) {
8662
8718
  aiError = cause instanceof Error ? cause.message : String(cause);
8663
8719
  }
8664
- if (await client.createOrReplace({
8720
+ if (mode === "create") {
8721
+ doc[field] = t.language;
8722
+ let slugField = pageType?.slugField, titleField = pageType?.titleField ?? "title", title = typeof doc[titleField] == "string" ? doc[titleField] : "", sourceSlug = slugField ? after[slugField]?.current : void 0;
8723
+ if (slugField && (title || sourceSlug)) {
8724
+ let base = slugify(title) || String(sourceSlug), slug = base;
8725
+ for (let n = 2; await client.fetch(`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**"))]) > 0`, {
8726
+ type,
8727
+ slug,
8728
+ language: t.language
8729
+ }); n++) slug = `${base}-${n}`;
8730
+ doc[slugField] = {
8731
+ _type: "slug",
8732
+ current: slug
8733
+ };
8734
+ }
8735
+ }
8736
+ let publish = ai && translatedOk, tx = client.transaction();
8737
+ publish ? (tx.createOrReplace({
8665
8738
  ...doc,
8666
- _id: `drafts.${t.id}`,
8739
+ _id: targetId,
8667
8740
  _type: type
8668
- }), remaining.length) {
8669
- let todoId = translationTodoId(t.id), existing = await client.fetch("*[_id == $todoId][0].paths", { todoId });
8670
- await client.createOrReplace({
8671
- _id: todoId,
8672
- _type: TRANSLATION_TODO_TYPE,
8673
- documentId: t.id,
8674
- sourceId: id,
8675
- sourceLanguage: source,
8676
- paths: [.../* @__PURE__ */ new Set([...existing ?? [], ...remaining])]
8677
- });
8678
- }
8679
- applied.push(t.language.toUpperCase());
8741
+ }), t.id && tx.delete(`drafts.${t.id}`)) : tx.createOrReplace({
8742
+ ...doc,
8743
+ _id: `drafts.${targetId}`,
8744
+ _type: type
8745
+ }), await tx.commit();
8746
+ let todoId = translationTodoId(targetId), existing = await client.fetch("*[_id == $todoId][0].paths", { todoId }) ?? [], done = new Set(t.result.toTranslate.filter((p) => !remaining.includes(p))), paths = [.../* @__PURE__ */ new Set([...existing.filter((p) => !done.has(p)), ...remaining])];
8747
+ (paths.length || existing.length) && await client.createOrReplace({
8748
+ _id: todoId,
8749
+ _type: TRANSLATION_TODO_TYPE,
8750
+ documentId: targetId,
8751
+ sourceId: id,
8752
+ sourceLanguage: source,
8753
+ paths
8754
+ }), t.id || created.push({
8755
+ language: t.language,
8756
+ id: targetId
8757
+ }), (publish ? published : drafted).push(t.language.toUpperCase());
8680
8758
  }
8681
- toast.push({
8759
+ await linkTranslations(client, id, source, type, created), toast.push({
8682
8760
  status: aiError ? "warning" : "success",
8683
- title: `Drafts updated: ${applied.join(", ")}`,
8684
- description: aiError ? `AI translation failed (${aiError}): the changed texts are marked "To translate".` : translatedCount ? `${translatedCount} text${translatedCount > 1 ? "s" : ""} translated with AI. Review, then publish each language.` : "Translate the fields marked \"To translate\", then publish each language.",
8761
+ title: [published.length ? `Published: ${published.join(", ")}` : "", drafted.length ? `Drafts: ${drafted.join(", ")}` : ""].filter(Boolean).join(" · "),
8762
+ 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.",
8685
8763
  duration: 8e3
8686
8764
  }), onDone();
8687
8765
  } catch (cause) {
8688
- setError(`Propagation failed, nothing was published. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 140)})`);
8766
+ setError(`Failed. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 160)})`);
8689
8767
  } finally {
8690
8768
  setBusy(!1);
8691
8769
  }
@@ -8697,14 +8775,12 @@ function PropagateDialog(props) {
8697
8775
  /* @__PURE__ */ jsxs(Text, {
8698
8776
  size: 1,
8699
8777
  children: [
8700
- "The ",
8701
- source.toUpperCase(),
8702
- " version is published. Apply its changes to the drafts of the other languages? Changed texts are ",
8703
- ai ? "translated with AI" : "marked \"To translate\"",
8704
- ". Nothing is published."
8778
+ mode === "create" ? `The ${source.toUpperCase()} page is published. Create it in the other languages?` : `The ${source.toUpperCase()} version is published. Apply its changes to the other languages?`,
8779
+ " ",
8780
+ ai ? "Texts are translated with AI and each language is published." : "Each language is saved as a draft, texts marked \"To translate\"."
8705
8781
  ]
8706
8782
  }),
8707
- config.history && targets.some((t) => t.result.toTranslate.length) && /* @__PURE__ */ jsxs(Flex, {
8783
+ config.history && hasTexts && /* @__PURE__ */ jsxs(Flex, {
8708
8784
  as: "label",
8709
8785
  align: "center",
8710
8786
  gap: 2,
@@ -8713,7 +8789,7 @@ function PropagateDialog(props) {
8713
8789
  onChange: () => setAi(!ai)
8714
8790
  }), /* @__PURE__ */ jsx(Text, {
8715
8791
  size: 1,
8716
- children: "Translate changed texts with AI"
8792
+ children: "Translate with AI and publish"
8717
8793
  })]
8718
8794
  }),
8719
8795
  /* @__PURE__ */ jsx(Stack, {
@@ -8727,7 +8803,7 @@ function PropagateDialog(props) {
8727
8803
  align: "flex-start",
8728
8804
  children: [/* @__PURE__ */ jsx(Checkbox, {
8729
8805
  checked: t.selected,
8730
- disabled: !hasChanges(t.result),
8806
+ disabled: mode === "update" && !hasChanges(t.result),
8731
8807
  onChange: () => setTargets(targets.map((x, i) => i === index ? {
8732
8808
  ...x,
8733
8809
  selected: !x.selected
@@ -8743,12 +8819,12 @@ function PropagateDialog(props) {
8743
8819
  }), /* @__PURE__ */ jsx(Text, {
8744
8820
  size: 1,
8745
8821
  muted: !0,
8746
- children: summary(t.result)
8822
+ children: mode === "create" ? `New version (${t.result.toTranslate.length} texts)` : summary(t.result)
8747
8823
  })]
8748
8824
  })
8749
8825
  })]
8750
8826
  })
8751
- }, t.id))
8827
+ }, `${t.language}-${t.id ?? "new"}`))
8752
8828
  }),
8753
8829
  error && /* @__PURE__ */ jsx(Card, {
8754
8830
  tone: "critical",
@@ -8768,7 +8844,7 @@ function PropagateDialog(props) {
8768
8844
  onClick: onDone,
8769
8845
  disabled: busy
8770
8846
  }), /* @__PURE__ */ jsx(Button, {
8771
- text: busy ? "Propagating…" : "Propagate",
8847
+ text: busy ? "Working…" : mode === "create" ? "Create" : "Propagate",
8772
8848
  tone: "primary",
8773
8849
  onClick: () => void apply(),
8774
8850
  disabled: busy || !targets.some((t) => t.selected)
@@ -9091,7 +9167,7 @@ const ncfKit = definePlugin((options) => {
9091
9167
  },
9092
9168
  document: {
9093
9169
  newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
9094
- actions: (prev, context) => config.pageTypeNames.includes(context.schemaType) ? prev.map((action) => action.action === "unpublish" ? RemoveFromSiteAction : action.action === "publish" && config.i18n ? withPropagation(action, config) : action) : context.schemaType === config.componentPreview.defaultsType && config.i18n ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action) : prev
9170
+ 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) : prev
9095
9171
  },
9096
9172
  studio: { components: { toolMenu: createPreviewLauncher(config, issues) } },
9097
9173
  form: { components: { input: createKitInput(config) } }