@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.35.0",
3
+ "version": "2.37.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -0,0 +1,187 @@
1
+ import {useEffect, useState} from 'react'
2
+ import {Box, Button, Card, Checkbox, Flex, Spinner, Stack, Text} from '@sanity/ui'
3
+ import {useToast} from '@sanity/ui/toast'
4
+ import type {DocumentActionComponent, DocumentActionProps} from 'sanity'
5
+ import type {ResolvedKitConfig} from '../config/types'
6
+ import {useKitClient} from '../hooks/useKitClient'
7
+ import {translationsOf} from '../lib/translateDocument'
8
+
9
+ type Doc = Record<string, unknown>
10
+ type Referrer = {_id: string; _type: string; title?: string}
11
+ interface Version {
12
+ language: string
13
+ id: string
14
+ selected: boolean
15
+ }
16
+
17
+ /** Identifiants publiés + brouillons d'une liste de documents. */
18
+ export const withDrafts = (ids: string[]): string[] => ids.flatMap((id) => [id, `drafts.${id}`])
19
+
20
+ /**
21
+ * Supprimer la version PRINCIPALE d'un document traduit (page, fiche de collection,
22
+ * réglage par langue) : la fenêtre propose de supprimer aussi ses autres langues
23
+ * (cochées par défaut), en une fois. Bloqué, avec la liste, si un autre document y
24
+ * fait encore référence (comme la suppression native de Sanity). Les liens de
25
+ * traduction sont nettoyés. Sans traduction, ou depuis une autre langue : la
26
+ * suppression native, inchangée.
27
+ */
28
+ export function withTranslationDelete(
29
+ Delete: DocumentActionComponent,
30
+ config: ResolvedKitConfig,
31
+ masterLocale?: string,
32
+ ): DocumentActionComponent {
33
+ const i18n = config.i18n
34
+ const master = masterLocale ?? i18n?.defaultLocale
35
+ const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
36
+ const base = Delete(props)
37
+ const client = useKitClient()
38
+ const [versions, setVersions] = useState<Version[] | null>(null)
39
+ const current = (props.draft ?? props.published) as Doc | null
40
+ useEffect(() => {
41
+ if (!i18n || current?.[i18n.field] !== master) return
42
+ let alive = true
43
+ translationsOf(client, props.id)
44
+ .then((list) => alive && setVersions(list.filter((t) => t.id !== props.id).map((t) => ({...t, selected: true}))))
45
+ .catch(() => alive && setVersions([]))
46
+ return () => {
47
+ alive = false
48
+ }
49
+ }, [client, props.id, current?.[i18n?.field ?? 'language']])
50
+ const [open, setOpen] = useState(false)
51
+ if (!base || !i18n || current?.[i18n.field] !== master || !versions?.length) return base
52
+ return {
53
+ ...base,
54
+ onHandle: () => setOpen(true),
55
+ dialog: open
56
+ ? {
57
+ type: 'dialog',
58
+ header: 'Delete this document',
59
+ width: 'medium',
60
+ onClose: () => setOpen(false),
61
+ content: (
62
+ <DeleteDialog
63
+ id={props.id}
64
+ language={String(current?.[i18n.field] ?? '')}
65
+ versions={versions}
66
+ onDone={() => {
67
+ setOpen(false)
68
+ props.onComplete()
69
+ }}
70
+ />
71
+ ),
72
+ }
73
+ : base.dialog,
74
+ }
75
+ }
76
+ return Wrapped
77
+ }
78
+
79
+ function DeleteDialog(props: {id: string; language: string; versions: Version[]; onDone: () => void}) {
80
+ const {id, language, onDone} = props
81
+ const client = useKitClient()
82
+ const toast = useToast()
83
+ const [versions, setVersions] = useState(props.versions)
84
+ const [referrers, setReferrers] = useState<Referrer[] | null>(null)
85
+ const [busy, setBusy] = useState(false)
86
+ const [error, setError] = useState<string | null>(null)
87
+ const ids = [id, ...versions.filter((v) => v.selected).map((v) => v.id)]
88
+ const key = ids.join(',')
89
+
90
+ // Documents (hors versions supprimées et liens de traduction) qui y font référence.
91
+ useEffect(() => {
92
+ setReferrers(null)
93
+ const all = withDrafts(ids)
94
+ client
95
+ .fetch<Referrer[]>(
96
+ `*[references($ids) && !(_id in $all) && _type != "translation.metadata"]{_id, _type, "title": coalesce(title, name, heading, _id)}`,
97
+ {ids, all},
98
+ )
99
+ .then(setReferrers)
100
+ .catch(() => setReferrers([]))
101
+ // eslint-disable-next-line react-hooks/exhaustive-deps
102
+ }, [client, key])
103
+
104
+ const remove = async () => {
105
+ setBusy(true)
106
+ setError(null)
107
+ try {
108
+ const tx = client.transaction()
109
+ for (const docId of withDrafts(ids)) tx.delete(docId)
110
+ // Liens de traduction : retirés pour les versions supprimées, document de
111
+ // liens supprimé s'il ne relie plus rien.
112
+ const meta = await client.fetch<{_id: string; translations?: {_key: string; value?: {_ref?: string}}[]} | null>(
113
+ `*[_type == "translation.metadata" && references($id)][0]{_id, translations}`,
114
+ {id},
115
+ )
116
+ if (meta) {
117
+ const gone = (meta.translations ?? []).filter((t) => ids.includes(t.value?._ref ?? ''))
118
+ if ((meta.translations ?? []).length - gone.length > 1) tx.patch(meta._id, (p) => p.unset(gone.map((t) => `translations[_key == "${t._key}"]`)))
119
+ else tx.delete(meta._id)
120
+ }
121
+ await tx.commit({visibility: 'async'})
122
+ toast.push({status: 'success', title: `Deleted: ${[language, ...versions.filter((v) => v.selected).map((v) => v.language)].map((l) => l.toUpperCase()).join(', ')}`, duration: 6000})
123
+ onDone()
124
+ } catch (cause) {
125
+ setError(`Failed. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 160)})`)
126
+ setBusy(false)
127
+ }
128
+ }
129
+
130
+ const blocked = !!referrers?.length
131
+ return (
132
+ <Stack gap={4} padding={4}>
133
+ <Text size={1}>
134
+ The {language.toUpperCase()} version will be deleted for good (published and draft). Delete the other language versions too?
135
+ </Text>
136
+ <Stack gap={2}>
137
+ {versions.map((v, index) => (
138
+ <Card key={v.id} padding={3} radius={2} border>
139
+ <Flex as="label" gap={3} align="center">
140
+ <Checkbox checked={v.selected} disabled={busy} onChange={() => setVersions(versions.map((x, i) => (i === index ? {...x, selected: !x.selected} : x)))} />
141
+ <Text size={1} weight="semibold">
142
+ {v.language.toUpperCase()}
143
+ </Text>
144
+ </Flex>
145
+ </Card>
146
+ ))}
147
+ </Stack>
148
+ {referrers === null ? (
149
+ <Flex justify="center">
150
+ <Spinner muted />
151
+ </Flex>
152
+ ) : blocked ? (
153
+ <Card tone="critical" padding={3} radius={2}>
154
+ <Stack gap={2}>
155
+ <Text size={1}>Still referenced by these documents: remove the references first.</Text>
156
+ {referrers.slice(0, 8).map((r) => (
157
+ <Text key={r._id} size={1} muted>
158
+ {r.title} ({r._type})
159
+ </Text>
160
+ ))}
161
+ {referrers.length > 8 && (
162
+ <Text size={1} muted>
163
+ …and {referrers.length - 8} more
164
+ </Text>
165
+ )}
166
+ </Stack>
167
+ </Card>
168
+ ) : null}
169
+ {error && (
170
+ <Card tone="critical" padding={3} radius={2}>
171
+ <Text size={1}>{error}</Text>
172
+ </Card>
173
+ )}
174
+ <Flex justify="flex-end" gap={2}>
175
+ <Box>
176
+ <Button text="Cancel" mode="ghost" onClick={onDone} disabled={busy} />
177
+ </Box>
178
+ <Button
179
+ text={busy ? 'Deleting…' : `Delete ${ids.length > 1 ? `${ids.length} versions` : `${language.toUpperCase()} only`}`}
180
+ tone="critical"
181
+ onClick={() => void remove()}
182
+ disabled={busy || referrers === null || blocked}
183
+ />
184
+ </Flex>
185
+ </Stack>
186
+ )
187
+ }
@@ -1,10 +1,13 @@
1
1
  import {useEffect, useState} from 'react'
