@nocode-factory/sanity-kit 2.20.1 → 2.21.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/README.md CHANGED
@@ -85,7 +85,9 @@ Dans le Studio :
85
85
  la Map, chaque page listée ouvre le formulaire sur l'instance.
86
86
  - **Propager aux autres langues** (publication de la version principale) : structure
87
87
  et valeurs non textuelles appliquées aux brouillons des traductions, textes modifiés
88
- marqués « À traduire » (jamais écrasés).
88
+ marqués « À traduire » (jamais écrasés). Onglet Pages : pastille « À traduire · n »
89
+ et filtre. Traduction groupée : `npx ncf-kit translations` (export JSON) puis
90
+ `npx ncf-kit translations apply <fichier>` (brouillons, rien de publié).
89
91
  - **Retirer du site** (actions d'une page) : dépublie sans rien perdre (contenu gardé
90
92
  en brouillon), après avoir listé les documents qui pointent vers la page.
91
93
  - **Champ Slug d'une page** : l'adresse complète de la page en ligne s'affiche
package/bin/ncf-kit.mjs CHANGED
@@ -34,6 +34,8 @@ function usage(code = 0) {
34
34
  npx ncf-kit setup --types page,homePage [options] active le projet, clé du journal, webhook
35
35
  npx ncf-kit doctor [--web <dossier>] [--offline] vérifie que le projet est complet
36
36
  npx ncf-kit check-environments [--page <chemin>] test prod / préprod, BLOQUANT (postbuild du site)
37
+ npx ncf-kit translations [export] [--out <fichier>] champs « À traduire » → JSON (texte source et actuel)
38
+ npx ncf-kit translations apply <fichier> écrit les traductions dans les brouillons
37
39
 
38
40
  Depuis le dossier du studio (celui de sanity.config.ts et de .env).
39
41
 
@@ -406,10 +408,146 @@ async function doctor() {
406
408
  process.exit(kos ? 1 : 0)
407
409
  }
408
410
 
411
+ // ─── translations : champs « À traduire » (propagation depuis la version principale) ───
412
+ // export : écrit un fichier JSON (une entrée par page traduite, chaque champ avec le
413
+ // texte de la version principale et le texte actuel) ; on le remplit
414
+ // (champ `translation` de chaque élément, ex. depuis Claude Code), puis
415
+ // apply : écrit chaque traduction dans le BROUILLON de la page et retire le champ de
416
+ // la liste « À traduire ». Rien n'est publié. Texte riche : `translation` est
417
+ // le tableau de blocs complet (mêmes _key, textes traduits).
418
+ const TODO_TYPE = 'ncfTranslationTodo'
419
+
420
+ /** `sections[a].title` → segments ; `[x]` = clé d'élément (ou rang si la liste n'a pas de clé). */
421
+ function parsePath(path) {
422
+ const out = []
423
+ for (const m of path.matchAll(/([^.[\]]+)|\[([^\]]+)\]/g)) out.push(m[1] !== undefined ? {field: m[1]} : {item: m[2]})
424
+ return out
425
+ }
426
+ function valueAt(doc, path) {
427
+ let cur = doc
428
+ for (const seg of parsePath(path)) {
429
+ if (cur == null) return undefined
430
+ if (seg.field) cur = cur[seg.field]
431
+ else if (Array.isArray(cur)) cur = cur.find((i) => i && i._key === seg.item) ?? (/^\d+$/.test(seg.item) ? cur[Number(seg.item)] : undefined)
432
+ else return undefined
433
+ }
434
+ return cur
435
+ }
436
+ /** Chemin de patch Sanity : `sections[_key=="a"].title`. */
437
+ function patchPath(doc, path) {
438
+ let cur = doc
439
+ let out = ''
440
+ for (const seg of parsePath(path)) {
441
+ if (seg.field) {
442
+ out += out ? `.${seg.field}` : seg.field
443
+ cur = cur?.[seg.field]
444
+ } else {
445
+ const byKey = Array.isArray(cur) && cur.some((i) => i && i._key === seg.item)
446
+ out += byKey || !/^\d+$/.test(seg.item) ? `[_key=="${seg.item}"]` : `[${seg.item}]`
447
+ cur = Array.isArray(cur) ? (cur.find((i) => i && i._key === seg.item) ?? cur[Number(seg.item)]) : undefined
448
+ }
449
+ }
450
+ return out
451
+ }
452
+
453
+ async function translations() {
454
+ const sub = args[1] && !args[1].startsWith('--') ? args[1] : 'export'
455
+ const dir = resolve(flag('dir') ?? process.cwd())
456
+ const envFile = join(dir, '.env')
457
+ const env = existsSync(envFile) ? parseEnv(readFileSync(envFile, 'utf8')) : {}
458
+ const projectId = env.SANITY_STUDIO_PROJECT_ID ?? process.env.SANITY_STUDIO_PROJECT_ID
459
+ const dataset = flag('dataset') ?? env.SANITY_STUDIO_DATASET ?? 'production'
460
+ if (!projectId) fail('SANITY_STUDIO_PROJECT_ID introuvable : lance la commande depuis le dossier du studio.')
461
+ const token = sanityToken()
462
+ if (!token) fail('Aucun jeton Sanity : lance `npx sanity login`, ou exporte SANITY_AUTH_TOKEN.')
463
+ const api = `https://${projectId}.api.sanity.io/v2025-02-19/data`
464
+ const headers = {authorization: `Bearer ${token}`, 'content-type': 'application/json'}
465
+ const query = async (q, params = {}) => {
466
+ const url = new URL(`${api}/query/${dataset}`)
467
+ url.searchParams.set('query', q)
468
+ url.searchParams.set('perspective', 'raw')
469
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(`$${k}`, JSON.stringify(v))
470
+ const r = await request(url, {headers})
471
+ if (!r.ok) fail(`Lecture Sanity refusée (${r.status}) : ${JSON.stringify(r.body).slice(0, 200)}`)
472
+ return r.body.result
473
+ }
474
+ const mutate = async (mutations) => {
475
+ const r = await request(`${api}/mutate/${dataset}?returnIds=true`, {method: 'POST', headers, body: JSON.stringify({mutations})})
476
+ if (!r.ok) fail(`Écriture Sanity refusée (${r.status}) : ${JSON.stringify(r.body).slice(0, 300)}`)
477
+ }
478
+
479
+ if (sub === 'export') {
480
+ const out = resolve(flag('out') ?? 'translations-todo.json')
481
+ const todos = await query(`*[_type == $type && count(paths) > 0]{_id, documentId, sourceId, sourceLanguage, paths}`, {type: TODO_TYPE})
482
+ const entries = []
483
+ for (const todo of todos) {
484
+ const [draft, published, source] = await Promise.all([
485
+ query(`*[_id == $id][0]`, {id: `drafts.${todo.documentId}`}),
486
+ query(`*[_id == $id][0]`, {id: todo.documentId}),
487
+ query(`*[_id == $id][0]`, {id: todo.sourceId}),
488
+ ])
489
+ const target = draft ?? published
490
+ if (!target) continue
491
+ entries.push({
492
+ documentId: todo.documentId,
493
+ type: target._type,
494
+ title: target.title ?? target.name ?? null,
495
+ language: target.language ?? null,
496
+ sourceLanguage: todo.sourceLanguage ?? null,
497
+ fields: todo.paths.map((path) => ({path, source: valueAt(source, path) ?? null, current: valueAt(target, path) ?? null, translation: null})),
498
+ })
499
+ }
500
+ writeFileSync(out, `${JSON.stringify(entries, null, 2)}\n`)
501
+ const n = entries.reduce((sum, e) => sum + e.fields.length, 0)
502
+ console.log(`✔ ${n} champ(s) à traduire sur ${entries.length} page(s) → ${out}`)
503
+ console.log('Remplir `translation` (même forme que `source`), puis : npx ncf-kit translations apply ' + out)
504
+ return
505
+ }
506
+
507
+ if (sub === 'apply') {
508
+ const file = resolve(args[2] && !args[2].startsWith('--') ? args[2] : 'translations-todo.json')
509
+ if (!existsSync(file)) fail(`Fichier introuvable : ${file}`)
510
+ const entries = JSON.parse(readFileSync(file, 'utf8'))
511
+ let written = 0
512
+ for (const entry of entries) {
513
+ const fields = (entry.fields ?? []).filter((f) => f.translation !== null && f.translation !== undefined)
514
+ if (!fields.length) continue
515
+ const draftId = `drafts.${entry.documentId}`
516
+ const draft = await query(`*[_id == $id][0]`, {id: draftId})
517
+ const published = draft ? null : await query(`*[_id == $id][0]`, {id: entry.documentId})
518
+ const base = draft ?? published
519
+ if (!base) {
520
+ console.log(`⚠ ${entry.documentId} : page introuvable, ignorée`)
521
+ continue
522
+ }
523
+ const set = {}
524
+ for (const f of fields) set[patchPath(base, f.path)] = f.translation
525
+ const mutations = []
526
+ if (!draft) {
527
+ const {_rev, _updatedAt, _createdAt, ...copy} = published
528
+ mutations.push({createIfNotExists: {...copy, _id: draftId}})
529
+ }
530
+ mutations.push({patch: {id: draftId, set}})
531
+ const todoId = `ncfTodo.${entry.documentId}`
532
+ const todo = await query(`*[_id == $id][0]{paths}`, {id: todoId})
533
+ const done = new Set(fields.map((f) => f.path))
534
+ if (todo) mutations.push({patch: {id: todoId, set: {paths: (todo.paths ?? []).filter((p) => !done.has(p))}}})
535
+ await mutate(mutations)
536
+ written += fields.length
537
+ console.log(`✔ ${entry.title ?? entry.documentId} (${entry.language ?? '?'}) : ${fields.length} champ(s) traduit(s) en brouillon`)
538
+ }
539
+ console.log(`\n${written} champ(s) écrit(s). Rien n'est publié : relire puis publier chaque langue dans le Studio.`)
540
+ return
541
+ }
542
+ fail(`translations : sous-commande inconnue « ${sub} » (export | apply <fichier>)`)
543
+ }
544
+
409
545
  if (command === 'setup') {
410
546
  setup().catch((error) => fail(error?.message ?? String(error)))
411
547
  } else if (command === 'doctor') {
412
548
  doctor().catch((error) => fail(error?.message ?? String(error)))
549
+ } else if (command === 'translations') {
550
+ translations().catch((error) => fail(error?.message ?? String(error)))
413
551
  } else if (command === 'check-environments') {
414
552
  // Script autonome (il démarre le site construit) : chargé seulement à la demande.
415
553
  import('./check-environments.mjs').catch((error) => fail(error?.message ?? String(error)))
package/dist/index.d.ts CHANGED
@@ -1339,7 +1339,7 @@ export declare function ActorName(props: {
1339
1339
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1340
1340
  * le vérifie.
1341
1341
  */
1342
- export declare const KIT_VERSION = "2.20.1";
1342
+ export declare const KIT_VERSION = "2.21.0";
1343
1343
  /**
1344
1344
  * Données de la page proposées comme colonnes.
1345
1345
  *
package/dist/index.js CHANGED
@@ -37,6 +37,7 @@ import { RestoreIcon } from "@sanity/icons/Restore";
37
37
  import { UndoIcon } from "@sanity/icons/Undo";
38
38
  import { Tooltip } from "@sanity/ui/tooltip";
39
39
  import { EyeClosedIcon } from "@sanity/icons/EyeClosed";
40
+ import { useToast } from "@sanity/ui/toast";
40
41
  const DEFAULT_PAGE_BUILDER_FIELD = "sections", DEFAULT_SLUG_FIELD = "slug", DEFAULT_TITLE_FIELD = "title", DEFAULT_NOINDEX_FIELDS = ["seo.noindex", "noindex"], DEFAULT_I18N = {
41
42
  field: "language",
42
43
  defaultLocale: "fr",
@@ -1417,7 +1418,7 @@ function explainGrantError(error) {
1417
1418
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1418
1419
  * le vérifie.
1419
1420
  */
1420
- const KIT_VERSION = "2.20.1";
1421
+ const KIT_VERSION = "2.21.0";
1421
1422
  /**
1422
1423
  * Signale ce Studio au service du kit, une fois par montage.
1423
1424
  *
@@ -1744,7 +1745,7 @@ function useKitUpdate() {
1744
1745
  !controller.signal.aborted && body?.version && setLatest(body.version);
1745
1746
  }).catch(() => {}), () => controller.abort();
1746
1747
  }, []);
1747
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.20.1") > 0);
1748
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.21.0") > 0);
1748
1749
  return {
1749
1750
  current: KIT_VERSION,
1750
1751
  latest,
@@ -2941,6 +2942,17 @@ function SharePreview() {
2941
2942
  })
2942
2943
  }) : null;
2943
2944
  }
2945
+ /**
2946
+ * Nombre de champs « À traduire » par page (id publié), tenu à jour en direct.
2947
+ * Vide sur un site monolingue.
2948
+ */
2949
+ function useTranslationTodos() {
2950
+ let config = useKitConfig(), { data } = useQueryData("*[_type == $type && count(paths) > 0]{documentId, \"count\": count(paths)}", useMemo(() => ({ type: TRANSLATION_TODO_TYPE }), []), {
2951
+ listenTypes: [TRANSLATION_TODO_TYPE],
2952
+ enabled: !!config.i18n
2953
+ });
2954
+ return useMemo(() => new Map((data ?? []).map((t) => [t.documentId, t.count])), [data]);
2955
+ }
2944
2956
  const UNSET_LABEL = "Non renseigné", fieldIdOf = (groupBy) => groupBy.startsWith("field:") ? groupBy.slice(6) : null;
2945
2957
  /** Valeur du critère pour une ligne. Chaîne vide = non renseigné. */
2946
2958
  function groupValue(row, groupBy, options) {
@@ -3904,7 +3916,7 @@ const BASE_COLUMNS = [
3904
3916
  }
3905
3917
  ];
3906
3918
  function PagesTable(props) {
3907
- let { groups, sortKey, sortDirection, onSort, columns, meta, tags, colorBy, fields, onField, dataColumns, onAddOption, onRemoveOption, onOptionColor, onAddColumn, onRenameColumn, onRemoveColumn, onMoveColumn, onOpen, hidden, onTag } = props, [collapsed, setCollapsed] = useState(/* @__PURE__ */ new Set()), [hovered, setHovered] = useState(null), { siteUrlFor } = usePreviewTarget(), toggle = (key) => setCollapsed((current) => {
3919
+ let { groups, sortKey, sortDirection, onSort, columns, meta, tags, colorBy, fields, onField, dataColumns, onAddOption, onRemoveOption, onOptionColor, onAddColumn, onRenameColumn, onRemoveColumn, onMoveColumn, onOpen, hidden, onTag, todos } = props, [collapsed, setCollapsed] = useState(/* @__PURE__ */ new Set()), [hovered, setHovered] = useState(null), { siteUrlFor } = usePreviewTarget(), toggle = (key) => setCollapsed((current) => {
3908
3920
  let next = new Set(current);
3909
3921
  return next.has(key) ? next.delete(key) : next.add(key), next;
3910
3922
  }), showLocale = [...meta.keys()].length >= 0 && groups.some((g) => g.rows.some((r) => r.locale)), locales = new Set(groups.flatMap((g) => g.rows.map((r) => r.locale)).filter(Boolean)), baseColumns = BASE_COLUMNS.filter((column) => !hidden.has(column.key)), showTag = !hidden.has("tag"), row = {
@@ -4085,13 +4097,23 @@ function PagesTable(props) {
4085
4097
  !hidden.has("status") && /* @__PURE__ */ jsxs(Flex, {
4086
4098
  align: "center",
4087
4099
  gap: 2,
4100
+ wrap: "wrap",
4088
4101
  style: CELL,
4089
- children: [/* @__PURE__ */ jsx(StatusBadge, { status: entryRow.status }), entryRow.noindex && /* @__PURE__ */ jsx(Badge, {
4090
- tone: "caution",
4091
- fontSize: 0,
4092
- title: "Exclue de Google, du sitemap et de llms.txt",
4093
- children: "Noindex"
4094
- })]
4102
+ children: [
4103
+ /* @__PURE__ */ jsx(StatusBadge, { status: entryRow.status }),
4104
+ !!todos?.get(entryRow.id) && /* @__PURE__ */ jsxs(Badge, {
4105
+ tone: "caution",
4106
+ fontSize: 0,
4107
+ title: "Champs modifiés dans la version principale, pas encore traduits (marqués « À traduire » dans le formulaire)",
4108
+ children: ["À traduire · ", todos?.get(entryRow.id)]
4109
+ }),
4110
+ entryRow.noindex && /* @__PURE__ */ jsx(Badge, {
4111
+ tone: "caution",
4112
+ fontSize: 0,
4113
+ title: "Exclue de Google, du sitemap et de llms.txt",
4114
+ children: "Noindex"
4115
+ })
4116
+ ]
4095
4117
  }),
4096
4118
  !hidden.has("blockCount") && /* @__PURE__ */ jsx(Box, {
4097
4119
  style: { textAlign: "right" },
@@ -5468,7 +5490,7 @@ function BoardView(props) {
5468
5490
  return /* @__PURE__ */ jsx(ReactFlowProvider, { children: /* @__PURE__ */ jsx(Board, { ...props }) });
5469
5491
  }
5470
5492
  function PagesTool() {
5471
- let config = useKitConfig(), router = useRouter(), { byId, saveColumns, patchNode, patchField } = useBoardLayout(), columnOptions = useColumnOptions(), preview = usePreviewTarget(), columns = useInternalColumns(), [view, setView] = useState("list"), [search, setSearch] = useState(""), [locale, setLocale] = useState(""), [groupBy, setGroupBy] = useState("none"), [rawColorBy, setColorBy] = useState("tag"), [sortKey, setSortKey] = useState("structure"), [sortDirection, setSortDirection] = useState("asc"), [page, setPage] = useState(0), [hidden, setHidden] = useState(/* @__PURE__ */ new Set()), [shownData, setShownData] = useState(/* @__PURE__ */ new Set()), toggleData = useCallback((key) => {
5493
+ let config = useKitConfig(), router = useRouter(), { byId, saveColumns, patchNode, patchField } = useBoardLayout(), columnOptions = useColumnOptions(), preview = usePreviewTarget(), columns = useInternalColumns(), [view, setView] = useState("list"), [search, setSearch] = useState(""), [locale, setLocale] = useState(""), todos = useTranslationTodos(), [onlyTodo, setOnlyTodo] = useState(!1), [groupBy, setGroupBy] = useState("none"), [rawColorBy, setColorBy] = useState("tag"), [sortKey, setSortKey] = useState("structure"), [sortDirection, setSortDirection] = useState("asc"), [page, setPage] = useState(0), [hidden, setHidden] = useState(/* @__PURE__ */ new Set()), [shownData, setShownData] = useState(/* @__PURE__ */ new Set()), toggleData = useCallback((key) => {
5472
5494
  setShownData((current) => {
5473
5495
  let next = new Set(current);
5474
5496
  return next.has(key) ? next.delete(key) : next.add(key), next;
@@ -5476,10 +5498,12 @@ function PagesTool() {
5476
5498
  }, []), documentColumns = useDocumentColumns(), visibleDataColumns = useMemo(() => documentColumns.filter((column) => shownData.has(column.key)), [documentColumns, shownData]), { rows, loading, error, refresh } = usePages(visibleDataColumns), colorBy = resolveColorBy(rawColorBy, columns), locales = useMemo(() => config.i18n?.locales.length ? config.i18n.locales : localesInRows(rows), [config.i18n, rows]), visible = useMemo(() => sortRows(filterRows(rows, {
5477
5499
  search,
5478
5500
  locales: locale ? [locale] : void 0
5479
- }), sortKey, sortDirection, { typeOrder: config.pageTypeNames }), [
5501
+ }).filter((row) => !onlyTodo || todos.has(row.id)), sortKey, sortDirection, { typeOrder: config.pageTypeNames }), [
5480
5502
  rows,
5481
5503
  search,
5482
5504
  locale,
5505
+ onlyTodo,
5506
+ todos,
5483
5507
  sortKey,
5484
5508
  sortDirection,
5485
5509
  config.pageTypeNames
@@ -5600,6 +5624,31 @@ function PagesTool() {
5600
5624
  }, code))]
5601
5625
  })]
5602
5626
  }),
5627
+ (todos.size > 0 || onlyTodo) && /* @__PURE__ */ jsxs(Box, {
5628
+ style: {
5629
+ width: 150,
5630
+ flex: "none"
5631
+ },
5632
+ children: [/* @__PURE__ */ jsx(FieldLabel, { children: "Traduction" }), /* @__PURE__ */ jsxs(Select, {
5633
+ fontSize: 1,
5634
+ radius: 2,
5635
+ value: onlyTodo ? "todo" : "",
5636
+ onChange: (event) => {
5637
+ setOnlyTodo(event.currentTarget.value === "todo"), setPage(0);
5638
+ },
5639
+ children: [/* @__PURE__ */ jsx("option", {
5640
+ value: "",
5641
+ children: "Toutes"
5642
+ }), /* @__PURE__ */ jsxs("option", {
5643
+ value: "todo",
5644
+ children: [
5645
+ "À traduire (",
5646
+ todos.size,
5647
+ ")"
5648
+ ]
5649
+ })]
5650
+ })]
5651
+ }),
5603
5652
  view === "list" && /* @__PURE__ */ jsxs(Box, {
5604
5653
  style: {
5605
5654
  width: 168,
@@ -5709,7 +5758,8 @@ function PagesTool() {
5709
5758
  onMoveColumn: (id, delta) => saveColumns(moveColumn(columns, id, delta)),
5710
5759
  onOpen: openPage,
5711
5760
  hidden,
5712
- onTag
5761
+ onTag,
5762
+ todos
5713
5763
  })
5714
5764
  }), /* @__PURE__ */ jsxs(Flex, {
5715
5765
  align: "center",
@@ -8188,15 +8238,20 @@ function hasChanges(r) {
8188
8238
  */
8189
8239
  function withPropagation(Publish, config) {
8190
8240
  let i18n = config.i18n, Wrapped = (props) => {
8191
- let base = Publish(props), [run, setRun] = useState(null), current = props.draft ?? props.published;
8241
+ let base = Publish(props), client = useKitClient(), schema = useSchema(), [run, setRun] = useState(null), current = props.draft ?? props.published;
8192
8242
  return !base || !i18n || current?.[i18n.field] !== i18n.defaultLocale ? base : {
8193
8243
  ...base,
8194
8244
  onHandle: () => {
8195
8245
  let before = props.published, after = props.draft;
8196
- base.onHandle?.(), before && after && setRun({
8197
- before,
8198
- after
8199
- });
8246
+ if (base.onHandle?.(), !before || !after) return;
8247
+ let documentType = schema.get(props.type);
8248
+ findTargets(client, props.id, String(after[i18n.field] ?? ""), before, after, documentType).then((targets) => {
8249
+ targets.some((t) => hasChanges(t.result)) && setRun({
8250
+ before,
8251
+ after,
8252
+ targets
8253
+ });
8254
+ }).catch(() => {});
8200
8255
  },
8201
8256
  dialog: run ? {
8202
8257
  type: "dialog",
@@ -8211,6 +8266,7 @@ function withPropagation(Publish, config) {
8211
8266
  type: props.type,
8212
8267
  before: run.before,
8213
8268
  after: run.after,
8269
+ targets: run.targets,
8214
8270
  onDone: () => {
8215
8271
  setRun(null), props.onComplete();
8216
8272
  }
@@ -8220,40 +8276,28 @@ function withPropagation(Publish, config) {
8220
8276
  };
8221
8277
  return Wrapped.action = Publish.action, Wrapped;
8222
8278
  }
8279
+ async function findTargets(client, id, source, before, after, documentType) {
8280
+ let translations = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0].translations[]{language, \"id\": value._ref}", { id }), list = [];
8281
+ for (let t of translations ?? []) {
8282
+ if (!t?.id || t.id === id || t.language === source) continue;
8283
+ let target = await client.getDocument(`drafts.${t.id}`) ?? await client.getDocument(t.id) ?? null;
8284
+ if (!target) continue;
8285
+ let result = propagate(target, before, after, documentType);
8286
+ list.push({
8287
+ language: t.language,
8288
+ id: t.id,
8289
+ result,
8290
+ selected: hasChanges(result)
8291
+ });
8292
+ }
8293
+ return list;
8294
+ }
8223
8295
  function PropagateDialog(props) {
8224
- 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);
8225
- useEffect(() => {
8226
- let documentType = schema.get(type);
8227
- (async () => {
8228
- let translations = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0].translations[]{language, \"id\": value._ref}", { id }), list = [];
8229
- for (let t of translations ?? []) {
8230
- if (!t?.id || t.id === id || t.language === source) continue;
8231
- let target = await client.getDocument(`drafts.${t.id}`) ?? await client.getDocument(t.id) ?? null;
8232
- if (!target) continue;
8233
- let result = propagate(target, before, after, documentType);
8234
- list.push({
8235
- language: t.language,
8236
- id: t.id,
8237
- result,
8238
- selected: hasChanges(result)
8239
- });
8240
- }
8241
- setTargets(list);
8242
- })().catch(() => setTargets([]));
8243
- }, [
8244
- client,
8245
- schema,
8246
- id,
8247
- type,
8248
- before,
8249
- after,
8250
- source
8251
- ]);
8252
- let apply = async () => {
8296
+ 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), apply = async () => {
8253
8297
  setBusy(!0), setError(null);
8254
8298
  try {
8255
8299
  let applied = [];
8256
- for (let t of targets ?? []) {
8300
+ for (let t of targets) {
8257
8301
  if (!t.selected) continue;
8258
8302
  let { _rev, _createdAt, _updatedAt, ...doc } = t.result.document;
8259
8303
  if (await client.createOrReplace({
@@ -8273,28 +8317,19 @@ function PropagateDialog(props) {
8273
8317
  }
8274
8318
  applied.push(t.language.toUpperCase());
8275
8319
  }
8276
- setDone(applied);
8320
+ toast.push({
8321
+ status: "success",
8322
+ title: `Brouillons mis à jour : ${applied.join(", ")}`,
8323
+ description: "Traduisez les champs marqués « À traduire », puis publiez chaque langue.",
8324
+ duration: 8e3
8325
+ }), onDone();
8277
8326
  } catch (cause) {
8278
8327
  setError(`La propagation a échoué, rien n'a été publié. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 140)})`);
8279
8328
  } finally {
8280
8329
  setBusy(!1);
8281
8330
  }
8282
8331
  };
8283
- return done ? /* @__PURE__ */ jsxs(Stack, {
8284
- gap: 4,
8285
- padding: 4,
8286
- children: [/* @__PURE__ */ jsx(Text, {
8287
- size: 1,
8288
- children: done.length ? `Brouillons mis à jour : ${done.join(", ")}. Relisez, traduisez les champs marqués « À traduire », puis publiez chaque langue.` : "Rien n’a été propagé."
8289
- }), /* @__PURE__ */ jsx(Flex, {
8290
- justify: "flex-end",
8291
- children: /* @__PURE__ */ jsx(Button, {
8292
- text: "Fermer",
8293
- mode: "ghost",
8294
- onClick: onDone
8295
- })
8296
- })]
8297
- }) : targets ? targets.some((t) => hasChanges(t.result)) ? /* @__PURE__ */ jsxs(Stack, {
8332
+ return /* @__PURE__ */ jsxs(Stack, {
8298
8333
  gap: 4,
8299
8334
  padding: 4,
8300
8335
  children: [
@@ -8365,29 +8400,6 @@ function PropagateDialog(props) {
8365
8400
  })]
8366
8401
  })
8367
8402
  ]
8368
- }) : /* @__PURE__ */ jsxs(Stack, {
8369
- gap: 4,
8370
- padding: 4,
8371
- children: [/* @__PURE__ */ jsx(Text, {
8372
- size: 1,
8373
- children: "Aucune traduction à mettre à jour."
8374
- }), /* @__PURE__ */ jsx(Flex, {
8375
- justify: "flex-end",
8376
- children: /* @__PURE__ */ jsx(Button, {
8377
- text: "Fermer",
8378
- mode: "ghost",
8379
- onClick: onDone
8380
- })
8381
- })]
8382
- }) : /* @__PURE__ */ jsxs(Flex, {
8383
- align: "center",
8384
- gap: 3,
8385
- padding: 4,
8386
- children: [/* @__PURE__ */ jsx(Spinner, { muted: !0 }), /* @__PURE__ */ jsx(Text, {
8387
- size: 1,
8388
- muted: !0,
8389
- children: "Comparaison avec les traductions…"
8390
- })]
8391
8403
  });
8392
8404
  }
8393
8405
  function summary(r) {