@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,79 @@
1
+ import {useState} from 'react'
2
+ import {Box, Card, Flex, Stack, Text} from '@sanity/ui'
3
+ import {blockName, humanizeBlockName} from '../../lib/blocks'
4
+ import {MONO, TABULAR} from '../../ui/tokens'
5
+ import type {BlockOccurrence} from '../../lib/occurrences'
6
+ import type {BlockTypeInfo} from '../../lib/schemaTypes'
7
+
8
+ export interface BlockCardProps {
9
+ block: BlockTypeInfo
10
+ occurrence: BlockOccurrence
11
+ namespace: string
12
+ thumbnailUrl: string | null
13
+ }
14
+
15
+ /**
16
+ * Tuile d'un bloc dans la grille.
17
+ *
18
+ * Volontairement dépouillée : la capture, le nom, sa référence technique et
19
+ * le nombre d'occurrences. Le détail — pages, lien vers le design system —
20
+ * appartient à la carte, au clic : la grille sert à balayer le catalogue, pas
21
+ * à le lire.
22
+ */
23
+ export function BlockCard(props: BlockCardProps) {
24
+ const {block, occurrence, namespace, thumbnailUrl} = props
25
+ const [failed, setFailed] = useState(false)
26
+ const unused = occurrence.count === 0
27
+
28
+ return (
29
+ <Card radius={3} shadow={1} padding={0} style={{height: '100%', overflow: 'hidden'}}>
30
+ <Stack gap={0} style={{height: '100%'}}>
31
+ <Box
32
+ style={{
33
+ aspectRatio: '16 / 10',
34
+ overflow: 'hidden',
35
+ background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))',
36
+ }}
37
+ >
38
+ {thumbnailUrl && !failed ? (
39
+ <img
40
+ src={thumbnailUrl}
41
+ alt=""
42
+ loading="lazy"
43
+ onError={() => setFailed(true)}
44
+ style={{width: '100%', height: '100%', objectFit: 'contain', display: 'block'}}
45
+ />
46
+ ) : (
47
+ <Flex align="center" justify="center" style={{height: '100%'}} padding={3}>
48
+ <Text size={0} muted align="center">
49
+ {failed ? 'Capture introuvable' : 'Pas de capture'}
50
+ </Text>
51
+ </Flex>
52
+ )}
53
+ </Box>
54
+
55
+ <Box padding={3}>
56
+ <Flex align="baseline" justify="space-between" gap={3}>
57
+ <Stack gap={2} flex={1} style={{minWidth: 0}}>
58
+ <Text size={1} weight="medium" textOverflow="ellipsis">
59
+ {block.title || humanizeBlockName(block.name, namespace)}
60
+ </Text>
61
+ <Text size={0} muted textOverflow="ellipsis" style={MONO}>
62
+ {blockName(block.name, namespace)}
63
+ </Text>
64
+ </Stack>
65
+ <Text
66
+ size={1}
67
+ weight="medium"
68
+ muted={unused}
69
+ style={{...TABULAR, flex: 'none'}}
70
+ title={unused ? 'Jamais utilisé' : `${occurrence.count} occurrences`}
71
+ >
72
+ {occurrence.count}
73
+ </Text>
74
+ </Flex>
75
+ </Box>
76
+ </Stack>
77
+ </Card>
78
+ )
79
+ }
@@ -0,0 +1,171 @@
1
+ import {useMemo, useState} from 'react'
2
+ import {Box, Button, Card, Flex, Grid, Spinner, Stack, Text} from '@sanity/ui'
3
+ import {useKitConfig} from '../../context/KitContext'
4
+ import {useOccurrences, OCCURRENCE_SCAN_LIMIT} from '../../hooks/useOccurrences'
5
+ import {fillTemplate} from '../../lib/blocks'
6
+ import {QueryError} from '../../ui/QueryError'
7
+ import {BlockCard} from './BlockCard'
8
+ import {SectionsMap} from './map/SectionsMap'
9
+
10
+ type View = 'grid' | 'map'
11
+
12
+ type Order = 'type' | 'schema' | 'usage' | 'unused'
13
+
14
+ const ORDERS: {value: Order; label: string}[] = [
15
+ {value: 'type', label: 'Par type'},
16
+ {value: 'usage', label: 'Les plus utilisés'},
17
+ {value: 'unused', label: 'Les inutilisés d’abord'},
18
+ {value: 'schema', label: 'Ordre du schéma'},
19
+ ]
20
+
21
+ export function ComponentsTool() {
22
+ const config = useKitConfig()
23
+ const {blockTypes, occurrences, pagesById, truncated, scanned, loading, error, refresh} =
24
+ useOccurrences()
25
+ const [order, setOrder] = useState<Order>('type')
26
+ const [view, setView] = useState<View>('grid')
27
+
28
+ const preview = config.componentPreview
29
+ const canPreview = preview.provider === 'designSystemPage' && Boolean(config.previewUrl)
30
+
31
+ const cards = useMemo(() => {
32
+ const byName = new Map(blockTypes.map((b) => [b.name, b]))
33
+ const rows = occurrences
34
+ .map((occurrence) => ({occurrence, block: byName.get(occurrence.type)}))
35
+ .filter((row): row is {occurrence: (typeof occurrences)[number]; block: (typeof blockTypes)[number]} =>
36
+ Boolean(row.block),
37
+ )
38
+
39
+ if (order === 'schema') return rows
40
+ if (order === 'type') {
41
+ return [...rows].sort((a, b) => a.block.name.localeCompare(b.block.name, 'fr'))
42
+ }
43
+ if (order === 'unused') {
44
+ return [...rows].sort((a, b) => a.occurrence.count - b.occurrence.count)
45
+ }
46
+ return [...rows].sort((a, b) => b.occurrence.count - a.occurrence.count)
47
+ }, [occurrences, blockTypes, order])
48
+
49
+ const unusedCount = occurrences.filter((o) => o.count === 0).length
50
+
51
+ if (error) return <QueryError error={error} onRetry={refresh} />
52
+
53
+ if (loading && blockTypes.length === 0) {
54
+ return (
55
+ <Flex align="center" justify="center" padding={5} gap={3}>
56
+ <Spinner muted />
57
+ <Text size={1} muted>
58
+ Analyse du page builder…
59
+ </Text>
60
+ </Flex>
61
+ )
62
+ }
63
+
64
+ if (blockTypes.length === 0) {
65
+ return (
66
+ <Card padding={4} radius={3} shadow={1} tone="caution">
67
+ <Stack gap={3}>
68
+ <Text weight="semibold">Aucun bloc trouvé.</Text>
69
+ <Text size={1}>
70
+ Le champ « {config.pageBuilderField} » n’existe sur aucun des types{' '}
71
+ {config.pageTypeNames.join(', ')}, ou il n’est pas un tableau. Vérifie
72
+ `pageBuilderField` dans l’appel à ncfKit().
73
+ </Text>
74
+ </Stack>
75
+ </Card>
76
+ )
77
+ }
78
+
79
+ return (
80
+ <Stack gap={4}>
81
+ <Flex gap={2}>
82
+ <Button
83
+ text="Grille"
84
+ mode={view === 'grid' ? 'default' : 'ghost'}
85
+ fontSize={1}
86
+ padding={2}
87
+ onClick={() => setView('grid')}
88
+ />
89
+ <Button
90
+ text="Map"
91
+ mode={view === 'map' ? 'default' : 'ghost'}
92
+ fontSize={1}
93
+ padding={2}
94
+ onClick={() => setView('map')}
95
+ />
96
+ </Flex>
97
+
98
+ <Flex align="center" justify="space-between" gap={3} wrap="wrap">
99
+ <Text size={1} muted>
100
+ {blockTypes.length} blocs · {scanned} pages analysées
101
+ {unusedCount > 0 ? ` · ${unusedCount} jamais utilisé${unusedCount > 1 ? 's' : ''}` : ''}
102
+ </Text>
103
+
104
+ <Flex gap={2} wrap="wrap">
105
+ {ORDERS.filter((option) => view === 'grid' || option.value !== 'schema').map((option) => (
106
+ <Button
107
+ key={option.value}
108
+ mode={order === option.value ? 'default' : 'ghost'}
109
+ fontSize={1}
110
+ padding={2}
111
+ text={option.label}
112
+ onClick={() => setOrder(option.value)}
113
+ />
114
+ ))}
115
+ <Button
116
+ text="Rafraîchir"
117
+ mode="ghost"
118
+ fontSize={1}
119
+ padding={2}
120
+ onClick={refresh}
121
+ disabled={loading}
122
+ />
123
+ </Flex>
124
+ </Flex>
125
+
126
+ {/* Un comptage tronqué est un chiffre faux : il faut le dire. */}
127
+ {truncated && (
128
+ <Card padding={3} radius={2} tone="caution">
129
+ <Text size={1}>
130
+ Analyse limitée aux {OCCURRENCE_SCAN_LIMIT} premières pages : les chiffres
131
+ ci-dessous sont un minimum, pas un total.
132
+ </Text>
133
+ </Card>
134
+ )}
135
+
136
+ {!canPreview && (
137
+ <Card padding={3} radius={2} tone="transparent" border>
138
+ <Text size={1} muted>
139
+ Vignettes désactivées : renseigne `previewUrl` dans ncfKit() pour afficher les
140
+ captures du design system.
141
+ </Text>
142
+ </Card>
143
+ )}
144
+
145
+ {view === 'map' ? (
146
+ <SectionsMap
147
+ blockTypes={blockTypes}
148
+ occurrences={occurrences}
149
+ pagesById={pagesById}
150
+ order={order === 'schema' ? 'type' : order}
151
+ />
152
+ ) : (
153
+ <Grid gridTemplateColumns={[1, 2, 3, 4]} gap={3}>
154
+ {cards.map(({block, occurrence}) => (
155
+ <BlockCard
156
+ key={block.name}
157
+ block={block}
158
+ occurrence={occurrence}
159
+ namespace={config.blockNamespace}
160
+ thumbnailUrl={
161
+ canPreview
162
+ ? `${config.previewUrl}${fillTemplate(preview.thumbnail, block.name, config.blockNamespace)}`
163
+ : null
164
+ }
165
+ />
166
+ ))}
167
+ </Grid>
168
+ )}
169
+ </Stack>
170
+ )
171
+ }
@@ -0,0 +1,109 @@
1
+ import {memo, useState} from 'react'
2
+ import {useViewport, type Node, type NodeProps} from '@xyflow/react'
3
+ import {Box, Card, Flex, Stack, Text} from '@sanity/ui'
4
+ import type {BlockOccurrence} from '../../../lib/occurrences'
5
+ import type {BlockTypeInfo} from '../../../lib/schemaTypes'
6
+ import {blockName} from '../../../lib/blocks'
7
+ import {MONO, TABULAR} from '../../../ui/tokens'
8
+
9
+ export interface SectionNodeData extends Record<string, unknown> {
10
+ block: BlockTypeInfo
11
+ occurrence: BlockOccurrence
12
+ size: number
13
+ thumbnailUrl: string | null
14
+ /** Estompé quand une autre section est sélectionnée. */
15
+ dimmed: boolean
16
+ selected: boolean
17
+ /** Préfixe à retirer pour afficher la référence du bloc. */
18
+ namespace: string
19
+ }
20
+
21
+ export type SectionFlowNode = Node<SectionNodeData, 'section'>
22
+
23
+ /** Contre-échelle du texte : voir `textScaleFor` du nœud de page. */
24
+ const textScaleFor = (zoom: number): number => Math.min(2.4, Math.max(1, 1 / zoom))
25
+
26
+ function SectionNodeComponent(props: NodeProps<SectionFlowNode>) {
27
+ const {block, occurrence, size, thumbnailUrl, dimmed, selected, namespace} = props.data
28
+ const [failed, setFailed] = useState(false)
29
+ const {zoom} = useViewport()
30
+ const textScale = textScaleFor(zoom)
31
+ const unused = occurrence.count === 0
32
+
33
+ return (
34
+ <Card
35
+ radius={3}
36
+ shadow={selected ? 3 : dimmed ? 0 : 2}
37
+ padding={0}
38
+ tone={unused ? 'caution' : 'default'}
39
+ style={{
40
+ width: size,
41
+ height: size,
42
+ overflow: 'hidden',
43
+ opacity: dimmed ? 0.3 : 1,
44
+ transition: 'opacity 120ms ease',
45
+ cursor: 'pointer',
46
+ outline: selected ? '2px solid var(--card-focus-ring-color, #2276fc)' : 'none',
47
+ }}
48
+ >
49
+ <Flex direction="column" style={{height: '100%'}}>
50
+ <Box
51
+ flex={1}
52
+ style={{
53
+ overflow: 'hidden',
54
+ minHeight: 0,
55
+ background: 'var(--card-muted-bg-color, rgba(127,127,127,0.12))',
56
+ }}
57
+ >
58
+ {thumbnailUrl && !failed ? (
59
+ <img
60
+ src={thumbnailUrl}
61
+ alt=""
62
+ loading="lazy"
63
+ onError={() => setFailed(true)}
64
+ style={{width: '100%', height: '100%', objectFit: 'contain', display: 'block'}}
65
+ />
66
+ ) : (
67
+ <Flex align="center" justify="center" style={{height: '100%'}} padding={2}>
68
+ <Text size={0} muted align="center">
69
+ {failed ? 'Capture introuvable' : 'Pas de capture'}
70
+ </Text>
71
+ </Flex>
72
+ )}
73
+ </Box>
74
+ <Box padding={2} style={{flex: 'none'}}>
75
+ <Flex align="flex-start" justify="space-between" gap={2}>
76
+ <Stack gap={1} flex={1} style={{minWidth: 0}}>
77
+ <Text
78
+ size={0}
79
+ weight="medium"
80
+ textOverflow="ellipsis"
81
+ style={{fontSize: Math.round(11 * textScale), lineHeight: 1.3}}
82
+ >
83
+ {block.title}
84
+ </Text>
85
+ {/* La référence technique, celle qu'on cite dans le code. */}
86
+ <Text
87
+ size={0}
88
+ muted
89
+ textOverflow="ellipsis"
90
+ style={{...MONO, fontSize: Math.round(10 * textScale), lineHeight: 1.3}}
91
+ >
92
+ {blockName(block.name, namespace)}
93
+ </Text>
94
+ </Stack>
95
+ <Text
96
+ size={0}
97
+ muted
98
+ style={{...TABULAR, fontSize: Math.round(11 * textScale), lineHeight: 1.3, flex: 'none'}}
99
+ >
100
+ {occurrence.count}
101
+ </Text>
102
+ </Flex>
103
+ </Box>
104
+ </Flex>
105
+ </Card>
106
+ )
107
+ }
108
+
109
+ export const SectionNode = memo(SectionNodeComponent)
@@ -0,0 +1,339 @@
1
+ import {useCallback, useEffect, useMemo, useState} from 'react'
2
+ import {
3
+ Background,
4
+ Controls,
5
+ ReactFlow,
6
+ ReactFlowProvider,
7
+ useNodesState,
8
+ useReactFlow,
9
+ type NodeChange,
10
+ } from '@xyflow/react'
11
+ import '@xyflow/react/dist/style.css'
12
+ import {Box, Button, Card, Flex, Stack, Text} from '@sanity/ui'
13
+ import {IntentLink} from 'sanity/router'
14
+ import {AddIcon} from '@sanity/icons/Add'
15
+ import {useKitConfig} from '../../../context/KitContext'
16
+ import {useBoardLayout} from '../../../context/BoardLayoutContext'
17
+ import {blockName, fillTemplate} from '../../../lib/blocks'
18
+ import {MONO} from '../../../ui/tokens'
19
+ import {CloseIcon} from '@sanity/icons/Close'
20
+ import {LaunchIcon} from '@sanity/icons/Launch'
21
+ import {layoutSectionsMap, type SectionOrder} from '../../../lib/sectionsMap'
22
+ import type {BlockOccurrence} from '../../../lib/occurrences'
23
+ import type {BlockTypeInfo} from '../../../lib/schemaTypes'
24
+ import type {OccurrencePage} from '../../../hooks/useOccurrences'
25
+ import {SectionNode, type SectionFlowNode, type SectionNodeData} from './SectionNode'
26
+ import {AnnotationNode, type AnnotationFlowNode} from '../../shared/AnnotationNode'
27
+ import {useAnnotations} from '../../../hooks/useAnnotations'
28
+
29
+ const nodeTypes = {section: SectionNode, annotation: AnnotationNode}
30
+
31
+ /** Le canvas mélange les sections et les annotations posées derrière elles. */
32
+ type MapFlowNode = SectionFlowNode | AnnotationFlowNode
33
+
34
+ const isSectionNode = (node: MapFlowNode): node is SectionFlowNode => node.type === 'section'
35
+
36
+ const FLOW_THEME: React.CSSProperties = {
37
+ width: '100%',
38
+ height: '100%',
39
+ ['--xy-background-color' as string]: 'var(--card-bg-color)',
40
+ ['--xy-controls-button-background-color' as string]: 'var(--card-bg-color)',
41
+ ['--xy-controls-button-background-color-hover' as string]: 'var(--card-muted-bg-color, rgba(127,127,127,0.2))',
42
+ ['--xy-controls-button-color' as string]: 'var(--card-fg-color)',
43
+ ['--xy-controls-button-border-color' as string]: 'var(--card-border-color, rgba(127,127,127,0.25))',
44
+ ['--xy-attribution-background-color' as string]: 'transparent',
45
+ }
46
+
47
+ export interface SectionsMapProps {
48
+ blockTypes: readonly BlockTypeInfo[]
49
+ occurrences: readonly BlockOccurrence[]
50
+ pagesById: Map<string, OccurrencePage>
51
+ order: SectionOrder
52
+ }
53
+
54
+ function MapCanvas(props: SectionsMapProps) {
55
+ const {blockTypes, occurrences, pagesById, order} = props
56
+ const config = useKitConfig()
57
+ const {sectionsByName, loading, saveError, saveSections, resetSections} = useBoardLayout()
58
+
59
+ // Sélection au clic, pas au survol : un panneau qui disparaît dès qu'on
60
+ // bouge la souris interdit de cliquer les pages qu'il liste.
61
+ const [selected, setSelected] = useState<string | null>(null)
62
+ const {screenToFlowPosition} = useReactFlow()
63
+ const {annotations, add: addAnnotation, update: updateAnnotation, remove: removeAnnotation} =
64
+ useAnnotations('sections')
65
+ const [nodes, setNodes, onNodesChange] = useNodesState<MapFlowNode>([])
66
+
67
+ const preview = config.componentPreview
68
+ const canPreview = preview.provider === 'designSystemPage' && Boolean(config.previewUrl)
69
+
70
+ const placed = useMemo(
71
+ () => layoutSectionsMap(blockTypes, occurrences, {order}),
72
+ [blockTypes, occurrences, order],
73
+ )
74
+
75
+ useEffect(() => {
76
+ if (loading) return
77
+ setNodes(
78
+ placed.map((entry) => {
79
+ const saved = sectionsByName.get(entry.id)
80
+ const data: SectionNodeData = {
81
+ block: entry.block,
82
+ occurrence: entry.occurrence,
83
+ size: entry.size,
84
+ thumbnailUrl: canPreview
85
+ ? `${config.previewUrl}${fillTemplate(preview.thumbnail, entry.block.name, config.blockNamespace)}`
86
+ : null,
87
+ dimmed: false,
88
+ selected: false,
89
+ namespace: config.blockNamespace,
90
+ }
91
+ return {
92
+ id: entry.id,
93
+ type: 'section' as const,
94
+ position: saved ? {x: saved.x, y: saved.y} : entry.position,
95
+ data,
96
+ }
97
+ }),
98
+ )
99
+ // `sectionsByName` volontairement absent : enregistrer une position ne
100
+ // doit pas replacer les tuiles sous les doigts de l'utilisateur.
101
+ // eslint-disable-next-line react-hooks/exhaustive-deps
102
+ }, [placed, canPreview, config.previewUrl, config.blockNamespace, preview.thumbnail, loading, setNodes])
103
+
104
+
105
+ // La mise en avant passe par les données du nœud : React Flow ne relaie pas
106
+ // la sélection d'un nœud aux autres.
107
+ useEffect(() => {
108
+ setNodes((current) =>
109
+ current.map((node): MapFlowNode => {
110
+ // Une annotation ne se sélectionne pas comme une section.
111
+ if (!isSectionNode(node)) return node
112
+ return {
113
+ ...node,
114
+ data: {
115
+ ...node.data,
116
+ dimmed: selected !== null && node.id !== selected,
117
+ selected: node.id === selected,
118
+ },
119
+ }
120
+ }),
121
+ )
122
+ }, [selected, setNodes])
123
+
124
+ const handleNodesChange = useCallback(
125
+ (changes: NodeChange<MapFlowNode>[]) => {
126
+ const dropped = changes.filter(
127
+ (change) => change.type === 'position' && change.dragging === false,
128
+ )
129
+ // Les annotations vivent dans la disposition, pas dans l'état des nœuds.
130
+ for (const change of dropped) {
131
+ if (change.type !== 'position' || !change.position) continue
132
+ const annotation = annotations.find((a) => a.id === change.id)
133
+ if (annotation) {
134
+ updateAnnotation(annotation.id, {
135
+ x: Math.round(change.position.x),
136
+ y: Math.round(change.position.y),
137
+ })
138
+ }
139
+ }
140
+
141
+ onNodesChange(
142
+ changes.filter(
143
+ (change) => !('id' in change) || !annotations.some((a) => a.id === change.id),
144
+ ),
145
+ )
146
+
147
+ if (dropped.length > 0) {
148
+ setNodes((current) => {
149
+ saveSections(
150
+ current.filter(isSectionNode).map((node) => ({
151
+ blockName: node.id,
152
+ x: node.position.x,
153
+ y: node.position.y,
154
+ })),
155
+ )
156
+ return current
157
+ })
158
+ }
159
+ },
160
+ [onNodesChange, saveSections, setNodes, annotations, updateAnnotation],
161
+ )
162
+
163
+ const rearrange = useCallback(() => {
164
+ setNodes((current) => {
165
+ const byId = new Map(placed.map((entry) => [entry.id, entry.position]))
166
+ return current.map((node) => ({...node, position: byId.get(node.id) ?? node.position}))
167
+ })
168
+ resetSections()
169
+ }, [placed, resetSections, setNodes])
170
+
171
+ const allNodes = useMemo<MapFlowNode[]>(
172
+ () => [
173
+ ...annotations.map((annotation) => ({
174
+ id: annotation.id,
175
+ type: 'annotation' as const,
176
+ position: {x: annotation.x, y: annotation.y},
177
+ // Derrière les tuiles : une annotation commente la carte.
178
+ zIndex: -1,
179
+ data: {annotation, onChange: updateAnnotation, onRemove: removeAnnotation},
180
+ })),
181
+ ...nodes.filter(isSectionNode),
182
+ ],
183
+ [annotations, updateAnnotation, removeAnnotation, nodes],
184
+ )
185
+
186
+ const selectedEntry = placed.find((entry) => entry.id === selected)
187
+ const designSystemUrl =
188
+ canPreview && selectedEntry
189
+ ? `${config.previewUrl}${preview.path}#${fillTemplate(preview.anchor, selectedEntry.block.name, config.blockNamespace)}`
190
+ : null
191
+ const selectedPages = (selectedEntry?.occurrence.documentIds ?? [])
192
+ .map((id) => pagesById.get(id))
193
+ .filter((page): page is OccurrencePage => Boolean(page))
194
+
195
+ return (
196
+ <Stack gap={3}>
197
+ <Flex gap={2} align="center" wrap="wrap">
198
+ <Button
199
+ text="Réorganiser automatiquement"
200
+ mode="ghost"
201
+ fontSize={1}
202
+ padding={2}
203
+ onClick={rearrange}
204
+ />
205
+ <Button
206
+ icon={AddIcon}
207
+ text="Note"
208
+ mode="ghost"
209
+ fontSize={1}
210
+ padding={2}
211
+ onClick={() => addAnnotation('text', screenToFlowPosition({x: 240, y: 260}))}
212
+ />
213
+ <Button
214
+ icon={AddIcon}
215
+ text="Forme"
216
+ mode="ghost"
217
+ fontSize={1}
218
+ padding={2}
219
+ onClick={() => addAnnotation('rect', screenToFlowPosition({x: 300, y: 320}))}
220
+ />
221
+ <Text size={0} muted>
222
+ Glisser une tuile enregistre sa position · cliquer affiche ses pages
223
+ </Text>
224
+ </Flex>
225
+
226
+ {saveError && (
227
+ <Card padding={3} radius={2} tone="critical">
228
+ <Text size={1}>La disposition n’a pas pu être enregistrée : {saveError.message}</Text>
229
+ </Card>
230
+ )}
231
+
232
+ <Flex gap={3} align="stretch">
233
+ <Card radius={3} shadow={1} style={{flex: 1, height: '70vh', overflow: 'hidden'}}>
234
+ <Box style={FLOW_THEME}>
235
+ <ReactFlow<MapFlowNode>
236
+ nodes={allNodes}
237
+ edges={[]}
238
+ nodeTypes={nodeTypes}
239
+ onNodesChange={handleNodesChange}
240
+ fitView
241
+ nodesConnectable={false}
242
+ minZoom={0.2}
243
+ maxZoom={2}
244
+ // Le clic passe par le canvas : React Flow enveloppe chaque nœud,
245
+ // et un gestionnaire posé sur la carte peut ne jamais le voir.
246
+ onNodeClick={(_event, node) => {
247
+ if (!isSectionNode(node)) return
248
+ setSelected((current) => (current === node.id ? null : node.id))
249
+ }}
250
+ onPaneClick={() => setSelected(null)}
251
+ >
252
+ <Background gap={24} size={1} />
253
+ <Controls showInteractive={false} />
254
+ </ReactFlow>
255
+ </Box>
256
+ </Card>
257
+
258
+ <Card
259
+ radius={3}
260
+ shadow={1}
261
+ padding={3}
262
+ style={{width: 280, flex: 'none', height: '70vh', overflow: 'auto'}}
263
+ >
264
+ {selectedEntry ? (
265
+ <Stack gap={3}>
266
+ <Flex align="flex-start" justify="space-between" gap={2}>
267
+ <Stack gap={2} flex={1} style={{minWidth: 0}}>
268
+ <Text size={1} weight="medium">
269
+ {selectedEntry.block.title}
270
+ </Text>
271
+ <Text size={0} muted textOverflow="ellipsis" style={MONO}>
272
+ {blockName(selectedEntry.block.name, config.blockNamespace)}
273
+ </Text>
274
+ </Stack>
275
+ <Button
276
+ mode="bleed"
277
+ padding={1}
278
+ fontSize={0}
279
+ icon={CloseIcon}
280
+ aria-label="Fermer"
281
+ onClick={() => setSelected(null)}
282
+ />
283
+ </Flex>
284
+ <Text size={0} muted>
285
+ {selectedEntry.occurrence.count === 0
286
+ ? 'Jamais utilisé sur le site.'
287
+ : `${selectedPages.length} page${selectedPages.length > 1 ? 's' : ''} · ${selectedEntry.occurrence.count} instance${selectedEntry.occurrence.count > 1 ? 's' : ''}`}
288
+ </Text>
289
+ <Stack gap={2}>
290
+ {selectedPages.map((page) => (
291
+ <IntentLink
292
+ key={page.id}
293
+ intent="edit"
294
+ params={{id: page.id, type: page.type}}
295
+ style={{textDecoration: 'none', color: 'inherit'}}
296
+ >
297
+ <Text size={1} textOverflow="ellipsis">
298
+ {page.title}
299
+ </Text>
300
+ </IntentLink>
301
+ ))}
302
+ </Stack>
303
+
304
+ {designSystemUrl && (
305
+ <Box>
306
+ <Button
307
+ as="a"
308
+ href={designSystemUrl}
309
+ target="_blank"
310
+ rel="noreferrer"
311
+ mode="ghost"
312
+ fontSize={1}
313
+ padding={2}
314
+ icon={LaunchIcon}
315
+ text="Voir sur le design system"
316
+ />
317
+ </Box>
318
+ )}
319
+ </Stack>
320
+ ) : (
321
+ <Flex align="center" justify="center" style={{height: '100%'}}>
322
+ <Text size={0} muted align="center">
323
+ Cliquer une section pour voir les pages qui l’utilisent.
324
+ </Text>
325
+ </Flex>
326
+ )}
327
+ </Card>
328
+ </Flex>
329
+ </Stack>
330
+ )
331
+ }
332
+
333
+ export function SectionsMap(props: SectionsMapProps) {
334
+ return (
335
+ <ReactFlowProvider>
336
+ <MapCanvas {...props} />
337
+ </ReactFlowProvider>
338
+ )
339
+ }