@nocode-factory/sanity-kit 2.52.0 → 2.54.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 (43) hide show
  1. package/README.md +36 -4
  2. package/dist/{finalUrl-CaFXmYvm.js → finalUrl-IXF3zbT9.js} +7 -2
  3. package/dist/finalUrl-IXF3zbT9.js.map +1 -0
  4. package/dist/{fixCrossLanguageReferences-w3whO9xM.d.ts → fixCrossLanguageReferences-C1VsmGsJ.d.ts} +21 -2
  5. package/dist/{fixCrossLanguageReferences-BeXywAAU.js → fixCrossLanguageReferences-CDczoic9.js} +2 -2
  6. package/dist/{fixCrossLanguageReferences-BeXywAAU.js.map → fixCrossLanguageReferences-CDczoic9.js.map} +1 -1
  7. package/dist/index.d.ts +186 -8
  8. package/dist/index.js +1136 -121
  9. package/dist/index.js.map +1 -1
  10. package/dist/jsonld.js +1 -1
  11. package/dist/schema.d.ts +1 -1
  12. package/dist/schema.js +2 -2
  13. package/package.json +1 -1
  14. package/src/config/resolve.ts +5 -0
  15. package/src/config/types.ts +21 -0
  16. package/src/hooks/useAssetDelete.ts +60 -0
  17. package/src/hooks/useBoardLayout.ts +25 -1
  18. package/src/hooks/useCollection.ts +51 -0
  19. package/src/index.ts +23 -1
  20. package/src/lib/assetRefs.ts +53 -0
  21. package/src/lib/collectionColumns.ts +114 -0
  22. package/src/lib/collectionQuery.ts +23 -0
  23. package/src/lib/collectionRows.ts +92 -0
  24. package/src/lib/collectionTable.ts +72 -0
  25. package/src/lib/collectionTypes.ts +49 -0
  26. package/src/lib/csv.ts +24 -0
  27. package/src/lib/download.ts +24 -0
  28. package/src/lib/i18nTemplates.ts +40 -0
  29. package/src/lib/pageOrder.ts +36 -0
  30. package/src/lib/pages.ts +11 -1
  31. package/src/lib/schemaColumns.ts +18 -5
  32. package/src/schema/boardLayout.ts +7 -0
  33. package/src/structure/collections.tsx +103 -0
  34. package/src/tools/assets/AssetCard.tsx +8 -10
  35. package/src/tools/assets/AssetDetail.tsx +97 -2
  36. package/src/tools/assets/AssetsTool.tsx +28 -11
  37. package/src/tools/collections/CollectionColumnPicker.tsx +122 -0
  38. package/src/tools/collections/CollectionTable.tsx +259 -0
  39. package/src/tools/collections/CollectionToolbar.tsx +68 -0
  40. package/src/tools/pages/PagesTool.tsx +15 -9
  41. package/src/tools/presentation/PagesNavigator.tsx +51 -6
  42. package/src/version.ts +1 -1
  43. package/dist/finalUrl-CaFXmYvm.js.map +0 -1
package/dist/jsonld.js CHANGED
@@ -1,4 +1,4 @@
1
- import { o as pageTypeFor, t as finalPath, u as toUrl } from "./finalUrl-CaFXmYvm.js";
1
+ import { o as pageTypeFor, t as finalPath, u as toUrl } from "./finalUrl-IXF3zbT9.js";
2
2
  import { c as valueAtKey, f as useOptionalKitConfig, i as guessDocumentTitle, n as DEFAULT_JSONLD_FIELD, r as collectDocumentText, t as generateJsonLd } from "./aiJsonLd-BFyxgYen.js";
3
3
  import { useCallback, useMemo, useState } from "react";
4
4
  import { defineField, defineType, set, setIfMissing, unset, useFormValue } from "sanity";
package/dist/schema.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as componentDefaultsMainDocuments, d as requiredUnlessDefault, f as requiredUnlessDefaultFor, i as SiteRoutesRegistry, l as defaultsFieldName, n as fixCrossLanguageReferences, o as DEFAULT_COMPONENT_DEFAULTS_TYPE, r as withSameLanguageReferences, s as componentDefaultsMainDocument, t as CrossLanguageReport, u as defineComponentDefaults } from "./fixCrossLanguageReferences-w3whO9xM.js";
1
+ import { c as componentDefaultsMainDocuments, d as requiredUnlessDefault, f as requiredUnlessDefaultFor, i as SiteRoutesRegistry, l as defaultsFieldName, n as fixCrossLanguageReferences, o as DEFAULT_COMPONENT_DEFAULTS_TYPE, r as withSameLanguageReferences, s as componentDefaultsMainDocument, t as CrossLanguageReport, u as defineComponentDefaults } from "./fixCrossLanguageReferences-C1VsmGsJ.js";
2
2
  import { ComponentType } from "react";
