@nocode-factory/sanity-kit 2.20.0 → 2.21.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.20.0",
3
+ "version": "2.21.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -1,5 +1,6 @@
1
- import {useEffect, useState} from 'react'
2
- import {Box, Button, Card, Checkbox, Flex, Spinner, Stack, Text} from '@sanity/ui'
1
+ import {useState} from 'react'
2
+ import {Box, Button, Card, Checkbox, Flex, Stack, Text} from '@sanity/ui'
3
+ import {useToast} from '@sanity/ui/toast'
3
4
  import {useSchema, type DocumentActionComponent, type DocumentActionProps} from 'sanity'
4
5
  import type {ResolvedKitConfig} from '../config/types'
5
6
  import {useKitClient} from '../hooks/useKitClient'
@@ -26,7 +27,9 @@ export function withPropagation(Publish: DocumentActionComponent, config: Resolv
26
27
  const i18n = config.i18n
27
28
  const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
28
29
  const base = Publish(props)
29
- const [run, setRun] = useState<{before: Doc; after: Doc} | null>(null)
30
+ const client = useKitClient()
31
+ const schema = useSchema()
32
+ const [run, setRun] = useState<{before: Doc; after: Doc; targets: Target[]} | null>(null)
30
33
  const current = (props.draft ?? props.published) as Doc | null
31
34
  if (!base || !i18n || current?.[i18n.field] !== i18n.defaultLocale) return base
32
35
  return {
@@ -35,8 +38,15 @@ export function withPropagation(Publish: DocumentActionComponent, config: Resolv
35
38
  const before = props.published as Doc | null
36
39
  const after = props.draft as Doc | null
37
40
  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})
41
+ // Une page déjà publiée qu'on modifie : la fenêtre ne s'ouvre que s'il y a
42
+ // vraiment quelque chose à propager (sinon, aucun clic de plus).
43
+ if (!before || !after) return
44
+ const documentType = schema.get(props.type) as unknown as SchemaTypeLike | undefined
45
+ void findTargets(client, props.id, String(after[i18n.field] ?? ''), before, after, documentType)
46
+ .then((targets) => {
47
+ if (targets.some((t) => hasChanges(t.result))) setRun({before, after, targets})
48
+ })
49
+ .catch(() => {})
40
50
  },
41
51
  dialog: run
