@nocode-factory/sanity-kit 2.13.1 → 2.14.1

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.13.1",
3
+ "version": "2.14.1",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -0,0 +1,313 @@
1
+ import {useCallback, useEffect, useMemo, useState} from 'react'
2
+ import {Badge, Box, Button, Card, Checkbox, Flex, Spinner, Stack, Text} from '@sanity/ui'
3
+ import {useToast} from '@sanity/ui/toast'
4
+ import {PublishIcon} from '@sanity/icons/Publish'
5
+ import {
6
+ Preview,
7
+ useSchema,
8
+ useSyncState,
9
+ useValidationStatus,
10
+ type DocumentActionComponent,
11
+ type DocumentActionProps,
12
+ } from 'sanity'
13
+ import {useKitClient} from '../hooks/useKitClient'
14
+ import {isKitType} from '../schema/boardLayout'
15
+ import {
16
+ DRAFTS_QUERY,
17
+ PUBLISHED_IDS_QUERY,
18
+ explainPublishError,
19
+ publishActions,
20
+ publishLabel,
21
+ publishableDrafts,
22
+ publishedIdOf,
23
+ sinceLabel,
24
+ type DraftEntry,
25
+ type DraftRow,
26
+ } from '../lib/batchPublish'
27
+
28
+ /**
29
+ * Brouillons du projet, tenus à jour en direct : chaque modification, publication ou
30
+ * suppression relance la requête (regroupées, une fois par demi-seconde au plus).
31
+ */
32
+ function useDrafts(currentId: string | null) {
33
+ const client = useKitClient()
34
+ const schema = useSchema()
35
+ const [rows, setRows] = useState<{drafts: DraftRow[]; published: string[]} | null>(null)
36
+
37
+ const [reloadKey, setReloadKey] = useState(0)
38
+
39
+ useEffect(() => {
40
+ let cancelled = false
41
+ let timer: ReturnType<typeof setTimeout> | undefined
42
+ let retry: ReturnType<typeof setTimeout> | undefined
43
+ let subscription: {unsubscribe: () => void} | undefined
44
+ const load = async () => {
45
+ const drafts = await client.fetch<DraftRow[]>(DRAFTS_QUERY)
46
+ const published = await client.fetch<string[]>(PUBLISHED_IDS_QUERY, {ids: drafts.map((d) => publishedIdOf(d._id))})
47
+ if (!cancelled) setRows({drafts, published})
48
+ }
49
+ load().catch(() => {
50
+ if (!cancelled) setRows((prev) => prev ?? {drafts: [], published: []})
51
+ })
52
+ // Écoute en direct, best effort : si le service temps réel de Sanity tombe, on ne
53
+ // fait JAMAIS remonter l'erreur (elle s'afficherait en « Uncaught error » dans tout
54
+ // le Studio). On réessaie plus tard, et la liste est relue à l'ouverture de la
55
+ // fenêtre de toute façon.
56
+ const listen = (delay: number) => {
57
+ subscription = client
58
+ .listen(`*[_id in path("drafts.**") || _id in path("*")]`, {}, {visibility: 'query', includeResult: false, events: ['mutation']})
59
+ .subscribe({
60
+ next: () => {
61
+ clearTimeout(timer)
62
+ timer = setTimeout(() => void load().catch(() => {}), 500)
63
+ },
64
+ error: () => {
65
+ if (cancelled) return
66
+ retry = setTimeout(() => listen(Math.min(delay * 2, 120_000)), delay)
67
+ },
68
+ })
69
+ }
70
+ listen(15_000)
71
+ return () => {
72
+ cancelled = true
73
+ clearTimeout(timer)
74
+ clearTimeout(retry)
75
+ subscription?.unsubscribe()
76
+ }
77
+ }, [client, reloadKey])
78
+
79
+ const reload = useCallback(() => setReloadKey((k) => k + 1), [])
80
+
81
+ const drafts = useMemo(
82
+ () =>
83
+ rows
84
+ ? publishableDrafts(rows.drafts, rows.published, {
85
+ isDocumentType: (type) => schema.get(type)?.jsonType === 'object' && isDocumentSchema(schema.get(type)),
86
+ isInternalType: isKitType,
87
+ currentId,
88
+ })
89
+ : null,
90
+ [rows, schema, currentId],
91
+ )
92
+ return {drafts, reload}
93
+ }
94
+
95
+ function isDocumentSchema(type: unknown): boolean {
96
+ let current = type as {name?: string; type?: unknown} | undefined
97
+ while (current) {
98
+ if (current.name === 'document') return true
99
+ current = current.type as typeof current
100
+ }
101
+ return false
102
+ }
103
+
104
+ /**
105
+ * Remplace le bouton « Publier » du document : il ouvre la liste de TOUS les
106
+ * brouillons du projet, cochés par défaut. On publie tout d'un coup ou on décoche
107
+ * ce qui n'est pas prêt. Avec un seul brouillon (celui qu'on édite), le bouton
108
+ * d'origine est gardé tel quel : pas de fenêtre pour rien.
109
+ *
110
+ * En perspective de release ou de variante, l'action d'origine reste aussi : la
111
+ * publication groupée ne concerne que les brouillons.
112
+ */
113
+ export function createBatchPublishAction(original: DocumentActionComponent): DocumentActionComponent {
114
+ const BatchPublishAction: DocumentActionComponent = (props: DocumentActionProps) => {
115
+ const base = original(props)
116
+ const {drafts, reload} = useDrafts(props.id)
117
+ const [open, setOpen] = useState(false)
118
+
119
+ if (!base || props.release || props.version || !drafts) return base
120
+ const current = publishedIdOf(props.id)
121
+ const others = drafts.filter((d) => d.publishedId !== current)
122
+ if (others.length === 0) return base
123
+
124
+ return {
125
+ ...base,
126
+ label: `Publier… (${drafts.length})`,
127
+ title: 'Choisir les brouillons à publier, ensemble',
128
+ icon: PublishIcon,
129
+ disabled: false,
130
+ onHandle: () => {
131
+ reload()
132
+ setOpen(true)
133
+ },
134
+ dialog: open
135
+ ? {
136
+ type: 'dialog',
137
+ width: 'medium',
138
+ header: 'Publier les modifications',
139
+ onClose: () => setOpen(false),
140
+ content: <BatchPublishDialog drafts={drafts} currentId={current} currentType={props.type} onDone={() => setOpen(false)} />,
141
+ }
142
+ : null,
143
+ }
144
+ }
145
+ BatchPublishAction.action = original.action
146
+ BatchPublishAction.displayName = 'NcfBatchPublishAction'
147
+ return BatchPublishAction
148
+ }
149
+
150
+ function BatchPublishDialog(props: {drafts: DraftEntry[]; currentId: string; currentType: string; onDone: () => void}) {
151
+ const {drafts, currentId, currentType, onDone} = props
152
+ const client = useKitClient()
153
+ const toast = useToast()
154
+ // Les décochés, pas les cochés : un brouillon apparu pendant que la fenêtre est
155
+ // ouverte arrive coché, comme les autres.
156
+ const [unchecked, setUnchecked] = useState<Set<string>>(() => new Set())
157
+ const [invalid, setInvalid] = useState<Set<string>>(() => new Set())
158
+ const [busy, setBusy] = useState(false)
159
+ const [error, setError] = useState<string | null>(null)
160
+ // Le document ouvert peut avoir des frappes pas encore enregistrées.
161
+ const {isSyncing} = useSyncState(currentId, currentType)
162
+
163
+ const report = useCallback((id: string, hasErrors: boolean) => {
164
+ setInvalid((prev) => {
165
+ if (prev.has(id) === hasErrors) return prev
166
+ const next = new Set(prev)
167
+ if (hasErrors) next.add(id)
168
+ else next.delete(id)
169
+ return next
170
+ })
171
+ }, [])
172
+
173
+ const selectable = drafts.filter((d) => !invalid.has(d._id))
174
+ const selected = selectable.filter((d) => !unchecked.has(d._id))
175
+ const allChecked = selected.length === selectable.length && selectable.length > 0
176
+
177
+ const toggle = (id: string) =>
178
+ setUnchecked((prev) => {
179
+ const next = new Set(prev)
180
+ if (next.has(id)) next.delete(id)
181
+ else next.add(id)
182
+ return next
183
+ })
184
+ const toggleAll = () => setUnchecked(allChecked ? new Set(selectable.map((d) => d._id)) : new Set())
185
+
186
+ const publish = async () => {
187
+ setBusy(true)
188
+ setError(null)
189
+ try {
190
+ await client.action(publishActions(selected))
191
+ toast.push({
192
+ status: 'success',
193
+ title: selected.length > 1 ? `${selected.length} documents publiés` : 'Document publié',
194
+ })
195
+ onDone()
196
+ } catch (cause) {
197
+ setError(explainPublishError(cause))
198
+ } finally {
199
+ setBusy(false)
200
+ }
201
+ }
202
+
203
+ return (
204
+ <Stack gap={4} padding={4}>
205
+ <Flex align="center" justify="space-between" gap={3}>
206
+ <Text size={1} muted>
207
+ {drafts.length} document{drafts.length > 1 ? 's' : ''} en brouillon. Décochez ce qui n'est pas prêt.
208
+ </Text>
209
+ <Button mode="bleed" fontSize={1} padding={2} text={allChecked ? 'Tout décocher' : 'Tout cocher'} onClick={toggleAll} disabled={busy} />
210
+ </Flex>
211
+
212
+ <Card radius={2} border style={{maxHeight: '55vh', overflowY: 'auto'}}>
213
+ <Stack>
214
+ {drafts.map((draft, index) => (
215
+ <DraftLine
216
+ key={draft._id}
217
+ draft={draft}
218
+ current={draft.publishedId === currentId}
219
+ checked={!unchecked.has(draft._id) && !invalid.has(draft._id)}
220
+ invalid={invalid.has(draft._id)}
221
+ onToggle={() => toggle(draft._id)}
222
+ onValidation={report}
223
+ divider={index > 0}
224
+ disabled={busy}
225
+ />
226
+ ))}
227
+ </Stack>
228
+ </Card>
229
+
230
+ {error && (
231
+ <Card padding={3} radius={2} tone="critical">
232
+ <Text size={1}>{error}</Text>
233
+ </Card>
234
+ )}
235
+
236
+ <Flex justify="flex-end" align="center" gap={2}>
237
+ {isSyncing && (
238
+ <Flex align="center" gap={2}>
239
+ <Spinner muted />
240
+ <Text size={1} muted>
241
+ Enregistrement en cours…
242
+ </Text>
243
+ </Flex>
244
+ )}
245
+ <Button mode="bleed" text="Annuler" onClick={onDone} disabled={busy} />
246
+ <Button
247
+ tone="positive"
248
+ icon={busy ? Spinner : PublishIcon}
249
+ text={busy ? 'Publication…' : publishLabel(selected.length)}
250
+ disabled={busy || isSyncing || selected.length === 0}
251
+ onClick={publish}
252
+ />
253
+ </Flex>
254
+ </Stack>
255
+ )
256
+ }
257
+
258
+ function DraftLine(props: {
259
+ draft: DraftEntry
260
+ current: boolean
261
+ checked: boolean
262
+ invalid: boolean
263
+ disabled: boolean
264
+ divider: boolean
265
+ onToggle: () => void
266
+ onValidation: (id: string, hasErrors: boolean) => void
267
+ }) {
268
+ const {draft, current, checked, invalid, disabled, divider, onToggle, onValidation} = props
269
+ const schema = useSchema()
270
+ const schemaType = schema.get(draft._type)
271
+ // Mêmes règles que le bouton « Publier » de Sanity : un document invalide ne part pas.
272
+ // Les références vers des contenus jamais publiés sont laissées à la transaction, qui
273
+ // les accepte quand le contenu référencé part avec.
274
+ const {validation, isValidating} = useValidationStatus(draft._id, draft._type, false)
275
+ const hasErrors = validation.some((marker) => marker.level === 'error')
276
+ useEffect(() => {
277
+ if (!isValidating) onValidation(draft._id, hasErrors)
278
+ }, [draft._id, hasErrors, isValidating, onValidation])
279
+
280
+ return (
281
+ <Card
282
+ as="label"
283
+ padding={2}
284
+ paddingX={3}
285
+ tone={invalid ? 'critical' : current ? 'primary' : 'default'}
286
+ style={{cursor: invalid || disabled ? 'default' : 'pointer', borderTop: divider ? '1px solid var(--card-border-color)' : undefined}}
287
+ >
288
+ <Flex align="center" gap={3}>
289
+ <Checkbox checked={checked} disabled={invalid || disabled} onChange={onToggle} />
290
+ <Box flex={1} style={{minWidth: 0}}>
291
+ {schemaType ? (
292
+ <Preview schemaType={schemaType} value={{_id: draft._id, _type: draft._type}} layout="default" />
293
+ ) : (
294
+ <Text size={1}>{draft.publishedId}</Text>
295
+ )}
296
+ </Box>
297
+ <Stack gap={2} style={{flex: 'none', textAlign: 'right'}}>
298
+ <Flex gap={1} justify="flex-end">
299
+ {current && <Badge tone="primary">Ouvert</Badge>}
300
+ {invalid ? (
301
+ <Badge tone="critical">Erreurs à corriger</Badge>
302
+ ) : (
303
+ <Badge tone={draft.published ? 'caution' : 'positive'}>{draft.published ? 'Modifié' : 'Nouveau'}</Badge>
304
+ )}
305
+ </Flex>
306
+ <Text size={0} muted>
307
+ {schemaType?.title ?? draft._type} · {sinceLabel(draft._updatedAt)}
308
+ </Text>
309
+ </Stack>
310
+ </Flex>
311
+ </Card>
312
+ )
313
+ }
@@ -115,6 +115,7 @@ export function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {
115
115
  : null,
116
116
  tools: {...DEFAULT_TOOLS, ...input.tools},
117
117
  moreTools: input.moreTools === false ? [] : (input.moreTools ?? DEFAULT_TOOLBAR_MORE),
118
+ batchPublish: input.batchPublish !== false,
118
119
  boardTags: input.boardTags?.length ? input.boardTags : DEFAULT_BOARD_TAGS,
119
120
  internalFields: input.internalFields?.length
120
121
  ? input.internalFields
@@ -208,6 +208,11 @@ export interface NcfKitConfig {
208
208
  * (« Scheduled drafts » / Releases, nom d'outil `releases`). `false` : aucun.
209
209
  */
210
210
  moreTools?: string[] | false
211
+ /**
212
+ * « Publier » ouvre la liste de tous les brouillons du projet, cochés : on publie
213
+ * vingt modifications d'un coup, ou on décoche ce qui n'est pas prêt. Défaut : `true`.
214
+ */
215
+ batchPublish?: boolean
211
216
  /**
212
217
  * Étiquettes de suivi du board. Remplacent entièrement les valeurs par
213
218
  * défaut quand elles sont fournies.
@@ -269,6 +274,7 @@ export interface ResolvedKitConfig {
269
274
  tools: Required<NcfToolsConfig>
270
275
  /** Outils rangés dans le menu « Plus » de la barre (noms d'outils). */
271
276
  moreTools: string[]
277
+ batchPublish: boolean
272
278
  boardTags: NcfBoardTag[]
273
279
  internalFields: NcfInternalField[]
274
280
  documentColumns: ResolvedDocumentColumn[]
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ import {PagesTool} from './tools/pages/PagesTool'
12
12
  import {ComponentsTool} from './tools/components/ComponentsTool'
13
13
  import {HistoryTool} from './tools/history/HistoryTool'
14
14
  import {DesignSystemTool} from './tools/designSystem/DesignSystemTool'
15
+ import {createBatchPublishAction} from './actions/BatchPublish'
15
16
  import {BOARD_LAYOUT_TYPE, isKitType, kitSchemaTypes} from './schema/boardLayout'
16
17
  import type {NcfKitConfig, NcfToolName} from './config/types'
17
18
 
@@ -122,6 +123,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
122
123
  document: {
123
124
  newDocumentOptions: (prev) =>
124
125
  prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
126
+ // « Publier » : choisir parmi tous les brouillons du projet et les publier ensemble.
127
+ actions: (prev) =>
128
+ config.batchPublish
129
+ ? prev.map((action) => (action.action === 'publish' ? createBatchPublishAction(action) : action))
130
+ : prev,
125
131
  },
126
132
 
127
133
  // Le lanceur d'aperçu s'ajoute à droite des outils, dans la barre du haut
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Publication groupée : logique pure (testée), sans React ni Studio.
3
+ *
4
+ * On modifie vingt documents, on publie tout d'un coup, ou seulement ce qu'on a
5
+ * coché. La publication passe par l'API Actions de Sanity, en UNE transaction :
6
+ * tout part ensemble ou rien ne part (un document qui en référence un autre encore
7
+ * jamais publié peut ainsi partir avec lui).
8
+ */
9
+
10
+ const DRAFTS_PREFIX = 'drafts.'
11
+
12
+ export interface DraftRow {
13
+ _id: string
14
+ _rev: string
15
+ _type: string
16
+ _updatedAt: string
17
+ }
18
+
19
+ export interface DraftEntry extends DraftRow {
20
+ publishedId: string
21
+ /** `false` : jamais publié (ce sera une création). */
22
+ published: boolean
23
+ }
24
+
25
+ export interface PublishDocumentAction {
26
+ actionType: 'sanity.action.document.publish'
27
+ draftId: string
28
+ publishedId: string
29
+ ifDraftRevisionId: string
30
+ }
31
+
32
+ /** Brouillons (`drafts.*`) de tous les documents, sans les versions de release. */
33
+ export const DRAFTS_QUERY = `*[_id in path("drafts.**")]{_id, _rev, _type, _updatedAt}`
34
+ /** Parmi ces ids publiés, ceux qui existent déjà. */
35
+ export const PUBLISHED_IDS_QUERY = `*[_id in $ids]._id`
36
+
37
+ export const publishedIdOf = (id: string): string =>
38
+ id.startsWith(DRAFTS_PREFIX) ? id.slice(DRAFTS_PREFIX.length) : id
39
+
40
+ /**
41
+ * Brouillons publiables : types du schéma (documents), hors types internes (kit,
42
+ * `sanity.*`). Le document ouvert d'abord, puis du plus récent au plus ancien.
43
+ */
44
+ export function publishableDrafts(
45
+ rows: DraftRow[],
46
+ publishedIds: Iterable<string>,
47
+ options: {isDocumentType: (type: string) => boolean; isInternalType?: (type: string) => boolean; currentId?: string | null},
48
+ ): DraftEntry[] {
49
+ const published = new Set(publishedIds)
50
+ const current = options.currentId ? publishedIdOf(options.currentId) : null
51
+ return rows
52
+ .filter((row) => row._id.startsWith(DRAFTS_PREFIX) && !row._id.slice(DRAFTS_PREFIX.length).includes('.'))
53
+ .filter((row) => !row._type.startsWith('sanity.') && options.isDocumentType(row._type) && !options.isInternalType?.(row._type))
54
+ .map((row) => ({...row, publishedId: publishedIdOf(row._id), published: published.has(publishedIdOf(row._id))}))
55
+ .sort((a, b) => {
56
+ if (a.publishedId === current) return -1
57
+ if (b.publishedId === current) return 1
58
+ return b._updatedAt.localeCompare(a._updatedAt)
59
+ })
60
+ }
61
+
62
+ /**
63
+ * Actions de publication. `ifDraftRevisionId` : on publie exactement la version
64
+ * affichée ; si quelqu'un l'a modifiée entre-temps, la transaction est refusée
65
+ * plutôt que de publier un contenu que personne n'a relu.
66
+ */
67
+ export function publishActions(selected: DraftEntry[]): PublishDocumentAction[] {
68
+ return selected.map((draft) => ({
69
+ actionType: 'sanity.action.document.publish',
70
+ draftId: draft._id,
71
+ publishedId: draft.publishedId,
72
+ ifDraftRevisionId: draft._rev,
73
+ }))
74
+ }
75
+
76
+ /** Libellé du bouton : « Publier 1 document », « Publier 12 documents ». */
77
+ export function publishLabel(count: number): string {
78
+ if (count === 0) return 'Rien à publier'
79
+ return `Publier ${count} document${count > 1 ? 's' : ''}`
80
+ }
81
+
82
+ /** Erreur de l'API rendue lisible. */
83
+ export function explainPublishError(error: unknown): string {
84
+ const err = error as {statusCode?: number; message?: string; details?: {description?: string; items?: Array<{error?: {description?: string}}>}}
85
+ const description = err?.details?.description ?? err?.details?.items?.[0]?.error?.description ?? err?.message ?? ''
86
+ if (/revision|mismatch|ifDraftRevisionId/i.test(description)) {
87
+ return "Un des documents a été modifié pendant que la fenêtre était ouverte : la liste vient d'être mise à jour, relancez la publication."
88
+ }
89
+ if (/reference/i.test(description)) {
90
+ return `Un document référence un contenu jamais publié qui n'est pas coché : cochez-le aussi, ou retirez la référence. (${description})`
91
+ }
92
+ if (err?.statusCode === 403 || /permission/i.test(description)) return "Vous n'avez pas le droit de publier un de ces documents."
93
+ return description ? `Publication refusée : ${description}` : 'Publication refusée.'
94
+ }
95
+
96
+ /** « à l'instant », « il y a 5 min », « il y a 3 h », « il y a 2 j ». */
97
+ export function sinceLabel(iso: string, now = Date.now()): string {
98
+ const minutes = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000))
99
+ if (minutes < 1) return "à l'instant"
100
+ if (minutes < 60) return `il y a ${minutes} min`
101
+ const hours = Math.round(minutes / 60)
102
+ if (hours < 24) return `il y a ${hours} h`
103
+ return `il y a ${Math.round(hours / 24)} j`
104
+ }
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.13.1'
6
+ export const KIT_VERSION = '2.14.1'