@nocode-factory/sanity-kit 2.18.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.18.0",
3
+ "version": "2.20.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,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,110 @@
1
+ import {useEffect, useState} from 'react'
2
+ import {Stack, Text} from '@sanity/ui'
3
+ import {EyeClosedIcon} from '@sanity/icons/EyeClosed'
4
+ import type {DocumentActionComponent, DocumentActionProps} from 'sanity'
5
+ import {useKitClient} from '../hooks/useKitClient'
6
+
7
+ type Referrer = {_id: string; _type: string; title?: string}
8
+
9
+ /**
10
+ * « Retirer du site » : dépublication native de Sanity, rendue visible et expliquée.
11
+ * La version EN LIGNE est supprimée, tout le contenu reste dans le BROUILLON (rien
12
+ * n'est perdu) : la page disparaît du site (404 en production et en préproduction
13
+ * « En ligne », purge par le webhook), l'onglet Pages l'affiche « Non publiée », et
14
+ * on la remet en ligne en publiant le brouillon.
15
+ *
16
+ * Avant de confirmer, la liste des documents publiés qui pointent vers la page :
17
+ * leurs liens vers elle disparaîtront du site. Une référence FORTE (non `weak`)
18
+ * empêche Sanity de dépublier : le message l'explique au lieu d'une erreur brute.
19
+ */
20
+ export const RemoveFromSiteAction: DocumentActionComponent = (props: DocumentActionProps) => {
21
+ const client = useKitClient()
22
+ const [open, setOpen] = useState(false)
23
+ const [referrers, setReferrers] = useState<Referrer[] | null>(null)
24
+ const [busy, setBusy] = useState(false)
25
+ const [error, setError] = useState<string | null>(null)
26
+
27
+ useEffect(() => {
28
+ if (!open) return
29
+ setReferrers(null)
30
+ client
31
+ .fetch<Referrer[]>(
32
+ `*[references($id) && !(_id in path("drafts.**")) && _type != "translation.metadata"]{_id, _type, "title": coalesce(title, name, _id)}`,
33
+ {id: props.id},
34
+ )
35
+ .then(setReferrers)
36
+ .catch(() => setReferrers([]))
37
+ }, [open, client, props.id])
38
+
39
+ if (!props.published) return null
40
+
41
+ const confirm = async () => {
42
+ setBusy(true)
43
+ setError(null)
44
+ try {
45
+ const {_rev, _updatedAt, ...published} = props.published as Record<string, unknown>
46
+ 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)
50
+ await tx.commit()
51
+ setOpen(false)
52
+ props.onComplete()
53
+ } catch (cause) {
54
+ const message = cause instanceof Error ? cause.message : String(cause)
55
+ setError(
56
+ /referenc/i.test(message)
57
+ ? "Sanity refuse : un document publié pointe vers cette page par une référence forte. Retirez ou modifiez ce lien, puis recommencez."
58
+ : `Le retrait a échoué, rien n'a changé. (${message.slice(0, 140)})`,
59
+ )
60
+ } finally {
61
+ setBusy(false)
62
+ }
63
+ }
64
+
65
+ return {
66
+ label: 'Retirer du site',
67
+ title: 'Dépublier : la page quitte le site, son contenu reste en brouillon',
68
+ icon: EyeClosedIcon,
69
+ tone: 'critical',
70
+ disabled: busy,
71
+ onHandle: () => setOpen(true),
72
+ dialog: open && {
73
+ type: 'confirm',
74
+ tone: 'critical',
75
+ onCancel: () => {
76
+ setOpen(false)
77
+ props.onComplete()
78
+ },
79
+ onConfirm: () => void confirm(),
80
+ message: (
81
+ <Stack gap={3}>
82
+ <Text size={1}>
83
+ La page quitte le site (production et préproduction « En ligne »). Tout son contenu reste dans le
84
+ brouillon : pour la remettre en ligne, publiez-le.
85
+ </Text>
86
+ {referrers === null ? (
87
+ <Text size={1} muted>
88
+ Recherche des liens vers cette page…
89
+ </Text>
90
+ ) : referrers.length > 0 ? (
91
+ <Text size={1}>
92
+ Ces documents publiés pointent vers elle ; leurs liens vers cette page disparaîtront du site :{' '}
93
+ {referrers.map((r) => r.title || r._id).join(', ')}.
94
+ </Text>
95
+ ) : (
96
+ <Text size={1} muted>
97
+ Aucun document publié ne pointe vers cette page.
98
+ </Text>
99
+ )}
100
+ {error && (
101
+ <Text size={1} weight="semibold">
102
+ {error}
103
+ </Text>
104
+ )}
105
+ </Stack>
106
+ ),
107
+ },
108
+ }
109
+ }
110
+ RemoveFromSiteAction.action = 'unpublish'
@@ -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
@@ -41,7 +41,10 @@ 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
45
  import {createSlugUrlInput, isSlugInput} from './form/SlugUrlInput'
46
+ import {withTranslationTodo} from './form/TranslationTodoInput'
47
+ import {withPropagation} from './actions/PropagatePublish'
45
48
 
46
49
  /** Champs du formulaire : adresse sous le Slug d'une page, pastille sur les sections. */
47
50
  function createKitInput(config: Parameters<typeof createOverrideInput>[0]): ComponentType<InputProps> {
@@ -50,7 +53,8 @@ function createKitInput(config: Parameters<typeof createOverrideInput>[0]): Comp
50
53
  function KitInput(props: InputProps) {
51
54
  return isSlugInput(props) ? createElement(SlugUrl, props) : createElement(Override, props)
52
55
  }
53
- return KitInput
56
+ // Traductions : pastille « À traduire » sur les champs modifiés dans la version principale.
57
+ return config.i18n ? withTranslationTodo(KitInput, config) : KitInput
54
58
  }
55
59
 
56
60
  export const ncfKit = definePlugin<NcfKitConfig>((options) => {
@@ -135,6 +139,16 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
135
139
  document: {
136
140
  newDocumentOptions: (prev) =>
137
141
  prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
142
+ // Pages : « Retirer du site » (dépublication expliquée, liens listés) à la place
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 »).
146
+ actions: (prev, context) =>
147
+ config.pageTypeNames.includes(context.schemaType)
148
+ ? prev.map((action) =>
149
+ action.action === 'unpublish' ? RemoveFromSiteAction : action.action === 'publish' && config.i18n ? withPropagation(action, config) : action,
150
+ )
151
+ : prev,
138
152
  },
139
153
 
140
154
  // Le lanceur d'aperçu s'ajoute à droite des outils, dans la barre du haut