@nocode-factory/sanity-kit 2.20.1 → 2.22.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
 
@@ -277,6 +279,11 @@ async function doctor() {
277
279
  if (!version) ko('Version du kit', 'non installé dans le studio')
278
280
  else if (latest && version !== latest) warn('Version du kit', `${version} installée, ${latest} disponible : npm install ${PKG}@latest (studio et site)`)
279
281
  else ok('Version du kit', version)
282
+ // Le site embarque aussi le kit (bandeau, garde, liens, valeurs par défaut) : une
283
+ // version différente du Studio = corrections du kit absentes d'un côté.
284
+ const webInstalled = [web, root].map((d) => read(join(d, 'node_modules', PKG, 'package.json'))).find(Boolean)
285
+ const webVersion = webInstalled ? JSON.parse(webInstalled).version : null
286
+ if (webVersion && version && webVersion !== version) warn('Version du kit (site)', `${webVersion} sur le site, ${version} dans le studio : le kit a besoin de la même version des deux côtés ; npm install ${PKG}@latest dans web/ et studio/.`)
280
287
 
281
288
  /* Studio : URLs et clés */
282
289
  const previewUrl = env.SANITY_STUDIO_PREVIEW_URL
@@ -322,25 +329,45 @@ async function doctor() {
322
329
  const chain = [scripts.build, scripts.postbuild].filter(Boolean).join(' ')
323
330
  const runsCheck = /ncf-kit check-environments/.test(chain) || files.some((f) => /\.(m?js|ts)$/.test(f) && chain.includes(f.split('/').pop()) && /ncf-kit[^\n]*check-environments|check-environments/.test(read(f)))
324
331
  runsCheck ? ok('Test prod / préprod', 'lancé après chaque build') : ko('Test prod / préprod', 'le build du site ne lance pas `ncf-kit check-environments` : ajouter "postbuild": "ncf-kit check-environments" dans package.json. Sans lui, une fuite de brouillon en production serait mise en ligne.')
332
+ // Purge de la préprod : un seul webhook Sanity (vers la production), qui RELAIE
333
+ // à la préprod. Sans relais, une page modifiée ou retirée reste servie en préprod.
334
+ if (preprod) {
335
+ const route = files.find((f) => /api\/revalidate\/route\.[jt]s$/.test(f))
336
+ if (!route) ko('Purge de la préprod', "le kit a besoin d'une route /api/revalidate (purge du cache à la publication) ; le projet ne l'a pas : reprendre app/api/revalidate/route.ts du starter, puis le webhook Sanity vers la production.")
337
+ else if (!/PREPROD_URL/.test(read(route))) ko('Purge de la préprod', `le kit a besoin que la production relaie la purge à la préprod (sinon une page retirée du site reste visible en préprod) ; le projet ne l'a pas : relais PREPROD_URL dans ${route.replace(root + '/', '')} (voir le starter), puis PREPROD_URL dans les variables Vercel de Production.`)
338
+ else ok('Purge de la préprod', `${route.replace(root + '/', '')} relaie à PREPROD_URL (variable Vercel de Production)`)
339
+ }
325
340
  }
326
341
 
327
342
  /* Valeurs par défaut des composants : instances, overrides, preview */
328
343
  {
329
344
  const studioFiles = walk(studio)
330
- // LANGUES (site multilingue) : les trois règles des liens vers une page.
345
+ // LANGUES (site multilingue) : ce dont le kit a besoin dans le PROJET pour que
346
+ // les trois règles des liens et la propagation fonctionnent.
331
347
  // 1. pages reliées à leurs traductions (document-internationalization) ;
332
348
  // 2. le choix de la page ne propose que la langue du document, publiées, sans création ;
333
349
  // 3. au rendu, un lien vise la traduction de la page cible dans la langue affichée.
350
+ // Formulation : « le kit a besoin de X (pour Y) ; le projet ne l'a pas : correction ».
334
351
  const locales = String(env.SANITY_STUDIO_LOCALES || '').split(',').map((l) => l.trim()).filter(Boolean)
335
352
  if (locales.length > 1) {
353
+ const need = (what, why, fix) => `le kit a besoin de ${what} (${why}) ; le projet ne l'a pas : ${fix}`
336
354
  const i18nPlugin = studioFiles.some((f) => read(f).includes('documentInternationalization('))
337
- i18nPlugin ? ok('Langues : pages reliées', 'documentInternationalization') : ko('Langues : pages reliées', 'site multilingue sans @sanity/document-internationalization : les pages ne sont pas reliées à leurs traductions (hreflang, bascule de langue).')
355
+ i18nPlugin ? ok('Langues : pages reliées', 'documentInternationalization') : ko('Langues : pages reliées', need('@sanity/document-internationalization', 'hreflang, bascule de langue, propagation', 'ajouter le plugin dans sanity.config.ts (voir le starter).'))
356
+ const kitI18n = /\bi18n\s*:\s*\{[^}]*defaultLocale/.test(config) || studioFiles.some((f) => /\bi18n\s*:\s*\{[^}]*defaultLocale/.test(read(f)) && /ncf/i.test(read(f)))
357
+ kitI18n ? ok('Langues : réglage du kit', 'i18n déclaré') : ko('Langues : réglage du kit', need("l'option i18n de ncfKit", 'propagation aux autres langues, « À traduire », filtre par langue de l\'onglet Pages', "ncfKit({..., i18n: {field: 'language', defaultLocale, locales}}) dans sanity.config.ts."))
338
358
  const picker = studioFiles.find((f) => /disableNew:\s*true/.test(read(f)) && /language == \$lang/.test(read(f)))
339
- picker ? ok('Langues : choix de la page liée', picker.replace(root + '/', '')) : ko('Langues : choix de la page liée', 'le champ « page » des liens doit filtrer sur la langue du document (language == $lang), sans création (disableNew: true) et sans brouillons (voir link.ts du starter).')
359
+ if (!picker) ko('Langues : choix de la page liée', need('un champ « page » des liens filtré', 'règle 2 : langue du document, pages publiées, sans création', 'filter language == $lang et !(_id in path("drafts.**")), disableNew: true (voir link.ts du starter).'))
360
+ else if (!/drafts\.\*\*/.test(read(picker))) ko('Langues : choix de la page liée', need('un filtre sans brouillons', 'règle 2 : une page liée doit être publiée', `ajouter !(_id in path("drafts.**")) au filtre de ${picker.replace(root + '/', '')}.`))
361
+ else ok('Langues : choix de la page liée', picker.replace(root + '/', ''))
362
+ if (picker) /weak:\s*true/.test(read(picker)) ? ok('Liens : référence faible', picker.replace(root + '/', '')) : warn('Liens : référence faible', need('des références faibles (weak: true) sur les liens', '« Retirer du site » et la suppression d\'une page liée ne sont pas bloqués', `weak: true sur la référence « page » de ${picker.replace(root + '/', '')}.`))
340
363
  if (webPkg) {
341
364
  const render = walk(web).find((f) => /translation\.metadata/.test(read(f)) && /resolveLink|LINK_PROJECTION/.test(read(f)))
342
- render ? ok('Langues : lien dans la langue affichée', render.replace(root + '/', '')) : ko('Langues : lien dans la langue affichée', "un lien vers une page doit être rendu vers sa traduction dans la langue affichée (traductions de la page liée via translation.metadata, voir LINK_PROJECTION et resolveLink du starter).")
365
+ render ? ok('Langues : lien dans la langue affichée', render.replace(root + '/', '')) : ko('Langues : lien dans la langue affichée', need('un rendu des liens dans la langue affichée', 'règle 3 : un lien recopié par la propagation doit viser la traduction', 'traductions de la page liée via translation.metadata dans LINK_PROJECTION et resolveLink (voir le starter).'))
343
366
  }
367
+ const ci = walk(join(root, '.github', 'workflows')).some((f) => /check-translations/.test(read(f)))
368
+ ci ? ok('Langues : contrôle des données', 'check-translations en CI') : warn('Langues : contrôle des données', need('un contrôle des données en CI', 'pages sans traduction reliée, liens vers une autre langue', 'studio/scripts/check-translations.ts et son étape dans .github/workflows/ci.yml (voir le starter).'))
369
+ const rules = read(join(root, 'CLAUDE.md'))
370
+ rules && !/trois règles/i.test(rules) && warn('Langues : consignes', need('les trois règles des langues dans CLAUDE.md', 'Claude ne les connaîtrait pas dans ce projet', 'recopier le bloc « LANGUES » du CLAUDE.md du starter.'))
344
371
  }
345
372
  const hasDefaults = studioFiles.some((f) => /defineComponentDefaults\(|name:\s*['"]componentDefaults['"]/.test(read(f)))
346
373
  if (!hasDefaults) {
@@ -369,6 +396,14 @@ async function doctor() {
369
396
  }
370
397
  }
371
398
 
399
+ /* Schéma validé en CI : un document que le schéma refuse bloque le déploiement du Studio */
400
+ {
401
+ const wf = walk(join(root, '.github', 'workflows'))
402
+ wf.some((f) => /sanity schema validate/.test(read(f)))
403
+ ? ok('Schéma validé en CI', 'sanity schema validate')
404
+ : warn('Schéma validé en CI', "le kit a besoin d'un schéma valide (valeurs par défaut des composants générées depuis les sections) ; le projet ne le vérifie pas : étape `npx sanity schema validate` dans .github/workflows/ci.yml (voir le starter). Sinon `sanity deploy` peut échouer sans prévenir.")
405
+ }
406
+
372
407
  /* Captures des composants */
373
408
  const workflows = walk(join(root, '.github', 'workflows'))
374
409
  const captures = workflows.find((f) => /public\/sections/.test(read(f)))
@@ -376,6 +411,28 @@ async function doctor() {
376
411
 
377
412
  /* En ligne */
378
413
  if (!offline) {
414
+ // Purge du cache à la publication : webhook Sanity vers la PRODUCTION
415
+ // (/api/revalidate), qui relaie à la préprod. Sans lui, rien ne se met à jour
416
+ // sur le site avant le prochain build.
417
+ if (previewUrl && !/localhost/.test(previewUrl)) {
418
+ const endpoint = `${previewUrl.replace(/\/+$/, '')}/api/revalidate`
419
+ const route = await probe(endpoint, {method: 'POST', headers: {'content-type': 'application/json'}, body: '{}'})
420
+ if (route.status === 404) ko('Purge du cache (route)', `${endpoint} : 404. Le kit a besoin de la route /api/revalidate en production ; le projet ne l'a pas (ou pas déployée) : reprendre app/api/revalidate/route.ts du starter.`)
421
+ else if (route.status) ok('Purge du cache (route)', `${endpoint} répond (${route.status} sans signature)`)
422
+ const projectId = env.SANITY_STUDIO_PROJECT_ID
423
+ const token = sanityToken()
424
+ if (projectId && token) {
425
+ const list = await request(`${SANITY_API}/v2021-10-04/hooks/projects/${projectId}`, {headers: {authorization: `Bearer ${token}`}})
426
+ const hooks = Array.isArray(list.body) ? list.body : []
427
+ const host = new URL(previewUrl).host
428
+ const hook = hooks.find((h) => typeof h.url === 'string' && /\/api\/revalidate/.test(h.url) && h.url.includes(host))
429
+ if (!list.ok) warn('Purge du cache (webhook)', `webhooks Sanity illisibles (${list.status}) : le jeton administre-t-il ce projet ?`)
430
+ else if (!hook) ko('Purge du cache (webhook)', `le kit a besoin d'un webhook Sanity vers ${endpoint} (purge du cache à la publication, relayée à la préprod) ; le projet ne l'a pas : Sanity → API → Webhooks, avec le secret SANITY_REVALIDATE_SECRET (voir PASSATION du starter).`)
431
+ else if (hook.isDisabled || hook.isDisabledByUser) ko('Purge du cache (webhook)', `webhook « ${hook.name} » désactivé : la publication ne purge plus le cache.`)
432
+ else ok('Purge du cache (webhook)', `« ${hook.name} » → ${hook.url.split('?')[0]}`) // jamais le secret à l'écran
433
+ } else warn('Purge du cache (webhook)', 'non vérifié : SANITY_STUDIO_PROJECT_ID ou jeton Sanity absent (npx sanity login).')
434
+ }
435
+
379
436
  if (previewUrl && !/localhost/.test(previewUrl)) {
380
437
  const r = await probe(previewUrl)
381
438
  r.status && r.status < 500 ? ok('Site en ligne', `${previewUrl} répond (${r.status})`) : ko('Site en ligne', `${previewUrl} : ${r.error ?? r.status}`)
@@ -406,10 +463,146 @@ async function doctor() {
406
463
  process.exit(kos ? 1 : 0)
407
464
  }
408
465
 
466
+ // ─── translations : champs « À traduire » (propagation depuis la version principale) ───
467
+ // export : écrit un fichier JSON (une entrée par page traduite, chaque champ avec le
468
+ // texte de la version principale et le texte actuel) ; on le remplit
469
+ // (champ `translation` de chaque élément, ex. depuis Claude Code), puis
470
+ // apply : écrit chaque traduction dans le BROUILLON de la page et retire le champ de
471
+ // la liste « À traduire ». Rien n'est publié. Texte riche : `translation` est
472
+ // le tableau de blocs complet (mêmes _key, textes traduits).
473
+ const TODO_TYPE = 'ncfTranslationTodo'
474
+
475
+ /** `sections[a].title` → segments ; `[x]` = clé d'élément (ou rang si la liste n'a pas de clé). */
476
+ function parsePath(path) {
477
+ const out = []
478
+ for (const m of path.matchAll(/([^.[\]]+)|\[([^\]]+)\]/g)) out.push(m[1] !== undefined ? {field: m[1]} : {item: m[2]})
479
+ return out
480
+ }
481
+ function valueAt(doc, path) {
482
+ let cur = doc
483
+ for (const seg of parsePath(path)) {
484
+ if (cur == null) return undefined
485
+ if (seg.field) cur = cur[seg.field]
486
+ else if (Array.isArray(cur)) cur = cur.find((i) => i && i._key === seg.item) ?? (/^\d+$/.test(seg.item) ? cur[Number(seg.item)] : undefined)
487
+ else return undefined
488
+ }
489
+ return cur
490
+ }
491
+ /** Chemin de patch Sanity : `sections[_key=="a"].title`. */
492
+ function patchPath(doc, path) {
493
+ let cur = doc
494
+ let out = ''
495
+ for (const seg of parsePath(path)) {
496
+ if (seg.field) {
497
+ out += out ? `.${seg.field}` : seg.field
498
+ cur = cur?.[seg.field]
499
+ } else {
500
+ const byKey = Array.isArray(cur) && cur.some((i) => i && i._key === seg.item)
501
+ out += byKey || !/^\d+$/.test(seg.item) ? `[_key=="${seg.item}"]` : `[${seg.item}]`
502
+ cur = Array.isArray(cur) ? (cur.find((i) => i && i._key === seg.item) ?? cur[Number(seg.item)]) : undefined
503
+ }
504
+ }
505
+ return out
506
+ }
507
+
508
+ async function translations() {
509
+ const sub = args[1] && !args[1].startsWith('--') ? args[1] : 'export'
510
+ const dir = resolve(flag('dir') ?? process.cwd())
511
+ const envFile = join(dir, '.env')
512
+ const env = existsSync(envFile) ? parseEnv(readFileSync(envFile, 'utf8')) : {}
513
+ const projectId = env.SANITY_STUDIO_PROJECT_ID ?? process.env.SANITY_STUDIO_PROJECT_ID
514
+ const dataset = flag('dataset') ?? env.SANITY_STUDIO_DATASET ?? 'production'
515
+ if (!projectId) fail('SANITY_STUDIO_PROJECT_ID introuvable : lance la commande depuis le dossier du studio.')
516
+ const token = sanityToken()
517
+ if (!token) fail('Aucun jeton Sanity : lance `npx sanity login`, ou exporte SANITY_AUTH_TOKEN.')
518
+ const api = `https://${projectId}.api.sanity.io/v2025-02-19/data`
519
+ const headers = {authorization: `Bearer ${token}`, 'content-type': 'application/json'}
520
+ const query = async (q, params = {}) => {
521
+ const url = new URL(`${api}/query/${dataset}`)
522
+ url.searchParams.set('query', q)
523
+ url.searchParams.set('perspective', 'raw')
524
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(`$${k}`, JSON.stringify(v))
525
+ const r = await request(url, {headers})
526
+ if (!r.ok) fail(`Lecture Sanity refusée (${r.status}) : ${JSON.stringify(r.body).slice(0, 200)}`)
527
+ return r.body.result
528
+ }
529
+ const mutate = async (mutations) => {
530
+ const r = await request(`${api}/mutate/${dataset}?returnIds=true`, {method: 'POST', headers, body: JSON.stringify({mutations})})
531
+ if (!r.ok) fail(`Écriture Sanity refusée (${r.status}) : ${JSON.stringify(r.body).slice(0, 300)}`)
532
+ }
533
+
534
+ if (sub === 'export') {
535
+ const out = resolve(flag('out') ?? 'translations-todo.json')
536
+ const todos = await query(`*[_type == $type && count(paths) > 0]{_id, documentId, sourceId, sourceLanguage, paths}`, {type: TODO_TYPE})
537
+ const entries = []
538
+ for (const todo of todos) {
539
+ const [draft, published, source] = await Promise.all([
540
+ query(`*[_id == $id][0]`, {id: `drafts.${todo.documentId}`}),
541
+ query(`*[_id == $id][0]`, {id: todo.documentId}),
542
+ query(`*[_id == $id][0]`, {id: todo.sourceId}),
543
+ ])
544
+ const target = draft ?? published
545
+ if (!target) continue
546
+ entries.push({
547
+ documentId: todo.documentId,
548
+ type: target._type,
549
+ title: target.title ?? target.name ?? null,
550
+ language: target.language ?? null,
551
+ sourceLanguage: todo.sourceLanguage ?? null,
552
+ fields: todo.paths.map((path) => ({path, source: valueAt(source, path) ?? null, current: valueAt(target, path) ?? null, translation: null})),
553
+ })
554
+ }
555
+ writeFileSync(out, `${JSON.stringify(entries, null, 2)}\n`)
556
+ const n = entries.reduce((sum, e) => sum + e.fields.length, 0)
557
+ console.log(`✔ ${n} champ(s) à traduire sur ${entries.length} page(s) → ${out}`)
558
+ console.log('Remplir `translation` (même forme que `source`), puis : npx ncf-kit translations apply ' + out)
559
+ return
560
+ }
561
+
562
+ if (sub === 'apply') {
563
+ const file = resolve(args[2] && !args[2].startsWith('--') ? args[2] : 'translations-todo.json')
564
+ if (!existsSync(file)) fail(`Fichier introuvable : ${file}`)
565
+ const entries = JSON.parse(readFileSync(file, 'utf8'))
566
+ let written = 0
567
+ for (const entry of entries) {
568
+ const fields = (entry.fields ?? []).filter((f) => f.translation !== null && f.translation !== undefined)
569
+ if (!fields.length) continue
570
+ const draftId = `drafts.${entry.documentId}`
571
+ const draft = await query(`*[_id == $id][0]`, {id: draftId})
572
+ const published = draft ? null : await query(`*[_id == $id][0]`, {id: entry.documentId})
573
+ const base = draft ?? published
574
+ if (!base) {
575
+ console.log(`⚠ ${entry.documentId} : page introuvable, ignorée`)
576
+ continue
577
+ }
578
+ const set = {}
579
+ for (const f of fields) set[patchPath(base, f.path)] = f.translation
580
+ const mutations = []
581
+ if (!draft) {
582
+ const {_rev, _updatedAt, _createdAt, ...copy} = published
583
+ mutations.push({createIfNotExists: {...copy, _id: draftId}})
584
+ }
585
+ mutations.push({patch: {id: draftId, set}})
586
+ const todoId = `ncfTodo.${entry.documentId}`
587
+ const todo = await query(`*[_id == $id][0]{paths}`, {id: todoId})
588
+ const done = new Set(fields.map((f) => f.path))
589
+ if (todo) mutations.push({patch: {id: todoId, set: {paths: (todo.paths ?? []).filter((p) => !done.has(p))}}})
590
+ await mutate(mutations)
591
+ written += fields.length
592
+ console.log(`✔ ${entry.title ?? entry.documentId} (${entry.language ?? '?'}) : ${fields.length} champ(s) traduit(s) en brouillon`)
593
+ }
594
+ console.log(`\n${written} champ(s) écrit(s). Rien n'est publié : relire puis publier chaque langue dans le Studio.`)
595
+ return
596
+ }
597
+ fail(`translations : sous-commande inconnue « ${sub} » (export | apply <fichier>)`)
598
+ }
599
+
409
600
  if (command === 'setup') {
410
601
  setup().catch((error) => fail(error?.message ?? String(error)))
411
602
  } else if (command === 'doctor') {
412
603
  doctor().catch((error) => fail(error?.message ?? String(error)))
604
+ } else if (command === 'translations') {
605
+ translations().catch((error) => fail(error?.message ?? String(error)))
413
606
  } else if (command === 'check-environments') {
414
607
  // Script autonome (il démarre le site construit) : chargé seulement à la demande.
415
608
  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.22.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.22.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.22.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) {