@nocode-factory/sanity-kit 2.34.0 → 2.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +299 -20
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/DeleteTranslations.tsx +187 -0
- package/src/actions/PropagatePublish.tsx +4 -1
- package/src/actions/RemoveFromSite.tsx +79 -16
- package/src/index.ts +28 -4
- package/src/lib/localizeReferences.ts +48 -0
- package/src/lib/translateDocument.ts +3 -0
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -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
|
+
}
|
|
@@ -10,6 +10,7 @@ import {collectTexts, setAtKey, valueAtKey} from '../lib/aiTexts'
|
|
|
10
10
|
import {translateValues} from '../lib/aiTranslate'
|
|
11
11
|
import {createTranslatedVersion, translationsOf} from '../lib/translateDocument'
|
|
12
12
|
import {isReplaceable, readTrace, recordTrace} from '../lib/translationTrace'
|
|
13
|
+
import {localizeReferences} from '../lib/localizeReferences'
|
|
13
14
|
|
|
14
15
|
type Doc = Record<string, unknown>
|
|
15
16
|
type Client = ReturnType<typeof useKitClient>
|
|
@@ -184,7 +185,9 @@ function PropagateDialog(props: {
|
|
|
184
185
|
;(created.published ? published : drafted).push(t.language.toUpperCase())
|
|
185
186
|
continue
|
|
186
187
|
}
|
|
187
|
-
const {_id, _rev, _createdAt, _updatedAt, ...
|
|
188
|
+
const {_id, _rev, _createdAt, _updatedAt, ...raw} = structuredClone(t.result.document) as Doc
|
|
189
|
+
// Références vers la version de la même langue (type, catégorie, pages liées).
|
|
190
|
+
const doc = await localizeReferences(client, raw, t.language)
|
|
188
191
|
const targetId = t.id as string
|
|
189
192
|
// Textes modifiés à la main dans cette langue : gardés (et marqués « To
|
|
190
193
|
// translate », texte source affiché), sauf case « Overwrite » cochée.
|
|
@@ -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 = (
|
|
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($
|
|
33
|
-
{
|
|
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
|
-
|
|
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
|
-
//
|
|
48
|
-
|
|
49
|
-
|
|
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
|
-
|
|
84
|
-
|
|
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
|
|
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
|
|
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
|
|
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,18 +146,35 @@ 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))
|
|
159
|
-
:
|
|
161
|
+
? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action.action === 'delete' ? withTranslationDelete(action, config, config.i18n?.defaultsSourceLocale) : action))
|
|
162
|
+
: // Tout autre type traduit document par document (collections, réglages
|
|
163
|
+
// par langue) : même proposition que les pages à la publication de la
|
|
164
|
+
// version principale (mettre à jour ou créer les autres langues).
|
|
165
|
+
// Détecté par le champ de langue du schéma : une nouvelle collection
|
|
166
|
+
// traduite en profite sans réglage.
|
|
167
|
+
config.i18n && !isKitType(context.schemaType) && hasLanguageField(context.schema.get(context.schemaType), config.i18n.field)
|
|
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
|
+
)
|
|
177
|
+
: prev,
|
|
160
178
|
},
|
|
161
179
|
|
|
162
180
|
// Le lanceur d'aperçu s'ajoute à droite des outils, dans la barre du haut
|
|
@@ -258,6 +276,12 @@ export {
|
|
|
258
276
|
} from './lib/studioLinks'
|
|
259
277
|
export type {PreviewPerspective, PresentationOptions} from './lib/studioLinks'
|
|
260
278
|
export {usePreviewTarget} from './context/PreviewTargetContext'
|
|
279
|
+
/** Le type de document porte-t-il le champ de langue (traduit document par document) ? */
|
|
280
|
+
function hasLanguageField(schemaType: unknown, field: string): boolean {
|
|
281
|
+
const fields = (schemaType as {fields?: {name?: string}[]} | undefined)?.fields
|
|
282
|
+
return Array.isArray(fields) && fields.some((f) => f?.name === field)
|
|
283
|
+
}
|
|
284
|
+
|
|
261
285
|
export {NcfPreviewHeader, ncfPreviewComponents} from './tools/presentation/PreviewHeader'
|
|
262
286
|
export {ncfPresentationComponents} from './tools/presentation/PagesNavigator'
|
|
263
287
|
export {NcfPreviewLauncher, createPreviewLauncher} from './tools/navbar/PreviewLauncher'
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type {SanityClient} from 'sanity'
|
|
2
|
+
|
|
3
|
+
type Doc = Record<string, unknown>
|
|
4
|
+
|
|
5
|
+
/** Références de contenu d'une valeur (hors fichiers et images : leurs assets n'ont pas de langue). */
|
|
6
|
+
export function contentRefs(value: unknown, out = new Set<string>()): Set<string> {
|
|
7
|
+
if (Array.isArray(value)) for (const item of value) contentRefs(item, out)
|
|
8
|
+
else if (value && typeof value === 'object') {
|
|
9
|
+
const ref = (value as {_ref?: unknown})._ref
|
|
10
|
+
if (typeof ref === 'string' && !/^(image|file)-/.test(ref)) out.add(ref.replace(/^drafts\./, ''))
|
|
11
|
+
for (const [k, v] of Object.entries(value)) if (k !== '_ref') contentRefs(v, out)
|
|
12
|
+
}
|
|
13
|
+
return out
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Remplace chaque référence par celle de `map` (sans toucher au reste). Rend une copie. */
|
|
17
|
+
export function replaceRefs<T>(value: T, map: Map<string, string>): T {
|
|
18
|
+
if (Array.isArray(value)) return value.map((item) => replaceRefs(item, map)) as T
|
|
19
|
+
if (value && typeof value === 'object') {
|
|
20
|
+
const out: Doc = {}
|
|
21
|
+
for (const [k, v] of Object.entries(value as Doc)) {
|
|
22
|
+
if (k === '_ref' && typeof v === 'string' && map.has(v.replace(/^drafts\./, ''))) out[k] = map.get(v.replace(/^drafts\./, ''))
|
|
23
|
+
else out[k] = replaceRefs(v, map)
|
|
24
|
+
}
|
|
25
|
+
return out as T
|
|
26
|
+
}
|
|
27
|
+
return value
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Version d'une autre langue : chaque référence vers un document traduit pointe la
|
|
32
|
+
* traduction de CETTE langue (type de publication, catégorie, pages liées...). Une
|
|
33
|
+
* référence sans traduction dans la langue reste telle quelle (document commun à
|
|
34
|
+
* toutes les langues, ou traduction pas encore créée).
|
|
35
|
+
*/
|
|
36
|
+
export async function localizeReferences<T>(client: SanityClient, value: T, language: string): Promise<T> {
|
|
37
|
+
const refs = [...contentRefs(value)]
|
|
38
|
+
if (!refs.length) return value
|
|
39
|
+
const rows = await client.fetch<{from: string; to: string | null}[]>(
|
|
40
|
+
`*[_type == "translation.metadata" && count(translations[value._ref in $refs]) > 0]{
|
|
41
|
+
"pairs": translations[value._ref in $refs]{"from": value._ref, "to": ^.translations[_key == $language || language == $language][0].value._ref}
|
|
42
|
+
}.pairs[]`,
|
|
43
|
+
{refs, language},
|
|
44
|
+
)
|
|
45
|
+
const map = new Map<string, string>()
|
|
46
|
+
for (const row of rows ?? []) if (row?.from && row.to && row.to !== row.from) map.set(row.from, row.to)
|
|
47
|
+
return map.size ? replaceRefs(value, map) : value
|
|
48
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {localizeReferences} from './localizeReferences'
|
|
1
2
|
import type {SanityClient} from 'sanity'
|
|
2
3
|
import type {ResolvedKitConfig} from '../config/types'
|
|
3
4
|
import {TRANSLATION_TODO_TYPE, translationTodoId} from '../schema/translationTodo'
|
|
@@ -117,6 +118,8 @@ export async function createTranslatedVersion(opts: {
|
|
|
117
118
|
}
|
|
118
119
|
}
|
|
119
120
|
doc[field] = language
|
|
121
|
+
// Références vers la version de la même langue (type, catégorie, pages liées).
|
|
122
|
+
Object.assign(doc, await localizeReferences(client, doc, language))
|
|
120
123
|
// Slug : traduit depuis le titre, unique dans la langue (-2, -3...).
|
|
121
124
|
const pageType = config.pageTypes.find((t) => t.type === type)
|
|
122
125
|
const slugField = pageType?.slugField ?? ((source.slug as {current?: string} | undefined)?.current ? 'slug' : null)
|
package/src/version.ts
CHANGED