3
3
  import { SanityClient } from "sanity";
4
4
  import { ListItemBuilder, StructureBuilder } from "sanity/structure";
package/dist/schema.js CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as DEFAULT_PAGE_BUILDER_FIELD, i as redirectMapOf, l as toPath, n as followRedirects, r as redirectKey } from "./finalUrl-CaFXmYvm.js";
2
- import { a as componentDefaultsMainDocument, c as defineComponentDefaults, d as syncTranslationRedirects, f as translationRedirectId, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, l as requiredUnlessDefault, n as withSameLanguageReferences, o as componentDefaultsMainDocuments, r as pageTypesFromSiteRoutes, s as defaultsFieldName, t as fixCrossLanguageReferences, u as requiredUnlessDefaultFor } from "./fixCrossLanguageReferences-BeXywAAU.js";
1
+ import { _ as DEFAULT_PAGE_BUILDER_FIELD, i as redirectMapOf, l as toPath, n as followRedirects, r as redirectKey } from "./finalUrl-IXF3zbT9.js";
2
+ import { a as componentDefaultsMainDocument, c as defineComponentDefaults, d as syncTranslationRedirects, f as translationRedirectId, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, l as requiredUnlessDefault, n as withSameLanguageReferences, o as componentDefaultsMainDocuments, r as pageTypesFromSiteRoutes, s as defaultsFieldName, t as fixCrossLanguageReferences, u as requiredUnlessDefaultFor } from "./fixCrossLanguageReferences-CDczoic9.js";
3
3
  /**
4
4
  * Onglets du formulaire d'un document : Content, Sections, SEO, Settings.
5
5
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.52.0",
3
+ "version": "2.54.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -150,6 +150,11 @@ export function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {
150
150
  paths: [column.path].flat().map((path) => path.trim()).filter(Boolean),
151
151
  type: column.type ?? 'text',
152
152
  })),
153
+ collections: {
154
+ include: (input.collections?.include ?? []).map((name) => name.trim()).filter(Boolean),
155
+ exclude: (input.collections?.exclude ?? []).map((name) => name.trim()).filter(Boolean),
156
+ labels: input.collections?.labels ?? {},
157
+ },
153
158
  }
154
159
  }
155
160
 
@@ -270,6 +270,20 @@ export interface NcfKitConfig {
270
270
  * Défaut : meta description, titre SEO, indexabilité.
271
271
  */
272
272
  documentColumns?: NcfDocumentColumn[]
273
+ /**
274
+ * Vue table « Airtable » des collections, posée dans l'onglet Structure via
275
+ * `ncfCollections(S, context, options)`. Par défaut, tous les types de
276
+ * documents hors pages, redirections et types techniques du kit sont
277
+ * proposés. `include` fixe une liste explicite (fait foi), `exclude` retire
278
+ * des types, `labels` renomme l'entrée d'un type.
279
+ */
280
+ collections?: NcfCollectionsConfig
281
+ }
282
+
283
+ export interface NcfCollectionsConfig {
284
+ include?: string[]
285
+ exclude?: string[]
286
+ labels?: Record<string, string>
273
287
  }
274
288
 
275
289
  /* --- Configuration résolue : ce que voient les outils --- */
@@ -326,6 +340,13 @@ export interface ResolvedKitConfig {
326
340
  boardTags: NcfBoardTag[]
327
341
  internalFields: NcfInternalField[]
328
342
  documentColumns: ResolvedDocumentColumn[]
343
+ collections: ResolvedCollections
344
+ }
345
+
346
+ export interface ResolvedCollections {
347
+ include: string[]
348
+ exclude: string[]
349
+ labels: Record<string, string>
329
350
  }
330
351
 
