@nocode-factory/sanity-kit 2.53.0 → 2.56.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/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.53.0",
3
+ "version": "2.56.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,67 @@
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
+ export interface UseCollectionOptions {
21
+ /** Prédicat GROQ supplémentaire (ex. `language == $lang`) — niveau feuille. */
22
+ filter?: string
23
+ /** Valeurs des paramètres du `filter` (ex. `{lang: 'fr'}`). */
24
+ params?: Record<string, unknown>
25
+ }
26
+
27
+ /**
28
+ * Données d'une collection pour la vue table : colonnes tirées du schéma,
29
+ * lignes en direct. Seules les colonnes visibles sont projetées (comme
30
+ * `usePages`), pour ne pas tirer tout le schéma sur chaque document.
31
+ *
32
+ * `filter`/`params` restreignent la table au niveau feuille (une langue, une
33
+ * catégorie…). `useQueryData` stabilise lui-même les paramètres, donc l'objet
34
+ * peut être reconstruit à chaque rendu sans relancer la requête en boucle.
35
+ */
36
+ export function useCollection(
37
+ type: string,
38
+ visibleKeys: readonly string[],
39
+ options: UseCollectionOptions = {},
40
+ ): CollectionState {
41
+ const {filter, params: extraParams} = options
42
+ const schema = useSchema()
43
+
44
+ const allColumns = useMemo(
45
+ () => deriveCollectionColumns(schema.get(type) as SchemaTypeLike | undefined),
46
+ [schema, type],
47
+ )
48
+
49
+ const visibleColumns = useMemo(
50
+ () => visibleKeys.map((key) => allColumns.find((c) => c.key === key)).filter((c): c is CollectionColumn => Boolean(c)),
51
+ [allColumns, visibleKeys],
52
+ )
53
+
54
+ const query = useMemo(() => buildCollectionQuery(visibleColumns, filter), [visibleColumns, filter])
55
+ const params = {type, ...extraParams}
56
+
57
+ const {data, loading, error, refresh} = useQueryData<CollectionDoc[]>(query, params, {
58
+ listenTypes: [type],
59
+ })
60
+
61
+ const rows = useMemo(
62
+ () => buildCollectionRows(data ?? [], visibleColumns),
63
+ [data, visibleColumns],
64
+ )
65
+
66
+ return {allColumns, visibleColumns, rows, loading, error, refresh}
67
+ }
package/src/index.ts CHANGED
@@ -456,6 +456,24 @@ export {
456
456
  STATUS_LABELS,
457
457
  } from './lib/status'