2
- import {Stack, Text} from '@sanity/ui'
2
+ import {Card, Checkbox, Flex, Stack, Text} from '@sanity/ui'
3
3
  import {EyeClosedIcon} from '@sanity/icons/EyeClosed'
4
- import type {DocumentActionComponent, DocumentActionProps} from 'sanity'
4
+ import type {DocumentActionComponent, DocumentActionDescription, DocumentActionProps} from 'sanity'
5
5
  import {useKitClient} from '../hooks/useKitClient'
6
+ import type {ResolvedKitConfig} from '../config/types'
7
+ import {translationsOf} from '../lib/translateDocument'
6
8
 
7
9
  type Referrer = {_id: string; _type: string; title?: string}
10
+ type Version = {language: string; id: string; selected: boolean}
8
11
 
9
12
  /**
10
13
  * « Retirer du site » : dépublication native de Sanity, rendue visible et expliquée.
@@ -17,24 +20,60 @@ type Referrer = {_id: string; _type: string; title?: string}
17
20
  * leurs liens vers elle disparaîtront du site. Une référence FORTE (non `weak`)
18
21
  * empêche Sanity de dépublier : le message l'explique au lieu d'une erreur brute.
19
22
  */
20
- export const RemoveFromSiteAction: DocumentActionComponent = (props: DocumentActionProps) => {
23
+ export const RemoveFromSiteAction: DocumentActionComponent = createRemoveFromSite()
24
+
25
+ /**
26
+ * Variante multilingue : sur la version PRINCIPALE d'un document traduit (page ou
27
+ * fiche de collection), la fenêtre propose aussi de retirer du site ses autres
28
+ * langues publiées (cochées par défaut), en une seule opération.
29
+ */
30
+ export function createRemoveFromSite(config?: ResolvedKitConfig, masterLocale?: string): DocumentActionComponent {
31
+ const i18n = config?.i18n
32
+ const master = masterLocale ?? i18n?.defaultLocale
33
+ const Action: DocumentActionComponent = (props: DocumentActionProps) => useRemoveFromSite(props, i18n?.field, master)
34
+ Action.action = 'unpublish'
35
+ return Action
36
+ }
37
+
38
+ function useRemoveFromSite(props: DocumentActionProps, field: string | undefined, master: string | undefined): DocumentActionDescription | null {
21
39
  const client = useKitClient()
40
+ const current = (props.draft ?? props.published) as Record<string, unknown> | null
41
+ const isMaster = !!field && !!master && current?.[field] === master
42
+ const [versions, setVersions] = useState<Version[]>([])
22
43
  const [open, setOpen] = useState(false)
23
44
  const [referrers, setReferrers] = useState<Referrer[] | null>(null)
24
45
  const [busy, setBusy] = useState(false)
25
46
  const [error, setError] = useState<string | null>(null)
26
47
 
48
+ // Autres langues PUBLIÉES de la version principale (proposées, cochées).
49
+ useEffect(() => {
50
+ if (!open || !isMaster) return
51
+ let alive = true
52
+ translationsOf(client, props.id)
53
+ .then(async (list) => {
54
+ const others = list.filter((t) => t.id !== props.id)
55
+ const live = new Set(await client.fetch<string[]>(`*[_id in $ids]._id`, {ids: others.map((t) => t.id)}))
56
+ if (alive) setVersions(others.filter((t) => live.has(t.id)).map((t) => ({...t, selected: true})))
57
+ })
58
+ .catch(() => alive && setVersions([]))
59
+ return () => {
60
+ alive = false
61
+ }
62
+ }, [open, isMaster, client, props.id])
63
+ const ids = [props.id, ...versions.filter((v) => v.selected).map((v) => v.id)]
64
+
27
65
  useEffect(() => {
28
66
  if (!open) return
29
67
  setReferrers(null)
30
68
  client
31
69
  .fetch<Referrer[]>(
32
- `*[references($id) && !(_id in path("drafts.**")) && _type != "translation.metadata"]{_id, _type, "title": coalesce(title, name, _id)}`,
33
- {id: props.id},
70
+ `*[references($ids) && !(_id in path("drafts.**")) && !(_id in $ids) && _type != "translation.metadata"]{_id, _type, "title": coalesce(title, name, _id)}`,
71
+ {ids},
34
72
  )
35
73
  .then(setReferrers)
36
74
  .catch(() => setReferrers([]))
37
- }, [open, client, props.id])
75
+ // eslint-disable-next-line react-hooks/exhaustive-deps
76
+ }, [open, client, ids.join(',')])
38
77
 