331
352
  export interface ResolvedHistory {
@@ -0,0 +1,60 @@
1
+ import {useCallback} from 'react'
2
+ import {useKitClient} from './useKitClient'
3
+ import {assetUnsetPaths} from '../lib/assetRefs'
4
+
5
+ export interface AssetUsage {
6
+ /** Id (sans le préfixe brouillon). */
7
+ id: string
8
+ type: string
9
+ title: string
10
+ }
11
+
12
+ export interface AssetDeleteState {
13
+ /** Documents qui utilisent l'asset (dédoublonnés brouillon/publié). */
14
+ usage: (assetId: string) => Promise<AssetUsage[]>
15
+ /** Retire l'asset de tous les documents (champs vidés) puis le supprime. */
16
+ remove: (assetId: string) => Promise<void>
17
+ }
18
+
19
+ const baseId = (id: string): string => id.replace(/^drafts\./, '')
20
+
21
+ /**
22
+ * Suppression d'un asset depuis l'outil Assets. Sanity refuse de supprimer un
23
+ * asset référencé : on retire d'abord l'asset de chaque document (le champ
24
+ * devient vide), puis on supprime, dans une seule transaction.
25
+ */
26
+ export function useAssetDelete(): AssetDeleteState {
27
+ const client = useKitClient()
28
+
29
+ const usage = useCallback(
30
+ async (assetId: string): Promise<AssetUsage[]> => {
31
+ const docs = await client.fetch<{_id: string; _type: string; title?: string}[]>(
32
+ `*[references($id)]{_id, _type, "title": coalesce(title, name, originalFilename, slug.current, _id)}`,
33
+ {id: assetId},
34
+ )
35
+ const seen = new Map<string, AssetUsage>()
36
+ for (const doc of docs ?? []) {
37
+ const id = baseId(doc._id)
38
+ if (!seen.has(id)) seen.set(id, {id, type: doc._type, title: doc.title ?? id})
39
+ }
40
+ return [...seen.values()]
41
+ },
42
+ [client],
43
+ )
44
+
45
+ const remove = useCallback(
46
+ async (assetId: string): Promise<void> => {
47
+ const docs = await client.fetch<Record<string, unknown>[]>(`*[references($id)]`, {id: assetId})
48
+ const transaction = client.transaction()
49
+ for (const doc of docs ?? []) {
50
+ const paths = assetUnsetPaths(doc, assetId)
51
+ if (paths.length) transaction.patch(doc._id as string, {unset: paths})
52
+ }
53
+ transaction.delete(assetId)
54
+ await transaction.commit({visibility: 'async'})
55
+ },
56
+ [client],
57
+ )
58
+
59
+ return {usage, remove}
60
+ }
@@ -53,6 +53,9 @@ export interface BoardLayoutState {
53
53
  /** Notes et formes posées sur les canvas. */
54
54
  annotations: Annotation[]
55
55
  saveAnnotations: (next: readonly Annotation[]) => void
56
+ /** Ordre manuel des pages (liste d'ids), partagé Presentation / onglet Pages. */
57
+ pageOrder: string[]
58
+ savePageOrder: (ids: readonly string[]) => void
56
59
  /** Accès direct par identifiant de page, pour le rendu des nœuds. */
57
60
  byId: Map<string, NodeLayout>
58
61
  loading: boolean
@@ -117,6 +120,7 @@ export function useBoardLayoutState(): BoardLayoutState {
117
120
  const [columns, setColumns] = useState<NcfInternalField[]>([])
118
121
  const [columnsSet, setColumnsSet] = useState(false)
119
122
  const [annotations, setAnnotations] = useState<Annotation[]>([])
123
+ const [pageOrder, setPageOrder] = useState<string[]>([])
120
124
  const [loading, setLoading] = useState(true)
121
125
  const [saveError, setSaveError] = useState<Error | null>(null)
122
126
 
@@ -129,7 +133,8 @@ export function useBoardLayoutState(): BoardLayoutState {
129
133
  columns?: StoredColumn[]
130
134
  columnsSet?: boolean
131
135
  annotations?: StoredAnnotation[]
132
- } | null>(`*[_id == $id][0]{nodes, sections, columns, columnsSet, annotations}`, {
136
+ pageOrder?: string[]
137
+ } | null>(`*[_id == $id][0]{nodes, sections, columns, columnsSet, annotations, pageOrder}`, {
133
138
  id: BOARD_LAYOUT_ID,
134
139
  })
135
140
  .then((doc) => {
@@ -146,6 +151,7 @@ export function useBoardLayoutState(): BoardLayoutState {
146
151
  )
147
152
  setColumnsSet(Boolean(doc?.columnsSet))
148
153
  setAnnotations((doc?.annotations ?? []).map(({_key, ...rest}) => ({...rest})))
154
+ setPageOrder(Array.isArray(doc?.pageOrder) ? doc!.pageOrder.filter((id): id is string => typeof id === 'string') : [])
149
155
  })
150
156
  .catch(() => {
151
157
  // Pas de disposition lisible : on part du placement automatique
@@ -156,6 +162,7 @@ export function useBoardLayoutState(): BoardLayoutState {
156
162
  setColumns([])
157
163
  setColumnsSet(false)
158
164
  setAnnotations([])
165
+ setPageOrder([])
159
166
  }
160
167
  })
161
168
  .finally(() => {
@@ -181,11 +188,13 @@ export function useBoardLayoutState(): BoardLayoutState {
181
188
  const columnsRef = useRef<NcfInternalField[]>([])
182
189
  const columnsSetRef = useRef(false)
183
190
  const annotationsRef = useRef<Annotation[]>([])
191
+ const pageOrderRef = useRef<string[]>([])
184
192
  layoutRef.current = layout
185
193
  sectionsRef.current = sections
186
194
  columnsRef.current = columns
187
195
  columnsSetRef.current = columnsSet
188
196
  annotationsRef.current = annotations
197
+ pageOrderRef.current = pageOrder
189
198
 
190
199
  const write = useCallback(
191
200
  (next?: {
@@ -194,12 +203,14 @@ export function useBoardLayoutState(): BoardLayoutState {
194
203
  columns?: NcfInternalField[]
195
204
  columnsSet?: boolean
196
205
  annotations?: Annotation[]
206
+ pageOrder?: string[]
197
207
  }) => {
198
208
  const nodes = next?.nodes ?? layoutRef.current
199
209
  const nextSections = next?.sections ?? sectionsRef.current
200
210
  const nextColumns = next?.columns ?? columnsRef.current
201
211
  const nextColumnsSet = next?.columnsSet ?? columnsSetRef.current
202
212
  const nextAnnotations = next?.annotations ?? annotationsRef.current
213
+ const nextPageOrder = next?.pageOrder ?? pageOrderRef.current
203
214
  client
204
215
  .createOrReplace({
205
216
  _id: BOARD_LAYOUT_ID,
@@ -235,6 +246,7 @@ export function useBoardLayoutState(): BoardLayoutState {
235
246
  })),
236
247
  })),
237
248
  columnsSet: nextColumnsSet,
249
+ pageOrder: nextPageOrder,
238
250
  annotations: nextAnnotations.map((annotation) => ({
239
251
  _key: annotation.id,
240
252
  _type: 'ncfAnnotation',
@@ -364,6 +376,16 @@ export function useBoardLayoutState(): BoardLayoutState {
364
376
  write({sections: []})
365
377
  }, [write])
366
378
 
379
+ const savePageOrder = useCallback(
380
+ (ids: readonly string[]) => {
381
+ const value = [...ids]
382
+ setPageOrder(value)
383
+ if (timer.current) clearTimeout(timer.current)
384
+ timer.current = setTimeout(() => write({pageOrder: value}), 800)
385
+ },
386
+ [write],
387
+ )
388
+
367
389
  const sectionsByName = useMemo(
368
390
  () => new Map(sections.map((entry) => [entry.blockName, entry])),
369
391
  [sections],
@@ -390,6 +412,8 @@ export function useBoardLayoutState(): BoardLayoutState {
390
412
  saveColumns,
391
413
  annotations,
392
414
  saveAnnotations,
415
+ pageOrder,
416
+ savePageOrder,
393
417
  reset,
394
418
  resetSections,
395
419
  }
@@ -0,0 +1,51 @@
1
+ import {useMemo} from 'react'
2
+ import {useSchema} from 'sanity'
3
+ import {useQueryData} from './useQueryData'
4
+ import {deriveCollectionColumns, type CollectionColumn} from '../lib/collectionColumns'
5
+ import {buildCollectionQuery} from '../lib/collectionQuery'
6
+ import {buildCollectionRows, type CollectionDoc, type CollectionRow} from '../lib/collectionRows'
7
+ import type {SchemaTypeLike} from '../lib/schemaColumns'
8
+
9
+ export interface CollectionState {
10
+ /** Toutes les colonnes possibles du type (pour le sélecteur). */
11
+ allColumns: CollectionColumn[]
12
+ /** Colonnes réellement affichées (celles projetées). */
13
+ visibleColumns: CollectionColumn[]
14
+ rows: CollectionRow[]
15
+ loading: boolean
16
+ error: Error | null
17
+ refresh: () => void
18
+ }
19
+
20
+ /**
21
+ * Données d'une collection pour la vue table : colonnes tirées du schéma,
22
+ * lignes en direct. Seules les colonnes visibles sont projetées (comme
23
+ * `usePages`), pour ne pas tirer tout le schéma sur chaque document.
24
+ */
25
+ export function useCollection(type: string, visibleKeys: readonly string[]): CollectionState {
26
+ const schema = useSchema()
27
+
28
+ const allColumns = useMemo(
29
+ () => deriveCollectionColumns(schema.get(type) as SchemaTypeLike | undefined),
30
+ [schema, type],
31
+ )
32
+
33
+ const visibleColumns = useMemo(
34
+ () => visibleKeys.map((key) => allColumns.find((c) => c.key === key)).filter((c): c is CollectionColumn => Boolean(c)),
35
+ [allColumns, visibleKeys],
36
+ )
37
+
38
+ const query = useMemo(() => buildCollectionQuery(visibleColumns), [visibleColumns])
39
+ const params = useMemo(() => ({type}), [type])
40
+
41
+ const {data, loading, error, refresh} = useQueryData<CollectionDoc[]>(query, params, {
42
+ listenTypes: [type],
43
+ })
44
+
45
+ const rows = useMemo(
46
+ () => buildCollectionRows(data ?? [], visibleColumns),
47
+ [data, visibleColumns],
48
+ )
49
+
50
+ return {allColumns, visibleColumns, rows, loading, error, refresh}
51
+ }
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@ import {HistoryTool} from './tools/history/HistoryTool'
18
18
  import {DesignSystemTool} from './tools/designSystem/DesignSystemTool'
19
19
  import {AssetsTool} from './tools/assets/AssetsTool'
20
20
  import {BOARD_LAYOUT_TYPE, isKitType, kitSchemaTypes} from './schema/boardLayout'
21
+ import {dropRedundantLanguageTemplates} from './lib/i18nTemplates'
21
22
  import type {NcfKitConfig, NcfToolName} from './config/types'
22
23
 
23
24
  /** Noms des outils dans la barre du Studio. Exportés pour filtrer `tools`. */
@@ -194,8 +195,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
194
195
  },
195
196
 
196
197
  document: {
198
+ // On masque le singleton de board, puis — en monolingue — le doublon
199
+ // « + Français Article » que document-internationalization ajoute à côté
200
+ // du « + Article » de base (voir dropRedundantLanguageTemplates).
197
201
  newDocumentOptions: (prev) =>
198
- prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
202
+ dropRedundantLanguageTemplates(prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE)),
199
203
  // Pages : « Retirer du site » (dépublication expliquée, liens listés) à la place
200
204
  // du « Unpublish » natif, caché et bloqué sans explication par les références.
201
205
  // Supprimer la version principale d'un document traduit : suppression de ses
@@ -452,6 +456,24 @@ export {
452
456
  STATUS_LABELS,
453
457
  } from './lib/status'
454
458
 
459
+ /* --- Collections : vue table « Airtable » dans l'onglet Structure --- */
460
+ export {ncfCollections, ncfCollectionTable} from './structure/collections'
461
+ export {CollectionTable} from './tools/collections/CollectionTable'
462
+ export {useCollection} from './hooks/useCollection'
463
+ export type {CollectionState} from './hooks/useCollection'
464
+ export {deriveCollectionColumns, titleColumn} from './lib/collectionColumns'
465
+ export type {CollectionColumn, CollectionColumnKind} from './lib/collectionColumns'
466
+ export {discoverCollectionTypes} from './lib/collectionTypes'
467
+ export type {SchemaTypeInfo} from './lib/collectionTypes'
468
+ export {buildCollectionQuery} from './lib/collectionQuery'
469
+ export {buildCollectionRows} from './lib/collectionRows'
470
+ export type {CollectionRow, CollectionCell, CollectionDoc} from './lib/collectionRows'
471
+ export {sortRows as sortCollectionRows, filterRows as filterCollectionRows} from './lib/collectionTable'
472
+ export type {CollectionSort, CollectionFilters} from './lib/collectionTable'
473
+ export {toCsv} from './lib/csv'
474
+ export {downloadText} from './lib/download'
475
+ export type {NcfCollectionsConfig, ResolvedCollections} from './config/types'
476
+
455
477
  export type {
456
478
  ConfigIssue,
457
479
  IssueLevel,
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Trouve, dans un document, les endroits qui référencent un asset — pour les
3
+ * vider avant de supprimer l'asset (Sanity refuse de supprimer un asset encore
4
+ * référencé). Pur : testable sans Sanity.
5
+ */
6
+
7
+ type Rec = Record<string, unknown>
8
+ const isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
9
+
10
+ type PathSegment = string | number | {_key: string}
11
+
12
+ /** Chemins (segments) des objets du document qui pointent vers `assetId`. */
13
+ export function findAssetRefPaths(value: unknown, assetId: string, path: PathSegment[] = []): PathSegment[][] {
14
+ const out: PathSegment[][] = []
15
+ const walk = (node: unknown, current: PathSegment[]) => {
16
+ if (Array.isArray(node)) {
17
+ node.forEach((item, index) => {
18
+ const segment: PathSegment = isObj(item) && typeof item._key === 'string' ? {_key: item._key} : index
19
+ walk(item, [...current, segment])
20
+ })
21
+ return
22
+ }
23
+ if (!isObj(node)) return
24
+ // Objet image/fichier (`{asset: {_ref}}`) ou référence directe vers l'asset.
25
+ const assetRef = isObj(node.asset) ? node.asset._ref : undefined
26
+ if (assetRef === assetId || (node._type === 'reference' && node._ref === assetId)) {
27
+ out.push(current)
28
+ return
29
+ }
30
+ for (const [key, child] of Object.entries(node)) {
31
+ if (key.startsWith('_')) continue
32
+ walk(child, [...current, key])
33
+ }
34
+ }
35
+ walk(value, path)
36
+ return out
37
+ }
38
+
39
+ /** Chemin Sanity (`gallery[_key=="ab"].asset`) depuis des segments. */
40
+ export function toPatchPath(segments: readonly PathSegment[]): string {
41
+ let out = ''
42
+ for (const segment of segments) {
43
+ if (typeof segment === 'string') out += out ? `.${segment}` : segment
44
+ else if (typeof segment === 'number') out += `[${segment}]`
45
+ else out += `[_key=="${segment._key}"]`
46
+ }
47
+ return out
48
+ }
49
+
50
+ /** Chemins Sanity (chaînes) à retirer d'un document pour en ôter l'asset. */
51
+ export function assetUnsetPaths(doc: unknown, assetId: string): string[] {
52
+ return findAssetRefPaths(doc, assetId).map(toPatchPath).filter(Boolean)
53
+ }
@@ -0,0 +1,114 @@
1
+ import {isSafeColumnKey, isSafeFieldPath} from './query'
2
+ import {
3
+ isOpaque,
4
+ isReference,
5
+ jsonTypeOf,
6
+ keyForPath,
7
+ labelOf,
8
+ typeNameOf,
9
+ type SchemaFieldLike,
10
+ type SchemaTypeLike,
11
+ } from './schemaColumns'
12
+
13
+ /**
14
+ * Colonnes de la vue table d'une collection.
15
+ *
16
+ * À la différence de `deriveDocumentColumns` (onglet Pages, uniquement des
17
+ * valeurs scalaires), on garde ici les **références** : une collection se lit
18
+ * surtout par ses liens (auteur, catégorie…). Une colonne porte donc son
19
+ * expression GROQ toute faite plutôt qu'une simple liste de chemins.
20
+ */
21
+ export type CollectionColumnKind = 'text' | 'number' | 'boolean' | 'date' | 'reference'
22
+
23
+ export interface CollectionColumn {
24
+ /** Clé de projection, sûre (sert de nom de champ GROQ). */
25
+ key: string
26
+ label: string
27
+ kind: CollectionColumnKind
28
+ /** Expression GROQ relative au document, p. ex. `title` ou `author->title`. */
29
+ projection: string
30
+ }
31
+
32
+ /** Champs d'un titre affichable d'un document référencé, par ordre de préférence. */
33
+ const REFERENCE_TITLE_FIELDS = ['title', 'name', 'label', 'heading']
34
+
35
+ export interface DeriveCollectionOptions {
36
+ /** Profondeur d'imbrication explorée dans les objets. 1 couvre `seo.title`. */
37
+ depth?: number
38
+ }
39
+
40
+ /**
41
+ * Colonnes tirées du schéma d'un type de collection. Aucune liste à tenir :
42
+ * chaque champ scalaire, date ou référence devient une colonne proposable. Les
43
+ * tableaux, images, fichiers et blocs sont écartés — rien à rendre en ligne.
44
+ */
45
+ export function deriveCollectionColumns(
46
+ type: SchemaTypeLike | undefined,
47
+ options: DeriveCollectionOptions = {},
48
+ ): CollectionColumn[] {
49
+ const maxDepth = options.depth ?? 1
50
+ const found = new Map<string, CollectionColumn>()
51
+
52
+ const add = (path: string, label: string, kind: CollectionColumnKind, projection: string) => {
53
+ const key = keyForPath(path)
54
+ if (found.has(key) || !isSafeColumnKey(key)) return
55
+ found.set(key, {key, label, kind, projection})
56
+ }
57
+
58
+ const visit = (fields: readonly SchemaFieldLike[], prefix: string, prefixLabel: string, depth: number) => {
59
+ for (const field of fields) {
60
+ if (!field.name || field.name.startsWith('_')) continue
61
+
62
+ const path = prefix ? `${prefix}.${field.name}` : field.name
63
+ if (!isSafeFieldPath(path)) continue
64
+
65
+ const label = prefixLabel ? `${prefixLabel} · ${labelOf(field)}` : labelOf(field)
66
+ const typeName = typeNameOf(field.type)
67
+
68
+ // Un slug ne vaut que par son `current`.
69
+ if (typeName === 'slug') {
70
+ add(path, label, 'text', `${path}.current`)
71
+ continue
72
+ }
73
+
74
+ // Référence : on résout un titre lisible du document pointé.
75
+ if (isReference(field.type)) {
76
+ const titles = REFERENCE_TITLE_FIELDS.map((f) => `${path}->${f}`)
77
+ add(path, label, 'reference', `coalesce(${titles.join(', ')}, ${path}->_id)`)
78
+ continue
79
+ }
80
+
81
+ // Image, fichier, bloc, geopoint… : rien d'exploitable en ligne.
82
+ if (isOpaque(field.type)) continue
83
+
84
+ // Date / datetime : traité à part pour un tri chronologique.
85
+ if (typeName === 'datetime' || typeName === 'date') {
86
+ add(path, label, 'date', path)
87
+ continue
88
+ }
89
+
90
+ const json = jsonTypeOf(field.type)
91
+ if (json === 'string') {
92
+ add(path, label, 'text', path)
93
+ continue
94
+ }
95
+ if (json === 'number' || json === 'boolean') {
96
+ add(path, label, json, path)
97
+ continue
98
+ }
99
+
100
+ // Objet : on descend d'un niveau (seo.title…), sans tableaux ni opaques.
101
+ if (json === 'object' && depth < maxDepth && field.type?.fields?.length) {
102
+ visit(field.type.fields, path, label, depth + 1)
103
+ }
104
+ }
105
+ }
106
+
107
+ if (type?.fields?.length) visit(type.fields, '', '', 0)
108
+ return [...found.values()]
109
+ }
110
+
111
+ /** Nom du champ titre d'une collection, pour la colonne mise en avant. */
112
+ export function titleColumn(columns: readonly CollectionColumn[]): CollectionColumn | undefined {
113
+ return columns.find((c) => c.key === 'title') ?? columns.find((c) => c.kind === 'text')
114
+ }
@@ -0,0 +1,23 @@
1
+ import {DATA_PREFIX, isSafeColumnKey} from './query'
2
+ import type {CollectionColumn} from './collectionColumns'
3
+
4
+ /**
5
+ * Requête d'une collection : `_id`, `_updatedAt`, et une projection par colonne
6
+ * **visible** (clé préfixée `ncfData_` pour ne jamais heurter un champ du
7
+ * client). Les expressions des colonnes sont construites par le kit à partir de
8
+ * chemins déjà validés (`deriveCollectionColumns`), donc sûres ; la clé est
9
+ * revérifiée par prudence avant interpolation.
10
+ *
11
+ * Le type passe en paramètre (`$type`), jamais interpolé dans la requête.
12
+ *
13
+ * On ne filtre pas les brouillons : le client (perspective `raw`) renvoie
14
+ * `drafts.x` ET `x`, que `buildCollectionRows` fusionne par id de base — sans
15
+ * quoi un item jamais publié n'apparaîtrait pas.
16
+ */
17
+ export function buildCollectionQuery(columns: readonly CollectionColumn[]): string {
18
+ const lines = columns
19
+ .filter((column) => isSafeColumnKey(column.key))
20
+ .map((column) => ` "${DATA_PREFIX}${column.key}": ${column.projection},`)
21
+
22
+ return ['*[_type == $type]{', ' _id, _updatedAt,', ...lines, '}'].join('\n')
23
+ }
@@ -0,0 +1,92 @@
1
+ import {DATA_PREFIX} from './query'
2
+ import type {CollectionColumn} from './collectionColumns'
3
+
4
+ export type CellValue = string | number | boolean | null
5
+
6
+ export interface CollectionCell {
7
+ /** Valeur brute, pour un tri typé. */
8
+ raw: CellValue
9
+ /** Valeur mise en forme, pour l'affichage, le filtre et le CSV. */
10
+ text: string
11
+ }
12
+
13
+ export interface CollectionRow {
14
+ /** Id de base (sans `drafts.`), pour ouvrir le document. */
15
+ id: string
16
+ updatedAt: string | null
17
+ /** Vrai si l'item n'existe qu'en brouillon (jamais publié). */
18
+ draftOnly: boolean
19
+ cells: Record<string, CollectionCell>
20
+ }
21
+
22
+ /** Document tel que renvoyé par `buildCollectionQuery`. */
23
+ export interface CollectionDoc {
24
+ _id: string
25
+ _updatedAt?: string | null
26
+ [key: string]: unknown
27
+ }
28
+
29
+ const baseId = (id: string): string => (id.startsWith('drafts.') ? id.slice('drafts.'.length) : id)
30
+ const isDraft = (id: string): boolean => id.startsWith('drafts.')
31
+
32
+ const dateFormatter = new Intl.DateTimeFormat('en-US', {day: '2-digit', month: '2-digit', year: 'numeric'})
33
+
34
+ function formatDate(value: unknown): string {
35
+ if (typeof value !== 'string' || !value) return ''
36
+ const date = new Date(value)
37
+ return Number.isNaN(date.getTime()) ? '' : dateFormatter.format(date)
38
+ }
39
+
40
+ function cellOf(raw: unknown, kind: CollectionColumn['kind']): CollectionCell {
41
+ if (raw === null || raw === undefined) return {raw: null, text: ''}
42
+ if (kind === 'boolean') {
43
+ const value = Boolean(raw)
44
+ return {raw: value, text: value ? 'Yes' : 'No'}
45
+ }
46
+ if (kind === 'number') {
47
+ return typeof raw === 'number' ? {raw, text: String(raw)} : {raw: null, text: ''}
48
+ }
49
+ if (kind === 'date') {
50
+ // ISO conservé en brut (tri chronologique = tri lexical), date lisible en texte.
51
+ return {raw: typeof raw === 'string' ? raw : null, text: formatDate(raw)}
52
+ }
53
+ // text / reference
54
+ const text = typeof raw === 'string' ? raw.trim() : String(raw)
55
+ return {raw: text, text}
56
+ }
57
+
58
+ /**
59
+ * Documents → lignes, une par item. Le client (perspective `raw`) renvoie le
60
+ * brouillon ET la version publiée : on les fusionne par id de base, en gardant
61
+ * le brouillon s'il existe (valeurs les plus fraîches).
62
+ */
63
+ export function buildCollectionRows(
64
+ docs: readonly CollectionDoc[],
65
+ columns: readonly CollectionColumn[],
66
+ ): CollectionRow[] {
67
+ const byId = new Map<string, {draft?: CollectionDoc; published?: CollectionDoc}>()
68
+ for (const doc of docs) {
69
+ if (!doc?._id) continue
70
+ const entry = byId.get(baseId(doc._id)) ?? {}
71
+ if (isDraft(doc._id)) entry.draft = doc
72
+ else entry.published = doc
73
+ byId.set(baseId(doc._id), entry)
74
+ }
75
+
76
+ const rows: CollectionRow[] = []
77
+ for (const [id, {draft, published}] of byId) {
78
+ const source = draft ?? published
79
+ if (!source) continue
80
+ const cells: Record<string, CollectionCell> = {}
81
+ for (const column of columns) {
82
+ cells[column.key] = cellOf(source[`${DATA_PREFIX}${column.key}`], column.kind)
83
+ }
84
+ rows.push({
85
+ id,
86
+ updatedAt: source._updatedAt ?? null,
87
+ draftOnly: Boolean(draft) && !published,
88
+ cells,
89
+ })
90
+ }
91
+ return rows
92
+ }