@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,83 @@
1
+ import type {BlockOccurrence} from './occurrences'
2
+ import type {BlockTypeInfo} from './schemaTypes'
3
+
4
+ export interface SectionMapNode {
5
+ id: string
6
+ block: BlockTypeInfo
7
+ occurrence: BlockOccurrence
8
+ position: {x: number; y: number}
9
+ size: number
10
+ }
11
+
12
+ /** Ordre de placement des tuiles. */
13
+ export type SectionOrder = 'type' | 'usage' | 'unused'
14
+
15
+ export interface SectionsMapOptions {
16
+ /** Défaut : par type, pour que chaque bloc garde toujours la même place. */
17
+ order?: SectionOrder
18
+ /** Côté d'une tuile pour un bloc jamais utilisé. */
19
+ minSize?: number
20
+ /** Côté d'une tuile pour le bloc le plus utilisé. */
21
+ maxSize?: number
22
+ /** Nombre de colonnes de la grille. */
23
+ columns?: number
24
+ gap?: number
25
+ }
26
+
27
+ type Entry = {block: BlockTypeInfo; occurrence: BlockOccurrence}
28
+
29
+ /**
30
+ * Le classement par type l'emporte sur l'usage : un bloc doit garder la même
31
+ * place d'une visite à l'autre, sinon la carte se réordonne à chaque
32
+ * publication et il faut la relire entièrement.
33
+ */
34
+ function compareBy(order: SectionOrder): (a: Entry, b: Entry) => number {
35
+ if (order === 'usage') return (a, b) => b.occurrence.count - a.occurrence.count
36
+ if (order === 'unused') return (a, b) => a.occurrence.count - b.occurrence.count
37
+ return (a, b) => a.block.name.localeCompare(b.block.name, 'fr')
38
+ }
39
+
40
+ /**
41
+ * Disposition de la carte des sections.
42
+ *
43
+ * Grille ordonnée par usage décroissant, tuiles dimensionnées par le nombre
44
+ * d'occurrences : ce qui structure le site saute aux yeux, ce qui ne sert
45
+ * jamais se voit tout autant par sa petitesse.
46
+ */
47
+ export function layoutSectionsMap(
48
+ blocks: readonly BlockTypeInfo[],
49
+ occurrences: readonly BlockOccurrence[],
50
+ options: SectionsMapOptions = {},
51
+ ): SectionMapNode[] {
52
+ const {order = 'type', minSize = 120, maxSize = 260, columns = 4, gap = 32} = options
53
+
54
+ const byType = new Map(occurrences.map((o) => [o.type, o]))
55
+ const entries = blocks
56
+ .map((block) => ({
57
+ block,
58
+ occurrence: byType.get(block.name) ?? {type: block.name, count: 0, documentIds: []},
59
+ }))
60
+ .sort(compareBy(order))
61
+
62
+ const max = Math.max(1, ...entries.map((entry) => entry.occurrence.count))
63
+ const cell = maxSize + gap
64
+
65
+ return entries.map((entry, index) => {
66
+ const ratio = entry.occurrence.count / max
67
+ const size = Math.round(minSize + (maxSize - minSize) * Math.sqrt(ratio))
68
+ const column = index % columns
69
+ const rowIndex = Math.floor(index / columns)
70
+ return {
71
+ id: entry.block.name,
72
+ block: entry.block,
73
+ occurrence: entry.occurrence,
74
+ // Tuile centrée dans sa cellule : la grille reste lisible malgré des
75
+ // tailles différentes.
76
+ position: {
77
+ x: column * cell + (maxSize - size) / 2,
78
+ y: rowIndex * cell + (maxSize - size) / 2,
79
+ },
80
+ size,
81
+ }
82
+ })
83
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Appels au service du kit.
3
+ *
4
+ * Deux principes tiennent ce fichier :
5
+ *
6
+ * - **On échoue en silence, jamais en bloquant.** Une panne réseau ou une
7
+ * indisponibilité du service ne doit pas empêcher un éditeur de travailler.
8
+ * Le Studio d'un client ne dépend pas de notre disponibilité.
9
+ * - **On n'envoie rien du contenu.** Le signalement de présence porte un
10
+ * identifiant de projet, un dataset, un hôte et une version. Rien d'autre.
11
+ */
12
+
13
+ export type ProjectStatus = 'unregistered' | 'active' | 'suspended' | 'expired' | 'blocked'
14
+
15
+ export interface Registration {
16
+ status: ProjectStatus
17
+ expiresAt?: string | null
18
+ }
19
+
20
+ export interface HistoryEvent {
21
+ id: number
22
+ document_id: string
23
+ document_type: string
24
+ operation: 'create' | 'update' | 'delete'
25
+ /** Vrai quand le changement porte sur le brouillon, pas sur la version en ligne. */
26
+ is_draft: boolean
27
+ actor_id: string | null
28
+ actor_name: string | null
29
+ occurred_at: string
30
+ revision: string | null
31
+ }
32
+
33
+ export interface HistoryDetail {
34
+ current: HistoryEvent & {snapshot: Record<string, unknown> | null}
35
+ previous: (HistoryEvent & {snapshot: Record<string, unknown> | null}) | null
36
+ }
37
+
38
+ async function post<T>(url: string, body: unknown, signal?: AbortSignal): Promise<T> {
39
+ const response = await fetch(url, {
40
+ method: 'POST',
41
+ headers: {'content-type': 'application/json'},
42
+ body: JSON.stringify(body),
43
+ signal,
44
+ })
45
+ const payload = await response.json().catch(() => ({}))
46
+ if (!response.ok) {
47
+ const error = new Error((payload as {error?: string}).error ?? `HTTP ${response.status}`)
48
+ Object.assign(error, {status: response.status, payload})
49
+ throw error
50
+ }
51
+ return payload as T
52
+ }
53
+
54
+ /**
55
+ * Signale la présence de ce Studio et rend son statut.
56
+ *
57
+ * Rend `null` si le service ne répond pas : l'appelant traitera ce cas comme
58
+ * « rien à signaler », et surtout pas comme un refus.
59
+ */
60
+ export async function announce(
61
+ endpoint: string,
62
+ payload: {projectId: string; dataset: string; host: string; version: string},
63
+ signal?: AbortSignal,
64
+ ): Promise<Registration | null> {
65
+ try {
66
+ return await post<Registration>(`${endpoint}/register`, payload, signal)
67
+ } catch {
68
+ return null
69
+ }
70
+ }
71
+
72
+ export async function fetchTimeline(
73
+ endpoint: string,
74
+ key: string,
75
+ options: {documentId?: string; limit?: number; before?: string} = {},
76
+ signal?: AbortSignal,
77
+ ): Promise<{events: HistoryEvent[]; hasMore: boolean; retentionDays: number}> {
78
+ return post(`${endpoint}/history`, {key, ...options}, signal)
79
+ }
80
+
81
+ export async function fetchDetail(
82
+ endpoint: string,
83
+ key: string,
84
+ eventId: number,
85
+ signal?: AbortSignal,
86
+ ): Promise<HistoryDetail> {
87
+ return post(`${endpoint}/history`, {key, mode: 'detail', eventId}, signal)
88
+ }
@@ -0,0 +1,43 @@
1
+ import type {NcfPageTypeInput} from '../config/types'
2
+
3
+ /**
4
+ * Registre des pages du starter NoCode Factory (`web/app/lib/site-routes.json`).
5
+ * Seules les clés lues ici sont typées : le fichier en porte d'autres
6
+ * (sections, titres, noindex) qui ne concernent pas le kit.
7
+ */
8
+ export interface SiteRoutesRegistry {
9
+ fixed?: {path: string; homePage?: boolean; system?: boolean; notFound?: boolean}[]
10
+ collections?: {type: string; pathPrefix?: string}[]
11
+ }
12
+
13
+ /**
14
+ * `pageTypes` déduits du registre du starter, pour ne pas redire au kit ce que
15
+ * le site sait déjà : l'accueil (chemin fixe `/`) et chaque collection avec
16
+ * son préfixe d'URL (`/blog`, `/produits`, ou la racine).
17
+ *
18
+ * ```ts
19
+ * import routes from '../web/app/lib/site-routes.json'
20
+ * ncfKit({pageTypes: pageTypesFromSiteRoutes(routes)})
21
+ * ```
22
+ *
23
+ * `homePageType` : nom du type de l'accueil dans le schéma (le registre ne le
24
+ * porte pas). Les pages codées du registre (`pageSlug`) ne sont pas des types :
25
+ * elles n'apparaissent pas ici.
26
+ */
27
+ export function pageTypesFromSiteRoutes(
28
+ routes: SiteRoutesRegistry,
29
+ options: {homePageType?: string | null} = {},
30
+ ): NcfPageTypeInput[] {
31
+ const homePageType = options.homePageType === undefined ? 'homePage' : options.homePageType
32
+ const out: NcfPageTypeInput[] = []
33
+
34
+ if (homePageType && routes.fixed?.some((r) => r.homePage)) {
35
+ out.push({type: homePageType, path: '/'})
36
+ }
37
+ for (const collection of routes.collections ?? []) {
38
+ if (!collection.type) continue
39
+ const prefix = (collection.pathPrefix ?? '').trim()
40
+ out.push(prefix ? {type: collection.type, pathPrefix: prefix} : {type: collection.type})
41
+ }
42
+ return out
43
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Fusion des variantes d'un même document (publié / brouillon / version de
3
+ * release) pour en déduire un statut unique affichable.
4
+ */
5
+
6
+ export type PageStatus = 'published' | 'draft' | 'modified'
7
+
8
+ export interface VersionedDoc {
9
+ _id: string
10
+ _type: string
11
+ _updatedAt?: string
12
+ }
13
+
14
+ const DRAFTS_PREFIX = 'drafts.'
15
+ const VERSIONS_PREFIX = 'versions.'
16
+
17
+ export const isDraftId = (id: string): boolean => id.startsWith(DRAFTS_PREFIX)
18
+
19
+ /** Version issue d'une release de contenu (Sanity v6). */
20
+ export const isVersionId = (id: string): boolean => id.startsWith(VERSIONS_PREFIX)
21
+
22
+ /** Identifiant de la release, pour un id `versions.<release>.<doc>`. */
23
+ export function releaseId(id: string): string | null {
24
+ if (!isVersionId(id)) return null
25
+ const rest = id.slice(VERSIONS_PREFIX.length)
26
+ const separator = rest.indexOf('.')
27
+ return separator === -1 ? null : rest.slice(0, separator)
28
+ }
29
+
30
+ /** Identifiant du document publié, quel que soit l'identifiant reçu. */
31
+ export function baseId(id: string): string {
32
+ if (isDraftId(id)) return id.slice(DRAFTS_PREFIX.length)
33
+ if (isVersionId(id)) {
34
+ const rest = id.slice(VERSIONS_PREFIX.length)
35
+ const separator = rest.indexOf('.')
36
+ return separator === -1 ? rest : rest.slice(separator + 1)
37
+ }
38
+ return id
39
+ }
40
+
41
+ export interface MergedDoc<T extends VersionedDoc> {
42
+ id: string
43
+ status: PageStatus
44
+ /** Version de référence pour l'affichage : le brouillon s'il existe. */
45
+ doc: T
46
+ published?: T
47
+ draft?: T
48
+ /** Versions de release, par identifiant de release. */
49
+ versions: Record<string, T>
50
+ /** Date de la modification la plus récente, toutes variantes confondues. */
51
+ updatedAt?: string
52
+ }
53
+
54
+ const mostRecent = (a?: string, b?: string): string | undefined => {
55
+ if (!a) return b
56
+ if (!b) return a
57
+ return a > b ? a : b
58
+ }
59
+
60
+ /**
61
+ * Regroupe les documents par identifiant de base.
62
+ *
63
+ * - publié seul -> 'published'
64
+ * - brouillon seul -> 'draft' (jamais publié, absent du site)
65
+ * - publié + brouillon -> 'modified' (modifications non publiées)
66
+ *
67
+ * Les versions de release sont conservées mais n'influencent pas le statut :
68
+ * elles ne sont ni en ligne, ni des modifications en attente au sens du Studio.
69
+ */
70
+ export function mergeVersions<T extends VersionedDoc>(docs: readonly T[]): MergedDoc<T>[] {
71
+ const groups = new Map<string, {published?: T; draft?: T; versions: Record<string, T>}>()
72
+
73
+ for (const doc of docs) {
74
+ const id = baseId(doc._id)
75
+ const group = groups.get(id) ?? {versions: {}}
76
+
77
+ if (isDraftId(doc._id)) {
78
+ group.draft = doc
79
+ } else if (isVersionId(doc._id)) {
80
+ const release = releaseId(doc._id)
81
+ if (release) group.versions[release] = doc
82
+ } else {
83
+ group.published = doc
84
+ }
85
+
86
+ groups.set(id, group)
87
+ }
88
+
89
+ const merged: MergedDoc<T>[] = []
90
+
91
+ for (const [id, group] of groups) {
92
+ const reference = group.draft ?? group.published ?? Object.values(group.versions)[0]
93
+ // Un groupe ne contenant qu'une version de release n'est pas une page.
94
+ if (!reference || (!group.published && !group.draft)) continue
95
+
96
+ const status: PageStatus = group.published
97
+ ? group.draft
98
+ ? 'modified'
99
+ : 'published'
100
+ : 'draft'
101
+
102
+ merged.push({
103
+ id,
104
+ status,
105
+ doc: reference,
106
+ ...(group.published ? {published: group.published} : {}),
107
+ ...(group.draft ? {draft: group.draft} : {}),
108
+ versions: group.versions,
109
+ ...(mostRecent(group.published?._updatedAt, group.draft?._updatedAt)
110
+ ? {updatedAt: mostRecent(group.published?._updatedAt, group.draft?._updatedAt)}
111
+ : {}),
112
+ })
113
+ }
114
+
115
+ return merged
116
+ }
117
+
118
+ export const STATUS_LABELS: Record<PageStatus, {label: string; tone: 'positive' | 'caution' | 'default'; help: string}> = {
119
+ published: {label: 'Publiée', tone: 'positive', help: 'En ligne, à jour'},
120
+ modified: {label: 'Modifiée', tone: 'caution', help: 'En ligne, avec des modifications non publiées'},
121
+ draft: {label: 'Brouillon', tone: 'default', help: 'Jamais publiée : absente du site'},
122
+ }
@@ -0,0 +1,137 @@
1
+ import type {NcfEnvironment} from '../config/types'
2
+
3
+ /**
4
+ * Ce que l'aperçu donne à voir.
5
+ *
6
+ * `drafts` montre le contenu tel qu'il sortira après publication — c'est la
7
+ * question que se pose un relecteur. `published` montre ce que voit le public
8
+ * aujourd'hui.
9
+ */
10
+ export type PreviewPerspective = 'drafts' | 'published'
11
+
12
+ export const PERSPECTIVES: {id: PreviewPerspective; label: string; hint: string}[] = [
13
+ {id: 'drafts', label: 'Brouillons', hint: 'Ce qui sortira après publication'},
14
+ {id: 'published', label: 'En ligne', hint: 'Ce que voit le public aujourd\'hui'},
15
+ ]
16
+
17
+ /** Retire le slash final, pour ne pas produire d'URL à double slash. */
18
+ const trimEnd = (url: string): string => url.replace(/\/+$/, '')
19
+
20
+ /**
21
+ * URL d'une page sur un front donné.
22
+ *
23
+ * L'environnement porte le code, le chemin porte la page. Changer
24
+ * d'environnement ne change donc jamais le chemin : c'est la même page,
25
+ * rendue par une autre version du site.
26
+ */
27
+ export function urlOn(environment: NcfEnvironment | null, path: string | null): string | null {
28
+ if (!environment?.url) return null
29
+ if (!path) return trimEnd(environment.url)
30
+ return `${trimEnd(environment.url)}${path.startsWith('/') ? path : `/${path}`}`
31
+ }
32
+
33
+ export interface PresentationOptions {
34
+ /** Front à charger dans l'aperçu. */
35
+ environment?: NcfEnvironment | null
36
+ perspective?: PreviewPerspective
37
+ }
38
+
39
+ /**
40
+ * Liens internes au Studio.
41
+ *
42
+ * Ouvrir une page doit mener à **Presentation**, pas à la structure : on veut
43
+ * voir la page, pas son formulaire. Le tool attend l'URL du front en clair
44
+ * dans le paramètre `preview`, et la perspective dans `perspective`.
45
+ */
46
+ export function presentationPath(
47
+ url: string | null | undefined,
48
+ options: PresentationOptions = {},
49
+ ): string | null {
50
+ const target = options.environment ? urlOn(options.environment, pathOf(url)) : url
51
+ if (!target) return null
52
+
53
+ const params = new URLSearchParams({preview: target})
54
+ // Omise quand elle vaut `drafts` : c'est déjà ce que Presentation montre par
55
+ // défaut, et une URL sans paramètre superflu se partage mieux.
56
+ if (options.perspective && options.perspective !== 'drafts') {
57
+ params.set('perspective', options.perspective)
58
+ }
59
+ return `/presentation?${params.toString()}`
60
+ }
61
+
62
+ /** Chemin d'une URL absolue, ou la valeur telle quelle si elle est relative. */
63
+ function pathOf(url: string | null | undefined): string | null {
64
+ if (!url) return null
65
+ try {
66
+ return new URL(url).pathname
67
+ } catch {
68
+ return url.startsWith('/') ? url : `/${url}`
69
+ }
70
+ }
71
+
72
+ /** Lien d'édition classique, pour les cas où l'on veut le formulaire. */
73
+ export function editIntentPath(id: string, type: string): string {
74
+ return `/intent/edit/id=${encodeURIComponent(id)};type=${encodeURIComponent(type)}/`
75
+ }
76
+
77
+ /**
78
+ * Origines à autoriser dans `presentationTool({allowOrigins})`.
79
+ *
80
+ * Presentation refuse de dialoguer avec un front dont l'origine n'est pas
81
+ * déclarée : sans cela, basculer vers une préproduction donnerait un aperçu
82
+ * muet, sans édition visuelle ni surlignage.
83
+ *
84
+ * ```ts
85
+ * presentationTool({allowOrigins: ncfAllowedOrigins(kitConfig), previewUrl: …})
86
+ * ```
87
+ */
88
+ export function ncfAllowedOrigins(config: {
89
+ environments?: NcfEnvironment[]
90
+ previewUrl?: string | null
91
+ }): string[] {
92
+ const urls = [...(config.environments ?? []).map((e) => e.url), config.previewUrl]
93
+ const origins = urls
94
+ .filter((url): url is string => Boolean(url))
95
+ .map((url) => {
96
+ try {
97
+ return new URL(url).origin
98
+ } catch {
99
+ return null
100
+ }
101
+ })
102
+ .filter((origin): origin is string => Boolean(origin))
103
+
104
+ return [...new Set(origins)]
105
+ }
106
+
107
+
108
+ /** Identifiant de l'environnement libre, saisi à la volée. */
109
+ export const CUSTOM_ENVIRONMENT_ID = 'ncf-custom'
110
+
111
+ /**
112
+ * Environnement bâti depuis une URL collée.
113
+ *
114
+ * Les préversions sont innombrables et éphémères — une par branche, parfois
115
+ * une par commit. Les déclarer d'avance serait vain : on colle l'adresse du
116
+ * déploiement qu'on a sous les yeux.
117
+ *
118
+ * Rend `null` si l'URL n'est pas exploitable, plutôt qu'un environnement qui
119
+ * chargerait une page blanche.
120
+ */
121
+ export function customEnvironment(raw: string): NcfEnvironment | null {
122
+ const trimmed = raw.trim()
123
+ if (!trimmed) return null
124
+
125
+ const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`
126
+ try {
127
+ const parsed = new URL(withScheme)
128
+ if (!parsed.hostname.includes('.') && parsed.hostname !== 'localhost') return null
129
+ return {
130
+ id: CUSTOM_ENVIRONMENT_ID,
131
+ label: parsed.host,
132
+ url: `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`,
133
+ }
134
+ } catch {
135
+ return null
136
+ }
137
+ }
@@ -0,0 +1,190 @@
1
+ import {defineField, defineType} from 'sanity'
2
+
3
+ /** Type et identifiant du singleton portant la disposition du board. */
4
+ export const BOARD_LAYOUT_TYPE = 'ncfBoardLayout'
5
+ export const BOARD_LAYOUT_ID = 'ncfBoardLayout'
6
+ export const BOARD_NODE_TYPE = 'ncfBoardNode'
7
+ export const SECTION_NODE_TYPE = 'ncfSectionNode'
8
+ export const NODE_FIELD_TYPE = 'ncfNodeField'
9
+ export const COLUMN_TYPE = 'ncfColumn'
10
+ export const COLUMN_OPTION_TYPE = 'ncfColumnOption'
11
+ export const ANNOTATION_TYPE = 'ncfAnnotation'
12
+
13
+ /** Types déclarés par le kit : à masquer de la structure du Studio hôte. */
14
+ export const NCF_HIDDEN_TYPES = [BOARD_LAYOUT_TYPE] as const
15
+
16
+ const boardNodeType = defineType({
17
+ name: BOARD_NODE_TYPE,
18
+ title: 'Position d\'une page',
19
+ type: 'object',
20
+ fields: [
21
+ defineField({name: 'documentId', title: 'Document', type: 'string'}),
22
+ defineField({name: 'x', title: 'X', type: 'number'}),
23
+ defineField({name: 'y', title: 'Y', type: 'number'}),
24
+ // Taille choisie à la main ; absente tant que le nœud garde sa taille.
25
+ defineField({name: 'width', title: 'Largeur', type: 'number'}),
26
+ defineField({name: 'height', title: 'Hauteur', type: 'number'}),
27
+ defineField({name: 'tag', title: 'Étiquette de suivi', type: 'string'}),
28
+ defineField({
29
+ name: 'fields',
30
+ title: 'Gestion interne',
31
+ type: 'array',
32
+ of: [{type: NODE_FIELD_TYPE}],
33
+ }),
34
+ ],
35
+ preview: {
36
+ select: {title: 'documentId', x: 'x', y: 'y'},
37
+ prepare: ({title, x, y}) => ({title: title ?? 'Sans document', subtitle: `${x ?? 0} × ${y ?? 0}`}),
38
+ },
39
+ })
40
+
41
+ /** Note ou forme posée sur un canvas, derrière les nœuds. */
42
+ const annotationType = defineType({
43
+ name: ANNOTATION_TYPE,
44
+ title: 'Annotation',
45
+ type: 'object',
46
+ fields: [
47
+ defineField({name: 'id', title: 'Identifiant', type: 'string'}),
48
+ defineField({
49
+ name: 'scope',
50
+ title: 'Canvas',
51
+ type: 'string',
52
+ options: {list: [{title: 'Pages', value: 'pages'}, {title: 'Sections', value: 'sections'}]},
53
+ }),
54
+ defineField({
55
+ name: 'kind',
56
+ title: 'Nature',
57
+ type: 'string',
58
+ options: {list: [{title: 'Texte', value: 'text'}, {title: 'Forme', value: 'rect'}]},
59
+ }),
60
+ defineField({name: 'x', type: 'number'}),
61
+ defineField({name: 'y', type: 'number'}),
62
+ defineField({name: 'width', type: 'number'}),
63
+ defineField({name: 'height', type: 'number'}),
64
+ defineField({name: 'text', title: 'Texte', type: 'string'}),
65
+ defineField({name: 'color', title: 'Couleur', type: 'string'}),
66
+ ],
67
+ preview: {select: {title: 'text', subtitle: 'scope'}},
68
+ })
69
+
70
+ const columnOptionType = defineType({
71
+ name: COLUMN_OPTION_TYPE,
72
+ title: 'Choix',
73
+ type: 'object',
74
+ fields: [
75
+ defineField({name: 'id', title: 'Identifiant', type: 'string'}),
76
+ defineField({name: 'label', title: 'Libellé', type: 'string'}),
77
+ defineField({name: 'color', title: 'Couleur', type: 'string'}),
78
+ ],
79
+ preview: {select: {title: 'label', subtitle: 'id'}},
80
+ })
81
+
82
+ /**
83
+ * Colonne de gestion interne, ajoutée depuis l'interface. Elles vivent ici et
84
+ * non dans la configuration : un chef de projet doit pouvoir en créer une sans
85
+ * toucher au code ni redéployer le Studio.
86
+ */
87
+ const columnType = defineType({
88
+ name: COLUMN_TYPE,
89
+ title: 'Colonne de gestion interne',
90
+ type: 'object',
91
+ fields: [
92
+ defineField({name: 'id', title: 'Identifiant', type: 'string'}),
93
+ defineField({name: 'label', title: 'Nom', type: 'string'}),
94
+ defineField({
95
+ name: 'type',
96
+ title: 'Type',
97
+ type: 'string',
98
+ options: {list: [{title: 'Texte', value: 'text'}, {title: 'Liste', value: 'select'}]},
99
+ }),
100
+ defineField({name: 'options', title: 'Choix', type: 'array', of: [{type: COLUMN_OPTION_TYPE}]}),
101
+ ],
102
+ preview: {select: {title: 'label', subtitle: 'type'}},
103
+ })
104
+
105
+ const nodeFieldType = defineType({
106
+ name: NODE_FIELD_TYPE,
107
+ title: 'Champ de gestion interne',
108
+ type: 'object',
109
+ fields: [
110
+ defineField({name: 'fieldId', title: 'Champ', type: 'string'}),
111
+ defineField({name: 'value', title: 'Valeur', type: 'string'}),
112
+ ],
113
+ preview: {
114
+ select: {title: 'fieldId', subtitle: 'value'},
115
+ },
116
+ })
117
+
118
+ const sectionNodeType = defineType({
119
+ name: SECTION_NODE_TYPE,
120
+ title: 'Position d\'une section',
121
+ type: 'object',
122
+ fields: [
123
+ defineField({name: 'blockName', title: 'Type de bloc', type: 'string'}),
124
+ defineField({name: 'x', title: 'X', type: 'number'}),
125
+ defineField({name: 'y', title: 'Y', type: 'number'}),
126
+ ],
127
+ preview: {
128
+ select: {title: 'blockName', x: 'x', y: 'y'},
129
+ prepare: ({title, x, y}) => ({title: title ?? 'Sans bloc', subtitle: `${x ?? 0} × ${y ?? 0}`}),
130
+ },
131
+ })
132
+
133
+ /**
134
+ * Disposition manuelle du board. Document unique, écrit par l'outil Pages :
135
+ * jamais édité à la main, d'où l'absence de ce type dans « Créer ».
136
+ */
137
+ const boardLayoutType = defineType({
138
+ name: BOARD_LAYOUT_TYPE,
139
+ title: 'Disposition du board (NCF)',
140
+ type: 'document',
141
+ fields: [
142
+ defineField({
143
+ name: 'nodes',
144
+ title: 'Positions',
145
+ type: 'array',
146
+ of: [{type: BOARD_NODE_TYPE}],
147
+ }),
148
+ defineField({
149
+ name: 'annotations',
150
+ title: 'Annotations',
151
+ type: 'array',
152
+ of: [{type: ANNOTATION_TYPE}],
153
+ }),
154
+ defineField({
155
+ name: 'columns',
156
+ title: 'Colonnes de gestion interne',
157
+ type: 'array',
158
+ of: [{type: COLUMN_TYPE}],
159
+ }),
160
+ // Distingue « jamais réglé » de « volontairement vidé ».
161
+ defineField({name: 'columnsSet', title: 'Colonnes réglées', type: 'boolean'}),
162
+ defineField({
163
+ name: 'sections',
164
+ title: 'Positions des sections',
165
+ type: 'array',
166
+ of: [{type: SECTION_NODE_TYPE}],
167
+ }),
168
+ defineField({
169
+ name: 'updatedBy',
170
+ title: 'Modifié par',
171
+ type: 'string',
172
+ readOnly: true,
173
+ }),
174
+ ],
175
+ preview: {prepare: () => ({title: 'Disposition du board (NCF)'})},
176
+ })
177
+
178
+ export const kitSchemaTypes = [
179
+ boardLayoutType,
180
+ boardNodeType,
181
+ sectionNodeType,
182
+ nodeFieldType,
183
+ columnType,
184
+ columnOptionType,
185
+ annotationType,
186
+ ]
187
+
188
+ /** Vrai pour les types techniques du kit. */
189
+ export const isKitType = (typeName: string): boolean =>
190
+ (NCF_HIDDEN_TYPES as readonly string[]).includes(typeName)