39
78
  if (!props.published) return null
40
79
 
@@ -42,11 +81,17 @@ export const RemoveFromSiteAction: DocumentActionComponent = (props: DocumentAct
42
81
  setBusy(true)
43
82
  setError(null)
44
83
  try {
45
- const {_rev, _updatedAt, ...published} = props.published as Record<string, unknown>
46
84
  const tx = client.transaction()
47
- // Le brouillon en cours est conservé tel quel ; sinon il reprend la version en ligne.
48
- if (!props.draft) tx.createIfNotExists({...published, _id: `drafts.${props.id}`} as {_id: string; _type: string})
49
- tx.delete(props.id)
85
+ // Chaque version : le brouillon en cours est conservé tel quel ; sinon il
86
+ // reprend la version en ligne. Puis la version en ligne est supprimée.
87
+ const docs = await client.fetch<Record<string, unknown>[]>(`*[_id in $ids]`, {ids})
88
+ const drafts = new Set(await client.fetch<string[]>(`*[_id in $drafts]._id`, {drafts: ids.map((id) => `drafts.${id}`)}))
89
+ for (const doc of docs) {
90
+ const {_rev, _updatedAt, ...published} = doc
91
+ const id = String(doc._id)
92
+ if (!drafts.has(`drafts.${id}`)) tx.createIfNotExists({...published, _id: `drafts.${id}`} as {_id: string; _type: string})
93
+ tx.delete(id)
94
+ }
50
95
  await tx.commit()
51
96
  setOpen(false)
52
97
  props.onComplete()
@@ -80,21 +125,40 @@ export const RemoveFromSiteAction: DocumentActionComponent = (props: DocumentAct
80
125
  message: (
81
126
  <Stack gap={3}>
82
127
  <Text size={1}>
83
- The page leaves the site (production and staging "Published"). All its content stays in the
84
- draft: to put it back online, publish it.
128
+ It leaves the site (production and staging "Published"). All its content stays in the draft:
129
+ to put it back online, publish it.
85
130
  </Text>
131
+ {versions.length > 0 && (
132
+ <Stack gap={2}>
133
+ <Text size={1} weight="semibold">
134
+ Also remove the other languages from the site:
135
+ </Text>
136
+ {versions.map((v, index) => (
137
+ <Card key={v.id} padding={2} radius={2} border>
138
+ <Flex as="label" gap={3} align="center">
139
+ <Checkbox
140
+ checked={v.selected}
141
+ disabled={busy}
142
+ onChange={() => setVersions(versions.map((x, i) => (i === index ? {...x, selected: !x.selected} : x)))}
143
+ />
144
+ <Text size={1}>{v.language.toUpperCase()}</Text>
145
+ </Flex>
146
+ </Card>
147
+ ))}
148
+ </Stack>
149
+ )}
86
150
  {referrers === null ? (
87
151
  <Text size={1} muted>
88
- Looking for links to this page…
152
+ Looking for links…
89
153
  </Text>
90
154
  ) : referrers.length > 0 ? (
91
155
  <Text size={1}>
92
- These published documents point to it; their links to this page will disappear from the site:{' '}
156
+ These published documents point to it; their links will disappear from the site:{' '}
93
157
  {referrers.map((r) => r.title || r._id).join(', ')}.
94
158
  </Text>
95
159
  ) : (
96
160
  <Text size={1} muted>
97
- No published document points to this page.
161
+ No published document points to it.
98
162
  </Text>
99
163
  )}
100
164
  {error && (
@@ -107,4 +171,3 @@ export const RemoveFromSiteAction: DocumentActionComponent = (props: DocumentAct
107
171
  },
108
172
  }
109
173
  }
110
- RemoveFromSiteAction.action = 'unpublish'
package/src/index.ts CHANGED
@@ -41,12 +41,13 @@ export const NCF_TOOL_NAMES = [
41
41
  * pas le Studio de démarrer : l'onglet concerné affiche le détail à corriger.
42
42
  */
43
43
  import {createOverrideInput} from './form/OverrideInput'
44
- import {RemoveFromSiteAction} from './actions/RemoveFromSite'
44
+ import {RemoveFromSiteAction, createRemoveFromSite} from './actions/RemoveFromSite'
45
45
  import {createSlugUrlInput, isSlugInput} from './form/SlugUrlInput'
46
46
  import {withTranslationTodo} from './form/TranslationTodoInput'
47
47
  import {withPublishedHint} from './form/PublishedHint'
48
48
  import {withLanguageMismatch} from './form/LanguageMismatch'
49
49
  import {withPropagation} from './actions/PropagatePublish'
50
+ import {withTranslationDelete} from './actions/DeleteTranslations'
50
51
 
51
52
  /** Champs du formulaire : adresse sous le Slug d'une page, pastille sur les sections. */
52
53
  function createKitInput(config: Parameters<typeof createOverrideInput>[0]): ComponentType<InputProps> {
@@ -145,24 +146,34 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
145
146
  prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
146
147
  // Pages : « Retirer du site » (dépublication expliquée, liens listés) à la place
147
148
  // du « Unpublish » natif, caché et bloqué sans explication par les références.
149
+ // Supprimer la version principale d'un document traduit : suppression de ses
150
+ // autres langues proposée (cochées par défaut).
148
151
  // Publier la version principale d'une page traduite : propagation proposée aux
149
152
  // brouillons des autres langues (structure et valeurs ; textes « à traduire »).
150
153
  actions: (prev, context) =>
151
154
  config.pageTypeNames.includes(context.schemaType)
152
155
  ? prev.map((action) =>
153
- action.action === 'unpublish' ? RemoveFromSiteAction : action.action === 'publish' && config.i18n ? withPropagation(action, config, undefined, {allowCreate: true}) : action,
156
+ action.action === 'unpublish' ? (config.i18n ? createRemoveFromSite(config) : RemoveFromSiteAction) : action.action === 'publish' && config.i18n ? withPropagation(action, config, undefined, {allowCreate: true}) : action.action === 'delete' && config.i18n ? withTranslationDelete(action, config) : action,
154
157
  )
155
158
  : // Valeurs par défaut des composants : publier celles de la langue source
156
159
  // (anglais en général) propose de retraduire celles des autres langues.
157
160
  context.schemaType === config.componentPreview.defaultsType && config.i18n
158
- ? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action))
161
+ ? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action.action === 'delete' ? withTranslationDelete(action, config, config.i18n?.defaultsSourceLocale) : action))
159
162
  : // Tout autre type traduit document par document (collections, réglages
160
163
  // par langue) : même proposition que les pages à la publication de la
161
164
  // version principale (mettre à jour ou créer les autres langues).
162
165
  // Détecté par le champ de langue du schéma : une nouvelle collection
163
166
  // traduite en profite sans réglage.
164
167
  config.i18n && !isKitType(context.schemaType) && hasLanguageField(context.schema.get(context.schemaType), config.i18n.field)
165
- ? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, undefined, {allowCreate: true}) : action))
168
+ ? prev.map((action) =>
169
+ action.action === 'publish'
170
+ ? withPropagation(action, config, undefined, {allowCreate: true})
171
+ : action.action === 'delete'
172
+ ? withTranslationDelete(action, config)
173
+ : action.action === 'unpublish'
174
+ ? createRemoveFromSite(config)
175
+ : action,
176
+ )
166
177
  : prev,
