@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.
- package/bin/ncf-kit.mjs +201 -0
- package/dist/index.d.ts +1643 -0
- package/dist/index.js +6632 -0
- package/dist/index.js.map +1 -0
- package/dist/web-server.d.ts +46 -0
- package/dist/web-server.js +51 -0
- package/dist/web-server.js.map +1 -0
- package/dist/web.d.ts +27 -0
- package/dist/web.js +117 -0
- package/dist/web.js.map +1 -0
- package/package.json +90 -0
- package/scripts/use-client.mjs +20 -0
- package/src/config/defaults.ts +74 -0
- package/src/config/resolve.ts +153 -0
- package/src/config/types.ts +290 -0
- package/src/config/validate.ts +193 -0
- package/src/context/BoardLayoutContext.tsx +24 -0
- package/src/context/KitContext.tsx +30 -0
- package/src/context/PreviewTargetContext.tsx +27 -0
- package/src/hooks/useAnnotations.ts +60 -0
- package/src/hooks/useBoardLayout.ts +398 -0
- package/src/hooks/useColumnOptions.ts +47 -0
- package/src/hooks/useDocumentColumns.ts +61 -0
- package/src/hooks/useHistory.ts +89 -0
- package/src/hooks/useInternalColumns.ts +19 -0
- package/src/hooks/useKitClient.ts +15 -0
- package/src/hooks/useOccurrences.ts +62 -0
- package/src/hooks/usePageContents.ts +65 -0
- package/src/hooks/usePages.ts +41 -0
- package/src/hooks/usePreviewTarget.ts +162 -0
- package/src/hooks/useQueryData.ts +103 -0
- package/src/hooks/useRegistration.ts +50 -0
- package/src/index.ts +280 -0
- package/src/lib/blocks.ts +38 -0
- package/src/lib/colors.ts +103 -0
- package/src/lib/columns.ts +137 -0
- package/src/lib/diff.ts +200 -0
- package/src/lib/elkLayout.ts +124 -0
- package/src/lib/graph.ts +238 -0
- package/src/lib/grouping.ts +116 -0
- package/src/lib/links.ts +70 -0
- package/src/lib/occurrences.ts +93 -0
- package/src/lib/pageThumbnail.ts +43 -0
- package/src/lib/pages.ts +199 -0
- package/src/lib/paths.ts +68 -0
- package/src/lib/query.ts +113 -0
- package/src/lib/schemaColumns.ts +162 -0
- package/src/lib/schemaTypes.ts +75 -0
- package/src/lib/sectionsMap.ts +83 -0
- package/src/lib/service.ts +88 -0
- package/src/lib/siteRoutes.ts +43 -0
- package/src/lib/status.ts +122 -0
- package/src/lib/studioLinks.ts +137 -0
- package/src/schema/boardLayout.ts +190 -0
- package/src/tools/components/BlockCard.tsx +79 -0
- package/src/tools/components/ComponentsTool.tsx +171 -0
- package/src/tools/components/map/SectionNode.tsx +109 -0
- package/src/tools/components/map/SectionsMap.tsx +339 -0
- package/src/tools/createToolComponent.tsx +67 -0
- package/src/tools/history/ChangeRow.tsx +87 -0
- package/src/tools/history/DiffPanel.tsx +227 -0
- package/src/tools/history/HistoryTool.tsx +230 -0
- package/src/tools/more/MoreTool.tsx +82 -0
- package/src/tools/pages/ColumnHeader.tsx +216 -0
- package/src/tools/pages/ColumnVisibility.tsx +173 -0
- package/src/tools/pages/FieldValue.tsx +327 -0
- package/src/tools/pages/PagesTable.tsx +394 -0
- package/src/tools/pages/PagesTool.tsx +333 -0
- package/src/tools/pages/PagesToolbar.tsx +53 -0
- package/src/tools/pages/PathCell.tsx +71 -0
- package/src/tools/pages/PreviewTarget.tsx +226 -0
- package/src/tools/pages/TagCell.tsx +124 -0
- package/src/tools/pages/ViewTabs.tsx +57 -0
- package/src/tools/pages/board/BoardView.tsx +661 -0
- package/src/tools/pages/board/PageNode.tsx +306 -0
- package/src/tools/pages/board/PagePanel.tsx +228 -0
- package/src/tools/presentation/PreviewHeader.tsx +75 -0
- package/src/tools/shared/AnnotationNode.tsx +126 -0
- package/src/ui/ActorName.tsx +20 -0
- package/src/ui/ConfigIssues.tsx +41 -0
- package/src/ui/InlineCode.tsx +22 -0
- package/src/ui/Popover.tsx +85 -0
- package/src/ui/ProjectStatusNotice.tsx +58 -0
- package/src/ui/QueryError.tsx +16 -0
- package/src/ui/QuietInput.tsx +64 -0
- package/src/ui/StatusBadge.tsx +11 -0
- package/src/ui/ToolPlaceholder.tsx +23 -0
- package/src/ui/formatDate.ts +14 -0
- package/src/ui/tokens.ts +54 -0
- package/src/version.ts +5 -0
- package/src/web/PreviewBanner.tsx +115 -0
- package/src/web/draftModeToggle.ts +56 -0
- package/src/web/environment.ts +21 -0
- package/src/web/index.ts +15 -0
- package/src/web/server.ts +11 -0
package/src/lib/pages.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import type {ResolvedDocumentColumn, ResolvedKitConfig} from '../config/types'
|
|
2
|
+
import {pageTypeFor, toPath, toUrl} from './paths'
|
|
3
|
+
import {DATA_PREFIX} from './query'
|
|
4
|
+
import {mergeVersions, type PageStatus, type VersionedDoc} from './status'
|
|
5
|
+
|
|
6
|
+
/** Document tel que le renvoie `buildPagesQuery`. */
|
|
7
|
+
export interface PageDoc extends VersionedDoc {
|
|
8
|
+
ncfTitle?: string | null
|
|
9
|
+
ncfSlug?: string | null
|
|
10
|
+
ncfLocale?: string | null
|
|
11
|
+
ncfBlockCount?: number | null
|
|
12
|
+
ncfNoindex?: boolean | null
|
|
13
|
+
/** Projections `ncfData_<clé>` des colonnes de données déclarées. */
|
|
14
|
+
[key: string]: unknown
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PageRow {
|
|
18
|
+
/** Identifiant du document publié (sans préfixe `drafts.`). */
|
|
19
|
+
id: string
|
|
20
|
+
type: string
|
|
21
|
+
title: string
|
|
22
|
+
/** Chemin sur le site, ou `null` si le type n'en permet pas le calcul. */
|
|
23
|
+
path: string | null
|
|
24
|
+
url: string | null
|
|
25
|
+
locale: string | null
|
|
26
|
+
status: PageStatus
|
|
27
|
+
updatedAt: string | null
|
|
28
|
+
blockCount: number
|
|
29
|
+
/** Marquée non indexable dans le CMS. */
|
|
30
|
+
noindex: boolean
|
|
31
|
+
/** Données du document, déjà mises en forme pour une cellule. */
|
|
32
|
+
data: Record<string, string>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Met une valeur du document en forme pour une cellule.
|
|
37
|
+
*
|
|
38
|
+
* Ce qui ne tient pas sur une ligne — un objet, un tableau de sections — n'est
|
|
39
|
+
* pas tronqué mais écarté : une cellule affichant `[object Object]` vaut moins
|
|
40
|
+
* qu'une cellule vide.
|
|
41
|
+
*/
|
|
42
|
+
export function formatDocumentValue(
|
|
43
|
+
value: unknown,
|
|
44
|
+
type: 'text' | 'boolean' | 'number',
|
|
45
|
+
invert = false,
|
|
46
|
+
): string {
|
|
47
|
+
if (value === null || value === undefined) return type === 'boolean' && invert ? 'Oui' : ''
|
|
48
|
+
if (type === 'boolean') return (invert ? !value : Boolean(value)) ? 'Oui' : 'Non'
|
|
49
|
+
if (type === 'number') return typeof value === 'number' ? String(value) : ''
|
|
50
|
+
if (typeof value === 'string') return value.trim()
|
|
51
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
|
|
52
|
+
return ''
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function buildPageRows(
|
|
56
|
+
docs: readonly PageDoc[],
|
|
57
|
+
config: ResolvedKitConfig,
|
|
58
|
+
documentColumns: readonly ResolvedDocumentColumn[] = [],
|
|
59
|
+
): PageRow[] {
|
|
60
|
+
return mergeVersions(docs).map((merged) => {
|
|
61
|
+
const doc = merged.doc
|
|
62
|
+
const pageType = pageTypeFor(doc._type, config.pageTypes)
|
|
63
|
+
const path = toPath(
|
|
64
|
+
{
|
|
65
|
+
slug: doc.ncfSlug ?? null,
|
|
66
|
+
path: pageType?.path ?? null,
|
|
67
|
+
pathPrefix: pageType?.pathPrefix ?? null,
|
|
68
|
+
locale: doc.ncfLocale ?? null,
|
|
69
|
+
},
|
|
70
|
+
config.i18n,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
id: merged.id,
|
|
75
|
+
type: doc._type,
|
|
76
|
+
title: doc.ncfTitle?.trim() || 'Sans titre',
|
|
77
|
+
path,
|
|
78
|
+
url: toUrl(config.previewUrl, path),
|
|
79
|
+
locale: doc.ncfLocale ?? null,
|
|
80
|
+
status: merged.status,
|
|
81
|
+
updatedAt: merged.updatedAt ?? null,
|
|
82
|
+
blockCount: doc.ncfBlockCount ?? 0,
|
|
83
|
+
noindex: Boolean(doc.ncfNoindex),
|
|
84
|
+
data: Object.fromEntries(
|
|
85
|
+
documentColumns.map((column) => [
|
|
86
|
+
column.key,
|
|
87
|
+
formatDocumentValue(
|
|
88
|
+
(doc as Record<string, unknown>)[`${DATA_PREFIX}${column.key}`],
|
|
89
|
+
column.type,
|
|
90
|
+
column.invert,
|
|
91
|
+
),
|
|
92
|
+
]),
|
|
93
|
+
),
|
|
94
|
+
}
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/* --- Tri --- */
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* `structure` reproduit l'ordre du Studio : les types dans l'ordre où
|
|
102
|
+
* `pageTypes` les déclare, puis les titres. C'est l'ordre par défaut, celui
|
|
103
|
+
* que l'éditeur a déjà en tête en arrivant de la structure.
|
|
104
|
+
*/
|
|
105
|
+
export type SortKey =
|
|
106
|
+
| 'structure'
|
|
107
|
+
| 'title'
|
|
108
|
+
| 'type'
|
|
109
|
+
| 'path'
|
|
110
|
+
| 'status'
|
|
111
|
+
| 'updatedAt'
|
|
112
|
+
| 'blockCount'
|
|
113
|
+
export type SortDirection = 'asc' | 'desc'
|
|
114
|
+
|
|
115
|
+
/** Ordre d'affichage des statuts : du plus « à traiter » au plus stable. */
|
|
116
|
+
const STATUS_ORDER: Record<PageStatus, number> = {modified: 0, draft: 1, published: 2}
|
|
117
|
+
|
|
118
|
+
export interface SortOptions {
|
|
119
|
+
/** Ordre de déclaration des types, pour le tri « structure ». */
|
|
120
|
+
typeOrder?: readonly string[]
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const compare = (a: PageRow, b: PageRow, key: SortKey, options: SortOptions): number => {
|
|
124
|
+
switch (key) {
|
|
125
|
+
case 'structure': {
|
|
126
|
+
const order = options.typeOrder ?? []
|
|
127
|
+
const rank = (row: PageRow) => {
|
|
128
|
+
const index = order.indexOf(row.type)
|
|
129
|
+
// Un type hors liste passe après ceux qui y sont.
|
|
130
|
+
return index === -1 ? order.length : index
|
|
131
|
+
}
|
|
132
|
+
return rank(a) - rank(b) || a.title.localeCompare(b.title, 'fr')
|
|
133
|
+
}
|
|
134
|
+
case 'title':
|
|
135
|
+
return a.title.localeCompare(b.title, 'fr')
|
|
136
|
+
case 'type':
|
|
137
|
+
return a.type.localeCompare(b.type, 'fr') || a.title.localeCompare(b.title, 'fr')
|
|
138
|
+
case 'path':
|
|
139
|
+
// Les pages sans chemin en dernier : elles n'ont pas de place dans l'arbre.
|
|
140
|
+
if (a.path === null || b.path === null) {
|
|
141
|
+
return Number(a.path === null) - Number(b.path === null)
|
|
142
|
+
}
|
|
143
|
+
return a.path.localeCompare(b.path, 'fr')
|
|
144
|
+
case 'status':
|
|
145
|
+
return STATUS_ORDER[a.status] - STATUS_ORDER[b.status] ||
|
|
146
|
+
a.title.localeCompare(b.title, 'fr')
|
|
147
|
+
case 'updatedAt':
|
|
148
|
+
// Jamais modifié = le plus ancien possible.
|
|
149
|
+
return (a.updatedAt ?? '').localeCompare(b.updatedAt ?? '')
|
|
150
|
+
case 'blockCount':
|
|
151
|
+
return a.blockCount - b.blockCount
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function sortRows(
|
|
156
|
+
rows: readonly PageRow[],
|
|
157
|
+
key: SortKey,
|
|
158
|
+
direction: SortDirection,
|
|
159
|
+
options: SortOptions = {},
|
|
160
|
+
): PageRow[] {
|
|
161
|
+
const sorted = [...rows].sort((a, b) => compare(a, b, key, options))
|
|
162
|
+
return direction === 'asc' ? sorted : sorted.reverse()
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/* --- Filtres --- */
|
|
166
|
+
|
|
167
|
+
export interface PageFilters {
|
|
168
|
+
types?: readonly string[]
|
|
169
|
+
statuses?: readonly PageStatus[]
|
|
170
|
+
locales?: readonly string[]
|
|
171
|
+
/** Recherche insensible à la casse et aux accents, sur le titre et le chemin. */
|
|
172
|
+
search?: string
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const normalize = (value: string): string =>
|
|
176
|
+
value
|
|
177
|
+
.toLocaleLowerCase('fr')
|
|
178
|
+
.normalize('NFD')
|
|
179
|
+
.replace(/\p{Diacritic}/gu, '')
|
|
180
|
+
|
|
181
|
+
export function filterRows(rows: readonly PageRow[], filters: PageFilters): PageRow[] {
|
|
182
|
+
const search = filters.search?.trim() ? normalize(filters.search.trim()) : null
|
|
183
|
+
|
|
184
|
+
return rows.filter((row) => {
|
|
185
|
+
if (filters.types?.length && !filters.types.includes(row.type)) return false
|
|
186
|
+
if (filters.statuses?.length && !filters.statuses.includes(row.status)) return false
|
|
187
|
+
if (filters.locales?.length && !filters.locales.includes(row.locale ?? '')) return false
|
|
188
|
+
if (search) {
|
|
189
|
+
const haystack = `${normalize(row.title)} ${normalize(row.path ?? '')}`
|
|
190
|
+
if (!haystack.includes(search)) return false
|
|
191
|
+
}
|
|
192
|
+
return true
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Langues réellement présentes, pour ne proposer que des filtres utiles. */
|
|
197
|
+
export function localesInRows(rows: readonly PageRow[]): string[] {
|
|
198
|
+
return [...new Set(rows.map((r) => r.locale).filter((l): l is string => Boolean(l)))].sort()
|
|
199
|
+
}
|
package/src/lib/paths.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import {normalizePath} from '../config/resolve'
|
|
2
|
+
import type {ResolvedI18n, ResolvedPageType} from '../config/types'
|
|
3
|
+
|
|
4
|
+
export interface PathInput {
|
|
5
|
+
/** Valeur du champ slug (`slug.current`). Peut contenir des `/`. */
|
|
6
|
+
slug?: string | null
|
|
7
|
+
/** Chemin fixe du type de page, s'il en a un. */
|
|
8
|
+
path?: string | null
|
|
9
|
+
/** Préfixe d'URL du type de page ('/blog'), devant le slug. */
|
|
10
|
+
pathPrefix?: string | null
|
|
11
|
+
/** Langue du document. */
|
|
12
|
+
locale?: string | null
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Chemin d'une page sur le site. Le chemin fixe l'emporte sur le slug, le
|
|
17
|
+
* préfixe du type se place devant le slug ('/blog' + 'mon-article'), et la
|
|
18
|
+
* langue par défaut n'est pas préfixée (convention Next.js du starter).
|
|
19
|
+
*/
|
|
20
|
+
export function toPath(input: PathInput, i18n: ResolvedI18n | null): string | null {
|
|
21
|
+
const prefix =
|
|
22
|
+
typeof input.pathPrefix === 'string' && input.pathPrefix ? normalizePath(input.pathPrefix) : '/'
|
|
23
|
+
const base =
|
|
24
|
+
typeof input.path === 'string' && input.path
|
|
25
|
+
? normalizePath(input.path)
|
|
26
|
+
: input.slug
|
|
27
|
+
? normalizePath(prefix === '/' ? input.slug : `${prefix}/${input.slug.replace(/^\/+/, '')}`)
|
|
28
|
+
: null
|
|
29
|
+
|
|
30
|
+
if (base === null) return null
|
|
31
|
+
if (!i18n || !input.locale || input.locale === i18n.defaultLocale) return base
|
|
32
|
+
return base === '/' ? `/${input.locale}` : `/${input.locale}${base}`
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** URL absolue d'une page, ou `null` si le front n'est pas configuré. */
|
|
36
|
+
export function toUrl(previewUrl: string | null, path: string | null): string | null {
|
|
37
|
+
if (!previewUrl || path === null) return null
|
|
38
|
+
return path === '/' ? previewUrl : `${previewUrl}${path}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Segments d'un chemin : '/services/plomberie' -> ['services', 'plomberie']. */
|
|
42
|
+
export function segments(path: string): string[] {
|
|
43
|
+
return path.split('/').filter(Boolean)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Profondeur dans l'arborescence. '/' vaut 0. */
|
|
47
|
+
export function depth(path: string): number {
|
|
48
|
+
return segments(path).length
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Chemin du parent, ou `null` à la racine. Sert au placement automatique du
|
|
53
|
+
* board : '/services/plomberie' -> '/services'.
|
|
54
|
+
*/
|
|
55
|
+
export function parentPath(path: string): string | null {
|
|
56
|
+
const parts = segments(path)
|
|
57
|
+
if (parts.length === 0) return null
|
|
58
|
+
if (parts.length === 1) return '/'
|
|
59
|
+
return `/${parts.slice(0, -1).join('/')}`
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Le type de page correspondant à un document. */
|
|
63
|
+
export function pageTypeFor(
|
|
64
|
+
type: string,
|
|
65
|
+
pageTypes: ResolvedPageType[],
|
|
66
|
+
): ResolvedPageType | undefined {
|
|
67
|
+
return pageTypes.find((p) => p.type === type)
|
|
68
|
+
}
|
package/src/lib/query.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type {ResolvedDocumentColumn, ResolvedKitConfig} from '../config/types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Les projections sont préfixées `ncf` pour ne jamais entrer en collision avec
|
|
5
|
+
* un champ du client, quel que soit son schéma.
|
|
6
|
+
*/
|
|
7
|
+
export const PROJECTION = {
|
|
8
|
+
title: 'ncfTitle',
|
|
9
|
+
slug: 'ncfSlug',
|
|
10
|
+
locale: 'ncfLocale',
|
|
11
|
+
blockCount: 'ncfBlockCount',
|
|
12
|
+
noindex: 'ncfNoindex',
|
|
13
|
+
blocks: 'ncfBlocks',
|
|
14
|
+
} as const
|
|
15
|
+
|
|
16
|
+
/** Préfixe des projections de données de page, une par colonne déclarée. */
|
|
17
|
+
export const DATA_PREFIX = 'ncfData_'
|
|
18
|
+
|
|
19
|
+
/** Clé de colonne acceptable : elle devient un nom de projection GROQ. */
|
|
20
|
+
export const isSafeColumnKey = (key: string): boolean => /^[A-Za-z][A-Za-z0-9_]*$/.test(key)
|
|
21
|
+
|
|
22
|
+
/** Chemin de champ GROQ acceptable : identifiants séparés par des points. */
|
|
23
|
+
export const isSafeFieldPath = (path: string): boolean =>
|
|
24
|
+
/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(path)
|
|
25
|
+
|
|
26
|
+
const distinct = (values: readonly (string | null)[]): string[] =>
|
|
27
|
+
[...new Set(values.filter((v): v is string => Boolean(v)))]
|
|
28
|
+
|
|
29
|
+
const coalesce = (expressions: string[], fallback: string): string =>
|
|
30
|
+
expressions.length === 0
|
|
31
|
+
? fallback
|
|
32
|
+
: expressions.length === 1
|
|
33
|
+
? (expressions[0] as string)
|
|
34
|
+
: `coalesce(${expressions.join(', ')}, ${fallback})`
|
|
35
|
+
|
|
36
|
+
/** Expression du titre, fusionnée quand les types utilisent des champs différents. */
|
|
37
|
+
function titleExpression(config: ResolvedKitConfig): string {
|
|
38
|
+
const fields = distinct(config.pageTypes.map((p) => p.titleField)).filter(isSafeFieldPath)
|
|
39
|
+
return coalesce(fields, '_id')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Requête de la liste des pages : projection légère, sans le contenu du page
|
|
44
|
+
* builder. Seul son cardinal est remonté, pour que 500 pages restent tenables.
|
|
45
|
+
*
|
|
46
|
+
* Les champs titre et slug pouvant différer d'un type à l'autre, ils sont
|
|
47
|
+
* fusionnés par `coalesce` plutôt que projetés type par type.
|
|
48
|
+
*/
|
|
49
|
+
export function buildPagesQuery(
|
|
50
|
+
config: ResolvedKitConfig,
|
|
51
|
+
/** Seules les colonnes réellement affichées sont projetées. */
|
|
52
|
+
documentColumns: readonly ResolvedDocumentColumn[] = [],
|
|
53
|
+
): string {
|
|
54
|
+
const slugFields = distinct(config.pageTypes.map((p) => p.slugField)).filter(isSafeFieldPath)
|
|
55
|
+
|
|
56
|
+
const title = titleExpression(config)
|
|
57
|
+
const slug = coalesce(
|
|
58
|
+
slugFields.map((field) => `${field}.current`),
|
|
59
|
+
'null',
|
|
60
|
+
)
|
|
61
|
+
const locale =
|
|
62
|
+
config.i18n && isSafeFieldPath(config.i18n.field) ? config.i18n.field : 'null'
|
|
63
|
+
// Plusieurs conventions coexistent selon les projets : on prend la première
|
|
64
|
+
// valeur renseignée, et « indexable » par défaut.
|
|
65
|
+
const noindexPaths = config.noindexFields.filter(isSafeFieldPath)
|
|
66
|
+
const noindex =
|
|
67
|
+
noindexPaths.length > 0 ? `coalesce(${noindexPaths.join(', ')}, false)` : 'false'
|
|
68
|
+
|
|
69
|
+
// Une colonne dont aucun chemin n'est exploitable est projetée `null` plutôt
|
|
70
|
+
// qu'omise : la requête reste valide et la cellule s'affiche vide.
|
|
71
|
+
const dataColumns = documentColumns
|
|
72
|
+
.filter((column) => isSafeColumnKey(column.key))
|
|
73
|
+
.map((column) => {
|
|
74
|
+
const paths = column.paths.filter(isSafeFieldPath)
|
|
75
|
+
return ` "${DATA_PREFIX}${column.key}": ${coalesce(paths, 'null')},`
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
const blockCount = isSafeFieldPath(config.pageBuilderField)
|
|
79
|
+
? `count(${config.pageBuilderField})`
|
|
80
|
+
: '0'
|
|
81
|
+
|
|
82
|
+
return [
|
|
83
|
+
'*[_type in $types]{',
|
|
84
|
+
' _id, _type, _updatedAt,',
|
|
85
|
+
` "${PROJECTION.title}": ${title},`,
|
|
86
|
+
` "${PROJECTION.slug}": ${slug},`,
|
|
87
|
+
` "${PROJECTION.locale}": ${locale},`,
|
|
88
|
+
` "${PROJECTION.blockCount}": ${blockCount},`,
|
|
89
|
+
...dataColumns,
|
|
90
|
+
` "${PROJECTION.noindex}": ${noindex}`,
|
|
91
|
+
'}',
|
|
92
|
+
].join('\n')
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Requête du contenu complet des pages.
|
|
97
|
+
*
|
|
98
|
+
* Elle sert à deux choses qu'aucune projection GROQ ne peut exprimer
|
|
99
|
+
* génériquement : compter des blocs imbriqués à profondeur inconnue, et
|
|
100
|
+
* relever les liens internes où qu'ils se trouvent dans le document. D'où le
|
|
101
|
+
* document entier, la limite explicite, et le fait qu'elle ne parte qu'à
|
|
102
|
+
* l'ouverture de l'outil qui en a besoin.
|
|
103
|
+
*/
|
|
104
|
+
export function buildContentsQuery(config: ResolvedKitConfig, limit: number): string {
|
|
105
|
+
const field = isSafeFieldPath(config.pageBuilderField) ? config.pageBuilderField : 'null'
|
|
106
|
+
return [
|
|
107
|
+
`*[_type in $types][0...${limit}]{`,
|
|
108
|
+
' ...,',
|
|
109
|
+
` "${PROJECTION.title}": ${titleExpression(config)},`,
|
|
110
|
+
` "${PROJECTION.blocks}": ${field}`,
|
|
111
|
+
'}',
|
|
112
|
+
].join('\n')
|
|
113
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import type {ResolvedDocumentColumn} from '../config/types'
|
|
2
|
+
import {isSafeColumnKey, isSafeFieldPath} from './query'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Sous-ensemble du schéma du Studio dont on a besoin.
|
|
6
|
+
*
|
|
7
|
+
* Déclaré structurellement plutôt qu'importé de `@sanity/types` : le parcours
|
|
8
|
+
* reste une fonction pure, testable sans monter un Studio.
|
|
9
|
+
*/
|
|
10
|
+
export interface SchemaTypeLike {
|
|
11
|
+
name?: string
|
|
12
|
+
title?: string
|
|
13
|
+
jsonType?: string
|
|
14
|
+
fields?: SchemaFieldLike[]
|
|
15
|
+
/** Type parent, quand le champ hérite d'un type nommé. */
|
|
16
|
+
type?: SchemaTypeLike
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface SchemaFieldLike {
|
|
20
|
+
name: string
|
|
21
|
+
type?: SchemaTypeLike
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Types dont on ne tire rien : ils ne se rendent pas dans une cellule, ou
|
|
26
|
+
* demanderaient une jointure.
|
|
27
|
+
*/
|
|
28
|
+
const OPAQUE_TYPES = new Set([
|
|
29
|
+
'image',
|
|
30
|
+
'file',
|
|
31
|
+
'reference',
|
|
32
|
+
'crossDatasetReference',
|
|
33
|
+
'globalDocumentReference',
|
|
34
|
+
'block',
|
|
35
|
+
'geopoint',
|
|
36
|
+
])
|
|
37
|
+
|
|
38
|
+
/** Remonte la chaîne d'héritage jusqu'à trouver la nature JSON du champ. */
|
|
39
|
+
function jsonTypeOf(type: SchemaTypeLike | undefined): string | undefined {
|
|
40
|
+
let current = type
|
|
41
|
+
for (let depth = 0; current && depth < 10; depth += 1) {
|
|
42
|
+
if (current.jsonType) return current.jsonType
|
|
43
|
+
current = current.type
|
|
44
|
+
}
|
|
45
|
+
return undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Nom du type de schéma, `slug` ou `datetime` par exemple. */
|
|
49
|
+
function typeNameOf(type: SchemaTypeLike | undefined): string | undefined {
|
|
50
|
+
let current = type
|
|
51
|
+
for (let depth = 0; current && depth < 10; depth += 1) {
|
|
52
|
+
if (current.name && current.name !== current.type?.name) return current.name
|
|
53
|
+
current = current.type
|
|
54
|
+
}
|
|
55
|
+
return type?.name
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isOpaque(type: SchemaTypeLike | undefined): boolean {
|
|
59
|
+
let current = type
|
|
60
|
+
for (let depth = 0; current && depth < 10; depth += 1) {
|
|
61
|
+
if (current.name && OPAQUE_TYPES.has(current.name)) return true
|
|
62
|
+
current = current.type
|
|
63
|
+
}
|
|
64
|
+
return false
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const labelOf = (field: SchemaFieldLike): string =>
|
|
68
|
+
field.type?.title?.trim() || humanise(field.name)
|
|
69
|
+
|
|
70
|
+
/** `metaDescription` → `Meta description`. */
|
|
71
|
+
function humanise(name: string): string {
|
|
72
|
+
const spaced = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ')
|
|
73
|
+
return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `seo.description` → `seo_description`, utilisable comme nom de projection. */
|
|
77
|
+
export function keyForPath(path: string): string {
|
|
78
|
+
return path.replace(/\./g, '_')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface DeriveOptions {
|
|
82
|
+
/** Chemins déjà représentés ailleurs dans le tableau. */
|
|
83
|
+
exclude?: readonly string[]
|
|
84
|
+
/** Profondeur d'imbrication explorée. 1 couvre `seo.description`. */
|
|
85
|
+
depth?: number
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Colonnes tirées du schéma des types de page.
|
|
90
|
+
*
|
|
91
|
+
* Aucune liste à tenir à jour : ce que le client stocke au niveau de la page
|
|
92
|
+
* est proposé, et lui seul sait ce qu'il veut voir. Seules les valeurs qui
|
|
93
|
+
* tiennent sur une ligne sont retenues — un tableau de sections ou une image
|
|
94
|
+
* n'ont rien à faire dans une cellule.
|
|
95
|
+
*
|
|
96
|
+
* Les types se recouvrent souvent : un même chemin trouvé sur deux types ne
|
|
97
|
+
* donne qu'une colonne, que la requête résoudra par `coalesce`.
|
|
98
|
+
*/
|
|
99
|
+
export function deriveDocumentColumns(
|
|
100
|
+
types: readonly (SchemaTypeLike | undefined)[],
|
|
101
|
+
options: DeriveOptions = {},
|
|
102
|
+
): ResolvedDocumentColumn[] {
|
|
103
|
+
const excluded = new Set(options.exclude ?? [])
|
|
104
|
+
const maxDepth = options.depth ?? 1
|
|
105
|
+
const found = new Map<string, ResolvedDocumentColumn>()
|
|
106
|
+
|
|
107
|
+
const visit = (
|
|
108
|
+
fields: readonly SchemaFieldLike[],
|
|
109
|
+
prefix: string,
|
|
110
|
+
prefixLabel: string,
|
|
111
|
+
depth: number,
|
|
112
|
+
) => {
|
|
113
|
+
for (const field of fields) {
|
|
114
|
+
if (!field.name || field.name.startsWith('_')) continue
|
|
115
|
+
|
|
116
|
+
const path = prefix ? `${prefix}.${field.name}` : field.name
|
|
117
|
+
if (excluded.has(path) || !isSafeFieldPath(path)) continue
|
|
118
|
+
|
|
119
|
+
const label = prefixLabel ? `${prefixLabel} · ${labelOf(field)}` : labelOf(field)
|
|
120
|
+
const json = jsonTypeOf(field.type)
|
|
121
|
+
const typeName = typeNameOf(field.type)
|
|
122
|
+
|
|
123
|
+
// Un slug ne vaut que par son `current` : la cellule montre le chemin,
|
|
124
|
+
// pas l'objet qui l'enveloppe.
|
|
125
|
+
if (typeName === 'slug') {
|
|
126
|
+
add(found, `${path}.current`, label, 'text', excluded)
|
|
127
|
+
continue
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (isOpaque(field.type)) continue
|
|
131
|
+
|
|
132
|
+
if (json === 'string' || json === 'number' || json === 'boolean') {
|
|
133
|
+
add(found, path, label, json === 'string' ? 'text' : json, excluded)
|
|
134
|
+
continue
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (json === 'object' && depth < maxDepth && field.type?.fields?.length) {
|
|
138
|
+
visit(field.type.fields, path, label, depth + 1)
|
|
139
|
+
}
|
|
140
|
+
// Les tableaux sont écartés sans descendre : rien d'exploitable en ligne.
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
for (const type of types) {
|
|
145
|
+
if (type?.fields?.length) visit(type.fields, '', '', 0)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return [...found.values()]
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function add(
|
|
152
|
+
found: Map<string, ResolvedDocumentColumn>,
|
|
153
|
+
path: string,
|
|
154
|
+
label: string,
|
|
155
|
+
type: 'text' | 'boolean' | 'number',
|
|
156
|
+
excluded: ReadonlySet<string>,
|
|
157
|
+
): void {
|
|
158
|
+
if (excluded.has(path) || found.has(path)) return
|
|
159
|
+
const key = keyForPath(path)
|
|
160
|
+
if (!isSafeColumnKey(key)) return
|
|
161
|
+
found.set(path, {key, label, paths: [path], type})
|
|
162
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type {ArraySchemaType, ObjectSchemaType, Schema, SchemaType} from 'sanity'
|
|
2
|
+
import type {ResolvedPageType} from '../config/types'
|
|
3
|
+
|
|
4
|
+
export interface BlockTypeInfo {
|
|
5
|
+
name: string
|
|
6
|
+
title: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const isObjectType = (type: SchemaType | undefined): type is ObjectSchemaType =>
|
|
10
|
+
Boolean(type && 'fields' in type && Array.isArray((type as ObjectSchemaType).fields))
|
|
11
|
+
|
|
12
|
+
const isArrayType = (type: SchemaType | undefined): type is ArraySchemaType =>
|
|
13
|
+
Boolean(type && 'of' in type && Array.isArray((type as ArraySchemaType).of))
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Types de blocs autorisés dans le page builder, lus dans le schéma du Studio.
|
|
17
|
+
*
|
|
18
|
+
* Jamais saisis à la main : la liste vient des types déclarés dans le champ
|
|
19
|
+
* `of` du tableau, exactement comme le menu d'insertion la construit. Un bloc
|
|
20
|
+
* ajouté au schéma apparaît donc ici sans toucher au kit.
|
|
21
|
+
*/
|
|
22
|
+
export function blockTypesFromSchema(
|
|
23
|
+
schema: Schema,
|
|
24
|
+
pageTypes: readonly ResolvedPageType[],
|
|
25
|
+
pageBuilderField: string,
|
|
26
|
+
): BlockTypeInfo[] {
|
|
27
|
+
const found = new Map<string, BlockTypeInfo>()
|
|
28
|
+
|
|
29
|
+
for (const pageType of pageTypes) {
|
|
30
|
+
const documentType = schema.get(pageType.type)
|
|
31
|
+
if (!isObjectType(documentType)) continue
|
|
32
|
+
|
|
33
|
+
const field = documentType.fields.find((f) => f.name === pageBuilderField)
|
|
34
|
+
if (!field || !isArrayType(field.type)) continue
|
|
35
|
+
|
|
36
|
+
for (const member of field.type.of) {
|
|
37
|
+
// L'ordre du schéma fait foi : c'est celui du menu d'insertion.
|
|
38
|
+
if (!member.name || found.has(member.name)) continue
|
|
39
|
+
found.set(member.name, {name: member.name, title: member.title ?? member.name})
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return [...found.values()]
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Types de pages déclarés dans la config mais absents du schéma. Une faute de
|
|
48
|
+
* frappe dans `pageTypes` se traduirait sinon par une liste vide et aucune
|
|
49
|
+
* explication.
|
|
50
|
+
*/
|
|
51
|
+
export function missingPageTypes(
|
|
52
|
+
schema: Schema,
|
|
53
|
+
pageTypes: readonly ResolvedPageType[],
|
|
54
|
+
): string[] {
|
|
55
|
+
return pageTypes.filter((p) => !schema.get(p.type)).map((p) => p.type)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Types de pages dont le champ page builder est absent du schéma. Ils restent
|
|
60
|
+
* listables, mais leur nombre de blocs sera toujours nul.
|
|
61
|
+
*/
|
|
62
|
+
export function pageTypesWithoutBuilder(
|
|
63
|
+
schema: Schema,
|
|
64
|
+
pageTypes: readonly ResolvedPageType[],
|
|
65
|
+
pageBuilderField: string,
|
|
66
|
+
): string[] {
|
|
67
|
+
return pageTypes
|
|
68
|
+
.filter((pageType) => {
|
|
69
|
+
const documentType = schema.get(pageType.type)
|
|
70
|
+
if (!isObjectType(documentType)) return false
|
|
71
|
+
const field = documentType.fields.find((f) => f.name === pageBuilderField)
|
|
72
|
+
return !field || !isArrayType(field.type)
|
|
73
|
+
})
|
|
74
|
+
.map((p) => p.type)
|
|
75
|
+
}
|