@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,290 @@
1
+ /**
2
+ * Configuration publique du plugin. Tout est optionnel sauf `pageTypes` :
3
+ * le kit ne doit rien savoir du contenu d'un projet client.
4
+ */
5
+
6
+ /** Un type de document considéré comme une page du site. */
7
+ export interface NcfPageTypeInput {
8
+ /** Nom du type de document Sanity (ex. 'page'). */
9
+ type: string
10
+ /**
11
+ * Champ de type `slug` portant l'URL. Hérite de `slugField` global.
12
+ * Mettre à `null` pour un type sans slug : `path` devient obligatoire.
13
+ */
14
+ slugField?: string | null
15
+ /**
16
+ * Chemin fixe, pour les pages sans slug (ex. l'accueil : '/').
17
+ * Prioritaire sur `slugField` quand les deux sont renseignés.
18
+ */
19
+ path?: string
20
+ /**
21
+ * Préfixe d'URL placé devant le slug, pour les collections servies sous un
22
+ * répertoire : `pathPrefix: '/blog'` donne `/blog/<slug>`. Sans effet avec
23
+ * `path`. C'est la clé `pathPrefix` du registre `site-routes.json` du starter.
24
+ */
25
+ pathPrefix?: string
26
+ /** Champ portant le titre affiché. Hérite de `titleField` global. */
27
+ titleField?: string
28
+ }
29
+
30
+ export type NcfPageTypeConfig = string | NcfPageTypeInput
31
+
32
+ /** Sites multilingues (ex. @sanity/document-internationalization). */
33
+ export interface NcfI18nConfig {
34
+ /** Champ portant le code de langue sur le document. */
35
+ field?: string
36
+ /** Langue servie à la racine, sans préfixe d'URL. */
37
+ defaultLocale?: string
38
+ /** Langues attendues. Vide = déduites des documents rencontrés. */
39
+ locales?: string[]
40
+ }
41
+
42
+ /**
43
+ * Aperçu visuel des blocs du page builder. Aujourd'hui un seul fournisseur :
44
+ * la page « design system » du front, avec les captures générées par la CI.
45
+ * Storybook viendra s'ajouter ici le jour où un projet en aura un.
46
+ */
47
+ export interface NcfComponentPreviewConfig {
48
+ provider?: 'designSystemPage' | 'none'
49
+ /** Chemin de la page de démonstration, relatif à `previewUrl`. */
50
+ path?: string
51
+ /** Ancre vers le bloc sur cette page. Gabarit : {name} / {kebab}. */
52
+ anchor?: string
53
+ /** Chemin de la capture, relatif à `previewUrl`. Gabarit : {name} / {kebab}. */
54
+ thumbnail?: string
55
+ }
56
+
57
+ /** Journal des modifications (phase 2). */
58
+ export interface NcfHistoryConfig {
59
+ /**
60
+ * Clé de lecture du projet, écrite dans `studio/.env` par `npx ncf-kit setup`
61
+ * (variable `SANITY_STUDIO_NCF_PROJECT_KEY`). Elle voyage dans le bundle du
62
+ * Studio : imprévisible, pas confidentielle. Jamais une clé d'écriture.
63
+ * Vide ou absente : l'onglet Historique explique comment l'obtenir.
64
+ */
65
+ projectKey?: string
66
+ /** Base des Edge Functions. Par défaut, le service du kit. */
67
+ endpoint?: string
68
+ }
69
+
70
+ /** Étiquette de suivi posable sur une page dans le board. */
71
+ export interface NcfBoardTag {
72
+ /** Identifiant stable, enregistré dans le document de disposition. */
73
+ id: string
74
+ label: string
75
+ /** Couleur CSS de la pastille et de la bordure du nœud. */
76
+ color: string
77
+ }
78
+
79
+ /** Choix possible d'un champ de gestion interne de type « select ». */
80
+ export interface NcfInternalFieldOption {
81
+ id: string
82
+ label: string
83
+ /** Couleur de la pastille. Sans elle, le choix s'affiche en texte. */
84
+ color?: string
85
+ }
86
+
87
+ /**
88
+ * Champ de suivi éditorial, libre. Autant qu'on veut : responsable, cible,
89
+ * rôle de la page… Ces valeurs vivent dans le document du kit, jamais dans le
90
+ * schéma du client.
91
+ */
92
+ export interface NcfInternalField {
93
+ /** Identifiant stable, enregistré avec la valeur. */
94
+ id: string
95
+ label: string
96
+ /** `text` par défaut. `select` exige `options`. */
97
+ type?: 'text' | 'select'
98
+ options?: NcfInternalFieldOption[]
99
+ }
100
+
101
+ /**
102
+ * Donnée du document de la page, affichable telle quelle dans une colonne.
103
+ *
104
+ * Réservé aux valeurs qui tiennent sur une ligne : une meta description, un
105
+ * booléen d'indexabilité, une date. Surtout pas un tableau de sections, qu'on
106
+ * ne saurait pas rendre dans une cellule.
107
+ */
108
+ export interface NcfDocumentColumn {
109
+ /** Identifiant stable. Lettres, chiffres et tirets. */
110
+ key: string
111
+ label: string
112
+ /** Chemins essayés dans l'ordre, le premier renseigné gagne. */
113
+ path: string | string[]
114
+ /** `text` par défaut. `boolean` affiche Oui/Non. */
115
+ type?: 'text' | 'boolean' | 'number'
116
+ }
117
+
118
+ /**
119
+ * Une version du front déployée quelque part : production, préproduction,
120
+ * branche de recette.
121
+ *
122
+ * Le code change d'un environnement à l'autre, **pas les données** : c'est
123
+ * toujours le même dataset qu'on regarde. Voir le contenu de production dans
124
+ * le front d'une branche est justement l'intérêt.
125
+ */
126
+ export interface NcfEnvironment {
127
+ /** Identifiant stable, retenu d'une session à l'autre. */
128
+ id: string
129
+ label: string
130
+ /** Base URL du front, sans slash final. */
131
+ url: string
132
+ }
133
+
134
+ export interface NcfToolsConfig {
135
+ pages?: boolean
136
+ components?: boolean
137
+ history?: boolean
138
+ }
139
+
140
+ export interface NcfKitConfig {
141
+ /** Types de documents traités comme des pages. Au moins un. */
142
+ pageTypes: NcfPageTypeConfig[]
143
+ /** Champ tableau du page builder. */
144
+ pageBuilderField?: string
145
+ /**
146
+ * Préfixe commun aux types de blocs, retiré pour l'affichage et les gabarits
147
+ * d'URL. Ex. 'section.' pour des blocs nommés `section.hero`.
148
+ */
149
+ blockNamespace?: string
150
+ /** Champ slug par défaut des `pageTypes`. */
151
+ slugField?: string
152
+ /** Champ titre par défaut des `pageTypes`. */
153
+ titleField?: string
154
+ /**
155
+ * Champ booléen marquant une page comme non indexable. Plusieurs chemins
156
+ * sont essayés dans l'ordre, le premier renseigné gagne.
157
+ * Défaut : `['seo.noindex', 'noindex']`.
158
+ */
159
+ noindexField?: string | string[]
160
+ /** Base URL du front, sans slash final. */
161
+ previewUrl?: string
162
+ /**
163
+ * Fronts déployés entre lesquels basculer dans l'aperçu. Sans eux, le seul
164
+ * environnement proposé est `previewUrl`.
165
+ *
166
+ * Leurs origines doivent figurer dans `allowOrigins` de `presentationTool` :
167
+ * `ncfAllowedOrigins(config)` les produit.
168
+ */
169
+ environments?: NcfEnvironment[]
170
+ /**
171
+ * Gabarit d'URL de la capture d'une page, pour afficher la page entière dans
172
+ * le board plutôt qu'une iframe tronquée. Variables : {slug} (chemin sans
173
+ * slash de tête, avec des tirets), {locale}, {id}.
174
+ *
175
+ * Chemin relatif à `previewUrl` (« /pages/{slug}.png ») ou URL absolue.
176
+ * Vide : le board retombe sur l'aperçu iframe en direct.
177
+ */
178
+ pageThumbnail?: string
179
+ /** `false` (défaut) pour un site monolingue. */
180
+ i18n?: NcfI18nConfig | false
181
+ componentPreview?: NcfComponentPreviewConfig
182
+ history?: NcfHistoryConfig
183
+ /**
184
+ * Base des Edge Functions du kit, pour l'enregistrement et l'historique.
185
+ * `false` coupe tout appel sortant, y compris le signalement de présence.
186
+ */
187
+ serviceEndpoint?: string | false
188
+ /** Permet de n'activer qu'une partie des outils. */
189
+ tools?: NcfToolsConfig
190
+ /**
191
+ * Étiquettes de suivi du board. Remplacent entièrement les valeurs par
192
+ * défaut quand elles sont fournies.
193
+ */
194
+ boardTags?: NcfBoardTag[]
195
+ /**
196
+ * Colonnes de l'onglet « Gestion interne » de la liste des pages.
197
+ * Remplacent entièrement les valeurs par défaut quand elles sont fournies.
198
+ */
199
+ internalFields?: NcfInternalField[]
200
+ /**
201
+ * Données du document affichables en colonne, proposées dans le sélecteur de
202
+ * colonnes. Masquées tant que personne ne les coche.
203
+ * Défaut : meta description, titre SEO, indexabilité.
204
+ */
205
+ documentColumns?: NcfDocumentColumn[]
206
+ }
207
+
208
+ /* --- Configuration résolue : ce que voient les outils --- */
209
+
210
+ export interface ResolvedPageType {
211
+ type: string
212
+ slugField: string | null
213
+ path: string | null
214
+ /** Préfixe normalisé ('/blog'), `null` pour une collection à la racine. */
215
+ pathPrefix: string | null
216
+ titleField: string
217
+ }
218
+
219
+ export interface ResolvedI18n {
220
+ field: string
221
+ defaultLocale: string
222
+ locales: string[]
223
+ }
224
+
225
+ export interface ResolvedComponentPreview {
226
+ provider: 'designSystemPage' | 'none'
227
+ path: string
228
+ anchor: string
229
+ thumbnail: string
230
+ }
231
+
232
+ export interface ResolvedKitConfig {
233
+ pageTypes: ResolvedPageType[]
234
+ pageTypeNames: string[]
235
+ pageBuilderField: string
236
+ blockNamespace: string
237
+ noindexFields: string[]
238
+ previewUrl: string | null
239
+ environments: NcfEnvironment[]
240
+ pageThumbnail: string | null
241
+ i18n: ResolvedI18n | null
242
+ componentPreview: ResolvedComponentPreview
243
+ history: ResolvedHistory | null
244
+ /** `null` quand on a explicitement coupé les appels sortants. */
245
+ serviceEndpoint: string | null
246
+ tools: Required<NcfToolsConfig>
247
+ boardTags: NcfBoardTag[]
248
+ internalFields: NcfInternalField[]
249
+ documentColumns: ResolvedDocumentColumn[]
250
+ }
251
+
252
+ export interface ResolvedHistory {
253
+ projectKey: string
254
+ endpoint: string
255
+ }
256
+
257
+ export interface ResolvedDocumentColumn {
258
+ key: string
259
+ label: string
260
+ /** Chemins retenus, nettoyés. */
261
+ paths: string[]
262
+ type: 'text' | 'boolean' | 'number'
263
+ /**
264
+ * Inverse un booléen à l'affichage. Sert à `noindex`, qu'on veut lire
265
+ * « Indexable : oui » plutôt que « Noindex : non ».
266
+ */
267
+ invert?: boolean
268
+ }
269
+
270
+ export type IssueLevel = 'error' | 'warning'
271
+
272
+ /**
273
+ * Un problème de configuration. `error` neutralise l'outil concerné (mais pas
274
+ * le Studio) ; `warning` laisse l'outil fonctionner en mode dégradé.
275
+ */
276
+ export interface ConfigIssue {
277
+ level: IssueLevel
278
+ /** Chemin de l'option fautive, ex. 'pageTypes[1].slugField'. */
279
+ path: string
280
+ message: string
281
+ /** Quels outils sont concernés. Vide = tous. */
282
+ tools?: NcfToolName[]
283
+ }
284
+
285
+ export type NcfToolName = 'pages' | 'components' | 'history'
286
+
287
+ export interface KitContextValue {
288
+ config: ResolvedKitConfig
289
+ issues: ConfigIssue[]
290
+ }
@@ -0,0 +1,193 @@
1
+ import type {ConfigIssue, NcfToolName, ResolvedKitConfig} from './types'
2
+
3
+ const isAbsoluteHttpUrl = (value: string): boolean => {
4
+ try {
5
+ const url = new URL(value)
6
+ return url.protocol === 'http:' || url.protocol === 'https:'
7
+ } catch {
8
+ return false
9
+ }
10
+ }
11
+
12
+ /**
13
+ * Contrôle la configuration résolue. Ne lève jamais : les problèmes sont
14
+ * rendus dans l'onglet concerné, pour qu'une faute de frappe dans
15
+ * sanity.config.ts ne rende pas le Studio entier inutilisable.
16
+ */
17
+ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
18
+ const issues: ConfigIssue[] = []
19
+ const error = (path: string, message: string, tools?: NcfToolName[]) =>
20
+ issues.push({level: 'error', path, message, ...(tools ? {tools} : {})})
21
+ const warn = (path: string, message: string, tools?: NcfToolName[]) =>
22
+ issues.push({level: 'warning', path, message, ...(tools ? {tools} : {})})
23
+
24
+ /* --- pageTypes --- */
25
+ if (config.pageTypes.length === 0) {
26
+ error(
27
+ 'pageTypes',
28
+ "`pageTypes` est vide. Renseigne au moins un type de document, ex. pageTypes: ['page'].",
29
+ )
30
+ }
31
+
32
+ const seen = new Set<string>()
33
+ config.pageTypes.forEach((pageType, index) => {
34
+ const at = `pageTypes[${index}]`
35
+
36
+ if (!pageType.type) {
37
+ error(`${at}.type`, 'Type de document manquant ou vide.')
38
+ return
39
+ }
40
+ if (seen.has(pageType.type)) {
41
+ error(`${at}.type`, `Le type « ${pageType.type} » est déclaré plusieurs fois.`)
42
+ }
43
+ seen.add(pageType.type)
44
+
45
+ // `path` et `pathPrefix` ensemble : le chemin fixe gagne, le préfixe ne
46
+ // sert à rien — le dire évite de chercher pourquoi il est ignoré.
47
+ if (pageType.path && pageType.pathPrefix) {
48
+ warn(`${at}.pathPrefix`, `« ${pageType.type} » a un chemin fixe : son pathPrefix est ignoré.`)
49
+ }
50
+
51
+ // Sans slug ni chemin fixe, impossible de situer la page : elle
52
+ // disparaîtrait silencieusement de la liste et du board.
53
+ if (!pageType.slugField && !pageType.path) {
54
+ error(
55
+ `${at}`,
56
+ `« ${pageType.type} » n'a ni slugField ni path : le kit ne peut pas construire son URL. ` +
57
+ `Donne-lui un chemin fixe, ex. {type: '${pageType.type}', path: '/'} pour une page d'accueil.`,
58
+ )
59
+ }
60
+ })
61
+
62
+ /* --- previewUrl --- */
63
+ if (config.previewUrl && !isAbsoluteHttpUrl(config.previewUrl)) {
64
+ error(
65
+ 'previewUrl',
66
+ `« ${config.previewUrl} » n'est pas une URL absolue. Attendu : https://exemple.fr`,
67
+ )
68
+ }
69
+
70
+ /* --- aperçu des composants --- */
71
+ if (config.componentPreview.provider === 'designSystemPage') {
72
+ if (!config.previewUrl) {
73
+ warn(
74
+ 'previewUrl',
75
+ "Aperçu des composants actif mais `previewUrl` est absent : les vignettes et les liens " +
76
+ 'vers la page design system seront désactivés.',
77
+ ['components'],
78
+ )
79
+ }
80
+ if (!config.componentPreview.thumbnail.includes('{name}') &&
81
+ !config.componentPreview.thumbnail.includes('{kebab}')) {
82
+ warn(
83
+ 'componentPreview.thumbnail',
84
+ 'Le gabarit ne contient ni {name} ni {kebab} : tous les blocs afficheront la même image.',
85
+ ['components'],
86
+ )
87
+ }
88
+ }
89
+
90
+ /* --- environnements d'aperçu --- */
91
+ const seenEnvironments = new Set<string>()
92
+ for (const environment of config.environments) {
93
+ if (!isAbsoluteHttpUrl(environment.url)) {
94
+ error(
95
+ `environments.${environment.id}.url`,
96
+ `« ${environment.url} » n'est pas une URL absolue. L'aperçu ne pourra pas charger cet environnement.`,
97
+ ['pages'],
98
+ )
99
+ }
100
+ if (seenEnvironments.has(environment.id)) {
101
+ error(
102
+ 'environments',
103
+ `Deux environnements portent l'identifiant « ${environment.id} » : le choix retenu serait imprévisible.`,
104
+ ['pages'],
105
+ )
106
+ }
107
+ seenEnvironments.add(environment.id)
108
+ }
109
+
110
+ // Presentation refuse de dialoguer avec une origine non déclarée : l'aperçu
111
+ // s'afficherait, mais muet, sans édition visuelle.
112
+ if (config.environments.length > 1) {
113
+ warn(
114
+ 'environments',
115
+ `${config.environments.length} environnements sont déclarés. Vérifie que leurs origines figurent dans ` +
116
+ '`allowOrigins` de presentationTool — `ncfAllowedOrigins(config)` les produit.',
117
+ ['pages'],
118
+ )
119
+ }
120
+
121
+ /* --- historique --- */
122
+ if (config.tools.history) {
123
+ if (!config.history) {
124
+ warn(
125
+ 'history',
126
+ "L'onglet Historique est activé mais aucune clé de lecture n'est configurée. " +
127
+ 'Lance `npx ncf-kit setup` dans le dossier du studio (elle est écrite dans .env), ' +
128
+ 'ou passe tools: {history: false}.',
129
+ ['history'],
130
+ )
131
+ } else {
132
+ if (!config.history.endpoint || !isAbsoluteHttpUrl(config.history.endpoint)) {
133
+ error(
134
+ 'history.endpoint',
135
+ `« ${config.history.endpoint || ''} » n'est pas une URL absolue vers l'Edge Function de lecture.`,
136
+ ['history'],
137
+ )
138
+ }
139
+ if (!config.history.projectKey?.trim()) {
140
+ error('history.projectKey', '`history.projectKey` est vide.', ['history'])
141
+ }
142
+ // Garde-fou : une clé de service Supabase dans le Studio serait publique.
143
+ if (/^eyJ|^sb_secret_|service_role/i.test(config.history.projectKey ?? '')) {
144
+ error(
145
+ 'history.projectKey',
146
+ 'Cette valeur ressemble à une clé Supabase. Le Studio est public : ' +
147
+ "n'y place jamais qu'un identifiant de projet opaque, sans droit d'écriture.",
148
+ ['history'],
149
+ )
150
+ }
151
+ }
152
+ }
153
+
154
+ /* --- champs de gestion interne --- */
155
+ const fieldIds = new Set<string>()
156
+ config.internalFields.forEach((field, index) => {
157
+ const at = `internalFields[${index}]`
158
+ if (!field.id?.trim()) {
159
+ error(`${at}.id`, 'Identifiant de champ manquant.', ['pages'])
160
+ return
161
+ }
162
+ if (fieldIds.has(field.id)) {
163
+ error(`${at}.id`, `Le champ « ${field.id} » est déclaré plusieurs fois.`, ['pages'])
164
+ }
165
+ fieldIds.add(field.id)
166
+ if (!field.label?.trim()) {
167
+ warn(`${at}.label`, `Le champ « ${field.id} » n'a pas de libellé : son identifiant sera affiché.`, ['pages'])
168
+ }
169
+ // Un select sans choix ne serait qu'une liste vide.
170
+ if (field.type === 'select' && !field.options?.length) {
171
+ error(`${at}.options`, `Le champ « ${field.id} » est de type select mais n'a aucune option.`, ['pages'])
172
+ }
173
+ })
174
+
175
+ /* --- page builder --- */
176
+ if (!config.pageBuilderField) {
177
+ error('pageBuilderField', 'Le champ du page builder ne peut pas être vide.', [
178
+ 'pages',
179
+ 'components',
180
+ ])
181
+ }
182
+
183
+ return issues
184
+ }
185
+
186
+ /** Problèmes bloquant un outil donné. */
187
+ export function issuesForTool(issues: ConfigIssue[], tool: NcfToolName): ConfigIssue[] {
188
+ return issues.filter((issue) => !issue.tools || issue.tools.includes(tool))
189
+ }
190
+
191
+ export function hasBlockingIssue(issues: ConfigIssue[], tool: NcfToolName): boolean {
192
+ return issuesForTool(issues, tool).some((issue) => issue.level === 'error')
193
+ }
@@ -0,0 +1,24 @@
1
+ import {createContext, useContext, type ReactNode} from 'react'
2
+ import {useBoardLayoutState, type BoardLayoutState} from '../hooks/useBoardLayout'
3
+
4
+ const BoardLayoutContext = createContext<BoardLayoutState | null>(null)
5
+
6
+ /**
7
+ * Une seule instance de la disposition par outil.
8
+ *
9
+ * Le document `ncfBoardLayout` est réécrit en entier à chaque enregistrement :
10
+ * deux instances du hook, chacune avec son état, finiraient par s'écraser —
11
+ * régler le board effacerait les colonnes, et réciproquement.
12
+ */
13
+ export function BoardLayoutProvider(props: {children: ReactNode}) {
14
+ const value = useBoardLayoutState()
15
+ return <BoardLayoutContext.Provider value={value}>{props.children}</BoardLayoutContext.Provider>
16
+ }
17
+
18
+ export function useBoardLayout(): BoardLayoutState {
19
+ const value = useContext(BoardLayoutContext)
20
+ if (!value) {
21
+ throw new Error('useBoardLayout doit être appelé sous BoardLayoutProvider.')
22
+ }
23
+ return value
24
+ }
@@ -0,0 +1,30 @@
1
+ import {createContext, useContext, useMemo, type ReactNode} from 'react'
2
+ import type {KitContextValue, ResolvedKitConfig, ConfigIssue} from '../config/types'
3
+
4
+ const KitContext = createContext<KitContextValue | null>(null)
5
+
6
+ export interface KitProviderProps {
7
+ config: ResolvedKitConfig
8
+ issues: ConfigIssue[]
9
+ children: ReactNode
10
+ }
11
+
12
+ export function KitProvider(props: KitProviderProps) {
13
+ const {config, issues, children} = props
14
+ const value = useMemo<KitContextValue>(() => ({config, issues}), [config, issues])
15
+ return <KitContext.Provider value={value}>{children}</KitContext.Provider>
16
+ }
17
+
18
+ /**
19
+ * Configuration résolue du kit. Erreur explicite hors contexte : une
20
+ * dépendance oubliée se voit tout de suite au développement.
21
+ */
22
+ export function useKitContext(): KitContextValue {
23
+ const value = useContext(KitContext)
24
+ if (!value) {
25
+ throw new Error('useKitContext doit être appelé dans un outil du plugin @nocode-factory/sanity-kit.')
26
+ }
27
+ return value
28
+ }
29
+
30
+ export const useKitConfig = (): ResolvedKitConfig => useKitContext().config
@@ -0,0 +1,27 @@
1
+ import {createContext, useContext, type ReactNode} from 'react'
2
+ import {usePreviewTargetState, type PreviewTargetState} from '../hooks/usePreviewTarget'
3
+
4
+ const PreviewTargetContext = createContext<PreviewTargetState | null>(null)
5
+
6
+ /**
7
+ * Une seule cible d'aperçu par outil.
8
+ *
9
+ * Le choix est fait dans la barre et lu partout ailleurs — tableau, board,
10
+ * fiche latérale. Deux instances du hook auraient chacune leur état, et
11
+ * basculer dans la barre ne changerait rien aux liens du tableau : c'est
12
+ * exactement le défaut qui a déjà coûté cher sur la disposition du board.
13
+ */
14
+ export function PreviewTargetProvider(props: {children: ReactNode}) {
15
+ const value = usePreviewTargetState()
16
+ return (
17
+ <PreviewTargetContext.Provider value={value}>{props.children}</PreviewTargetContext.Provider>
18
+ )
19
+ }
20
+
21
+ export function usePreviewTarget(): PreviewTargetState {
22
+ const value = useContext(PreviewTargetContext)
23
+ if (!value) {
24
+ throw new Error('usePreviewTarget doit être appelé sous PreviewTargetProvider.')
25
+ }
26
+ return value
27
+ }
@@ -0,0 +1,60 @@
1
+ import {useCallback, useMemo} from 'react'
2
+ import type {Annotation} from '../lib/graph'
3
+ import {useBoardLayout} from '../context/BoardLayoutContext'
4
+
5
+ let counter = 0
6
+ const nextId = (): string => `a${Date.now().toString(36)}${(counter += 1).toString(36)}`
7
+
8
+ export interface AnnotationsState {
9
+ annotations: Annotation[]
10
+ add: (kind: Annotation['kind'], position: {x: number; y: number}) => void
11
+ update: (id: string, patch: Partial<Annotation>) => void
12
+ remove: (id: string) => void
13
+ }
14
+
15
+ /**
16
+ * Notes et formes d'un canvas. Elles sont stockées avec le reste de la
17
+ * disposition, filtrées par `scope` : le board des pages et la carte des
18
+ * sections ne partagent pas leurs annotations.
19
+ */
20
+ export function useAnnotations(scope: Annotation['scope']): AnnotationsState {
21
+ const {annotations: all, saveAnnotations} = useBoardLayout()
22
+
23
+ const annotations = useMemo(
24
+ () => all.filter((annotation) => annotation.scope === scope),
25
+ [all, scope],
26
+ )
27
+
28
+ const add = useCallback(
29
+ (kind: Annotation['kind'], position: {x: number; y: number}) => {
30
+ saveAnnotations([
31
+ ...all,
32
+ {
33
+ id: nextId(),
34
+ scope,
35
+ kind,
36
+ x: Math.round(position.x),
37
+ y: Math.round(position.y),
38
+ width: kind === 'rect' ? 320 : 200,
39
+ height: kind === 'rect' ? 220 : 96,
40
+ text: '',
41
+ },
42
+ ])
43
+ },
44
+ [all, saveAnnotations, scope],
45
+ )
46
+
47
+ const update = useCallback(
48
+ (id: string, patch: Partial<Annotation>) => {
49
+ saveAnnotations(all.map((a) => (a.id === id ? {...a, ...patch} : a)))
50
+ },
51
+ [all, saveAnnotations],
52
+ )
53
+
54
+ const remove = useCallback(
55
+ (id: string) => saveAnnotations(all.filter((a) => a.id !== id)),
56
+ [all, saveAnnotations],
57
+ )
58
+
59
+ return {annotations, add, update, remove}
60
+ }