@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,661 @@
1
+ import {useCallback, useEffect, useMemo, useRef, useState} from 'react'
2
+ import {
3
+ Background,
4
+ Controls,
5
+ MiniMap,
6
+ ReactFlow,
7
+ ReactFlowProvider,
8
+ useEdgesState,
9
+ useNodesState,
10
+ useReactFlow,
11
+ MarkerType,
12
+ type Edge,
13
+ type NodeChange,
14
+ } from '@xyflow/react'
15
+ import '@xyflow/react/dist/style.css'
16
+ import {Box, Button, Card, Flex, Select, Spinner, Stack, Text} from '@sanity/ui'
17
+ import {useRouter} from 'sanity/router'
18
+ import {applySavedPositions, buildLinkGraph} from '../../../lib/graph'
19
+ import {pageThumbnailUrl} from '../../../lib/pageThumbnail'
20
+ import {colorForRow, type ColorBy} from '../../../lib/colors'
21
+ import {PagePanel} from './PagePanel'
22
+ import {
23
+ defaultNodeSize,
24
+ fallbackLayout,
25
+ layoutGraph,
26
+ type LayoutMode,
27
+ } from '../../../lib/elkLayout'
28
+ import {STATUS_LABELS, type PageStatus} from '../../../lib/status'
29
+ import {useBoardLayout} from '../../../context/BoardLayoutContext'
30
+ import {useInternalColumns} from '../../../hooks/useInternalColumns'
31
+ import {useColumnOptions} from '../../../hooks/useColumnOptions'
32
+ import {usePageContents} from '../../../hooks/usePageContents'
33
+ import {AddIcon} from '@sanity/icons/Add'
34
+ import {useKitConfig} from '../../../context/KitContext'
35
+ import {QueryError} from '../../../ui/QueryError'
36
+ import type {PageRow} from '../../../lib/pages'
37
+ import {PageNode, type PageFlowNode, type PageNodeData} from './PageNode'
38
+ import {AnnotationNode, type AnnotationFlowNode} from '../../shared/AnnotationNode'
39
+ import {useAnnotations} from '../../../hooks/useAnnotations'
40
+
41
+ const nodeTypes = {page: PageNode, annotation: AnnotationNode}
42
+
43
+ /** Le canvas mélange les pages et les annotations posées derrière elles. */
44
+ type BoardFlowNode = PageFlowNode | AnnotationFlowNode
45
+
46
+ const isPageNode = (node: BoardFlowNode): node is PageFlowNode => node.type === 'page'
47
+
48
+ /** Couleurs de la minimap, alignées sur les tons des badges de statut. */
49
+ const MINIMAP_COLORS: Record<PageStatus, string> = {
50
+ published: '#43d675',
51
+ modified: '#f5a623',
52
+ draft: '#8a8a8a',
53
+ }
54
+
55
+ /**
56
+ * React Flow s'habille via ses propres variables CSS. On les branche sur
57
+ * celles du thème Sanity pour que le board suive le mode clair/sombre du
58
+ * Studio au lieu d'imposer un rectangle blanc.
59
+ */
60
+ const FLOW_THEME: React.CSSProperties = {
61
+ width: '100%',
62
+ height: '100%',
63
+ ['--xy-background-color' as string]: 'var(--card-bg-color)',
64
+ ['--xy-edge-stroke' as string]: 'var(--card-border-color, rgba(127,127,127,0.4))',
65
+ ['--xy-edge-stroke-selected' as string]: 'var(--card-focus-ring-color, #2276fc)',
66
+ ['--xy-minimap-background-color' as string]: 'var(--card-muted-bg-color, rgba(127,127,127,0.12))',
67
+ ['--xy-minimap-mask-background-color' as string]: 'rgba(127,127,127,0.25)',
68
+ ['--xy-controls-button-background-color' as string]: 'var(--card-bg-color)',
69
+ ['--xy-controls-button-background-color-hover' as string]: 'var(--card-muted-bg-color, rgba(127,127,127,0.2))',
70
+ ['--xy-controls-button-color' as string]: 'var(--card-fg-color)',
71
+ ['--xy-controls-button-color-hover' as string]: 'var(--card-fg-color)',
72
+ ['--xy-controls-button-border-color' as string]: 'var(--card-border-color, rgba(127,127,127,0.25))',
73
+ ['--xy-attribution-background-color' as string]: 'transparent',
74
+ }
75
+
76
+ export interface BoardViewProps {
77
+ rows: readonly PageRow[]
78
+ /** Choisi par les onglets : arborescence ou cerveau. */
79
+ mode: LayoutMode
80
+ colorBy: ColorBy
81
+ /**
82
+ * Chemin vers l'aperçu d'une page, selon la cible choisie dans la barre.
83
+ *
84
+ * Passé en prop et non recalculé ici : deux appels au même hook auraient
85
+ * chacun leur état, et basculer dans la barre ne changerait rien au board.
86
+ */
87
+ pathFor: (url: string | null) => string | null
88
+ }
89
+
90
+ function Board(props: BoardViewProps) {
91
+ const {rows, mode, colorBy, pathFor} = props
92
+ const router = useRouter()
93
+ const config = useKitConfig()
94
+ const {contents, loading: contentsLoading, error, refresh} = usePageContents()
95
+ // Les colonnes réglées dans la liste, pas celles de la configuration : les
96
+ // deux vues doivent proposer les mêmes critères de couleur.
97
+ const columns = useInternalColumns()
98
+ const columnOptions = useColumnOptions()
99
+ const {byId, loading: layoutLoading, saveError, savePositions, patchNode, patchField, reset} =
100
+ useBoardLayout()
101
+
102
+ const [selectedId, setSelectedId] = useState<string | null>(null)
103
+ const [hoveredId, setHoveredId] = useState<string | null>(null)
104
+ const [tagFilter, setTagFilter] = useState('')
105
+ const [arranging, setArranging] = useState(false)
106
+
107
+ const {screenToFlowPosition} = useReactFlow()
108
+ const {annotations, add: addAnnotation, update: updateAnnotation, remove: removeAnnotation} =
109
+ useAnnotations('pages')
110
+ const [nodes, setNodes, onNodesChange] = useNodesState<BoardFlowNode>([])
111
+ // `onEdgesChange` complète le contrôle du flux : React Flow attend le
112
+ // couple prop + gestionnaire pour chacune des deux collections.
113
+ const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([])
114
+
115
+ const graph = useMemo(() => buildLinkGraph(rows, contents), [rows, contents])
116
+
117
+ const openPage = useCallback(
118
+ (row: {id: string; type: string; url: string | null}) => {
119
+ const path = pathFor(row.url)
120
+ if (path) router.navigateUrl({path})
121
+ else router.navigateIntent('edit', {id: row.id, type: row.type})
122
+ },
123
+ [router, pathFor],
124
+ )
125
+
126
+ const onTag = useCallback(
127
+ (documentId: string, tag: string | null) => patchNode(documentId, {tag: tag ?? undefined}),
128
+ [patchNode],
129
+ )
130
+ const onResize = useCallback(
131
+ (documentId: string, size: {width: number; height: number}) => patchNode(documentId, size),
132
+ [patchNode],
133
+ )
134
+
135
+ /**
136
+ * Taille d'un nœud : la taille choisie à la main d'abord, sinon celle qui
137
+ * fait tenir la capture entière, sinon le gabarit par défaut.
138
+ */
139
+ const sizeOf = useCallback(
140
+ (id: string) => {
141
+ const saved = byId.get(id)
142
+ const fallback = defaultNodeSize(mode, Boolean(config.pageThumbnail))
143
+ return {
144
+ width: saved?.width ?? fallback.width,
145
+ height: saved?.height ?? fallback.height,
146
+ }
147
+ },
148
+ [byId, mode, config.pageThumbnail],
149
+ )
150
+
151
+ const sizeOfRef = useRef(sizeOf)
152
+ sizeOfRef.current = sizeOf
153
+
154
+ const buildNodes = useCallback(
155
+ (placements: {id: string; position: {x: number; y: number}}[]): PageFlowNode[] => {
156
+ const byNodeId = new Map(graph.nodes.map((node) => [node.id, node]))
157
+ return placements
158
+ .map((placement): PageFlowNode | null => {
159
+ const node = byNodeId.get(placement.id)
160
+ if (!node) return null
161
+ const saved = byId.get(placement.id)
162
+ const data: PageNodeData = {
163
+ row: node.row,
164
+ mode,
165
+ tag: saved?.tag ?? null,
166
+ tags: config.boardTags,
167
+ color: colorForRow(node.row, colorBy, {
168
+ meta: byId,
169
+ tags: config.boardTags,
170
+ fields: columns,
171
+ }).color,
172
+ dimmed: false,
173
+ width: sizeOf(placement.id).width,
174
+ height: sizeOf(placement.id).height,
175
+ thumbnailUrl: pageThumbnailUrl(config.pageThumbnail, config.previewUrl, {
176
+ path: node.row.path,
177
+ locale: node.row.locale,
178
+ id: node.id,
179
+ }),
180
+ degree: node.incoming + node.outgoing,
181
+ onTag,
182
+ onResize,
183
+ }
184
+ // Tailles portées par le nœud lui-même, pas seulement par ses
185
+ // données : React Flow ne trace une arête que lorsqu'il connaît les
186
+ // dimensions de ses deux extrémités. En les lui donnant, on ne
187
+ // dépend plus de sa mesure du DOM — le canvas restait sans aucun
188
+ // lien tant qu'elle n'était pas faite.
189
+ const size = sizeOf(placement.id)
190
+ return {
191
+ id: placement.id,
192
+ type: 'page' as const,
193
+ position: placement.position,
194
+ width: size.width,
195
+ height: size.height,
196
+ data,
197
+ }
198
+ })
199
+ .filter((node): node is PageFlowNode => node !== null)
200
+ },
201
+ [
202
+ graph.nodes,
203
+ byId,
204
+ mode,
205
+ colorBy,
206
+ config.boardTags,
207
+ columns,
208
+ config.pageThumbnail,
209
+ config.previewUrl,
210
+ onTag,
211
+ onResize,
212
+ sizeOf,
213
+ ],
214
+ )
215
+
216
+ // Placement : layout automatique, puis positions manuelles par-dessus.
217
+ useEffect(() => {
218
+ if (layoutLoading) return
219
+ let cancelled = false
220
+
221
+ const run = async () => {
222
+ const sizes = new Map(graph.nodes.map((node) => [node.id, sizeOfRef.current(node.id)]))
223
+
224
+ const withScreenshots = Boolean(config.pageThumbnail)
225
+ let computed
226
+ try {
227
+ computed = await layoutGraph(graph.nodes, graph.edges, {mode, sizes, withScreenshots})
228
+ } catch {
229
+ // elkjs indisponible ou en échec : une grille vaut mieux qu'un tas.
230
+ computed = fallbackLayout(graph.nodes, mode, withScreenshots)
231
+ }
232
+ if (cancelled) return
233
+
234
+ setNodes(buildNodes(applySavedPositions(computed, [...byId.values()])))
235
+ }
236
+
237
+ void run()
238
+ return () => {
239
+ cancelled = true
240
+ }
241
+ // `byId` volontairement absent des dépendances : enregistrer une position
242
+ // ne doit pas relancer le layout sous les doigts de l'utilisateur.
243
+ // eslint-disable-next-line react-hooks/exhaustive-deps
244
+ }, [graph, mode, layoutLoading, setNodes, config.pageThumbnail])
245
+
246
+ /**
247
+ * Les arêtes dérivent du seul graphe.
248
+ *
249
+ * Elles étaient posées à la fin du calcul de placement, qui est asynchrone
250
+ * et s'annule dès qu'une dépendance bouge : une annulation les emportait, et
251
+ * le canvas restait sans aucun lien. Elles sont désormais synchrones, donc
252
+ * toujours présentes.
253
+ */
254
+ useEffect(() => {
255
+ setEdges(
256
+ graph.edges.map((edge) => ({
257
+ id: edge.id,
258
+ source: edge.source,
259
+ target: edge.target,
260
+ // Courbe libre : un maillage de liens se suit beaucoup mieux qu'une
261
+ // série de coudes à angle droit, qui se superposent vite.
262
+ type: mode === 'brain' ? 'straight' : 'default',
263
+ animated: false,
264
+ // Sans flèche, rien ne distingue un lien entrant d'un lien sortant.
265
+ markerEnd: {type: MarkerType.ArrowClosed, width: 14, height: 14},
266
+ })),
267
+ )
268
+ }, [graph.edges, mode, setEdges])
269
+
270
+ // Étiquettes et tailles doivent se refléter sans recalculer le placement.
271
+ useEffect(() => {
272
+ setNodes((current) =>
273
+ current.map((node): BoardFlowNode => {
274
+ // Les annotations n'ont ni étiquette ni couleur de critère.
275
+ if (!isPageNode(node)) return node
276
+ const saved = byId.get(node.id)
277
+ return {
278
+ ...node,
279
+ data: {
280
+ ...node.data,
281
+ mode,
282
+ tag: saved?.tag ?? null,
283
+ color: colorForRow(node.data.row, colorBy, {
284
+ meta: byId,
285
+ tags: config.boardTags,
286
+ fields: columns,
287
+ }).color,
288
+ width: sizeOf(node.id).width,
289
+ height: sizeOf(node.id).height,
290
+ },
291
+ }
292
+ }),
293
+ )
294
+ }, [byId, mode, colorBy, config.boardTags, columns, sizeOf, setNodes])
295
+
296
+ const annotationNodes = useMemo<AnnotationFlowNode[]>(
297
+ () =>
298
+ annotations.map((annotation) => ({
299
+ id: annotation.id,
300
+ type: 'annotation' as const,
301
+ position: {x: annotation.x, y: annotation.y},
302
+ // Derrière les pages : une annotation commente le board, elle ne le
303
+ // recouvre pas.
304
+ zIndex: -1,
305
+ data: {annotation, onChange: updateAnnotation, onRemove: removeAnnotation},
306
+ })),
307
+ [annotations, updateAnnotation, removeAnnotation],
308
+ )
309
+
310
+ /**
311
+ * Page mise en évidence : le survol prime, mais la sélection persiste.
312
+ * Sans ça, cliquer une page pour ouvrir sa fiche éteignait ses liens dès
313
+ * que la souris quittait le nœud.
314
+ */
315
+ const focusedId = hoveredId ?? selectedId
316
+
317
+ /** Voisins directs de chaque page, dans les deux sens. */
318
+ const neighbours = useMemo(() => {
319
+ const map = new Map<string, Set<string>>()
320
+ const link = (a: string, b: string) => {
321
+ const set = map.get(a) ?? new Set<string>()
322
+ set.add(b)
323
+ map.set(a, set)
324
+ }
325
+ for (const edge of graph.edges) {
326
+ link(edge.source, edge.target)
327
+ link(edge.target, edge.source)
328
+ }
329
+ return map
330
+ }, [graph.edges])
331
+
332
+ const visibleNodes = useMemo(() => {
333
+ const pages = tagFilter
334
+ ? nodes.filter((node) => isPageNode(node) && node.data.tag === tagFilter)
335
+ : nodes.filter(isPageNode)
336
+ return [...annotationNodes, ...pages]
337
+ }, [nodes, tagFilter, annotationNodes])
338
+ const visibleEdges = useMemo(() => {
339
+ if (!tagFilter) return edges
340
+ const kept = new Set(visibleNodes.filter(isPageNode).map((node) => node.id))
341
+ return edges.filter((edge) => kept.has(edge.source) && kept.has(edge.target))
342
+ }, [edges, visibleNodes, tagFilter])
343
+
344
+ /**
345
+ * Mise en évidence du voisinage, en CSS.
346
+ *
347
+ * La piloter par les données recréait tous les nœuds et toutes les arêtes à
348
+ * chaque mouvement de souris : avec des cartes d'un millier de pixels, le
349
+ * canvas se figeait. React Flow pose un `data-id` sur chaque élément, une
350
+ * feuille de style suffit donc, et le survol ne touche plus aucun état de
351
+ * rendu.
352
+ */
353
+ const focusCss = useMemo(() => {
354
+ const escape = (value: string) => value.replace(/["\\]/g, '\\$&')
355
+ const edgePath = (id: string) =>
356
+ `.ncf-flow .react-flow__edge[data-id="${escape(id)}"] .react-flow__edge-path`
357
+
358
+ /**
359
+ * Sens des liens, au clic seulement.
360
+ *
361
+ * Les tirets défilent de la source vers la cible : on lit d'un coup d'œil
362
+ * ce qui pointe vers la page et ce qu'elle pointe. Réservé à la page
363
+ * sélectionnée — animer tout un maillage au survol repeignait le canvas en
364
+ * continu.
365
+ */
366
+ const directionCss = selectedId
367
+ ? [
368
+ '@keyframes ncf-dash { to { stroke-dashoffset: -20; } }',
369
+ `${graph.edges
370
+ .filter((edge) => edge.source === selectedId || edge.target === selectedId)
371
+ .map((edge) => edgePath(edge.id))
372
+ .join(', ')} { stroke-dasharray: 6 5; animation: ncf-dash 700ms linear infinite; }`,
373
+ ].join('\n')
374
+ : ''
375
+
376
+ if (!focusedId) return directionCss
377
+
378
+ const lit = [focusedId, ...(neighbours.get(focusedId) ?? [])]
379
+ const litEdges = graph.edges
380
+ .filter((edge) => edge.source === focusedId || edge.target === focusedId)
381
+ .map((edge) => edge.id)
382
+
383
+ return [
384
+ directionCss,
385
+ `.ncf-flow[data-focused] .react-flow__node { opacity: 0.15; transition: opacity 120ms ease; }`,
386
+ `.ncf-flow[data-focused] .react-flow__edge { opacity: 0.12; transition: opacity 120ms ease; }`,
387
+ lit.length > 0 &&
388
+ `${lit.map((id) => `.ncf-flow[data-focused] .react-flow__node[data-id="${escape(id)}"]`).join(', ')} { opacity: 1; }`,
389
+ litEdges.length > 0 &&
390
+ `${litEdges.map((id) => `.ncf-flow[data-focused] .react-flow__edge[data-id="${escape(id)}"]`).join(', ')} { opacity: 1; }`,
391
+ litEdges.length > 0 &&
392
+ `${litEdges
393
+ .map(
394
+ (id) =>
395
+ `.ncf-flow[data-focused] .react-flow__edge[data-id="${escape(id)}"] .react-flow__edge-path`,
396
+ )
397
+ .join(', ')} { stroke: var(--card-focus-ring-color, #2276fc); stroke-width: 2.5; }`,
398
+ ]
399
+ .filter(Boolean)
400
+ .join('\n')
401
+ }, [focusedId, selectedId, neighbours, graph.edges])
402
+
403
+ const handleNodesChange = useCallback(
404
+ (changes: NodeChange<BoardFlowNode>[]) => {
405
+ const dropped = changes.filter(
406
+ (change) => change.type === 'position' && change.dragging === false,
407
+ )
408
+ // Une annotation déplacée ne passe pas par l'état des nœuds : elle vit
409
+ // dans la disposition, séparément des pages.
410
+ for (const change of dropped) {
411
+ if (change.type !== 'position' || !change.position) continue
412
+ const annotation = annotations.find((a) => a.id === change.id)
413
+ if (annotation) {
414
+ updateAnnotation(annotation.id, {
415
+ x: Math.round(change.position.x),
416
+ y: Math.round(change.position.y),
417
+ })
418
+ }
419
+ }
420
+
421
+ // Les annotations ne sont pas dans l'état des nœuds : leurs changements
422
+ // n'ont rien à y faire. `NodeAddChange` n'a pas d'`id`, d'où le garde.
423
+ onNodesChange(
424
+ changes.filter(
425
+ (change) => !('id' in change) || !annotations.some((a) => a.id === change.id),
426
+ ),
427
+ )
428
+
429
+ // On n'enregistre qu'à la fin du geste, pas à chaque pixel parcouru.
430
+ if (dropped.length > 0) {
431
+ setNodes((current) => {
432
+ savePositions(
433
+ current.filter(isPageNode).map((node) => ({
434
+ documentId: node.id,
435
+ x: Math.round(node.position.x),
436
+ y: Math.round(node.position.y),
437
+ })),
438
+ graph.nodes.map((node) => node.id),
439
+ )
440
+ return current
441
+ })
442
+ }
443
+ },
444
+ [onNodesChange, savePositions, setNodes, graph.nodes, annotations, updateAnnotation],
445
+ )
446
+
447
+ const rearrange = useCallback(async () => {
448
+ setArranging(true)
449
+ try {
450
+ const withScreenshots = Boolean(config.pageThumbnail)
451
+ const computed = await layoutGraph(graph.nodes, graph.edges, {
452
+ mode,
453
+ withScreenshots,
454
+ sizes: new Map(graph.nodes.map((node) => [node.id, sizeOf(node.id)])),
455
+ }).catch(() => fallbackLayout(graph.nodes, mode, withScreenshots))
456
+ setNodes(buildNodes(computed))
457
+ reset()
458
+ } finally {
459
+ setArranging(false)
460
+ }
461
+ }, [graph, mode, buildNodes, setNodes, reset, config.pageThumbnail, sizeOf])
462
+
463
+ if (error) return <QueryError error={error} onRetry={refresh} />
464
+
465
+ if (layoutLoading || (contentsLoading && graph.nodes.length === 0)) {
466
+ return (
467
+ <Flex align="center" justify="center" padding={5} gap={3}>
468
+ <Spinner muted />
469
+ <Text size={1} muted>
470
+ Analyse des liens entre les pages…
471
+ </Text>
472
+ </Flex>
473
+ )
474
+ }
475
+
476
+ const size = defaultNodeSize(mode, Boolean(config.pageThumbnail))
477
+ const legend: {key: string; label: string; color: string}[] =
478
+ colorBy === 'tag'
479
+ ? config.boardTags.map((tag) => ({key: tag.id, label: tag.label, color: tag.color}))
480
+ : colorBy === 'status'
481
+ ? (Object.keys(MINIMAP_COLORS) as PageStatus[]).map((status) => ({
482
+ key: status,
483
+ label: STATUS_LABELS[status].label,
484
+ color: MINIMAP_COLORS[status],
485
+ }))
486
+ : (columns
487
+ .find((field) => `field:${field.id}` === colorBy)
488
+ ?.options?.filter((option) => option.color)
489
+ .map((option) => ({
490
+ key: option.id,
491
+ label: option.label,
492
+ color: option.color as string,
493
+ })) ?? [])
494
+
495
+ const selectedNode = graph.nodes.find((node) => node.id === selectedId) ?? null
496
+ const selectedColor = selectedNode
497
+ ? colorForRow(selectedNode.row, colorBy, {
498
+ meta: byId,
499
+ tags: config.boardTags,
500
+ fields: columns,
501
+ })
502
+ : {color: null, label: null}
503
+
504
+ return (
505
+ <Stack gap={3}>
506
+ <Flex gap={2} align="center" wrap="wrap">
507
+ <Box style={{width: 180, flex: 'none'}}>
508
+ <Select
509
+ fontSize={1}
510
+ value={tagFilter}
511
+ onChange={(event) => setTagFilter(event.currentTarget.value)}
512
+ >
513
+ <option value="">Toutes les étiquettes</option>
514
+ {config.boardTags.map((tag) => (
515
+ <option key={tag.id} value={tag.id}>
516
+ {tag.label}
517
+ </option>
518
+ ))}
519
+ </Select>
520
+ </Box>
521
+ <Button
522
+ icon={AddIcon}
523
+ text="Note"
524
+ mode="ghost"
525
+ fontSize={1}
526
+ padding={2}
527
+ onClick={() => addAnnotation('text', screenToFlowPosition({x: 240, y: 260}))}
528
+ />
529
+ <Button
530
+ icon={AddIcon}
531
+ text="Forme"
532
+ mode="ghost"
533
+ fontSize={1}
534
+ padding={2}
535
+ onClick={() => addAnnotation('rect', screenToFlowPosition({x: 300, y: 320}))}
536
+ />
537
+ <Button
538
+ text={arranging ? 'Réorganisation…' : 'Réorganiser automatiquement'}
539
+ mode="ghost"
540
+ fontSize={1}
541
+ padding={2}
542
+ disabled={arranging}
543
+ onClick={() => void rearrange()}
544
+ />
545
+ <Text size={0} muted>
546
+ {visibleNodes.length} pages · {graph.edges.length} liens
547
+ {graph.orphans.length > 0 ? ` · ${graph.orphans.length} sans aucun lien` : ''}
548
+ </Text>
549
+ </Flex>
550
+
551
+ {saveError && (
552
+ <Card padding={3} radius={2} tone="critical">
553
+ <Text size={1}>La disposition n’a pas pu être enregistrée : {saveError.message}</Text>
554
+ </Card>
555
+ )}
556
+
557
+ {graph.duplicatePaths.length > 0 && (
558
+ <Card padding={3} radius={2} tone="caution">
559
+ <Text size={1}>
560
+ Plusieurs pages partagent le même chemin ({graph.duplicatePaths.join(', ')}).
561
+ Un lien vers ce chemin ne peut en désigner qu’une.
562
+ </Text>
563
+ </Card>
564
+ )}
565
+
566
+ <Flex gap={3} align="stretch">
567
+ <Card radius={3} shadow={1} style={{flex: 1, height: '70vh', overflow: 'hidden'}}>
568
+ <style>{focusCss}</style>
569
+ <Box className="ncf-flow" data-focused={focusedId ?? undefined} style={FLOW_THEME}>
570
+ <ReactFlow<BoardFlowNode>
571
+ nodes={visibleNodes}
572
+ edges={visibleEdges}
573
+ nodeTypes={nodeTypes}
574
+ onNodesChange={handleNodesChange}
575
+ onEdgesChange={onEdgesChange}
576
+ onNodeClick={(_event, node) => setSelectedId(isPageNode(node) ? node.id : null)}
577
+ onNodeMouseEnter={(_event, node) => setHoveredId(isPageNode(node) ? node.id : null)}
578
+ onNodeMouseLeave={() => setHoveredId(null)}
579
+ onPaneClick={() => setSelectedId(null)}
580
+ onNodeDoubleClick={(_event, node) => {
581
+ if (isPageNode(node)) openPage(node.data.row)
582
+ }}
583
+ fitView
584
+ // Au-delà de quelques dizaines de nœuds, ne monter que le visible
585
+ // change tout, surtout avec les aperçus.
586
+ onlyRenderVisibleElements
587
+ minZoom={0.1}
588
+ maxZoom={2}
589
+ nodeOrigin={mode === 'brain' ? [0.5, 0.5] : [0, 0]}
590
+ >
591
+ <Background gap={24} size={1} />
592
+ <Controls showInteractive={false} />
593
+ <MiniMap
594
+ pannable
595
+ zoomable
596
+ nodeColor={(node) => {
597
+ const candidate = node as BoardFlowNode
598
+ if (!isPageNode(candidate)) return 'transparent'
599
+ return candidate.data.color ?? MINIMAP_COLORS[candidate.data.row.status]
600
+ }}
601
+ nodeStrokeWidth={2}
602
+ nodeBorderRadius={mode === 'brain' ? size.width : 4}
603
+ />
604
+ </ReactFlow>
605
+ </Box>
606
+ </Card>
607
+
608
+ {selectedNode && (
609
+ <PagePanel
610
+ row={selectedNode.row}
611
+ thumbnailUrl={pageThumbnailUrl(config.pageThumbnail, config.previewUrl, {
612
+ path: selectedNode.row.path,
613
+ locale: selectedNode.row.locale,
614
+ id: selectedNode.id,
615
+ })}
616
+ tag={byId.get(selectedNode.id)?.tag ?? null}
617
+ tags={config.boardTags}
618
+ colorLabel={selectedColor.label}
619
+ color={selectedColor.color}
620
+ incoming={selectedNode.incoming}
621
+ outgoing={selectedNode.outgoing}
622
+ columns={columns}
623
+ values={byId.get(selectedNode.id)?.fields ?? {}}
624
+ onTag={onTag}
625
+ onField={patchField}
626
+ {...columnOptions}
627
+ onOpen={() => openPage(selectedNode.row)}
628
+ onClose={() => setSelectedId(null)}
629
+ />
630
+ )}
631
+ </Flex>
632
+
633
+ {/* La légende suit le critère de couleur : afficher les étiquettes
634
+ pendant qu'on colore par statut induirait en erreur. */}
635
+ <Flex gap={3} wrap="wrap" align="center">
636
+ {legend.map((item) => (
637
+ <Flex key={item.key} gap={2} align="center">
638
+ <Box style={{width: 10, height: 10, borderRadius: 2, background: item.color}} />
639
+ <Text size={0} muted>
640
+ {item.label}
641
+ </Text>
642
+ </Flex>
643
+ ))}
644
+ <Text size={0} muted>
645
+ {legend.length === 0 ? 'Couleur déduite de la valeur saisie · ' : '· '}
646
+ clic pour la fiche, double-clic pour ouvrir la page
647
+ </Text>
648
+ </Flex>
649
+ </Stack>
650
+ )
651
+ }
652
+
653
+ export function BoardView(props: BoardViewProps) {
654
+ // React Flow exige son contexte au-dessus de tout composant qui lit le
655
+ // viewport — les nœuds le font pour décider de charger leur aperçu.
656
+ return (
657
+ <ReactFlowProvider>
658
+ <Board {...props} />
659
+ </ReactFlowProvider>
660
+ )
661
+ }