167
178
  },
168
179
 
@@ -271,6 +282,8 @@ function hasLanguageField(schemaType: unknown, field: string): boolean {
271
282
  return Array.isArray(fields) && fields.some((f) => f?.name === field)
272
283
  }
273
284
 
285
+ export {withSameLanguageReferences} from './schema/sameLanguageReferences'
286
+ export {fixCrossLanguageReferences, type CrossLanguageReport} from './lib/fixCrossLanguageReferences'
274
287
  export {NcfPreviewHeader, ncfPreviewComponents} from './tools/presentation/PreviewHeader'
275
288
  export {ncfPresentationComponents} from './tools/presentation/PagesNavigator'
276
289
  export {NcfPreviewLauncher, createPreviewLauncher} from './tools/navbar/PreviewLauncher'
@@ -0,0 +1,76 @@
1
+ import type {SanityClient} from 'sanity'
2
+
3
+ type Obj = Record<string, unknown>
4
+ const isObj = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v)
5
+ const bare = (id: string) => id.replace(/^drafts\./, '')
6
+
7
+ export interface CrossLanguageReport {
8
+ /** Références repointées (ou à repointer en simulation). */
9
+ fixed: {documentId: string; path: string; from: string; to: string}[]
10
+ /** Références croisées sans équivalent dans la langue du document (laissées). */
11
+ missing: {documentId: string; path: string; ref: string; language: string}[]
12
+ }
13
+
14
+ /** Références d'une valeur, avec leur chemin de patch (`a.b[_key=="x"].c`). */
15
+ function refs(value: unknown, path: string, out: {path: string; ref: string}[]) {
16
+ if (Array.isArray(value)) {
17
+ value.forEach((item, i) => refs(item, `${path}[${isObj(item) && typeof item._key === 'string' ? `_key=="${item._key}"` : i}]`, out))
18
+ return
19
+ }
20
+ if (!isObj(value)) return
21
+ if (typeof value._ref === 'string' && !/^(image|file)-/.test(value._ref)) out.push({path: `${path}._ref`, ref: value._ref})
22
+ for (const [k, v] of Object.entries(value)) if (!k.startsWith('_')) refs(v, path ? `${path}.${k}` : k, out)
23
+ }
24
+
25
+ /**
26
+ * RÈGLE D'OR DU MULTILINGUE, côté données : chaque référence d'un document vise un
27
+ * document de SA langue (document sans langue : la langue principale). Une
28
+ * référence croisée est repointée vers la traduction de la bonne langue (liens de
29
+ * traduction) ; sans traduction, elle est signalée et laissée. Publiés et
30
+ * brouillons. `apply: false` : simulation.
31
+ *
32
+ * ```ts
33
+ * // studio/scripts/references-same-language.ts (sanity exec --with-user-token)
34
+ * const report = await fixCrossLanguageReferences(getCliClient(...), {defaultLocale: 'fr', apply})
35
+ * ```
36
+ */
37
+ export async function fixCrossLanguageReferences(
38
+ client: SanityClient,
39
+ options: {field?: string; defaultLocale: string; apply?: boolean},
40
+ ): Promise<CrossLanguageReport> {
41
+ const field = options.field ?? 'language'
42
+ const c = client.withConfig({perspective: 'raw'})
43
+ const docs = await c.fetch<Obj[]>(
44
+ `*[!(_type match "system.*") && !(_type match "sanity.*") && !(_type match "ncf.*") && _type != "translation.metadata"]`,
45
+ )
46
+ const language = new Map<string, string>()
47
+ for (const d of docs) if (typeof d[field] === 'string') language.set(bare(String(d._id)), String(d[field]))
48
+ const metas = await c.fetch<{translations?: {language?: string; _key?: string; value?: {_ref?: string}}[]}[]>(
49
+ `*[_type == "translation.metadata"]{translations}`,
50
+ )
51
+ const equivalent = new Map<string, Map<string, string>>()
52
+ for (const m of metas) {
53
+ const group = new Map<string, string>()
54
+ for (const t of m.translations ?? []) if (t.value?._ref) group.set(t.language ?? t._key ?? '', t.value._ref)
55
+ for (const id of group.values()) equivalent.set(id, group)
56
+ }
57
+
58
+ const report: CrossLanguageReport = {fixed: [], missing: []}
59
+ for (const d of docs) {
60
+ const own = typeof d[field] === 'string' ? String(d[field]) : options.defaultLocale
61
+ const found: {path: string; ref: string}[] = []
62
+ for (const [k, v] of Object.entries(d)) if (!k.startsWith('_')) refs(v, k, found)
63
+ const set: Record<string, string> = {}
64
+ for (const {path, ref} of found) {
65
+ const target = language.get(bare(ref))
66
+ if (!target || target === own) continue
67
+ const to = equivalent.get(bare(ref))?.get(own)
68
+ if (to) {
69
+ set[path] = to
70
+ report.fixed.push({documentId: String(d._id), path, from: ref, to})
71
+ } else report.missing.push({documentId: String(d._id), path, ref, language: own})
72
+ }
73
+ if (options.apply && Object.keys(set).length) await c.patch(String(d._id)).ifRevisionId(String(d._rev)).set(set).commit({visibility: 'async'})
74
+ }
75
+ return report
76
+ }
@@ -0,0 +1,65 @@
1
+ import type {NcfKitConfig} from '../config/types'
2
+
3
+ type Obj = Record<string, unknown>
4
+ type FilterResult = {filter?: string; params?: Record<string, unknown>}
5
+ type FilterFn = (context: {document?: Obj; [key: string]: unknown}) => FilterResult | Promise<FilterResult>
6
+
7
+ // Objet de configuration simple (jamais un élément React, une icône ou une instance).
8
+ const isObj = (v: unknown): v is Obj => {
9
+ if (!v || typeof v !== 'object' || Array.isArray(v) || '$$typeof' in v) return false
10
+ const proto = Object.getPrototypeOf(v)
11
+ return proto === Object.prototype || proto === null
12
+ }
13
+
14
+ /**
15
+ * RÈGLE D'OR DU MULTILINGUE : une référence ne propose que des documents de la
16
+ * MÊME langue que le document en cours (un article EN ne voit que les catégories EN,
17
+ * une page FR que les pages FR). Les documents sans langue (logos, régions, assets…)
18
+ * restent proposés. Un document commun à toutes les langues (Navigation…) vise la
19
+ * langue principale.
20
+ *
21
+ * Pose ce filtre sur TOUS les champs de référence des types donnés (champs, listes,
22
+ * objets imbriqués, annotations du texte riche), combiné avec un filtre déjà présent.
23
+ * À appliquer aux types du projet :
24
+ *
25
+ * ```ts
26
+ * schema: {types: withSameLanguageReferences(schemaTypes, ncfOptions)}
27
+ * ```
28
+ */
29
+ export function withSameLanguageReferences<T>(types: T[], options: Pick<NcfKitConfig, 'i18n'>): T[] {
30
+ const i18n = options.i18n
31
+ if (!i18n) return types
32
+ const field = i18n.field ?? 'language'
33
+ const fallback = i18n.defaultLocale ?? i18n.locales?.[0]
34
+ const condition = `(!defined(${field}) || ${field} == $ncfLanguage)`
35
+ const languageOf = (document: Obj | undefined) => (typeof document?.[field] === 'string' && document[field]) || fallback
36
+
37
+ const wrap = (opts: Obj | undefined): Obj => {
38
+ const previous = opts?.filter
39
+ const previousParams = (opts?.filterParams as Record<string, unknown> | undefined) ?? {}
40
+ const filter: FilterFn = async (context) => {
41
+ const base: FilterResult =
42
+ typeof previous === 'function'
43
+ ? ((await (previous as FilterFn)(context)) ?? {})
44
+ : typeof previous === 'string'
45
+ ? {filter: previous, params: previousParams}
46
+ : {}
47
+ return {
48
+ filter: base.filter ? `(${base.filter}) && ${condition}` : condition,
49
+ params: {...(base.params ?? {}), ncfLanguage: languageOf(context.document)},
50
+ }
51
+ }
52
+ const {filterParams: _ignored, ...rest} = opts ?? {}
53
+ return {...rest, filter}
54
+ }
55
+
56
+ const visit = (node: unknown): unknown => {
57
+ if (Array.isArray(node)) return node.map(visit)
58
+ if (!isObj(node)) return node
59
+ const out: Obj = {}
60
+ for (const [key, value] of Object.entries(node)) out[key] = key === 'options' || key === 'initialValue' || key === 'validation' ? value : visit(value)
61
+ if (node.type === 'reference' && Array.isArray(node.to)) out.options = wrap(node.options as Obj | undefined)
62
+ return out
63
+ }
64
+ return types.map((t) => visit(t) as T)
65
+ }
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
4
4
  * le vérifie.
5
5
  */
6
- export const KIT_VERSION = '2.35.0'
6
+ export const KIT_VERSION = '2.37.0'