@nocode-factory/sanity-kit 2.0.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.
Files changed (95) hide show
  1. package/bin/ncf-kit.mjs +201 -0
  2. package/dist/index.d.ts +1643 -0
  3. package/dist/index.js +6632 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/web-server.d.ts +46 -0
  6. package/dist/web-server.js +51 -0
  7. package/dist/web-server.js.map +1 -0
  8. package/dist/web.d.ts +27 -0
  9. package/dist/web.js +117 -0
  10. package/dist/web.js.map +1 -0
  11. package/package.json +90 -0
  12. package/scripts/use-client.mjs +20 -0
  13. package/src/config/defaults.ts +74 -0
  14. package/src/config/resolve.ts +153 -0
  15. package/src/config/types.ts +290 -0
  16. package/src/config/validate.ts +193 -0
  17. package/src/context/BoardLayoutContext.tsx +24 -0
  18. package/src/context/KitContext.tsx +30 -0
  19. package/src/context/PreviewTargetContext.tsx +27 -0
  20. package/src/hooks/useAnnotations.ts +60 -0
  21. package/src/hooks/useBoardLayout.ts +398 -0
  22. package/src/hooks/useColumnOptions.ts +47 -0
  23. package/src/hooks/useDocumentColumns.ts +61 -0
  24. package/src/hooks/useHistory.ts +89 -0
  25. package/src/hooks/useInternalColumns.ts +19 -0
  26. package/src/hooks/useKitClient.ts +15 -0
  27. package/src/hooks/useOccurrences.ts +62 -0
  28. package/src/hooks/usePageContents.ts +65 -0
  29. package/src/hooks/usePages.ts +41 -0
  30. package/src/hooks/usePreviewTarget.ts +162 -0
  31. package/src/hooks/useQueryData.ts +103 -0
  32. package/src/hooks/useRegistration.ts +50 -0
  33. package/src/index.ts +280 -0
  34. package/src/lib/blocks.ts +38 -0
  35. package/src/lib/colors.ts +103 -0
  36. package/src/lib/columns.ts +137 -0
  37. package/src/lib/diff.ts +200 -0
  38. package/src/lib/elkLayout.ts +124 -0
  39. package/src/lib/graph.ts +238 -0
  40. package/src/lib/grouping.ts +116 -0
  41. package/src/lib/links.ts +70 -0
  42. package/src/lib/occurrences.ts +93 -0
  43. package/src/lib/pageThumbnail.ts +43 -0
  44. package/src/lib/pages.ts +199 -0
  45. package/src/lib/paths.ts +68 -0
  46. package/src/lib/query.ts +113 -0
  47. package/src/lib/schemaColumns.ts +162 -0
  48. package/src/lib/schemaTypes.ts +75 -0
  49. package/src/lib/sectionsMap.ts +83 -0
  50. package/src/lib/service.ts +88 -0
  51. package/src/lib/siteRoutes.ts +43 -0
  52. package/src/lib/status.ts +122 -0
  53. package/src/lib/studioLinks.ts +137 -0
  54. package/src/schema/boardLayout.ts +190 -0
  55. package/src/tools/components/BlockCard.tsx +79 -0
  56. package/src/tools/components/ComponentsTool.tsx +171 -0
  57. package/src/tools/components/map/SectionNode.tsx +109 -0
  58. package/src/tools/components/map/SectionsMap.tsx +339 -0
  59. package/src/tools/createToolComponent.tsx +67 -0
  60. package/src/tools/history/ChangeRow.tsx +87 -0
  61. package/src/tools/history/DiffPanel.tsx +227 -0
  62. package/src/tools/history/HistoryTool.tsx +230 -0
  63. package/src/tools/more/MoreTool.tsx +82 -0
  64. package/src/tools/pages/ColumnHeader.tsx +216 -0
  65. package/src/tools/pages/ColumnVisibility.tsx +173 -0
  66. package/src/tools/pages/FieldValue.tsx +327 -0
  67. package/src/tools/pages/PagesTable.tsx +394 -0
  68. package/src/tools/pages/PagesTool.tsx +333 -0
  69. package/src/tools/pages/PagesToolbar.tsx +53 -0
  70. package/src/tools/pages/PathCell.tsx +71 -0
  71. package/src/tools/pages/PreviewTarget.tsx +226 -0
  72. package/src/tools/pages/TagCell.tsx +124 -0
  73. package/src/tools/pages/ViewTabs.tsx +57 -0
  74. package/src/tools/pages/board/BoardView.tsx +661 -0
  75. package/src/tools/pages/board/PageNode.tsx +306 -0
  76. package/src/tools/pages/board/PagePanel.tsx +228 -0
  77. package/src/tools/presentation/PreviewHeader.tsx +75 -0
  78. package/src/tools/shared/AnnotationNode.tsx +126 -0
  79. package/src/ui/ActorName.tsx +20 -0
  80. package/src/ui/ConfigIssues.tsx +41 -0
  81. package/src/ui/InlineCode.tsx +22 -0
  82. package/src/ui/Popover.tsx +85 -0
  83. package/src/ui/ProjectStatusNotice.tsx +58 -0
  84. package/src/ui/QueryError.tsx +16 -0
  85. package/src/ui/QuietInput.tsx +64 -0
  86. package/src/ui/StatusBadge.tsx +11 -0
  87. package/src/ui/ToolPlaceholder.tsx +23 -0
  88. package/src/ui/formatDate.ts +14 -0
  89. package/src/ui/tokens.ts +54 -0
  90. package/src/version.ts +5 -0
  91. package/src/web/PreviewBanner.tsx +115 -0
  92. package/src/web/draftModeToggle.ts +56 -0
  93. package/src/web/environment.ts +21 -0
  94. package/src/web/index.ts +15 -0
  95. package/src/web/server.ts +11 -0