42
52
  ? {
@@ -54,6 +64,7 @@ export function withPropagation(Publish: DocumentActionComponent, config: Resolv
54
64
  type={props.type}
55
65
  before={run.before}
56
66
  after={run.after}
67
+ targets={run.targets}
57
68
  onDone={() => {
58
69
  setRun(null)
59
70
  props.onComplete()
@@ -68,43 +79,53 @@ export function withPropagation(Publish: DocumentActionComponent, config: Resolv
68
79
  return Wrapped
69
80
  }
70
81
 
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
82
+ async function findTargets(
83
+ client: ReturnType<typeof useKitClient>,
84
+ id: string,
85
+ source: string,
86
+ before: Doc,
87
+ after: Doc,
88
+ documentType: SchemaTypeLike | undefined,
89
+ ): Promise<Target[]> {
90
+ const translations = await client.fetch<{language: string; id: string}[]>(
91
+ `*[_type == "translation.metadata" && references($id)][0].translations[]{language, "id": value._ref}`,
92
+ {id},
93
+ )
94
+ const list: Target[] = []
95
+ for (const t of translations ?? []) {
96
+ if (!t?.id || t.id === id || t.language === source) continue
97
+ const target = (await client.getDocument<Doc>(`drafts.${t.id}`)) ?? (await client.getDocument<Doc>(t.id)) ?? null
98
+ if (!target) continue
99
+ const result = propagate(target, before, after, documentType)
100
+ list.push({language: t.language, id: t.id, result, selected: hasChanges(result)})
101
+ }
102
+ return list
103
+ }
104
+
105
+ function PropagateDialog(props: {
106
+ config: ResolvedKitConfig
107
+ id: string
108
+ type: string
109
+ before: Doc
110
+ after: Doc
111
+ targets: Target[]
112
+ onDone: () => void
113
+ }) {
114
+ const {config, id, type, after, onDone} = props
73
115
  const client = useKitClient()
74
- const schema = useSchema()
75
116
  const field = config.i18n?.field ?? 'language'
76
117
  const source = String(after[field] ?? '')
77
- const [targets, setTargets] = useState<Target[] | null>(null)
118
+ const [targets, setTargets] = useState<Target[]>(props.targets)
78
119
  const [busy, setBusy] = useState(false)
79
- const [done, setDone] = useState<string[] | null>(null)
120
+ const toast = useToast()
80
121
  const [error, setError] = useState<string | null>(null)
81
122
 
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
123
  const apply = async () => {
103
124
  setBusy(true)
104
125
  setError(null)
105
126
  try {
106
127
  const applied: string[] = []
107
- for (const t of targets ?? []) {
128
+ for (const t of targets) {
108
129
  if (!t.selected) continue
109
130
  const {_rev, _createdAt, _updatedAt, ...doc} = t.result.document
110
131
  await client.createOrReplace({...doc, _id: `drafts.${t.id}`, _type: type} as {_id: string; _type: string})
@@ -122,7 +143,14 @@ function PropagateDialog(props: {config: ResolvedKitConfig; id: string; type: st
122
143
  }
123
144
  applied.push(t.language.toUpperCase())
124
145
  }
125
- setDone(applied)
146
+ // Fini : la fenêtre se ferme seule, le résultat s'affiche en notification.
147
+ toast.push({
148
+ status: 'success',
149
+ title: `Brouillons mis à jour : ${applied.join(', ')}`,
150
+ description: 'Traduisez les champs marqués « À traduire », puis publiez chaque langue.',
151
+ duration: 8000,
152
+ })
153
+ onDone()
126
154
  } catch (cause) {
127
155
  setError(`La propagation a échoué, rien n'a été publié. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 140)})`)
128
156
  } finally {
@@ -130,40 +158,6 @@ function PropagateDialog(props: {config: ResolvedKitConfig; id: string; type: st
130
158
  }
131
159
  }
132
160
 
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
161
  return (
168
162
  <Stack gap={4} padding={4}>
169
163
  <Text size={1}>
@@ -1,7 +1,7 @@
1
1
  import {useState, type ComponentType} from 'react'
2
2
  import {set, unset, useFormValue, useSchema, type InputProps} from 'sanity'
3
3
  import {useRouter} from 'sanity/router'
4
- import {Box, Flex, Stack, Text} from '@sanity/ui'
4
+ import {Box, Flex, Text} from '@sanity/ui'
5
5
  import {Tooltip} from '@sanity/ui/tooltip'
6
6
  import type {ResolvedKitConfig} from '../config/types'
7
7
  import {blockName, componentIntentParams} from '../lib/blocks'
@@ -62,36 +62,28 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
62
62
 
63
63
  const router = useRouter()
64
64
 
65
+ // UNE SEULE structure quel que soit l'état du champ (hérite, override, égal au
66
+ // défaut) : si l'enveloppe changeait à la première frappe (champ vide qui
67
+ // devient override), React recréerait le champ et le curseur sortirait.
65
68
  // Champ vide qui hérite : il affiche la valeur par défaut du composant
66
69
  // (grisée dans un champ texte, mentionnée sous les autres champs).
67
- if (isEmptyValue(inputProps.value) && !isEmptyValue(inherited)) {
68
- // Texte grisé seulement dans une zone de saisie libre (texte, nombre) ; un
69
- // choix (style, taille, variante, texture...) affiche la mention.
70
- const st = inputProps.schemaType as {jsonType?: string; options?: {list?: unknown[]}}
71
- const freeText = (st.jsonType === 'string' || st.jsonType === 'number') && !st.options?.list?.length
72
- const placeholder = freeText ? inheritedPlaceholder(inherited) : null
73
- const withPlaceholder =
74
- placeholder !== null
75
- ? ({...inputProps, elementProps: {...(inputProps.elementProps as object), placeholder}} as InputProps)
76
- : inputProps
77
- return (
78
- <Stack gap={2}>
79
- {inputProps.renderDefault(withPlaceholder)}
80
- {placeholder === null && (
81
- <Text size={0} muted>
82
- Valeur par défaut du composant : {describeValue(inherited)}
83
- </Text>
84
- )}
85
- </Stack>
86
- )
87
- }
70
+ const inherits = isEmptyValue(inputProps.value) && !isEmptyValue(inherited)
71
+ // Texte grisé seulement dans une zone de saisie libre (texte, nombre) ; un
72
+ // choix (style, taille, variante, texture...) affiche la mention.
73
+ const st = inputProps.schemaType as {jsonType?: string; options?: {list?: unknown[]}}
74
+ const freeText = (st.jsonType === 'string' || st.jsonType === 'number') && !st.options?.list?.length
75
+ const placeholder = inherits && freeText ? inheritedPlaceholder(inherited) : null
76
+ const shown =
77
+ placeholder !== null
78
+ ? ({...inputProps, elementProps: {...(inputProps.elementProps as object), placeholder}} as InputProps)
79
+ : inputProps
88
80
 
89
- if (!isOverride(inputProps.value, inherited, field, parent)) return inputProps.renderDefault(inputProps)
90
81
  // « Réinitialiser » remet le champ en HÉRITAGE (vidé en base) : il suit la
91
82
  // valeur par défaut, aujourd'hui comme après ses changements. Sans valeur par
92
83
  // défaut : ouvre le réglage du composant (un champ vidé n'afficherait rien).
93
84
  // Élément de liste : la liste remplie remplace celle du défaut en entier, la
94
85
  // valeur par défaut y est donc recopiée.
86
+ const override = !inherits && isOverride(inputProps.value, inherited, field, parent)
95
87
  const action = resetAction(inherited)
96
88
  const onClick =
97
89
  action.kind === 'noDefault'
@@ -106,9 +98,16 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
106
98
  return (
107
99
  <Flex align="flex-start" gap={2}>
108
100
  <Box flex={1} style={{minWidth: 0}}>
109
- {inputProps.renderDefault(inputProps)}
101
+ {inputProps.renderDefault(shown)}
102
+ {inherits && placeholder === null && (
103
+ <Box marginTop={2}>
104
+ <Text size={0} muted>
105
+ Valeur par défaut du composant : {describeValue(inherited)}
106
+ </Text>
107
+ </Box>
108
+ )}
110
109
  </Box>
111
- <OverrideDot hasDefault={action.kind !== 'noDefault'} full={describeValue(inherited)} short={shortValue(inherited)} onClick={onClick} />
110
+ {override && <OverrideDot hasDefault={action.kind !== 'noDefault'} full={describeValue(inherited)} short={shortValue(inherited)} onClick={onClick} />}
112
111
  </Flex>
113
112
  )
114
113
  }
@@ -21,18 +21,19 @@ export function createSlugUrlInput(config: ResolvedKitConfig): ComponentType<Inp
21
21
  const path = pageType ? toPath({slug, path: pageType.path, pathPrefix: pageType.pathPrefix, locale}, config.i18n) : null
22
22
  const url = toUrl(config.previewUrl, path)
23
23
 
24
- if (!url) return props.renderDefault(props)
25
-
26
24
  const copy = () => {
25
+ if (!url) return
27
26
  void navigator.clipboard.writeText(url).then(() => {
28
27
  setCopied(true)
29
28
  window.setTimeout(() => setCopied(false), 1500)
30
29
  })
31
30
  }
32
31
 
32
+ // Même structure avec ou sans adresse : le champ n'est jamais recréé pendant la frappe.
33
33
  return (
34
34
  <Stack gap={2}>
35
35
  {props.renderDefault(props)}
36
+ {url && (
36
37
  <Card tone="primary" padding={2} radius={2} border>
37
38
  <Flex align="center" gap={2}>
38
39
  <Text size={1} muted style={{flex: 1, minWidth: 0, wordBreak: 'break-all'}}>
@@ -42,6 +43,7 @@ export function createSlugUrlInput(config: ResolvedKitConfig): ComponentType<Inp
42
43
  <Button as="a" href={url} target="_blank" rel="noopener noreferrer" mode="ghost" fontSize={1} padding={2} text="Ouvrir" />
43
44
  </Flex>
44
45
  </Card>
46
+ )}
45
47
  </Stack>
46
48
  )
47
49
  }
@@ -17,8 +17,9 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
17
17
  const [busy, setBusy] = useState(false)
18
18
  const key = fieldPathKey(props.path)
19
19
  const inner = createElement(Inner, props)
20
- if (!todo?.paths?.includes(key)) return inner
20
+ const show = Boolean(todo?.paths?.includes(key))
21
21
  const done = () => {
22
+ if (!todo) return
22
23
  setBusy(true)
23
24
  void client
24
25
  .patch(todo._id)
@@ -26,17 +27,20 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
26
27
  .commit()
27
28
  .finally(() => setBusy(false))
28
29
  }
30
+ // Même structure que la mention soit là ou non : le champ n'est jamais recréé.
29
31
  return (
30
32
  <Stack gap={2}>
31
33
  {inner}
34
+ {show && (
32
35
  <Card tone="caution" padding={2} radius={2} border>
33
36
  <Flex align="center" gap={2}>
34
37
  <Text size={1} style={{flex: 1}}>
35
- À traduire : modifié dans la version {(todo.sourceLanguage ?? '').toUpperCase()}.
38
+ À traduire : modifié dans la version {(todo?.sourceLanguage ?? '').toUpperCase()}.
36
39
  </Text>
37
40
  <Button mode="ghost" fontSize={1} padding={2} text="Marquer comme traduit" disabled={busy} onClick={done} />
38
41
  </Flex>
39
42
  </Card>
43
+ )}
40
44
  </Stack>
41
45
  )
42
46
  }
@@ -0,0 +1,20 @@
1
+ import {useMemo} from 'react'
2
+ import {useKitConfig} from '../context/KitContext'
3
+ import {TRANSLATION_TODO_TYPE} from '../schema/translationTodo'
4
+ import {useQueryData} from './useQueryData'
5
+
6
+ const QUERY = `*[_type == $type && count(paths) > 0]{documentId, "count": count(paths)}`
7
+
8
+ /**
9
+ * Nombre de champs « À traduire » par page (id publié), tenu à jour en direct.
10
+ * Vide sur un site monolingue.
11
+ */
12
+ export function useTranslationTodos(): ReadonlyMap<string, number> {
13
+ const config = useKitConfig()
14
+ const params = useMemo(() => ({type: TRANSLATION_TODO_TYPE}), [])
15
+ const {data} = useQueryData<{documentId: string; count: number}[]>(QUERY, params, {
16
+ listenTypes: [TRANSLATION_TODO_TYPE],
17
+ enabled: Boolean(config.i18n),
18
+ })
19
+ return useMemo(() => new Map((data ?? []).map((t) => [t.documentId, t.count])), [data])
20
+ }
@@ -52,6 +52,8 @@ export interface PagesTableProps {
52
52
  /** Colonnes masquées par l'utilisateur. */
53
53
  hidden: ReadonlySet<string>
54
54
  onTag: (documentId: string, tag: string | null) => void
55
+ /** Champs « À traduire » par page (sites multilingues). */
56
+ todos?: ReadonlyMap<string, number>
55
57
  }
56
58
 
57
59
  /**
@@ -95,6 +97,7 @@ export function PagesTable(props: PagesTableProps) {
95
97
  onOpen,
96
98
  hidden,
97
99
  onTag,
100
+ todos,
98
101
  } = props
99
102
 
100
103
  // Tout est déplié au départ : on ne cache pas des pages à quelqu'un qui
@@ -315,8 +318,17 @@ export function PagesTable(props: PagesTableProps) {
315
318
  )}
316
319
 
317
320
  {!hidden.has('status') && (
318
- <Flex align="center" gap={2} style={CELL}>
321
+ <Flex align="center" gap={2} wrap="wrap" style={CELL}>
319
322
  <StatusBadge status={entryRow.status} />
323
+ {Boolean(todos?.get(entryRow.id)) && (
324
+ <Badge
325
+ tone="caution"
326
+ fontSize={0}
327
+ title="Champs modifiés dans la version principale, pas encore traduits (marqués « À traduire » dans le formulaire)"
328
+ >
329
+ À traduire · {todos?.get(entryRow.id)}
330
+ </Badge>
331
+ )}
320
332
  {/* L'indexation ne se signale que lorsqu'elle bloque :
321
333
  une page indexable est le cas normal. */}
322
334
  {entryRow.noindex && (
@@ -9,6 +9,7 @@ import {useDocumentColumns} from '../../hooks/useDocumentColumns'
9
9
  import {usePreviewTarget} from '../../context/PreviewTargetContext'
10
10
  import {PreviewTarget} from './PreviewTarget'
11
11
  import {SharePreview} from './SharePreview'
12
+ import {useTranslationTodos} from '../../hooks/useTranslationTodos'
12
13
  import {filterRows, localesInRows, sortRows, type PageRow, type SortDirection, type SortKey} from '../../lib/pages'
13
14
  import {groupPageRows, type GroupBy} from '../../lib/grouping'
14
15
  import {resolveColorBy, type ColorBy} from '../../lib/colors'
@@ -37,6 +38,9 @@ export function PagesTool() {
37
38
  const [search, setSearch] = useState('')
38
39
  // Langue affichée : '' = toutes.
39
40
  const [locale, setLocale] = useState('')
41
+ // Pages avec des champs « À traduire » (propagation depuis la version principale).
42
+ const todos = useTranslationTodos()
43
+ const [onlyTodo, setOnlyTodo] = useState(false)
40
44
  const [groupBy, setGroupBy] = useState<GroupBy>('none')
41
45
  const [rawColorBy, setColorBy] = useState<ColorBy>('tag')
42
46
  // L'ordre du Studio par défaut : aucune colonne n'est marquée triée tant
@@ -75,10 +79,13 @@ export function PagesTool() {
75
79
 
76
80
  const visible = useMemo(
77
81
  () =>
78
- sortRows(filterRows(rows, {search, locales: locale ? [locale] : undefined}), sortKey, sortDirection, {
79
- typeOrder: config.pageTypeNames,
80
- }),
81
- [rows, search, locale, sortKey, sortDirection, config.pageTypeNames],
82
+ sortRows(
83
+ filterRows(rows, {search, locales: locale ? [locale] : undefined}).filter((row) => !onlyTodo || todos.has(row.id)),
84
+ sortKey,
85
+ sortDirection,
86
+ {typeOrder: config.pageTypeNames},
87
+ ),
88
+ [rows, search, locale, onlyTodo, todos, sortKey, sortDirection, config.pageTypeNames],
82
89
  )
83
90
 
84
91
  // Un filtre qui réduit la liste ne doit pas laisser l'utilisateur sur une
@@ -213,6 +220,24 @@ export function PagesTool() {
213
220
  </Box>
214
221
  )}
215
222
 
223
+ {(todos.size > 0 || onlyTodo) && (
224
+ <Box style={{width: 150, flex: 'none'}}>
225
+ <FieldLabel>Traduction</FieldLabel>
226
+ <Select
227
+ fontSize={1}
228
+ radius={2}
229
+ value={onlyTodo ? 'todo' : ''}
230
+ onChange={(event) => {
231
+ setOnlyTodo(event.currentTarget.value === 'todo')
232
+ setPage(0)
233
+ }}
234
+ >
235
+ <option value="">Toutes</option>
236
+ <option value="todo">À traduire ({todos.size})</option>
237
+ </Select>
238
+ </Box>
239
+ )}
240
+
216
241
  {view === 'list' && (
217
242
  <Box style={{width: 168, flex: 'none'}}>
218
243
  <FieldLabel>Grouper par</FieldLabel>
@@ -319,6 +344,7 @@ export function PagesTool() {
319
344
  onOpen={openPage}
320
345
  hidden={hidden}
321
346
  onTag={onTag}
347
+ todos={todos}
322
348
  />
323
349
  )}
324
350
  </Card>
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.20.0'
6
+ export const KIT_VERSION = '2.21.0'