458
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
+
459
477
  export type {
460
478
  ConfigIssue,
461
479
  IssueLevel,
@@ -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,31 @@
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
+ * `filter` est un prédicat GROQ supplémentaire écrit par l'intégrateur (dans le
14
+ * résolveur de structure), par exemple `language == $lang` : il restreint la
15
+ * table au niveau feuille (une langue, une catégorie, une page…). Il est
16
+ * parenthésé puis combiné en `&&`, et ses valeurs passent par `params`, jamais
17
+ * interpolées. Même niveau de confiance que `S.documentList().filter(...)`.
18
+ *
19
+ * On ne filtre pas les brouillons : le client (perspective `raw`) renvoie
20
+ * `drafts.x` ET `x`, que `buildCollectionRows` fusionne par id de base — sans
21
+ * quoi un item jamais publié n'apparaîtrait pas.
22
+ */
23
+ export function buildCollectionQuery(columns: readonly CollectionColumn[], filter?: string): string {
24
+ const lines = columns
25
+ .filter((column) => isSafeColumnKey(column.key))
26
+ .map((column) => ` "${DATA_PREFIX}${column.key}": ${column.projection},`)
27
+
28
+ const predicate = filter && filter.trim() ? `_type == $type && (${filter.trim()})` : '_type == $type'
29
+
30
+ return [`*[${predicate}]{`, ' _id, _updatedAt,', ...lines, '}'].join('\n')
31
+ }
@@ -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
+ }
@@ -0,0 +1,72 @@
1
+ import type {CollectionColumn} from './collectionColumns'
2
+ import type {CollectionRow} from './collectionRows'
3
+
4
+ export type SortDirection = 'asc' | 'desc'
5
+
6
+ export interface CollectionSort {
7
+ /** Clé de colonne, ou `null` pour l'ordre d'arrivée. */
8
+ key: string | null
9
+ direction: SortDirection
10
+ }
11
+
12
+ export interface CollectionFilters {
13
+ /** Recherche globale sur les colonnes visibles. */
14
+ search?: string
15
+ /** Filtre « contient » par colonne (clé → texte recherché). */
16
+ columns?: Record<string, string>
17
+ }
18
+
19
+ /** Insensible à la casse et aux accents, comme la recherche de l'onglet Pages. */
20
+ const normalize = (value: string): string =>
21
+ value.toLocaleLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu, '')
22
+
23
+ /** Compare deux valeurs non vides selon le type de la colonne. */
24
+ function compareNonNull(ra: NonNullable<unknown>, rb: NonNullable<unknown>, kind: CollectionColumn['kind']): number {
25
+ if (kind === 'number' || kind === 'boolean') return Number(ra) - Number(rb)
26
+ if (kind === 'date') return String(ra).localeCompare(String(rb)) // ISO : lexical = chronologique
27
+ return String(ra).localeCompare(String(rb), undefined, {sensitivity: 'base'})
28
+ }
29
+
30
+ export function sortRows(
31
+ rows: readonly CollectionRow[],
32
+ sort: CollectionSort,
33
+ columns: readonly CollectionColumn[],
34
+ ): CollectionRow[] {
35
+ if (!sort.key) return [...rows]
36
+ const column = columns.find((c) => c.key === sort.key)
37
+ if (!column) return [...rows]
38
+ const dir = sort.direction === 'asc' ? 1 : -1
39
+ return [...rows].sort((a, b) => {
40
+ const ra = a.cells[column.key]?.raw ?? null
41
+ const rb = b.cells[column.key]?.raw ?? null
42
+ // Un vide passe toujours après le reste, quel que soit le sens du tri.
43
+ if (ra === null && rb === null) return 0
44
+ if (ra === null) return 1
45
+ if (rb === null) return -1
46
+ return dir * compareNonNull(ra, rb, column.kind)
47
+ })
48
+ }
49
+
50
+ export function filterRows(
51
+ rows: readonly CollectionRow[],
52
+ filters: CollectionFilters,
53
+ visibleColumns: readonly CollectionColumn[],
54
+ ): CollectionRow[] {
55
+ const search = filters.search?.trim() ? normalize(filters.search.trim()) : null
56
+ const columnNeedles = Object.entries(filters.columns ?? {})
57
+ .map(([key, value]) => [key, normalize(value.trim())] as const)
58
+ .filter(([, value]) => value.length > 0)
59
+
60
+ if (!search && columnNeedles.length === 0) return [...rows]
61
+
62
+ return rows.filter((row) => {
63
+ if (search) {
64
+ const haystack = visibleColumns.map((c) => normalize(row.cells[c.key]?.text ?? '')).join(' ')
65
+ if (!haystack.includes(search)) return false
66
+ }
67
+ for (const [key, needle] of columnNeedles) {
68
+ if (!normalize(row.cells[key]?.text ?? '').includes(needle)) return false
69
+ }
70
+ return true
71
+ })
72
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Découverte des types « collection » à montrer en table. Pur : prend la liste
3
+ * des types du schéma (nom + nature JSON) et rend les types de documents
4
+ * retenus. L'appelant (helper de structure) fournit la liste d'exclusion
5
+ * complète — pages, redirections, types techniques du kit, `sanity.*`.
6
+ */
7
+
8
+ export interface SchemaTypeInfo {
9
+ name: string
10
+ jsonType?: string
11
+ }
12
+
13
+ export interface DiscoverOptions {
14
+ /** Types à ne jamais lister (pages, redirections, types du kit…). */
15
+ exclude?: readonly string[]
16
+ /** Liste explicite : si fournie, elle fait foi (surcharge l'auto-découverte). */
17
+ include?: readonly string[]
18
+ }
19
+
20
+ const isReserved = (name: string): boolean => name.startsWith('sanity.') || name.startsWith('_')
21
+
22
+ /**
23
+ * Types de collection retenus.
24
+ *
25
+ * - `include` fournie → on respecte cette liste (dans son ordre), en gardant
26
+ * seulement ce qui est un type de document connu et hors `exclude`.
27
+ * - sinon → tous les types de documents, moins `exclude` et les types réservés,
28
+ * triés par nom pour une liste stable.
29
+ */
30
+ export function discoverCollectionTypes(
31
+ types: readonly SchemaTypeInfo[],
32
+ options: DiscoverOptions = {},
33
+ ): string[] {
34
+ const excluded = new Set(options.exclude ?? [])
35
+ const documents = new Set(types.filter((t) => t.jsonType === 'document').map((t) => t.name))
36
+
37
+ if (options.include?.length) {
38
+ const seen = new Set<string>()
39
+ return options.include.filter((name) => {
40
+ if (seen.has(name) || excluded.has(name) || !documents.has(name)) return false
41
+ seen.add(name)
42
+ return true
43
+ })
44
+ }
45
+
46
+ return [...documents]
47
+ .filter((name) => !excluded.has(name) && !isReserved(name))
48
+ .sort((a, b) => a.localeCompare(b))
49
+ }
package/src/lib/csv.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type {CollectionColumn} from './collectionColumns'
2
+ import type {CollectionRow} from './collectionRows'
3
+
4
+ /** Échappement RFC 4180 : guillemets doublés, champ cité s'il contient `,` `"` ou un saut de ligne. */
5
+ function escapeField(value: string): string {
6
+ return /[",\n\r]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
7
+ }
8
+
9
+ /**
10
+ * Lignes → CSV. En-têtes = libellés des colonnes visibles, cellules = le texte
11
+ * déjà mis en forme (`row.cells[key].text`). Lignes séparées par CRLF, comme
12
+ * l'attendent les tableurs. Pur : l'appelant ajoute l'éventuel BOM au moment du
13
+ * téléchargement.
14
+ */
15
+ export function toCsv(
16
+ rows: readonly CollectionRow[],
17
+ columns: readonly CollectionColumn[],
18
+ ): string {
19
+ const header = columns.map((column) => escapeField(column.label))
20
+ const body = rows.map((row) =>
21
+ columns.map((column) => escapeField(row.cells[column.key]?.text ?? '')).join(','),
22
+ )
23
+ return [header.join(','), ...body].join('\r\n')
24
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Propose un fichier texte au téléchargement depuis le navigateur. Déclenché
3
+ * par un clic de l'utilisateur (bouton « Exporter »), jamais tout seul.
4
+ *
5
+ * Un BOM UTF-8 est ajouté par défaut pour que les accents s'affichent dans
6
+ * Excel. No-op hors navigateur (rendu serveur, tests).
7
+ */
8
+ export function downloadText(
9
+ filename: string,
10
+ text: string,
11
+ mime = 'text/csv;charset=utf-8',
12
+ withBom = true,
13
+ ): void {
14
+ if (typeof window === 'undefined' || typeof document === 'undefined') return
15
+ const blob = new Blob([withBom ? `${text}` : text], {type: mime})
16
+ const url = URL.createObjectURL(blob)
17
+ const anchor = document.createElement('a')
18
+ anchor.href = url
19
+ anchor.download = filename
20
+ document.body.appendChild(anchor)
21
+ anchor.click()
22
+ anchor.remove()
23
+ URL.revokeObjectURL(url)
24
+ }
@@ -35,8 +35,11 @@ const OPAQUE_TYPES = new Set([
35
35
  'geopoint',
36
36
  ])
37
37
 
38
+ /** Noms de types qui désignent une référence vers un autre document. */
39
+ const REFERENCE_TYPES = new Set(['reference', 'crossDatasetReference', 'globalDocumentReference'])
40
+
38
41
  /** Remonte la chaîne d'héritage jusqu'à trouver la nature JSON du champ. */
39
- function jsonTypeOf(type: SchemaTypeLike | undefined): string | undefined {
42
+ export function jsonTypeOf(type: SchemaTypeLike | undefined): string | undefined {
40
43
  let current = type
41
44
  for (let depth = 0; current && depth < 10; depth += 1) {
42
45
  if (current.jsonType) return current.jsonType
@@ -46,7 +49,7 @@ function jsonTypeOf(type: SchemaTypeLike | undefined): string | undefined {
46
49
  }
47
50
 
48
51
  /** Nom du type de schéma, `slug` ou `datetime` par exemple. */
49
- function typeNameOf(type: SchemaTypeLike | undefined): string | undefined {
52
+ export function typeNameOf(type: SchemaTypeLike | undefined): string | undefined {
50
53
  let current = type
51
54
  for (let depth = 0; current && depth < 10; depth += 1) {
52
55
  if (current.name && current.name !== current.type?.name) return current.name
@@ -55,7 +58,7 @@ function typeNameOf(type: SchemaTypeLike | undefined): string | undefined {
55
58
  return type?.name
56
59
  }
57
60
 
58
- function isOpaque(type: SchemaTypeLike | undefined): boolean {
61
+ export function isOpaque(type: SchemaTypeLike | undefined): boolean {
59
62
  let current = type
60
63
  for (let depth = 0; current && depth < 10; depth += 1) {
61
64
  if (current.name && OPAQUE_TYPES.has(current.name)) return true
@@ -64,11 +67,21 @@ function isOpaque(type: SchemaTypeLike | undefined): boolean {
64
67
  return false
65
68
  }
66
69
 
67
- const labelOf = (field: SchemaFieldLike): string =>
70
+ /** Vrai pour un champ référence (vers un autre document). */
71
+ export function isReference(type: SchemaTypeLike | undefined): boolean {
72
+ let current = type
73
+ for (let depth = 0; current && depth < 10; depth += 1) {
74
+ if (current.name && REFERENCE_TYPES.has(current.name)) return true
75
+ current = current.type
76
+ }
77
+ return false
78
+ }
79
+
80
+ export const labelOf = (field: SchemaFieldLike): string =>
68
81
  field.type?.title?.trim() || humanise(field.name)
69
82
 
70
83
  /** `metaDescription` → `Meta description`. */
71
- function humanise(name: string): string {
84
+ export function humanise(name: string): string {
72
85
  const spaced = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ')
73
86
  return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase()
74
87
  }