@nocode-factory/sanity-kit 2.19.0 → 2.20.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 +3 -0
- package/bin/ncf-kit.mjs +15 -0
- package/dist/index.d.ts +38 -2
- package/dist/index.js +465 -22
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/PropagatePublish.tsx +218 -0
- package/src/form/TranslationTodoInput.tsx +44 -0
- package/src/hooks/useTranslationTodo.ts +80 -0
- package/src/index.ts +9 -2
- package/src/lib/propagate.ts +211 -0
- package/src/schema/boardLayout.ts +3 -1
- package/src/schema/translationTodo.ts +23 -0
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import {useEffect, useState} from 'react'
|
|
2
|
+
import {Box, Button, Card, Checkbox, Flex, Spinner, Stack, Text} from '@sanity/ui'
|
|
3
|
+
import {useSchema, type DocumentActionComponent, type DocumentActionProps} from 'sanity'
|
|
4
|
+
import type {ResolvedKitConfig} from '../config/types'
|
|
5
|
+
import {useKitClient} from '../hooks/useKitClient'
|
|
6
|
+
import {hasChanges, propagate, type PropagationResult, type SchemaTypeLike} from '../lib/propagate'
|
|
7
|
+
import {TRANSLATION_TODO_TYPE, translationTodoId} from '../schema/translationTodo'
|
|
8
|
+
|
|
9
|
+
type Doc = Record<string, unknown>
|
|
10
|
+
interface Target {
|
|
11
|
+
language: string
|
|
12
|
+
id: string
|
|
13
|
+
result: PropagationResult
|
|
14
|
+
selected: boolean
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Publier la version PRINCIPALE d'une page qui a des traductions : la publication
|
|
19
|
+
* part normalement, puis « Propager aux autres langues ? » propose d'appliquer aux
|
|
20
|
+
* BROUILLONS des traductions la structure (sections ajoutées, supprimées, déplacées)
|
|
21
|
+
* et les valeurs non textuelles (images, liens, options…). Les textes traduits ne
|
|
22
|
+
* sont jamais écrasés : les textes modifiés sont marqués « à traduire ». Rien n'est
|
|
23
|
+
* publié dans les autres langues : on relit, on traduit, on publie.
|
|
24
|
+
*/
|
|
25
|
+
export function withPropagation(Publish: DocumentActionComponent, config: ResolvedKitConfig): DocumentActionComponent {
|
|
26
|
+
const i18n = config.i18n
|
|
27
|
+
const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
|
|
28
|
+
const base = Publish(props)
|
|
29
|
+
const [run, setRun] = useState<{before: Doc; after: Doc} | null>(null)
|
|
30
|
+
const current = (props.draft ?? props.published) as Doc | null
|
|
31
|
+
if (!base || !i18n || current?.[i18n.field] !== i18n.defaultLocale) return base
|
|
32
|
+
return {
|
|
33
|
+
...base,
|
|
34
|
+
onHandle: () => {
|
|
35
|
+
const before = props.published as Doc | null
|
|
36
|
+
const after = props.draft as Doc | null
|
|
37
|
+
base.onHandle?.()
|
|
38
|
+
// Une page déjà publiée qu'on modifie : il y a quelque chose à propager.
|
|
39
|
+
if (before && after) setRun({before, after})
|
|
40
|
+
},
|
|
41
|
+
dialog: run
|
|
42
|
+
? {
|
|
43
|
+
type: 'dialog',
|
|
44
|
+
header: 'Propager aux autres langues ?',
|
|
45
|
+
width: 'medium',
|
|
46
|
+
onClose: () => {
|
|
47
|
+
setRun(null)
|
|
48
|
+
props.onComplete()
|
|
49
|
+
},
|
|
50
|
+
content: (
|
|
51
|
+
<PropagateDialog
|
|
52
|
+
config={config}
|
|
53
|
+
id={props.id}
|
|
54
|
+
type={props.type}
|
|
55
|
+
before={run.before}
|
|
56
|
+
after={run.after}
|
|
57
|
+
onDone={() => {
|
|
58
|
+
setRun(null)
|
|
59
|
+
props.onComplete()
|
|
60
|
+
}}
|
|
61
|
+
/>
|
|
62
|
+
),
|
|
63
|
+
}
|
|
64
|
+
: base.dialog,
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
Wrapped.action = Publish.action
|
|
68
|
+
return Wrapped
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function PropagateDialog(props: {config: ResolvedKitConfig; id: string; type: string; before: Doc; after: Doc; onDone: () => void}) {
|
|
72
|
+
const {config, id, type, before, after, onDone} = props
|
|
73
|
+
const client = useKitClient()
|
|
74
|
+
const schema = useSchema()
|
|
75
|
+
const field = config.i18n?.field ?? 'language'
|
|
76
|
+
const source = String(after[field] ?? '')
|
|
77
|
+
const [targets, setTargets] = useState<Target[] | null>(null)
|
|
78
|
+
const [busy, setBusy] = useState(false)
|
|
79
|
+
const [done, setDone] = useState<string[] | null>(null)
|
|
80
|
+
const [error, setError] = useState<string | null>(null)
|
|
81
|
+
|
|
82
|
+
useEffect(() => {
|
|
83
|
+
const documentType = schema.get(type) as unknown as SchemaTypeLike | undefined
|
|
84
|
+
void (async () => {
|
|
85
|
+
const translations = await client.fetch<{language: string; id: string}[]>(
|
|
86
|
+
`*[_type == "translation.metadata" && references($id)][0].translations[]{language, "id": value._ref}`,
|
|
87
|
+
{id},
|
|
88
|
+
)
|
|
89
|
+
const list: Target[] = []
|
|
90
|
+
for (const t of translations ?? []) {
|
|
91
|
+
if (!t?.id || t.id === id || t.language === source) continue
|
|
92
|
+
const target =
|
|
93
|
+
(await client.getDocument<Doc>(`drafts.${t.id}`)) ?? (await client.getDocument<Doc>(t.id)) ?? null
|
|
94
|
+
if (!target) continue
|
|
95
|
+
const result = propagate(target, before, after, documentType)
|
|
96
|
+
list.push({language: t.language, id: t.id, result, selected: hasChanges(result)})
|
|
97
|
+
}
|
|
98
|
+
setTargets(list)
|
|
99
|
+
})().catch(() => setTargets([]))
|
|
100
|
+
}, [client, schema, id, type, before, after, source])
|
|
101
|
+
|
|
102
|
+
const apply = async () => {
|
|
103
|
+
setBusy(true)
|
|
104
|
+
setError(null)
|
|
105
|
+
try {
|
|
106
|
+
const applied: string[] = []
|
|
107
|
+
for (const t of targets ?? []) {
|
|
108
|
+
if (!t.selected) continue
|
|
109
|
+
const {_rev, _createdAt, _updatedAt, ...doc} = t.result.document
|
|
110
|
+
await client.createOrReplace({...doc, _id: `drafts.${t.id}`, _type: type} as {_id: string; _type: string})
|
|
111
|
+
if (t.result.toTranslate.length) {
|
|
112
|
+
const todoId = translationTodoId(t.id)
|
|
113
|
+
const existing = await client.fetch<string[] | null>(`*[_id == $todoId][0].paths`, {todoId})
|
|
114
|
+
await client.createOrReplace({
|
|
115
|
+
_id: todoId,
|
|
116
|
+
_type: TRANSLATION_TODO_TYPE,
|
|
117
|
+
documentId: t.id,
|
|
118
|
+
sourceId: id,
|
|
119
|
+
sourceLanguage: source,
|
|
120
|
+
paths: [...new Set([...(existing ?? []), ...t.result.toTranslate])],
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
applied.push(t.language.toUpperCase())
|
|
124
|
+
}
|
|
125
|
+
setDone(applied)
|
|
126
|
+
} catch (cause) {
|
|
127
|
+
setError(`La propagation a échoué, rien n'a été publié. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 140)})`)
|
|
128
|
+
} finally {
|
|
129
|
+
setBusy(false)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (done) {
|
|
134
|
+
return (
|
|
135
|
+
<Stack gap={4} padding={4}>
|
|
136
|
+
<Text size={1}>
|
|
137
|
+
{done.length
|
|
138
|
+
? `Brouillons mis à jour : ${done.join(', ')}. Relisez, traduisez les champs marqués « À traduire », puis publiez chaque langue.`
|
|
139
|
+
: 'Rien n’a été propagé.'}
|
|
140
|
+
</Text>
|
|
141
|
+
<Flex justify="flex-end">
|
|
142
|
+
<Button text="Fermer" mode="ghost" onClick={onDone} />
|
|
143
|
+
</Flex>
|
|
144
|
+
</Stack>
|
|
145
|
+
)
|
|
146
|
+
}
|
|
147
|
+
if (!targets) {
|
|
148
|
+
return (
|
|
149
|
+
<Flex align="center" gap={3} padding={4}>
|
|
150
|
+
<Spinner muted />
|
|
151
|
+
<Text size={1} muted>
|
|
152
|
+
Comparaison avec les traductions…
|
|
153
|
+
</Text>
|
|
154
|
+
</Flex>
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
if (!targets.some((t) => hasChanges(t.result))) {
|
|
158
|
+
return (
|
|
159
|
+
<Stack gap={4} padding={4}>
|
|
160
|
+
<Text size={1}>Aucune traduction à mettre à jour.</Text>
|
|
161
|
+
<Flex justify="flex-end">
|
|
162
|
+
<Button text="Fermer" mode="ghost" onClick={onDone} />
|
|
163
|
+
</Flex>
|
|
164
|
+
</Stack>
|
|
165
|
+
)
|
|
166
|
+
}
|
|
167
|
+
return (
|
|
168
|
+
<Stack gap={4} padding={4}>
|
|
169
|
+
<Text size={1}>
|
|
170
|
+
La version {source.toUpperCase()} est publiée. Appliquer ses changements aux brouillons des autres langues ? Les
|
|
171
|
+
textes traduits ne sont jamais écrasés : les textes modifiés sont marqués « À traduire ». Rien n’est publié.
|
|
172
|
+
</Text>
|
|
173
|
+
<Stack gap={3}>
|
|
174
|
+
{targets.map((t, index) => (
|
|
175
|
+
<Card key={t.id} padding={3} radius={2} border>
|
|
176
|
+
<Flex gap={3} align="flex-start">
|
|
177
|
+
<Checkbox
|
|
178
|
+
checked={t.selected}
|
|
179
|
+
disabled={!hasChanges(t.result)}
|
|
180
|
+
onChange={() => setTargets(targets.map((x, i) => (i === index ? {...x, selected: !x.selected} : x)))}
|
|
181
|
+
/>
|
|
182
|
+
<Box flex={1}>
|
|
183
|
+
<Stack gap={2}>
|
|
184
|
+
<Text size={1} weight="semibold">
|
|
185
|
+
{t.language.toUpperCase()}
|
|
186
|
+
</Text>
|
|
187
|
+
<Text size={1} muted>
|
|
188
|
+
{summary(t.result)}
|
|
189
|
+
</Text>
|
|
190
|
+
</Stack>
|
|
191
|
+
</Box>
|
|
192
|
+
</Flex>
|
|
193
|
+
</Card>
|
|
194
|
+
))}
|
|
195
|
+
</Stack>
|
|
196
|
+
{error && (
|
|
197
|
+
<Card tone="critical" padding={3} radius={2}>
|
|
198
|
+
<Text size={1}>{error}</Text>
|
|
199
|
+
</Card>
|
|
200
|
+
)}
|
|
201
|
+
<Flex justify="flex-end" gap={2}>
|
|
202
|
+
<Button text="Ignorer" mode="ghost" onClick={onDone} disabled={busy} />
|
|
203
|
+
<Button text={busy ? 'Propagation…' : 'Propager'} tone="primary" onClick={() => void apply()} disabled={busy || !targets.some((t) => t.selected)} />
|
|
204
|
+
</Flex>
|
|
205
|
+
</Stack>
|
|
206
|
+
)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function summary(r: PropagationResult): string {
|
|
210
|
+
if (!hasChanges(r)) return 'Déjà à jour.'
|
|
211
|
+
const parts: string[] = []
|
|
212
|
+
if (r.added) parts.push(`${r.added} élément${r.added > 1 ? 's' : ''} ajouté${r.added > 1 ? 's' : ''}`)
|
|
213
|
+
if (r.removed) parts.push(`${r.removed} supprimé${r.removed > 1 ? 's' : ''}`)
|
|
214
|
+
if (r.moved) parts.push('ordre mis à jour')
|
|
215
|
+
if (r.copied.length) parts.push(`${r.copied.length} valeur${r.copied.length > 1 ? 's' : ''} recopiée${r.copied.length > 1 ? 's' : ''} (images, liens, options…)`)
|
|
216
|
+
if (r.toTranslate.length) parts.push(`${r.toTranslate.length} texte${r.toTranslate.length > 1 ? 's' : ''} à traduire`)
|
|
217
|
+
return parts.join(' · ')
|
|
218
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import {createElement, useState, type ComponentType} from 'react'
|
|
2
|
+
import {useFormValue, type InputProps} from 'sanity'
|
|
3
|
+
import {Button, Card, Flex, Stack, Text} from '@sanity/ui'
|
|
4
|
+
import type {ResolvedKitConfig} from '../config/types'
|
|
5
|
+
import {useKitClient} from '../hooks/useKitClient'
|
|
6
|
+
import {fieldPathKey, useTranslationTodo} from '../hooks/useTranslationTodo'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Sous un champ d'une traduction modifié dans la version principale (propagation) :
|
|
10
|
+
* « À traduire », avec « Marquer comme traduit » qui le retire de la liste.
|
|
11
|
+
*/
|
|
12
|
+
export function withTranslationTodo(Inner: ComponentType<InputProps>, config: ResolvedKitConfig): ComponentType<InputProps> {
|
|
13
|
+
function TranslationTodoInput(props: InputProps) {
|
|
14
|
+
const id = useFormValue(['_id']) as string | undefined
|
|
15
|
+
const client = useKitClient()
|
|
16
|
+
const todo = useTranslationTodo(client, config.i18n ? id : undefined)
|
|
17
|
+
const [busy, setBusy] = useState(false)
|
|
18
|
+
const key = fieldPathKey(props.path)
|
|
19
|
+
const inner = createElement(Inner, props)
|
|
20
|
+
if (!todo?.paths?.includes(key)) return inner
|
|
21
|
+
const done = () => {
|
|
22
|
+
setBusy(true)
|
|
23
|
+
void client
|
|
24
|
+
.patch(todo._id)
|
|
25
|
+
.set({paths: (todo.paths ?? []).filter((p) => p !== key)})
|
|
26
|
+
.commit()
|
|
27
|
+
.finally(() => setBusy(false))
|
|
28
|
+
}
|
|
29
|
+
return (
|
|
30
|
+
<Stack gap={2}>
|
|
31
|
+
{inner}
|
|
32
|
+
<Card tone="caution" padding={2} radius={2} border>
|
|
33
|
+
<Flex align="center" gap={2}>
|
|
34
|
+
<Text size={1} style={{flex: 1}}>
|
|
35
|
+
À traduire : modifié dans la version {(todo.sourceLanguage ?? '').toUpperCase()}.
|
|
36
|
+
</Text>
|
|
37
|
+
<Button mode="ghost" fontSize={1} padding={2} text="Marquer comme traduit" disabled={busy} onClick={done} />
|
|
38
|
+
</Flex>
|
|
39
|
+
</Card>
|
|
40
|
+
</Stack>
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
return TranslationTodoInput
|
|
44
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import {useEffect, useSyncExternalStore} from 'react'
|
|
2
|
+
import type {SanityClient} from 'sanity'
|
|
3
|
+
import {translationTodoId} from '../schema/translationTodo'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Champs « à traduire » d'un document (traduction), lus UNE fois et tenus à jour en
|
|
7
|
+
* direct pour tous les champs du formulaire (une requête, une écoute).
|
|
8
|
+
*/
|
|
9
|
+
export interface TranslationTodo {
|
|
10
|
+
_id: string
|
|
11
|
+
sourceLanguage?: string
|
|
12
|
+
paths?: string[]
|
|
13
|
+
}
|
|
14
|
+
interface Entry {
|
|
15
|
+
value: TranslationTodo | null
|
|
16
|
+
listeners: Set<() => void>
|
|
17
|
+
stop: (() => void) | null
|
|
18
|
+
}
|
|
19
|
+
const store = new Map<string, Entry>()
|
|
20
|
+
|
|
21
|
+
function entryFor(client: SanityClient, documentId: string): Entry {
|
|
22
|
+
const {projectId, dataset} = client.config()
|
|
23
|
+
const id = translationTodoId(documentId)
|
|
24
|
+
const key = `${projectId}:${dataset}:${id}`
|
|
25
|
+
let entry = store.get(key)
|
|
26
|
+
if (!entry) {
|
|
27
|
+
entry = {value: null, listeners: new Set(), stop: null}
|
|
28
|
+
store.set(key, entry)
|
|
29
|
+
}
|
|
30
|
+
const e = entry
|
|
31
|
+
if (!e.stop) {
|
|
32
|
+
const load = () =>
|
|
33
|
+
client
|
|
34
|
+
.fetch<TranslationTodo | null>(`*[_id == $id][0]{_id, sourceLanguage, paths}`, {id})
|
|
35
|
+
.then((value) => {
|
|
36
|
+
e.value = value
|
|
37
|
+
e.listeners.forEach((l) => l())
|
|
38
|
+
})
|
|
39
|
+
.catch(() => {})
|
|
40
|
+
void load()
|
|
41
|
+
const sub = client.listen(`*[_id == $id]`, {id}, {visibility: 'query', includeResult: false}).subscribe({next: () => void load()})
|
|
42
|
+
e.stop = () => sub.unsubscribe()
|
|
43
|
+
}
|
|
44
|
+
return e
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function useTranslationTodo(client: SanityClient, documentId: string | undefined): TranslationTodo | null {
|
|
48
|
+
const entry = documentId ? entryFor(client, documentId) : null
|
|
49
|
+
const value = useSyncExternalStore(
|
|
50
|
+
(listener) => {
|
|
51
|
+
if (!entry) return () => {}
|
|
52
|
+
entry.listeners.add(listener)
|
|
53
|
+
return () => {
|
|
54
|
+
entry.listeners.delete(listener)
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
() => entry?.value ?? null,
|
|
58
|
+
)
|
|
59
|
+
useEffect(
|
|
60
|
+
() => () => {
|
|
61
|
+
if (entry && entry.listeners.size === 0 && entry.stop) {
|
|
62
|
+
entry.stop()
|
|
63
|
+
entry.stop = null
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
[entry],
|
|
67
|
+
)
|
|
68
|
+
return value
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Chemin lisible d'un champ du formulaire, au format de la propagation (`sections[a].title`). */
|
|
72
|
+
export function fieldPathKey(path: readonly unknown[]): string {
|
|
73
|
+
let out = ''
|
|
74
|
+
for (const seg of path) {
|
|
75
|
+
if (typeof seg === 'string') out += out ? `.${seg}` : seg
|
|
76
|
+
else if (seg && typeof seg === 'object' && '_key' in seg) out += `[${String((seg as {_key: string})._key)}]`
|
|
77
|
+
else if (typeof seg === 'number') out += `[${seg}]`
|
|
78
|
+
}
|
|
79
|
+
return out
|
|
80
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -43,6 +43,8 @@ export const NCF_TOOL_NAMES = [
|
|
|
43
43
|
import {createOverrideInput} from './form/OverrideInput'
|
|
44
44
|
import {RemoveFromSiteAction} from './actions/RemoveFromSite'
|
|
45
45
|
import {createSlugUrlInput, isSlugInput} from './form/SlugUrlInput'
|
|
46
|
+
import {withTranslationTodo} from './form/TranslationTodoInput'
|
|
47
|
+
import {withPropagation} from './actions/PropagatePublish'
|
|
46
48
|
|
|
47
49
|
/** Champs du formulaire : adresse sous le Slug d'une page, pastille sur les sections. */
|
|
48
50
|
function createKitInput(config: Parameters<typeof createOverrideInput>[0]): ComponentType<InputProps> {
|
|
@@ -51,7 +53,8 @@ function createKitInput(config: Parameters<typeof createOverrideInput>[0]): Comp
|
|
|
51
53
|
function KitInput(props: InputProps) {
|
|
52
54
|
return isSlugInput(props) ? createElement(SlugUrl, props) : createElement(Override, props)
|
|
53
55
|
}
|
|
54
|
-
|
|
56
|
+
// Traductions : pastille « À traduire » sur les champs modifiés dans la version principale.
|
|
57
|
+
return config.i18n ? withTranslationTodo(KitInput, config) : KitInput
|
|
55
58
|
}
|
|
56
59
|
|
|
57
60
|
export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
@@ -138,9 +141,13 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
138
141
|
prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
|
|
139
142
|
// Pages : « Retirer du site » (dépublication expliquée, liens listés) à la place
|
|
140
143
|
// du « Unpublish » natif, caché et bloqué sans explication par les références.
|
|
144
|
+
// Publier la version principale d'une page traduite : propagation proposée aux
|
|
145
|
+
// brouillons des autres langues (structure et valeurs ; textes « à traduire »).
|
|
141
146
|
actions: (prev, context) =>
|
|
142
147
|
config.pageTypeNames.includes(context.schemaType)
|
|
143
|
-
? prev.map((action) =>
|
|
148
|
+
? prev.map((action) =>
|
|
149
|
+
action.action === 'unpublish' ? RemoveFromSiteAction : action.action === 'publish' && config.i18n ? withPropagation(action, config) : action,
|
|
150
|
+
)
|
|
144
151
|
: prev,
|
|
145
152
|
},
|
|
146
153
|
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Propagation d'une modification de la version PRINCIPALE d'un document vers ses
|
|
3
|
+
* traductions (fusion à trois états : avant, après, traduction actuelle).
|
|
4
|
+
*
|
|
5
|
+
* Règles (aucun texte traduit n'est jamais écrasé) :
|
|
6
|
+
* - STRUCTURE : un élément de liste (section, bouton, carte…) ajouté dans la
|
|
7
|
+
* version principale est ajouté à la traduction (avec le texte d'origine, marqué
|
|
8
|
+
* « à traduire ») ; supprimé, il est retiré ; l'ordre suit la version principale.
|
|
9
|
+
* Un élément qui n'existe que dans la traduction est conservé à sa place.
|
|
10
|
+
* - VALEURS non textuelles (image, lien, référence, option de style, nombre, case,
|
|
11
|
+
* date…) : recopiées. Un lien vers une page reste juste : le site le rend vers la
|
|
12
|
+
* traduction de la page cible dans la langue affichée.
|
|
13
|
+
* - TEXTES (chaîne libre, texte, texte riche) modifiés : la traduction est gardée et
|
|
14
|
+
* le champ est marqué « à traduire ». Un texte jamais traduit (identique à
|
|
15
|
+
* l'ancienne version principale, ou vide) prend le nouveau texte, marqué aussi.
|
|
16
|
+
* - Jamais touchés : champs système (`_…`), langue, slug.
|
|
17
|
+
* Ce qui n'a pas changé dans la version principale n'est pas touché.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export type FieldKind = 'text' | 'value' | 'object' | 'list'
|
|
21
|
+
|
|
22
|
+
/** Type de schéma Sanity (forme minimale lue ici). */
|
|
23
|
+
export interface SchemaTypeLike {
|
|
24
|
+
name?: string
|
|
25
|
+
jsonType?: string
|
|
26
|
+
type?: SchemaTypeLike
|
|
27
|
+
fields?: {name: string; type: SchemaTypeLike}[]
|
|
28
|
+
of?: SchemaTypeLike[]
|
|
29
|
+
to?: unknown
|
|
30
|
+
options?: {list?: unknown[]}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PropagationResult {
|
|
34
|
+
document: Record<string, unknown>
|
|
35
|
+
/** Chemins (lisibles) des textes à traduire. */
|
|
36
|
+
toTranslate: string[]
|
|
37
|
+
/** Chemins des valeurs recopiées. */
|
|
38
|
+
copied: string[]
|
|
39
|
+
added: number
|
|
40
|
+
removed: number
|
|
41
|
+
moved: boolean
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const VALUE_TYPE_NAMES = new Set(['image', 'file', 'reference', 'crossDatasetReference', 'slug', 'geopoint', 'url', 'email', 'date', 'datetime', 'number', 'boolean'])
|
|
45
|
+
const SKIP_KEYS = new Set(['language', 'slug'])
|
|
46
|
+
|
|
47
|
+
const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
48
|
+
const same = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
|
|
49
|
+
const keyed = (v: unknown): v is Record<string, unknown>[] => Array.isArray(v) && v.length > 0 && v.every((i) => isObj(i) && typeof i._key === 'string')
|
|
50
|
+
|
|
51
|
+
function typeNames(t: SchemaTypeLike | undefined): string[] {
|
|
52
|
+
const out: string[] = []
|
|
53
|
+
for (let c = t; c; c = c.type) if (c.name) out.push(c.name)
|
|
54
|
+
return out
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Nature d'un champ d'après son schéma (et sa valeur, faute de schéma). */
|
|
58
|
+
export function kindOf(t: SchemaTypeLike | undefined, value: unknown): FieldKind {
|
|
59
|
+
if (t) {
|
|
60
|
+
const names = typeNames(t)
|
|
61
|
+
if (names.some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return 'value'
|
|
62
|
+
if (t.jsonType === 'array') {
|
|
63
|
+
const of = t.of ?? []
|
|
64
|
+
if (of.some((m) => typeNames(m).includes('block'))) return 'text'
|
|
65
|
+
if (of.some((m) => m.jsonType === 'object' || typeNames(m).includes('object'))) return 'list'
|
|
66
|
+
const prim = of[0]
|
|
67
|
+
return prim && prim.jsonType === 'string' && !prim.options?.list?.length ? 'text' : 'value'
|
|
68
|
+
}
|
|
69
|
+
if (t.jsonType === 'object') return 'object'
|
|
70
|
+
if (t.jsonType === 'string') return t.options?.list?.length ? 'value' : 'text'
|
|
71
|
+
return 'value'
|
|
72
|
+
}
|
|
73
|
+
if (keyed(value)) return 'list'
|
|
74
|
+
if (isObj(value)) return 'object'
|
|
75
|
+
return 'value'
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function fieldType(t: SchemaTypeLike | undefined, name: string): SchemaTypeLike | undefined {
|
|
79
|
+
for (let c = t; c; c = c.type) {
|
|
80
|
+
const f = c.fields?.find((x) => x.name === name)
|
|
81
|
+
if (f) return f.type
|
|
82
|
+
}
|
|
83
|
+
return undefined
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function itemType(t: SchemaTypeLike | undefined, item: Record<string, unknown>): SchemaTypeLike | undefined {
|
|
87
|
+
let of: SchemaTypeLike[] | undefined
|
|
88
|
+
for (let c = t; c && !of; c = c.type) of = c.of
|
|
89
|
+
if (!of?.length) return undefined
|
|
90
|
+
return of.find((m) => typeNames(m).includes(item._type as string)) ?? (of.length === 1 ? of[0] : undefined)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface Acc {
|
|
94
|
+
toTranslate: string[]
|
|
95
|
+
copied: string[]
|
|
96
|
+
added: number
|
|
97
|
+
removed: number
|
|
98
|
+
moved: boolean
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Tous les textes d'un élément ajouté : à traduire. */
|
|
102
|
+
function collectTexts(value: unknown, t: SchemaTypeLike | undefined, path: string, acc: Acc) {
|
|
103
|
+
const kind = kindOf(t, value)
|
|
104
|
+
if (kind === 'text') {
|
|
105
|
+
if (value !== undefined && value !== null && value !== '') acc.toTranslate.push(path)
|
|
106
|
+
} else if (kind === 'object' && isObj(value)) {
|
|
107
|
+
for (const [k, v] of Object.entries(value)) if (!k.startsWith('_')) collectTexts(v, fieldType(t, k), `${path}.${k}`, acc)
|
|
108
|
+
} else if (kind === 'list' && Array.isArray(value)) {
|
|
109
|
+
for (const item of value) if (isObj(item)) collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const ABSENT = Symbol('absent')
|
|
114
|
+
|
|
115
|
+
function merge(target: unknown, before: unknown, after: unknown, t: SchemaTypeLike | undefined, path: string, acc: Acc): unknown {
|
|
116
|
+
if (same(before, after)) return target === undefined ? ABSENT : target
|
|
117
|
+
const kind = kindOf(t, after ?? before)
|
|
118
|
+
|
|
119
|
+
if (kind === 'text') {
|
|
120
|
+
if (after === undefined || after === null || after === '') {
|
|
121
|
+
// Texte vidé dans la version principale : la traduction le garde (à revoir).
|
|
122
|
+
if (target !== undefined && target !== null && target !== '') acc.toTranslate.push(path)
|
|
123
|
+
return target === undefined ? ABSENT : target
|
|
124
|
+
}
|
|
125
|
+
acc.toTranslate.push(path)
|
|
126
|
+
// Jamais traduit (vide, ou encore le texte d'origine) : prend le nouveau texte.
|
|
127
|
+
const untranslated = target === undefined || target === null || target === '' || same(target, before)
|
|
128
|
+
return untranslated ? after : target
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (kind === 'value') {
|
|
132
|
+
acc.copied.push(path)
|
|
133
|
+
return after === undefined ? ABSENT : after
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (kind === 'object') {
|
|
137
|
+
if (!isObj(after)) {
|
|
138
|
+
acc.copied.push(path)
|
|
139
|
+
return after === undefined ? ABSENT : after
|
|
140
|
+
}
|
|
141
|
+
const base: Record<string, unknown> = isObj(target) ? {...target} : {_type: after._type}
|
|
142
|
+
const b = isObj(before) ? before : {}
|
|
143
|
+
for (const k of new Set([...Object.keys(b), ...Object.keys(after)])) {
|
|
144
|
+
if (k.startsWith('_') || SKIP_KEYS.has(k)) continue
|
|
145
|
+
const v = merge(base[k], b[k], after[k], fieldType(t, k), path ? `${path}.${k}` : k, acc)
|
|
146
|
+
if (v === ABSENT) delete base[k]
|
|
147
|
+
else base[k] = v
|
|
148
|
+
}
|
|
149
|
+
return base
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Liste d'éléments (sections, boutons, cartes…) : identifiés par _key.
|
|
153
|
+
const tgt = Array.isArray(target) ? (target as Record<string, unknown>[]).filter(isObj) : []
|
|
154
|
+
const bef = Array.isArray(before) ? (before as Record<string, unknown>[]).filter(isObj) : []
|
|
155
|
+
const aft = Array.isArray(after) ? (after as Record<string, unknown>[]).filter(isObj) : []
|
|
156
|
+
const byKey = (list: Record<string, unknown>[]) => new Map(list.map((i) => [i._key as string, i]))
|
|
157
|
+
const tMap = byKey(tgt)
|
|
158
|
+
const bMap = byKey(bef)
|
|
159
|
+
const aMap = byKey(aft)
|
|
160
|
+
|
|
161
|
+
const result: Record<string, unknown>[] = []
|
|
162
|
+
for (const item of aft) {
|
|
163
|
+
const key = item._key as string
|
|
164
|
+
const it = itemType(t, item)
|
|
165
|
+
if (tMap.has(key)) {
|
|
166
|
+
const merged = merge(tMap.get(key), bMap.get(key), item, it, `${path}[${key}]`, acc)
|
|
167
|
+
result.push(merged === ABSENT ? item : (merged as Record<string, unknown>))
|
|
168
|
+
} else {
|
|
169
|
+
// Ajouté (ou absent de la traduction) : l'élément d'origine, textes à traduire.
|
|
170
|
+
result.push(structuredClone(item))
|
|
171
|
+
acc.added++
|
|
172
|
+
collectTexts(item, it, `${path}[${key}]`, acc)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
for (const key of bMap.keys()) if (!aMap.has(key) && tMap.has(key)) acc.removed++
|
|
176
|
+
|
|
177
|
+
// Éléments propres à la traduction (ni avant ni après) : gardés à leur place.
|
|
178
|
+
tgt.forEach((item, index) => {
|
|
179
|
+
const key = item._key as string
|
|
180
|
+
if (bMap.has(key) || aMap.has(key)) return
|
|
181
|
+
const prev = tgt.slice(0, index).reverse().find((p) => result.some((r) => r._key === p._key))
|
|
182
|
+
const at = prev ? result.findIndex((r) => r._key === prev._key) + 1 : 0
|
|
183
|
+
result.splice(at, 0, item)
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
const common = (list: Record<string, unknown>[]) => list.map((i) => i._key).filter((k) => tMap.has(k as string) && aMap.has(k as string))
|
|
187
|
+
if (!same(common(tgt), common(aft))) acc.moved = true
|
|
188
|
+
return result
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Applique la modification `before` → `after` (version principale) à `target`
|
|
193
|
+
* (brouillon ou version publiée de la traduction). `documentType` : schéma du
|
|
194
|
+
* document, pour distinguer textes et valeurs.
|
|
195
|
+
*/
|
|
196
|
+
export function propagate(
|
|
197
|
+
target: Record<string, unknown> | null,
|
|
198
|
+
before: Record<string, unknown> | null,
|
|
199
|
+
after: Record<string, unknown>,
|
|
200
|
+
documentType?: SchemaTypeLike,
|
|
201
|
+
): PropagationResult {
|
|
202
|
+
const acc: Acc = {toTranslate: [], copied: [], added: 0, removed: 0, moved: false}
|
|
203
|
+
const merged = merge(target ?? {}, before ?? {}, after, documentType, '', acc)
|
|
204
|
+
const document = {...(target ?? {}), ...(isObj(merged) ? merged : {})}
|
|
205
|
+
return {document, ...acc}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** La propagation changerait-elle quelque chose ? */
|
|
209
|
+
export function hasChanges(r: PropagationResult): boolean {
|
|
210
|
+
return r.toTranslate.length > 0 || r.copied.length > 0 || r.added > 0 || r.removed > 0 || r.moved
|
|
211
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {defineField, defineType} from 'sanity'
|
|
2
|
+
import {TRANSLATION_TODO_TYPE, translationTodoType} from './translationTodo'
|
|
2
3
|
|
|
3
4
|
/** Type et identifiant du singleton portant la disposition du board. */
|
|
4
5
|
export const BOARD_LAYOUT_TYPE = 'ncfBoardLayout'
|
|
@@ -11,7 +12,7 @@ export const COLUMN_OPTION_TYPE = 'ncfColumnOption'
|
|
|
11
12
|
export const ANNOTATION_TYPE = 'ncfAnnotation'
|
|
12
13
|
|
|
13
14
|
/** Types déclarés par le kit : à masquer de la structure du Studio hôte. */
|
|
14
|
-
export const NCF_HIDDEN_TYPES = [BOARD_LAYOUT_TYPE] as const
|
|
15
|
+
export const NCF_HIDDEN_TYPES = [BOARD_LAYOUT_TYPE, TRANSLATION_TODO_TYPE] as const
|
|
15
16
|
|
|
16
17
|
const boardNodeType = defineType({
|
|
17
18
|
name: BOARD_NODE_TYPE,
|
|
@@ -177,6 +178,7 @@ const boardLayoutType = defineType({
|
|
|
177
178
|
|
|
178
179
|
export const kitSchemaTypes = [
|
|
179
180
|
boardLayoutType,
|
|
181
|
+
translationTodoType,
|
|
180
182
|
boardNodeType,
|
|
181
183
|
sectionNodeType,
|
|
182
184
|
nodeFieldType,
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import {defineField, defineType} from 'sanity'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Champs « à traduire » d'une traduction, écrits par la propagation (publication de
|
|
5
|
+
* la version principale). Un document par traduction : `ncfTodo.<id de la traduction>`
|
|
6
|
+
* (point = jamais servi par l'API publique). Jamais créé ni édité à la main : la
|
|
7
|
+
* pastille du formulaire le lit et « Marquer comme traduit » retire le champ.
|
|
8
|
+
*/
|
|
9
|
+
export const TRANSLATION_TODO_TYPE = 'ncfTranslationTodo'
|
|
10
|
+
export const translationTodoId = (documentId: string) => `ncfTodo.${documentId.replace(/^drafts\./, '')}`
|
|
11
|
+
|
|
12
|
+
export const translationTodoType = defineType({
|
|
13
|
+
name: TRANSLATION_TODO_TYPE,
|
|
14
|
+
title: 'À traduire (NCF)',
|
|
15
|
+
type: 'document',
|
|
16
|
+
fields: [
|
|
17
|
+
defineField({name: 'documentId', title: 'Traduction', type: 'string', readOnly: true}),
|
|
18
|
+
defineField({name: 'sourceId', title: 'Version principale', type: 'string', readOnly: true}),
|
|
19
|
+
defineField({name: 'sourceLanguage', title: 'Langue principale', type: 'string', readOnly: true}),
|
|
20
|
+
defineField({name: 'paths', title: 'Champs à traduire', type: 'array', of: [{type: 'string'}], readOnly: true}),
|
|
21
|
+
],
|
|
22
|
+
preview: {select: {title: 'documentId'}, prepare: ({title}) => ({title: `À traduire : ${title}`})},
|
|
23
|
+
})
|
package/src/version.ts
CHANGED