@@ -0,0 +1,398 @@
1
+ import {useCallback, useEffect, useMemo, useRef, useState} from 'react'
2
+ import {useCurrentUser} from 'sanity'
3
+ import {BOARD_LAYOUT_ID, BOARD_LAYOUT_TYPE} from '../schema/boardLayout'
4
+ import {
5
+ pruneSavedPositions,
6
+ upsertLayout,
7
+ type Annotation,
8
+ type NodeLayout,
9
+ type SectionLayout,
10
+ } from '../lib/graph'
11
+ import type {NcfInternalField} from '../config/types'
12
+ import {useKitClient} from './useKitClient'
13
+
14
+ interface StoredField {
15
+ _key: string
16
+ fieldId: string
17
+ value?: string | null
18
+ }
19
+
20
+ interface StoredNode extends Omit<NodeLayout, 'fields'> {
21
+ _key: string
22
+ fields?: StoredField[]
23
+ }
24
+
25
+ interface StoredSection extends SectionLayout {
26
+ _key: string
27
+ }
28
+
29
+ interface StoredColumn extends NcfInternalField {
30
+ _key: string
31
+ }
32
+
33
+ interface StoredAnnotation extends Annotation {
34
+ _key: string
35
+ }
36
+
37
+ export interface BoardLayoutState {
38
+ layout: NodeLayout[]
39
+ /** Positions manuelles des sections sur la carte des composants. */
40
+ sections: SectionLayout[]
41
+ sectionsByName: Map<string, SectionLayout>
42
+ /**
43
+ * Colonnes de gestion interne. Vides tant que personne n'en a créé : c'est
44
+ * alors la configuration qui fournit le jeu de départ.
45
+ */
46
+ columns: NcfInternalField[]
47
+ saveColumns: (next: readonly NcfInternalField[]) => void
48
+ /**
49
+ * Vrai dès que quelqu'un a touché aux colonnes. Sans ce marqueur, supprimer
50
+ * la dernière colonne ferait réapparaître celles de la configuration.
51
+ */
52
+ columnsSet: boolean
53
+ /** Notes et formes posées sur les canvas. */
54
+ annotations: Annotation[]
55
+ saveAnnotations: (next: readonly Annotation[]) => void
56
+ /** Accès direct par identifiant de page, pour le rendu des nœuds. */
57
+ byId: Map<string, NodeLayout>
58
+ loading: boolean
59
+ /** Erreur d'enregistrement : l'utilisateur doit savoir que rien n'est gardé. */
60
+ saveError: Error | null
61
+ /** Enregistre des positions, en oubliant celles des pages disparues. */
62
+ savePositions: (
63
+ positions: readonly {documentId: string; x: number; y: number}[],
64
+ existingIds: readonly string[],
65
+ ) => void
66
+ /** Modifie une seule entrée : taille, étiquette… sans toucher au reste. */
67
+ patchNode: (documentId: string, patch: Partial<Omit<NodeLayout, 'documentId'>>) => void
68
+ /** Modifie une seule valeur de gestion interne. */
69
+ patchField: (documentId: string, fieldId: string, value: string) => void
70
+ /** Enregistre les positions des sections de la carte des composants. */
71
+ saveSections: (positions: readonly SectionLayout[]) => void
72
+ /** Efface la disposition manuelle : le placement automatique reprend la main. */
73
+ reset: () => void
74
+ /** Idem, pour la seule carte des composants. */
75
+ resetSections: () => void
76
+ }
77
+
78
+ /** Le tableau stocké devient un objet en mémoire, plus simple à lire et écrire. */
79
+ const fieldsFromStored = (stored?: StoredField[]): Record<string, string> | undefined => {
80
+ if (!stored?.length) return undefined
81
+ const entries = stored
82
+ .filter((field) => field.fieldId && field.value)
83
+ .map((field) => [field.fieldId, field.value as string] as const)
84
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined
85
+ }
86
+
87
+ const clean = (entries: readonly StoredNode[]): NodeLayout[] =>
88
+ entries.map(({documentId, x, y, width, height, tag, fields}) => ({
89
+ documentId,
90
+ ...(Number.isFinite(x) ? {x} : {}),
91
+ ...(Number.isFinite(y) ? {y} : {}),
92
+ ...(width ? {width} : {}),
93
+ ...(height ? {height} : {}),
94
+ ...(tag ? {tag} : {}),
95
+ ...(fieldsFromStored(fields) ? {fields: fieldsFromStored(fields)} : {}),
96
+ }))
97
+
98
+ /**
99
+ * Disposition manuelle du board : positions, tailles et étiquettes de suivi,
100
+ * dans le singleton `ncfBoardLayout`.
101
+ *
102
+ * Écriture directe sur le document publié : ce n'est pas du contenu éditorial,
103
+ * il n'a rien à faire dans le flux de relecture et de publication du client.
104
+ */
105
+ /**
106
+ * Implémentation. Ne pas appeler directement : le document de disposition est
107
+ * écrit en entier à chaque fois, donc deux instances concurrentes
108
+ * s'écraseraient l'une l'autre. Passer par `useBoardLayout`, qui lit l'unique
109
+ * instance fournie par `BoardLayoutProvider`.
110
+ */
111
+ export function useBoardLayoutState(): BoardLayoutState {
112
+ const client = useKitClient()
113
+ const user = useCurrentUser()
114
+
115
+ const [layout, setLayout] = useState<NodeLayout[]>([])
116
+ const [sections, setSections] = useState<SectionLayout[]>([])
117
+ const [columns, setColumns] = useState<NcfInternalField[]>([])
118
+ const [columnsSet, setColumnsSet] = useState(false)
119
+ const [annotations, setAnnotations] = useState<Annotation[]>([])
120
+ const [loading, setLoading] = useState(true)
121
+ const [saveError, setSaveError] = useState<Error | null>(null)
122
+
123
+ useEffect(() => {
124
+ let cancelled = false
125
+ client
126
+ .fetch<{
127
+ nodes?: StoredNode[]
128
+ sections?: StoredSection[]
129
+ columns?: StoredColumn[]
130
+ columnsSet?: boolean
131
+ annotations?: StoredAnnotation[]
132
+ } | null>(`*[_id == $id][0]{nodes, sections, columns, columnsSet, annotations}`, {
133
+ id: BOARD_LAYOUT_ID,
134
+ })
135
+ .then((doc) => {
136
+ if (cancelled) return
137
+ setLayout(clean(doc?.nodes ?? []))
138
+ setSections((doc?.sections ?? []).map(({blockName, x, y}) => ({blockName, x, y})))
139
+ setColumns(
140
+ (doc?.columns ?? []).map(({id, label, type, options}) => ({
141
+ id,
142
+ label,
143
+ type: type ?? 'text',
144
+ ...(options?.length ? {options: options.map(({id: oid, label: ol, color}) => ({id: oid, label: ol, ...(color ? {color} : {})}))} : {}),
145
+ })),
146
+ )
147
+ setColumnsSet(Boolean(doc?.columnsSet))
148
+ setAnnotations((doc?.annotations ?? []).map(({_key, ...rest}) => ({...rest})))
149
+ })
150
+ .catch(() => {
151
+ // Pas de disposition lisible : on part du placement automatique
152
+ // plutôt que de bloquer le board.
153
+ if (!cancelled) {
154
+ setLayout([])
155
+ setSections([])
156
+ setColumns([])
157
+ setColumnsSet(false)
158
+ setAnnotations([])
159
+ }
160
+ })
161
+ .finally(() => {
162
+ if (!cancelled) setLoading(false)
163
+ })
164
+
165
+ return () => {
166
+ cancelled = true
167
+ }
168
+ }, [client])
169
+
170
+ // Le glisser-déposer et le redimensionnement émettent beaucoup
171
+ // d'événements : on n'écrit qu'une fois le geste terminé et stabilisé.
172
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
173
+ useEffect(() => () => {
174
+ if (timer.current) clearTimeout(timer.current)
175
+ }, [])
176
+
177
+ // Le document porte les deux dispositions : chaque écriture doit republier
178
+ // l'autre telle quelle, sinon régler le board effacerait la carte.
179
+ const layoutRef = useRef<NodeLayout[]>([])
180
+ const sectionsRef = useRef<SectionLayout[]>([])
181
+ const columnsRef = useRef<NcfInternalField[]>([])
182
+ const columnsSetRef = useRef(false)
183
+ const annotationsRef = useRef<Annotation[]>([])
184
+ layoutRef.current = layout
185
+ sectionsRef.current = sections
186
+ columnsRef.current = columns
187
+ columnsSetRef.current = columnsSet
188
+ annotationsRef.current = annotations
189
+
190
+ const write = useCallback(
191
+ (next?: {
192
+ nodes?: NodeLayout[]
193
+ sections?: SectionLayout[]
194
+ columns?: NcfInternalField[]
195
+ columnsSet?: boolean
196
+ annotations?: Annotation[]
197
+ }) => {
198
+ const nodes = next?.nodes ?? layoutRef.current
199
+ const nextSections = next?.sections ?? sectionsRef.current
200
+ const nextColumns = next?.columns ?? columnsRef.current
201
+ const nextColumnsSet = next?.columnsSet ?? columnsSetRef.current
202
+ const nextAnnotations = next?.annotations ?? annotationsRef.current
203
+ client
204
+ .createOrReplace({
205
+ _id: BOARD_LAYOUT_ID,
206
+ _type: BOARD_LAYOUT_TYPE,
207
+ nodes: nodes.map(({fields, ...entry}) => ({
208
+ _key: entry.documentId,
209
+ _type: 'ncfBoardNode',
210
+ ...entry,
211
+ // Sanity n'accepte pas d'objet à clés libres : les valeurs
212
+ // repartent en tableau, chacune avec sa clé.
213
+ fields: Object.entries(fields ?? {})
214
+ .filter(([, value]) => value)
215
+ .map(([fieldId, value]) => ({
216
+ _key: fieldId,
217
+ _type: 'ncfNodeField',
218
+ fieldId,
219
+ value,
220
+ })),
221
+ })),
222
+ sections: nextSections.map((entry) => ({
223
+ _key: entry.blockName,
224
+ _type: 'ncfSectionNode',
225
+ ...entry,
226
+ })),
227
+ columns: nextColumns.map((column) => ({
228
+ _key: column.id,
229
+ _type: 'ncfColumn',
230
+ ...column,
231
+ options: (column.options ?? []).map((option) => ({
232
+ _key: option.id,
233
+ _type: 'ncfColumnOption',
234
+ ...option,
235
+ })),
236
+ })),
237
+ columnsSet: nextColumnsSet,
238
+ annotations: nextAnnotations.map((annotation) => ({
239
+ _key: annotation.id,
240
+ _type: 'ncfAnnotation',
241
+ ...annotation,
242
+ })),
243
+ updatedBy: user?.id ?? null,
244
+ })
245
+ .then(() => setSaveError(null))
246
+ .catch((cause: unknown) =>
247
+ setSaveError(cause instanceof Error ? cause : new Error(String(cause))),
248
+ )
249
+ },
250
+ [client, user?.id],
251
+ )
252
+
253
+ const savePositions = useCallback(
254
+ (
255
+ positions: readonly {documentId: string; x: number; y: number}[],
256
+ existingIds: readonly string[],
257
+ ) => {
258
+ setLayout((current) => {
259
+ // Les positions arrivent du canvas ; tailles et étiquettes viennent de
260
+ // l'état existant et ne doivent pas être écrasées au passage.
261
+ const previous = new Map(current.map((entry) => [entry.documentId, entry]))
262
+ const merged = positions.map((position) => ({
263
+ ...(previous.get(position.documentId) ?? {}),
264
+ ...position,
265
+ }))
266
+ const next = pruneSavedPositions(merged, existingIds)
267
+ if (timer.current) clearTimeout(timer.current)
268
+ timer.current = setTimeout(() => write({nodes: next}), 800)
269
+ return next
270
+ })
271
+ },
272
+ [write],
273
+ )
274
+
275
+ const patchNode = useCallback(
276
+ (documentId: string, patch: Partial<Omit<NodeLayout, 'documentId'>>) => {
277
+ setLayout((current) => {
278
+ const next = upsertLayout(current, documentId, patch)
279
+ if (timer.current) clearTimeout(timer.current)
280
+ timer.current = setTimeout(() => write({nodes: next}), 800)
281
+ return next
282
+ })
283
+ },
284
+ [write],
285
+ )
286
+
287
+ const reset = useCallback(() => {
288
+ if (timer.current) clearTimeout(timer.current)
289
+ // Réorganiser replace les nœuds ; ça n'efface ni les étiquettes ni les
290
+ // valeurs de gestion interne, qui sont du travail éditorial. Seules les
291
+ // coordonnées disparaissent — sans être remplacées par des zéros, qui
292
+ // empileraient tout à l'origine.
293
+ setLayout((current) => {
294
+ const kept = current
295
+ .filter((entry) => entry.tag || entry.fields)
296
+ .map(({documentId, tag, fields}) => ({
297
+ documentId,
298
+ ...(tag ? {tag} : {}),
299
+ ...(fields ? {fields} : {}),
300
+ }))
301
+ write({nodes: kept})
302
+ return kept
303
+ })
304
+ }, [write])
305
+
306
+ const patchField = useCallback(
307
+ (documentId: string, fieldId: string, value: string) => {
308
+ setLayout((current) => {
309
+ const existing = current.find((entry) => entry.documentId === documentId)
310
+ const fields = {...(existing?.fields ?? {})}
311
+ // Une valeur vidée disparaît : on ne conserve pas de chaînes vides.
312
+ if (value.trim()) fields[fieldId] = value.trim()
313
+ else delete fields[fieldId]
314
+
315
+ const next = upsertLayout(current, documentId, {
316
+ fields: Object.keys(fields).length > 0 ? fields : undefined,
317
+ })
318
+ if (timer.current) clearTimeout(timer.current)
319
+ timer.current = setTimeout(() => write({nodes: next}), 800)
320
+ return next
321
+ })
322
+ },
323
+ [write],
324
+ )
325
+
326
+ const saveSections = useCallback(
327
+ (positions: readonly SectionLayout[]) => {
328
+ const next = positions.map(({blockName, x, y}) => ({
329
+ blockName,
330
+ x: Math.round(x),
331
+ y: Math.round(y),
332
+ }))
333
+ setSections(next)
334
+ if (timer.current) clearTimeout(timer.current)
335
+ timer.current = setTimeout(() => write({sections: next}), 800)
336
+ },
337
+ [write],
338
+ )
339
+
340
+ const saveColumns = useCallback(
341
+ (next: readonly NcfInternalField[]) => {
342
+ const value = next.map((column) => ({...column}))
343
+ setColumns(value)
344
+ setColumnsSet(true)
345
+ if (timer.current) clearTimeout(timer.current)
346
+ timer.current = setTimeout(() => write({columns: value, columnsSet: true}), 800)
347
+ },
348
+ [write],
349
+ )
350
+
351
+ const saveAnnotations = useCallback(
352
+ (next: readonly Annotation[]) => {
353
+ const value = next.map((annotation) => ({...annotation}))
354
+ setAnnotations(value)
355
+ if (timer.current) clearTimeout(timer.current)
356
+ timer.current = setTimeout(() => write({annotations: value}), 800)
357
+ },
358
+ [write],
359
+ )
360
+
361
+ const resetSections = useCallback(() => {
362
+ if (timer.current) clearTimeout(timer.current)
363
+ setSections([])
364
+ write({sections: []})
365
+ }, [write])
366
+
367
+ const sectionsByName = useMemo(
368
+ () => new Map(sections.map((entry) => [entry.blockName, entry])),
369
+ [sections],
370
+ )
371
+
372
+ const byId = useMemo(
373
+ () => new Map(layout.map((entry) => [entry.documentId, entry])),
374
+ [layout],
375
+ )
376
+
377
+ return {
378
+ layout,
379
+ byId,
380
+ sections,
381
+ sectionsByName,
382
+ loading,
383
+ saveError,
384
+ savePositions,
385
+ patchNode,
386
+ patchField,
387
+ saveSections,
388
+ columns,
389
+ columnsSet,
390
+ saveColumns,
391
+ annotations,
392
+ saveAnnotations,
393
+ reset,
394
+ resetSections,
395
+ }
396
+ }
397
+
398
+ export type {Annotation, NodeLayout, SectionLayout}
@@ -0,0 +1,47 @@
1
+ import {useCallback, useMemo} from 'react'
2
+ import {useBoardLayout} from '../context/BoardLayoutContext'
3
+ import {useInternalColumns} from './useInternalColumns'
4
+ import * as columnOps from '../lib/columns'
5
+
6
+ export interface ColumnOptionHandlers {
7
+ onAddOption: (columnId: string, label: string) => void
8
+ onRemoveOption: (columnId: string, optionId: string) => void
9
+ onOptionColor: (columnId: string, optionId: string, color: string | null) => void
10
+ }
11
+
12
+ /**
13
+ * Gestion des choix d'une colonne liste.
14
+ *
15
+ * Le même jeu de gestes sert au tableau et à la fiche du board : les
16
+ * factoriser ici évite que l'un sache ajouter un choix et pas l'autre.
17
+ */
18
+ export function useColumnOptions(): ColumnOptionHandlers {
19
+ const {saveColumns} = useBoardLayout()
20
+ const columns = useInternalColumns()
21
+
22
+ const onAddOption = useCallback(
23
+ (columnId: string, label: string) => {
24
+ saveColumns(columnOps.addColumnOption(columns, columnId, label))
25
+ },
26
+ [columns, saveColumns],
27
+ )
28
+
29
+ const onRemoveOption = useCallback(
30
+ (columnId: string, optionId: string) => {
31
+ saveColumns(columnOps.removeColumnOption(columns, columnId, optionId))
32
+ },
33
+ [columns, saveColumns],
34
+ )
35
+
36
+ const onOptionColor = useCallback(
37
+ (columnId: string, optionId: string, color: string | null) => {
38
+ saveColumns(columnOps.setColumnOptionColor(columns, columnId, optionId, color))
39
+ },
40
+ [columns, saveColumns],
41
+ )
42
+
43
+ return useMemo(
44
+ () => ({onAddOption, onRemoveOption, onOptionColor}),
45
+ [onAddOption, onRemoveOption, onOptionColor],
46
+ )
47
+ }
@@ -0,0 +1,61 @@
1
+ import {useMemo} from 'react'
2
+ import {useSchema} from 'sanity'
3
+ import {useKitConfig} from '../context/KitContext'
4
+ import {deriveDocumentColumns, type SchemaTypeLike} from '../lib/schemaColumns'
5
+ import {isSafeFieldPath} from '../lib/query'
6
+ import type {ResolvedDocumentColumn} from '../config/types'
7
+
8
+ /**
9
+ * Données de la page proposées comme colonnes.
10
+ *
11
+ * Tirées du schéma du client : le Studio le connaît déjà, et aucune liste
12
+ * tenue à la main ne suivrait les schémas de tous les projets. `documentColumns`
13
+ * en configuration vient compléter, pour ce que le parcours ne sait pas
14
+ * exprimer — un chemin profond, ou plusieurs chemins fusionnés.
15
+ *
16
+ * Les chemins déjà représentés par une colonne de base — titre, slug, langue,
17
+ * page builder — sont écartés : les voir deux fois n'apprend rien.
18
+ */
19
+ export function useDocumentColumns(): ResolvedDocumentColumn[] {
20
+ const config = useKitConfig()
21
+ const schema = useSchema()
22
+
23
+ return useMemo(() => {
24
+ const exclude = [
25
+ ...config.pageTypes.map((type) => type.titleField),
26
+ ...config.pageTypes.map((type) => type.slugField),
27
+ ...config.pageTypes.map((type) => `${type.slugField}.current`),
28
+ config.pageBuilderField,
29
+ config.i18n?.field,
30
+ // Repris juste en dessous sous un libellé qui se lit à l'endroit.
31
+ ...config.noindexFields,
32
+ ].filter((path): path is string => Boolean(path))
33
+
34
+ const types = config.pageTypeNames.map(
35
+ (name) => schema.get(name) as SchemaTypeLike | undefined,
36
+ )
37
+
38
+ const indexation = indexationColumn(config.noindexFields)
39
+ const derived = deriveDocumentColumns(types, {exclude})
40
+
41
+ // La configuration l'emporte sur le schéma à chemin égal : elle a été
42
+ // écrite exprès.
43
+ const byKey = new Map<string, ResolvedDocumentColumn>()
44
+ for (const column of [...indexation, ...derived, ...config.documentColumns]) {
45
+ byKey.set(column.key, column)
46
+ }
47
+ return [...byKey.values()]
48
+ }, [config, schema])
49
+ }
50
+
51
+ /**
52
+ * Indexabilité, à partir des mêmes chemins que le reste du kit.
53
+ *
54
+ * Présentée à l'endroit — « Indexable : oui » — parce qu'une colonne
55
+ * « Noindex » se lit de travers dans un tableau qu'on survole.
56
+ */
57
+ function indexationColumn(noindexFields: readonly string[]): ResolvedDocumentColumn[] {
58
+ const paths = noindexFields.filter(isSafeFieldPath)
59
+ if (paths.length === 0) return []
60
+ return [{key: 'ncfIndexable', label: 'Indexable', paths, type: 'boolean', invert: true}]
61
+ }
@@ -0,0 +1,89 @@
1
+ import {useCallback, useEffect, useState} from 'react'
2
+ import {useKitConfig} from '../context/KitContext'
3
+ import {fetchTimeline, type HistoryEvent} from '../lib/service'
4
+
5
+ export interface HistoryState {
6
+ events: HistoryEvent[]
7
+ loading: boolean
8
+ /** Message prêt à afficher, déjà traduit depuis le code du service. */
9
+ error: string | null
10
+ hasMore: boolean
11
+ loadMore: () => void
12
+ refresh: () => void
13
+ }
14
+
15
+ /** Messages du service, rendus lisibles pour un éditeur. */
16
+ function explain(error: unknown): string {
17
+ const code = error instanceof Error ? error.message : String(error)
18
+ if (code === 'bad_key')
19
+ return "La clé de lecture n'est pas reconnue : relancez `npx ncf-kit setup` dans le dossier du studio, puis redéployez-le."
20
+ if (code === 'project_inactive')
21
+ return "Le journal n'est pas activé pour ce projet chez NoCode Factory : `npx ncf-kit setup` l'active, ou contactez NoCode Factory."
22
+ if (code === 'missing_key') return 'Aucune clé de lecture configurée.'
23
+ return "Le journal n'a pas pu être chargé."
24
+ }
25
+
26
+ /**
27
+ * Frise du journal, la plus récente d'abord.
28
+ *
29
+ * Paginée par curseur et non par décalage : des événements arrivent pendant
30
+ * qu'on lit, et un décalage ferait sauter des lignes.
31
+ */
32
+ export function useHistory(documentId?: string): HistoryState {
33
+ const config = useKitConfig()
34
+ const history = config.history
35
+
36
+ const [events, setEvents] = useState<HistoryEvent[]>([])
37
+ const [loading, setLoading] = useState(false)
38
+ const [error, setError] = useState<string | null>(null)
39
+ const [hasMore, setHasMore] = useState(false)
40
+ const [before, setBefore] = useState<string | undefined>(undefined)
41
+ const [nonce, setNonce] = useState(0)
42
+
43
+ useEffect(() => {
44
+ if (!history) {
45
+ setError('Aucune clé de lecture configurée.')
46
+ return undefined
47
+ }
48
+
49
+ const controller = new AbortController()
50
+ setLoading(true)
51
+ setError(null)
52
+
53
+ fetchTimeline(
54
+ history.endpoint,
55
+ history.projectKey,
56
+ {documentId, before},
57
+ controller.signal,
58
+ )
59
+ .then((result) => {
60
+ if (controller.signal.aborted) return
61
+ // Une page suivante s'ajoute ; un rechargement repart de zéro.
62
+ setEvents((current) => (before ? [...current, ...result.events] : result.events))
63
+ setHasMore(result.hasMore)
64
+ })
65
+ .catch((cause) => {
66
+ if (!controller.signal.aborted) setError(explain(cause))
67
+ })
68
+ .finally(() => {
69
+ if (!controller.signal.aborted) setLoading(false)
70
+ })
71
+
72
+ return () => controller.abort()
73
+ }, [history, documentId, before, nonce])
74
+
75
+ const loadMore = useCallback(() => {
76
+ setEvents((current) => {
77
+ const last = current[current.length - 1]
78
+ if (last) setBefore(last.occurred_at)
79
+ return current
80
+ })
81
+ }, [])
82
+
83
+ const refresh = useCallback(() => {
84
+ setBefore(undefined)
85
+ setNonce((value) => value + 1)
86
+ }, [])
87
+
88
+ return {events, loading, error, hasMore, loadMore, refresh}
89
+ }
@@ -0,0 +1,19 @@
1
+ import {useKitConfig} from '../context/KitContext'
2
+ import {useBoardLayout} from '../context/BoardLayoutContext'
3
+ import type {NcfInternalField} from '../config/types'
4
+
5
+ /**
6
+ * Colonnes de gestion interne effectives.
7
+ *
8
+ * Tant que personne n'y a touché, la configuration fournit le jeu de départ.
9
+ * Une fois réglées, celles du document font foi — y compris quand il n'en
10
+ * reste aucune, sinon supprimer la dernière les ferait toutes revenir.
11
+ *
12
+ * Toutes les vues doivent passer par ici : la liste, son regroupement et le
13
+ * board doivent proposer exactement les mêmes colonnes.
14
+ */
15
+ export function useInternalColumns(): NcfInternalField[] {
16
+ const config = useKitConfig()
17
+ const {columns, columnsSet} = useBoardLayout()
18
+ return columnsSet ? columns : config.internalFields
19
+ }
@@ -0,0 +1,15 @@
1
+ import {useMemo} from 'react'
2
+ import {useClient, type SanityClient} from 'sanity'
3
+
4
+ /** Figée : une montée de version d'API doit être un choix, pas un effet de bord. */
5
+ export const KIT_API_VERSION = '2026-09-01'
6
+
7
+ /**
8
+ * Client du kit. `perspective: 'raw'` est indispensable : la perspective par
9
+ * défaut masque les brouillons, et sans eux une page « modifiée » ou « jamais
10
+ * publiée » serait invisible dans la liste.
11
+ */
12
+ export function useKitClient(): SanityClient {
13
+ const client = useClient({apiVersion: KIT_API_VERSION})
14
+ return useMemo(() => client.withConfig({perspective: 'raw'}), [client])
15
+ }
@@ -0,0 +1,62 @@
1
+ import {useMemo} from 'react'
2
+ import {useSchema} from 'sanity'
3
+ import {useKitConfig} from '../context/KitContext'
4
+ import {PROJECTION} from '../lib/query'
5
+ import {blockTypesFromSchema, type BlockTypeInfo} from '../lib/schemaTypes'
6
+ import {occurrencesForTypes, type BlockOccurrence} from '../lib/occurrences'
7
+ import {usePageContents, CONTENT_SCAN_LIMIT} from './usePageContents'
8
+
9
+ export {CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT}
10
+
11
+ /** De quoi rendre une occurrence cliquable sans seconde requête. */
12
+ export interface OccurrencePage {
13
+ id: string
14
+ type: string
15
+ title: string
16
+ }
17
+
18
+ export interface OccurrencesState {
19
+ blockTypes: BlockTypeInfo[]
20
+ occurrences: BlockOccurrence[]
21
+ /** Pages indexées par identifiant, pour résoudre `documentIds`. */
22
+ pagesById: Map<string, OccurrencePage>
23
+ truncated: boolean
24
+ scanned: number
25
+ loading: boolean
26
+ error: Error | null
27
+ refresh: () => void
28
+ }
29
+
30
+ export function useOccurrences(): OccurrencesState {
31
+ const config = useKitConfig()
32
+ const schema = useSchema()
33
+ const {contents, truncated, scanned, loading, error, refresh} = usePageContents()
34
+
35
+ const blockTypes = useMemo(
36
+ () => blockTypesFromSchema(schema, config.pageTypes, config.pageBuilderField),
37
+ [schema, config.pageTypes, config.pageBuilderField],
38
+ )
39
+
40
+ const occurrences = useMemo(() => {
41
+ const inputs = [...contents.entries()].map(([id, doc]) => ({
42
+ _id: id,
43
+ blocks: doc[PROJECTION.blocks],
44
+ }))
45
+ return occurrencesForTypes(inputs, blockTypes.map((b) => b.name))
46
+ }, [contents, blockTypes])
47
+
48
+ const pagesById = useMemo(() => {
49
+ const map = new Map<string, OccurrencePage>()
50
+ for (const [id, doc] of contents) {
51
+ const title = doc[PROJECTION.title]
52
+ map.set(id, {
53
+ id,
54
+ type: doc._type,
55
+ title: (typeof title === 'string' ? title.trim() : '') || 'Sans titre',
56
+ })
57
+ }
58
+ return map
59
+ }, [contents])
60
+
61
+ return {blockTypes, occurrences, pagesById, truncated, scanned, loading, error, refresh}
62
+ }