@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,238 @@
1
+ import type {PageRow} from './pages'
2
+ import {collectLinks} from './links'
3
+ import {baseId} from './status'
4
+
5
+ export interface BoardNode {
6
+ /** Identifiant du document, réutilisé comme identifiant de nœud. */
7
+ id: string
8
+ row: PageRow
9
+ /** Nombre de pages qui pointent vers celle-ci. */
10
+ incoming: number
11
+ /** Nombre de pages vers lesquelles elle pointe. */
12
+ outgoing: number
13
+ /** Distance depuis une page sans lien entrant. Sert au placement de repli. */
14
+ depth: number
15
+ }
16
+
17
+ export interface BoardEdge {
18
+ id: string
19
+ source: string
20
+ target: string
21
+ }
22
+
23
+ export interface BoardGraph {
24
+ nodes: BoardNode[]
25
+ edges: BoardEdge[]
26
+ /** Pages sans chemin calculable : elles n'ont pas d'adresse à relier. */
27
+ unplaced: PageRow[]
28
+ /** Chemins portés par plusieurs pages, à signaler plutôt qu'à masquer. */
29
+ duplicatePaths: string[]
30
+ /** Pages sans aucun lien entrant ni sortant. */
31
+ orphans: string[]
32
+ }
33
+
34
+ /**
35
+ * Graphe des liens réels entre pages.
36
+ *
37
+ * Une arête existe quand le contenu d'une page pointe vers une autre, par
38
+ * chemin (`/contact`) ou par référence. La hiérarchie des slugs n'intervient
39
+ * pas : deux pages voisines dans l'URL mais jamais liées restent séparées, et
40
+ * une page que rien ne lie apparaît isolée — c'est une information, pas un défaut.
41
+ */
42
+ export function buildLinkGraph(
43
+ rows: readonly PageRow[],
44
+ contents: ReadonlyMap<string, unknown>,
45
+ ): BoardGraph {
46
+ const placed = rows.filter((row) => row.path !== null)
47
+ const unplaced = rows.filter((row) => row.path === null)
48
+
49
+ const byPath = new Map<string, string>()
50
+ const duplicates = new Set<string>()
51
+ for (const row of placed) {
52
+ const path = row.path as string
53
+ if (byPath.has(path)) duplicates.add(path)
54
+ else byPath.set(path, row.id)
55
+ }
56
+
57
+ const knownIds = new Set(placed.map((row) => row.id))
58
+ const incoming = new Map<string, number>()
59
+ const outgoing = new Map<string, number>()
60
+ const seen = new Set<string>()
61
+ const edges: BoardEdge[] = []
62
+
63
+ for (const row of placed) {
64
+ const {paths, refs} = collectLinks(contents.get(row.id))
65
+
66
+ const targets = new Set<string>()
67
+ for (const path of paths) {
68
+ const target = byPath.get(path)
69
+ if (target) targets.add(target)
70
+ }
71
+ for (const ref of refs) {
72
+ // Une référence peut viser un brouillon : on ramène à l'identifiant publié.
73
+ const target = baseId(ref)
74
+ if (knownIds.has(target)) targets.add(target)
75
+ }
76
+ targets.delete(row.id) // un lien d'une page vers elle-même n'apprend rien
77
+
78
+ for (const target of targets) {
79
+ const id = `${row.id}->${target}`
80
+ if (seen.has(id)) continue
81
+ seen.add(id)
82
+ edges.push({id, source: row.id, target})
83
+ outgoing.set(row.id, (outgoing.get(row.id) ?? 0) + 1)
84
+ incoming.set(target, (incoming.get(target) ?? 0) + 1)
85
+ }
86
+ }
87
+
88
+ const depths = computeDepths(placed.map((row) => row.id), edges, incoming)
89
+
90
+ const nodes: BoardNode[] = placed.map((row) => ({
91
+ id: row.id,
92
+ row,
93
+ incoming: incoming.get(row.id) ?? 0,
94
+ outgoing: outgoing.get(row.id) ?? 0,
95
+ depth: depths.get(row.id) ?? 0,
96
+ }))
97
+
98
+ return {
99
+ nodes,
100
+ edges,
101
+ unplaced,
102
+ duplicatePaths: [...duplicates].sort(),
103
+ orphans: nodes.filter((n) => n.incoming === 0 && n.outgoing === 0).map((n) => n.id),
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Profondeur par parcours en largeur depuis les pages sans lien entrant.
109
+ * Les cycles et les pages inatteignables restent à zéro plutôt que de faire
110
+ * boucler le calcul.
111
+ */
112
+ function computeDepths(
113
+ ids: readonly string[],
114
+ edges: readonly BoardEdge[],
115
+ incoming: ReadonlyMap<string, number>,
116
+ ): Map<string, number> {
117
+ const children = new Map<string, string[]>()
118
+ for (const edge of edges) {
119
+ children.set(edge.source, [...(children.get(edge.source) ?? []), edge.target])
120
+ }
121
+
122
+ const depths = new Map<string, number>()
123
+ const queue: string[] = ids.filter((id) => (incoming.get(id) ?? 0) === 0)
124
+ for (const id of queue) depths.set(id, 0)
125
+
126
+ while (queue.length > 0) {
127
+ const current = queue.shift() as string
128
+ const depth = depths.get(current) ?? 0
129
+ for (const child of children.get(current) ?? []) {
130
+ if (depths.has(child)) continue
131
+ depths.set(child, depth + 1)
132
+ queue.push(child)
133
+ }
134
+ }
135
+
136
+ for (const id of ids) if (!depths.has(id)) depths.set(id, 0)
137
+ return depths
138
+ }
139
+
140
+ /* --- Disposition enregistrée --- */
141
+
142
+ /**
143
+ * Position, taille et étiquette d'un nœud, telles qu'enregistrées.
144
+ *
145
+ * `x` et `y` sont **absents** tant que le nœud n'a pas été déplacé à la main.
146
+ * Les inventer à zéro faisait passer « jamais positionné » pour « positionné à
147
+ * l'origine », et toutes ces pages s'empilaient au coin du canvas.
148
+ */
149
+ export interface NodeLayout {
150
+ documentId: string
151
+ x?: number
152
+ y?: number
153
+ /** Taille choisie à la main, absente tant que le nœud n'a pas été redimensionné. */
154
+ width?: number
155
+ height?: number
156
+ /** Identifiant d'étiquette de suivi, ex. 'a-relire'. */
157
+ tag?: string
158
+ /** Valeurs des champs de gestion interne, par identifiant de champ. */
159
+ fields?: Record<string, string>
160
+ }
161
+
162
+ /**
163
+ * Note ou forme posée sur un canvas, derrière les nœuds. Sert à commenter une
164
+ * zone du board ou de la carte sans toucher au contenu.
165
+ */
166
+ export interface Annotation {
167
+ id: string
168
+ /** Canvas auquel la note appartient. */
169
+ scope: 'pages' | 'sections'
170
+ kind: 'text' | 'rect'
171
+ x: number
172
+ y: number
173
+ width: number
174
+ height: number
175
+ text?: string
176
+ color?: string
177
+ }
178
+
179
+ /** Position manuelle d'une section sur la carte des composants. */
180
+ export interface SectionLayout {
181
+ blockName: string
182
+ x: number
183
+ y: number
184
+ }
185
+
186
+ /** Compatibilité : une position seule reste un `NodeLayout` valide. */
187
+ export type NodePosition = NodeLayout
188
+
189
+ export interface Positioned {
190
+ id: string
191
+ position: {x: number; y: number}
192
+ }
193
+
194
+ /**
195
+ * Applique les positions enregistrées par-dessus celles du placement
196
+ * automatique. Une page déplacée à la main garde sa place ; une page ajoutée
197
+ * depuis prend celle que le layout lui a calculée.
198
+ */
199
+ export function applySavedPositions(
200
+ computed: readonly Positioned[],
201
+ saved: readonly NodeLayout[],
202
+ ): Positioned[] {
203
+ const overrides = new Map(saved.map((entry) => [entry.documentId, entry]))
204
+ return computed.map((node) => {
205
+ const override = overrides.get(node.id)
206
+ // Une entrée sans coordonnées ne porte qu'une étiquette ou des valeurs de
207
+ // suivi : le placement automatique garde la main.
208
+ return override && Number.isFinite(override.x) && Number.isFinite(override.y)
209
+ ? {id: node.id, position: {x: override.x as number, y: override.y as number}}
210
+ : node
211
+ })
212
+ }
213
+
214
+ /** Ne conserve que les entrées de pages encore existantes. */
215
+ export function pruneSavedPositions(
216
+ saved: readonly NodeLayout[],
217
+ existingIds: readonly string[],
218
+ ): NodeLayout[] {
219
+ const alive = new Set(existingIds)
220
+ return saved.filter((entry) => alive.has(entry.documentId))
221
+ }
222
+
223
+ /** Fusionne une modification dans la disposition, sans perdre le reste. */
224
+ export function upsertLayout(
225
+ saved: readonly NodeLayout[],
226
+ documentId: string,
227
+ patch: Partial<Omit<NodeLayout, 'documentId'>>,
228
+ ): NodeLayout[] {
229
+ const index = saved.findIndex((entry) => entry.documentId === documentId)
230
+ if (index === -1) {
231
+ // Surtout pas de position par défaut : étiqueter une page ne doit pas la
232
+ // déplacer.
233
+ return [...saved, {documentId, ...patch}]
234
+ }
235
+ const next = [...saved]
236
+ next[index] = {...(saved[index] as NodeLayout), ...patch}
237
+ return next
238
+ }
@@ -0,0 +1,116 @@
1
+ import type {NcfBoardTag, NcfInternalField} from '../config/types'
2
+ import type {NodeLayout} from './graph'
3
+ import type {PageRow} from './pages'
4
+ import {STATUS_LABELS} from './status'
5
+
6
+ /** Critère de regroupement de la liste des pages. */
7
+ export type GroupBy = 'none' | 'tag' | 'type' | 'status' | 'indexation' | `field:${string}`
8
+
9
+ export interface RowGroup {
10
+ /** Valeur brute du critère, ou `''` quand elle n'est pas renseignée. */
11
+ key: string
12
+ label: string
13
+ /** Couleur associée, pour les étiquettes et les choix qui en ont une. */
14
+ color?: string
15
+ rows: PageRow[]
16
+ }
17
+
18
+ export const UNSET_LABEL = 'Non renseigné'
19
+
20
+ export interface GroupOptions {
21
+ /** Disposition enregistrée, qui porte étiquettes et champs internes. */
22
+ meta: ReadonlyMap<string, NodeLayout>
23
+ tags: readonly NcfBoardTag[]
24
+ fields: readonly NcfInternalField[]
25
+ }
26
+
27
+ const fieldIdOf = (groupBy: GroupBy): string | null =>
28
+ groupBy.startsWith('field:') ? groupBy.slice('field:'.length) : null
29
+
30
+ /** Valeur du critère pour une ligne. Chaîne vide = non renseigné. */
31
+ export function groupValue(row: PageRow, groupBy: GroupBy, options: GroupOptions): string {
32
+ if (groupBy === 'type') return row.type
33
+ if (groupBy === 'status') return row.status
34
+ if (groupBy === 'indexation') return row.noindex ? 'noindex' : 'indexable'
35
+ const entry = options.meta.get(row.id)
36
+ if (groupBy === 'tag') return entry?.tag ?? ''
37
+ const fieldId = fieldIdOf(groupBy)
38
+ if (fieldId) return entry?.fields?.[fieldId] ?? ''
39
+ return ''
40
+ }
41
+
42
+ function describe(
43
+ value: string,
44
+ groupBy: GroupBy,
45
+ options: GroupOptions,
46
+ ): {label: string; color?: string} {
47
+ if (!value) return {label: UNSET_LABEL}
48
+ if (groupBy === 'status') return {label: STATUS_LABELS[row_status(value)].label}
49
+ if (groupBy === 'indexation') {
50
+ return value === 'noindex' ? {label: 'Non indexable'} : {label: 'Indexable'}
51
+ }
52
+ if (groupBy === 'tag') {
53
+ const tag = options.tags.find((t) => t.id === value)
54
+ return tag ? {label: tag.label, color: tag.color} : {label: value}
55
+ }
56
+ const fieldId = fieldIdOf(groupBy)
57
+ if (fieldId) {
58
+ const field = options.fields.find((f) => f.id === fieldId)
59
+ const choice = field?.options?.find((o) => o.id === value)
60
+ if (choice) return choice.color ? {label: choice.label, color: choice.color} : {label: choice.label}
61
+ }
62
+ return {label: value}
63
+ }
64
+
65
+ // Le statut est une union fermée : on la restreint avant d'indexer.
66
+ const row_status = (value: string): keyof typeof STATUS_LABELS =>
67
+ value in STATUS_LABELS ? (value as keyof typeof STATUS_LABELS) : 'published'
68
+
69
+ /**
70
+ * Regroupe les lignes selon le critère choisi.
71
+ *
72
+ * L'ordre des groupes suit celui de la configuration (étiquettes, options
73
+ * d'un champ) pour rester stable d'une visite à l'autre, et le groupe « non
74
+ * renseigné » ferme la marche : c'est une absence, pas une catégorie.
75
+ */
76
+ export function groupPageRows(
77
+ rows: readonly PageRow[],
78
+ groupBy: GroupBy,
79
+ options: GroupOptions,
80
+ ): RowGroup[] {
81
+ if (groupBy === 'none') return [{key: '', label: '', rows: [...rows]}]
82
+
83
+ const buckets = new Map<string, PageRow[]>()
84
+ for (const row of rows) {
85
+ const value = groupValue(row, groupBy, options)
86
+ buckets.set(value, [...(buckets.get(value) ?? []), row])
87
+ }
88
+
89
+ const configured =
90
+ groupBy === 'tag'
91
+ ? options.tags.map((tag) => tag.id)
92
+ : (() => {
93
+ const fieldId = fieldIdOf(groupBy)
94
+ const field = fieldId ? options.fields.find((f) => f.id === fieldId) : undefined
95
+ return field?.options?.map((option) => option.id) ?? []
96
+ })()
97
+
98
+ const seen = new Set<string>()
99
+ const ordered: string[] = []
100
+ for (const value of configured) {
101
+ if (buckets.has(value)) {
102
+ ordered.push(value)
103
+ seen.add(value)
104
+ }
105
+ }
106
+ for (const value of [...buckets.keys()].sort((a, b) => a.localeCompare(b, 'fr'))) {
107
+ if (value && !seen.has(value)) ordered.push(value)
108
+ }
109
+ if (buckets.has('')) ordered.push('')
110
+
111
+ return ordered.map((value) => ({
112
+ key: value,
113
+ ...describe(value, groupBy, options),
114
+ rows: buckets.get(value) ?? [],
115
+ }))
116
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Détection des liens réels entre pages.
3
+ *
4
+ * Deux formes sont reconnues, sans rien supposer du schéma du client :
5
+ *
6
+ * - les **chaînes de chemin** (`href: "/contact"`), convention du starter, y
7
+ * compris dans les annotations de texte riche ;
8
+ * - les **références Sanity** (`_ref`) vers un document de page, pour les
9
+ * projets qui lient par référence.
10
+ *
11
+ * Un chemin n'est retenu que s'il correspond à une page connue : les liens
12
+ * externes, les ancres, `mailto:` et les chemins morts disparaissent d'eux-mêmes.
13
+ */
14
+
15
+ const IGNORED_PREFIXES = ['//', 'http://', 'https://', 'mailto:', 'tel:', 'data:', '#']
16
+
17
+ /**
18
+ * Normalise une valeur en chemin interne comparable, ou `null`.
19
+ * `/contact?x=1#bas` → `/contact` · `/services/` → `/services`
20
+ */
21
+ export function normalizeInternalPath(value: unknown): string | null {
22
+ if (typeof value !== 'string') return null
23
+ const trimmed = value.trim()
24
+ if (!trimmed.startsWith('/')) return null
25
+ if (IGNORED_PREFIXES.some((prefix) => trimmed.startsWith(prefix))) return null
26
+
27
+ const withoutHash = trimmed.split('#')[0] ?? ''
28
+ const withoutQuery = withoutHash.split('?')[0] ?? ''
29
+ if (!withoutQuery.startsWith('/')) return null
30
+
31
+ const withoutTrailing = withoutQuery.length > 1
32
+ ? withoutQuery.replace(/\/+$/, '')
33
+ : withoutQuery
34
+ return withoutTrailing === '' ? '/' : withoutTrailing
35
+ }
36
+
37
+ export interface CollectedLinks {
38
+ paths: string[]
39
+ refs: string[]
40
+ }
41
+
42
+ /**
43
+ * Parcourt une valeur de document et relève tout ce qui ressemble à un lien
44
+ * interne. Ne filtre pas sur le nom du champ : un client peut appeler son
45
+ * champ `href`, `url`, `lien` ou le nicher dans du texte riche.
46
+ */
47
+ export function collectLinks(value: unknown): CollectedLinks {
48
+ const paths = new Set<string>()
49
+ const refs = new Set<string>()
50
+
51
+ const walk = (node: unknown): void => {
52
+ if (Array.isArray(node)) {
53
+ for (const item of node) walk(item)
54
+ return
55
+ }
56
+ if (node === null || typeof node !== 'object') {
57
+ const path = normalizeInternalPath(node)
58
+ if (path) paths.add(path)
59
+ return
60
+ }
61
+
62
+ const ref = (node as {_ref?: unknown})._ref
63
+ if (typeof ref === 'string' && ref) refs.add(ref)
64
+
65
+ for (const child of Object.values(node)) walk(child)
66
+ }
67
+
68
+ walk(value)
69
+ return {paths: [...paths], refs: [...refs]}
70
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Comptage des blocs du page builder, imbriqués compris.
3
+ *
4
+ * Le parcours descend dans tout ce qu'il rencontre (tableaux, objets), parce
5
+ * qu'un bloc conteneur peut porter ses enfants à n'importe quelle profondeur :
6
+ * `section.columns` → `columns[]` → `blocks[]` → `section.cta`.
7
+ */
8
+
9
+ export interface BlockOccurrence {
10
+ type: string
11
+ /** Nombre d'instances, toutes profondeurs confondues. */
12
+ count: number
13
+ /** Identifiants des documents où le bloc apparaît, sans doublon. */
14
+ documentIds: string[]
15
+ }
16
+
17
+ export interface OccurrenceInput {
18
+ _id: string
19
+ /** Contenu du champ page builder. */
20
+ blocks: unknown
21
+ }
22
+
23
+ export interface CollectOptions {
24
+ /**
25
+ * Types considérés comme des blocs. Nécessaire : sans cette liste on
26
+ * compterait aussi les objets internes d'un bloc (`faqItem`, `column`,
27
+ * `block`, `span`, `image`...).
28
+ */
29
+ blockTypes: readonly string[]
30
+ }
31
+
32
+ /** Compte les blocs par type sur un ensemble de documents. */
33
+ export function collectOccurrences(
34
+ docs: readonly OccurrenceInput[],
35
+ options: CollectOptions,
36
+ ): Map<string, BlockOccurrence> {
37
+ const known = new Set(options.blockTypes)
38
+ const result = new Map<string, BlockOccurrence>()
39
+ // Set intermédiaire : l'unicité par document doit être bon marché.
40
+ const seenPerType = new Map<string, Set<string>>()
41
+
42
+ for (const doc of docs) {
43
+ walk(doc.blocks, (type) => {
44
+ if (!known.has(type)) return
45
+
46
+ const entry = result.get(type) ?? {type, count: 0, documentIds: []}
47
+ entry.count += 1
48
+ result.set(type, entry)
49
+
50
+ const seen = seenPerType.get(type) ?? new Set<string>()
51
+ if (!seen.has(doc._id)) {
52
+ seen.add(doc._id)
53
+ seenPerType.set(type, seen)
54
+ entry.documentIds.push(doc._id)
55
+ }
56
+ })
57
+ }
58
+
59
+ return result
60
+ }
61
+
62
+ /** Appelle `visit` pour chaque `_type` rencontré, à toute profondeur. */
63
+ function walk(value: unknown, visit: (type: string) => void): void {
64
+ if (Array.isArray(value)) {
65
+ for (const item of value) walk(item, visit)
66
+ return
67
+ }
68
+ if (value === null || typeof value !== 'object') return
69
+
70
+ const type = (value as {_type?: unknown})._type
71
+ if (typeof type === 'string') visit(type)
72
+
73
+ for (const child of Object.values(value)) walk(child, visit)
74
+ }
75
+
76
+ /**
77
+ * Occurrences de tous les types connus, y compris ceux à zéro — ce sont eux
78
+ * qui intéressent le plus (blocs déclarés mais jamais utilisés).
79
+ */
80
+ export function occurrencesForTypes(
81
+ docs: readonly OccurrenceInput[],
82
+ blockTypes: readonly string[],
83
+ ): BlockOccurrence[] {
84
+ const counted = collectOccurrences(docs, {blockTypes})
85
+ return blockTypes.map(
86
+ (type) => counted.get(type) ?? {type, count: 0, documentIds: []},
87
+ )
88
+ }
89
+
90
+ /** Nombre de blocs de premier niveau d'une page (colonne « blocs » de la liste). */
91
+ export function topLevelBlockCount(blocks: unknown): number {
92
+ return Array.isArray(blocks) ? blocks.length : 0
93
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * URL de la capture d'une page.
3
+ *
4
+ * Le nom de fichier est dérivé du chemin, pas du titre : c'est la seule clé
5
+ * stable entre le Studio et le script qui produit les captures.
6
+ * `/services/plomberie` → `services-plomberie` · `/` → `home`
7
+ */
8
+ export function slugKey(path: string): string {
9
+ const trimmed = path.replace(/^\/+|\/+$/g, '')
10
+ if (!trimmed) return 'home'
11
+ return trimmed
12
+ .replace(/\//g, '-')
13
+ .replace(/[^a-zA-Z0-9\-_]/g, '-')
14
+ .replace(/-+/g, '-')
15
+ .replace(/^-|-$/g, '')
16
+ }
17
+
18
+ export interface ThumbnailInput {
19
+ path: string | null
20
+ locale?: string | null
21
+ id: string
22
+ }
23
+
24
+ /**
25
+ * Résout le gabarit. Renvoie `null` si aucune capture n'est configurée ou si
26
+ * la page n'a pas de chemin : le board retombe alors sur l'iframe en direct.
27
+ */
28
+ export function pageThumbnailUrl(
29
+ template: string | null,
30
+ previewUrl: string | null,
31
+ input: ThumbnailInput,
32
+ ): string | null {
33
+ if (!template || input.path === null) return null
34
+
35
+ const filled = template
36
+ .replaceAll('{slug}', slugKey(input.path))
37
+ .replaceAll('{locale}', input.locale ?? '')
38
+ .replaceAll('{id}', input.id)
39
+
40
+ if (/^https?:\/\//i.test(filled)) return filled
41
+ if (!previewUrl) return null
42
+ return `${previewUrl}${filled.startsWith('/') ? filled : `/${filled}`}`
43
+ }