@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
@@ -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
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Menu « + » du Studio en situation monolingue. Pur.
3
+ *
4
+ * `@sanity/document-internationalization` ajoute, pour chaque type traduit, un
5
+ * template « paramétré » (`${type}-parameterized`) et un template statique par
6
+ * langue (`${type}-${langue}`, p. ex. `article-fr`, titré « Français Article »).
7
+ * Avec une seule langue branchée, ces deux-là font doublon avec le « + Article »
8
+ * de base : le menu de création montre « + Article » ET « + Français Article ».
9
+ *
10
+ * On ne garde alors que la base. Avec plusieurs langues on ne touche à rien
11
+ * (« + master » et « + langues » sont voulus).
12
+ *
13
+ * Détection sans connaître la liste des langues : le template `-parameterized`
14
+ * est la signature du plugin ; s'il n'existe qu'UN statique pour ce type (et que
15
+ * la base du type est bien présente), on est en monolingue pour ce type. Zéro ou
16
+ * plusieurs statiques : on laisse tout, par prudence — jamais retirer la seule
17
+ * façon de créer un document.
18
+ */
19
+ export function dropRedundantLanguageTemplates<T extends {templateId: string}>(options: readonly T[]): T[] {
20
+ const ids = new Set(options.map((option) => option.templateId))
21
+ const remove = new Set<string>()
22
+ const suffix = '-parameterized'
23
+
24
+ for (const {templateId} of options) {
25
+ if (!templateId.endsWith(suffix)) continue
26
+ const base = templateId.slice(0, -suffix.length)
27
+ // Pas de type de base dans le menu : on ne retire rien.
28
+ if (!ids.has(base)) continue
29
+ const statics = options.filter(
30
+ (option) => option.templateId !== templateId && option.templateId.startsWith(`${base}-`),
31
+ )
32
+ // Exactement une langue : monolingue → la base suffit.
33
+ const only = statics.length === 1 ? statics[0] : undefined
34
+ if (!only) continue
35
+ remove.add(templateId)
36
+ remove.add(only.templateId)
37
+ }
38
+
39
+ return options.filter((option) => !remove.has(option.templateId))
40
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Ordre manuel des pages, partagé par le navigateur de Presentation et l'onglet
3
+ * Pages. Stocké comme une liste d'ids (board singleton `pageOrder`). Pur.
4
+ */
5
+
6
+ /**
7
+ * Ordonne des éléments par la liste d'ids `order` : ceux présents d'abord (dans
8
+ * l'ordre de `order`), les autres ensuite dans leur ordre d'entrée (donc une
9
+ * page nouvelle, absente de l'ordre manuel, apparaît à la fin).
10
+ */
11
+ export function orderByIds<T extends {id: string}>(items: readonly T[], order: readonly string[]): T[] {
12
+ if (order.length === 0) return [...items]
13
+ const rank = new Map(order.map((id, index) => [id, index]))
14
+ return [...items].sort((a, b) => {
15
+ const ra = rank.get(a.id)
16
+ const rb = rank.get(b.id)
17
+ if (ra === undefined && rb === undefined) return 0
18
+ if (ra === undefined) return 1
19
+ if (rb === undefined) return -1
20
+ return ra - rb
21
+ })
22
+ }
23
+
24
+ /**
25
+ * Déplace `dragged` juste avant `target` dans la séquence d'ids `ordered`
26
+ * (l'ordre courant complet). `target` null = place en fin. Filtre-sûr : on
27
+ * travaille sur les ids, pas sur une vue filtrée.
28
+ */
29
+ export function reorderBefore(ordered: readonly string[], dragged: string, target: string | null): string[] {
30
+ if (dragged === target) return [...ordered]
31
+ const without = ordered.filter((id) => id !== dragged)
32
+ if (target === null) return [...without, dragged]
33
+ const index = without.indexOf(target)
34
+ if (index < 0) return [...without, dragged]
35
+ return [...without.slice(0, index), dragged, ...without.slice(index)]
36
+ }
package/src/lib/pages.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import {finalPath, type RedirectMap} from './finalUrl'
2
+ import {orderByIds} from './pageOrder'
2
3
  import type {ResolvedDocumentColumn, ResolvedKitConfig} from '../config/types'
3
4
  import {pageTypeFor, toPath, toUrl} from './paths'
4
5
  import {DATA_PREFIX} from './query'
@@ -99,6 +100,7 @@ export function buildPageRows(
99
100
  */
100
101
  export type SortKey =
101
102
  | 'structure'
103
+ | 'manual'
102
104
  | 'title'
103
105
  | 'type'
104
106
  | 'path'
@@ -113,9 +115,11 @@ const STATUS_ORDER: Record<PageStatus, number> = {modified: 0, draft: 1, publish
113
115
  export interface SortOptions {
114
116
  /** Ordre de déclaration des types, pour le tri « structure ». */
115
117
  typeOrder?: readonly string[]
118
+ /** Ordre manuel (liste d'ids), pour le tri « manual ». */
119
+ pageOrder?: readonly string[]
116
120
  }
117
121
 
118
- const compare = (a: PageRow, b: PageRow, key: SortKey, options: SortOptions): number => {
122
+ const compare = (a: PageRow, b: PageRow, key: Exclude<SortKey, 'manual'>, options: SortOptions): number => {
119
123
  switch (key) {
120
124
  case 'structure': {
121
125
  const order = options.typeOrder ?? []
@@ -153,6 +157,12 @@ export function sortRows(
153
157
  direction: SortDirection,
154
158
  options: SortOptions = {},
155
159
  ): PageRow[] {
160
+ // Ordre manuel : séquence d'ids stockée ; les pages hors liste après, par titre.
161
+ if (key === 'manual') {
162
+ const byTitle = [...rows].sort((a, b) => a.title.localeCompare(b.title, undefined, {sensitivity: 'base'}))
163
+ const sorted = orderByIds(byTitle, options.pageOrder ?? [])
164
+ return direction === 'asc' ? sorted : sorted.reverse()
165
+ }
156
166
  const sorted = [...rows].sort((a, b) => compare(a, b, key, options))
157
167
  return direction === 'asc' ? sorted : sorted.reverse()
158
168
  }
@@ -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
  }
@@ -168,6 +168,13 @@ const boardLayoutType = defineType({
168
168
  type: 'array',
169
169
  of: [{type: SECTION_NODE_TYPE}],
170
170
  }),
171
+ // Ordre manuel des pages (liste d'ids), partagé Presentation / onglet Pages.
172
+ defineField({
173
+ name: 'pageOrder',
174
+ title: 'Manual page order',
175
+ type: 'array',
176
+ of: [{type: 'string'}],
177
+ }),
171
178
  defineField({
172
179
  name: 'updatedBy',
173
180
  title: 'Modified by',
@@ -0,0 +1,103 @@
1
+ import {Box} from '@sanity/ui'
2
+ import type {StructureBuilder, StructureResolverContext, ListItemBuilder, UserComponent} from 'sanity/structure'
3
+ import {KitProvider} from '../context/KitContext'
4
+ import {resolveConfig} from '../config/resolve'
5
+ import {validateConfig} from '../config/validate'
6
+ import {CollectionTable} from '../tools/collections/CollectionTable'
7
+ import {discoverCollectionTypes, type SchemaTypeInfo} from '../lib/collectionTypes'
8
+ import {humanise} from '../lib/schemaColumns'
9
+ import {NCF_HIDDEN_TYPES} from '../schema/boardLayout'
10
+ import type {ConfigIssue, NcfKitConfig, ResolvedKitConfig} from '../config/types'
11
+
12
+ /**
13
+ * Composant de panneau pour une collection. Le type arrive par les `options`
14
+ * du pane de structure ; la configuration est fermée par la fabrique (elle
15
+ * n'est pas sérialisable dans les options).
16
+ */
17
+ function createCollectionPane(config: ResolvedKitConfig, issues: ConfigIssue[]): UserComponent {
18
+ return function NcfCollectionPane(props) {
19
+ const type = typeof props.options?.type === 'string' ? props.options.type : ''
20
+ return (
21
+ <KitProvider config={config} issues={issues}>
22
+ <Box padding={3} height="fill" overflow="auto">
23
+ {type ? <CollectionTable type={type} /> : null}
24
+ </Box>
25
+ </KitProvider>
26
+ )
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Vue table d'UNE collection, à utiliser comme enfant d'une entrée de structure
32
+ * pour que cliquer la collection ouvre la table (au lieu de la liste native) :
33
+ *
34
+ * ```ts
35
+ * S.listItem().title('Articles').child(ncfCollectionTable(S, ncfOptions, 'article'))
36
+ * ```
37
+ */
38
+ export function ncfCollectionTable(
39
+ S: StructureBuilder,
40
+ options: NcfKitConfig,
41
+ type: string,
42
+ opts: {title?: string} = {},
43
+ ) {
44
+ const config = resolveConfig(options)
45
+ const issues = validateConfig(config)
46
+ const pane = createCollectionPane(config, issues)
47
+ return S.component(pane)
48
+ .id(`ncf-collection-${type}`)
49
+ .title(opts.title ?? type)
50
+ .options({type})
51
+ }
52
+
53
+ /** Libellé d'une entrée de collection : config, puis titre du schéma, puis nom humanisé. */
54
+ function labelFor(type: string, config: ResolvedKitConfig, schemaTitle?: string): string {
55
+ return config.collections.labels[type] ?? schemaTitle ?? humanise(type)
56
+ }
57
+
58
+ /** Types toujours écartés de la découverte, en plus de l'`exclude` du projet. */
59
+ function reservedExcludes(config: ResolvedKitConfig): string[] {
60
+ return [
61
+ ...config.pageTypeNames,
62
+ config.redirectType,
63
+ config.componentPreview.defaultsType,
64
+ ...NCF_HIDDEN_TYPES,
65
+ ...config.collections.exclude,
66
+ ].filter(Boolean)
67
+ }
68
+
69
+ /**
70
+ * Entrées « collection » pour la structure du Studio, une par type découvert,
71
+ * chacune ouvrant la vue table. À épandre dans la liste racine :
72
+ *
73
+ * ```ts
74
+ * structure: (S, context) =>
75
+ * S.list().title('Contenu').items([..., ...ncfCollections(S, context, ncfOptions)])
76
+ * ```
77
+ */
78
+ export function ncfCollections(
79
+ S: StructureBuilder,
80
+ context: StructureResolverContext,
81
+ options: NcfKitConfig,
82
+ ): ListItemBuilder[] {
83
+ const config = resolveConfig(options)
84
+
85
+ const types: SchemaTypeInfo[] = context.schema
86
+ .getTypeNames()
87
+ .map((name) => ({name, jsonType: context.schema.get(name)?.jsonType}))
88
+
89
+ const discovered = discoverCollectionTypes(types, {
90
+ include: config.collections.include,
91
+ exclude: reservedExcludes(config),
92
+ })
93
+
94
+ return discovered.map((type) => {
95
+ const schemaType = context.schema.get(type)
96
+ const label = labelFor(type, config, schemaType?.title)
97
+ const item = S.listItem()
98
+ .id(`ncf-collection-${type}`)
99
+ .title(label)
100
+ .child(ncfCollectionTable(S, options, type, {title: label}))
101
+ return schemaType?.icon ? item.icon(schemaType.icon) : item
102
+ })
103
+ }
@@ -15,20 +15,18 @@ export interface AssetCardProps {
15
15
  export function AssetCard(props: AssetCardProps) {
16
16
  const {asset, selected, onToggleSelect, onOpen} = props
17
17
  const [failed, setFailed] = useState(false)
18
- const thumb = thumbnailUrl(asset, {w: 320, h: 220})
18
+ const thumb = thumbnailUrl(asset, {w: 500})
19
19
  const unused = asset.uses === 0
20
+ // Vrai ratio de l'image (portrait / paysage visible sans cliquer). Borné pour
21
+ // éviter des tuiles absurdes ; un fichier sans image garde un ratio neutre.
22
+ const natural = asset.dimensions?.width && asset.dimensions?.height ? asset.dimensions.width / asset.dimensions.height : 4 / 3
23
+ const ratio = thumb ? Math.min(2, Math.max(0.56, natural)) : 4 / 3
20
24
  const meta = [formatBytes(asset.size), asset.dimensions?.width ? `${asset.dimensions.width}×${asset.dimensions.height}` : null, asset.extension?.toUpperCase()]
21
25
  .filter(Boolean)
22
26
  .join(' · ')
23
27
 
24
28
  return (
25
- <Card
26
- radius={3}
27
- shadow={1}
28
- padding={0}
29
- tone={selected ? 'primary' : 'default'}
30
- style={{height: '100%', overflow: 'hidden', position: 'relative'}}
31
- >
29
+ <Card radius={3} shadow={1} padding={0} tone={selected ? 'primary' : 'default'} style={{overflow: 'hidden', position: 'relative', width: '100%'}}>
32
30
  {/* Sélection : coin haut-gauche, n'ouvre pas le détail. */}
33
31
  <Box style={{position: 'absolute', top: 8, left: 8, zIndex: 1}} onClick={(e) => e.stopPropagation()}>
34
32
  <Card radius={2} padding={1} tone="default" style={{opacity: selected ? 1 : 0.85}}>
@@ -40,9 +38,9 @@ export function AssetCard(props: AssetCardProps) {
40
38
  gap={0}
41
39
  as="button"
42
40
  onClick={onOpen}
43
- style={{height: '100%', width: '100%', textAlign: 'left', cursor: 'pointer', background: 'transparent', border: 0, padding: 0}}
41
+ style={{width: '100%', textAlign: 'left', cursor: 'pointer', background: 'transparent', border: 0, padding: 0}}
44
42
  >
45
- <Box style={{aspectRatio: '16 / 11', overflow: 'hidden', background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))'}}>
43
+ <Box style={{aspectRatio: ratio, overflow: 'hidden', background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))'}}>
46
44
  {thumb && !failed ? (
47
45
  <img
48
46
  src={thumb}
@@ -1,9 +1,11 @@
1
1
  import {useEffect, useState} from 'react'
2
- import {Box, Button, Card, Flex, Grid, Label, Select, Stack, Text, TextArea, TextInput} from '@sanity/ui'
2
+ import {Box, Button, Card, Dialog, Flex, Grid, Label, Select, Spinner, Stack, Text, TextArea, TextInput} from '@sanity/ui'
3
3
  import {CloseIcon} from '@sanity/icons/Close'
4
4
  import {CopyIcon} from '@sanity/icons/Copy'
5
5
  import {LaunchIcon} from '@sanity/icons/Launch'
6
+ import {TrashIcon} from '@sanity/icons/Trash'
6
7
  import {useKitClient} from '../../hooks/useKitClient'
8
+ import {useAssetDelete, type AssetUsage} from '../../hooks/useAssetDelete'
7
9
  import {assetName, formatBytes, isImageAsset, thumbnailUrl, type AssetDoc, type AssetFolder} from '../../lib/assets'
8
10
  import {MONO} from '../../ui/tokens'
9
11
  import {formatDate} from '../../ui/formatDate'
@@ -14,6 +16,8 @@ export interface AssetDetailProps {
14
16
  folder: string | null
15
17
  onMove: (folder: string | null) => void
16
18
  onClose: () => void
19
+ /** Appelé après suppression (pour fermer le détail et rafraîchir). */
20
+ onDeleted?: () => void
17
21
  }
18
22
 
19
23
  function Metric(props: {label: string; value: string}) {
@@ -30,12 +34,39 @@ function Metric(props: {label: string; value: string}) {
30
34
  }
31
35
 
32
36
  export function AssetDetail(props: AssetDetailProps) {
33
- const {asset, folders, folder, onMove, onClose} = props
37
+ const {asset, folders, folder, onMove, onClose, onDeleted} = props
34
38
  const client = useKitClient()
39
+ const {usage, remove} = useAssetDelete()
35
40
  const [title, setTitle] = useState(asset.title ?? '')
36
41
  const [alt, setAlt] = useState(asset.altText ?? '')
37
42
  const [description, setDescription] = useState(asset.description ?? '')
38
43
  const [copied, setCopied] = useState(false)
44
+ // Suppression : null = fermé ; sinon on charge d'abord les usages, puis on confirme.
45
+ const [confirming, setConfirming] = useState(false)
46
+ const [uses, setUses] = useState<AssetUsage[] | null>(null)
47
+ const [busy, setBusy] = useState(false)
48
+ const [deleteError, setDeleteError] = useState<string | null>(null)
49
+
50
+ const openDelete = () => {
51
+ setConfirming(true)
52
+ setUses(null)
53
+ setDeleteError(null)
54
+ void usage(asset._id)
55
+ .then((list) => setUses(list))
56
+ .catch(() => setUses([]))
57
+ }
58
+ const doDelete = () => {
59
+ setBusy(true)
60
+ setDeleteError(null)
61
+ void remove(asset._id)
62
+ .then(() => {
63
+ setConfirming(false)
64
+ onDeleted?.()
65
+ onClose()
66
+ })
67
+ .catch((cause: unknown) => setDeleteError(cause instanceof Error ? cause.message : String(cause)))
68
+ .finally(() => setBusy(false))
69
+ }
39
70
 
40
71
  // Repart des valeurs de l'asset sélectionné quand il change.
41
72
  useEffect(() => {
@@ -144,7 +175,71 @@ export function AssetDetail(props: AssetDetailProps) {
144
175
  <Metric label="Usage" value={asset.uses === undefined ? '—' : `${asset.uses}`} />
145
176
  <Metric label="Ajouté" value={formatDate(asset._createdAt)} />
146
177
  </Grid>
178
+
179
+ <Box style={{borderTop: '1px solid var(--card-border-color)'}} paddingTop={3}>
180
+ <Button icon={TrashIcon} text="Supprimer le média" tone="critical" mode="ghost" fontSize={1} onClick={openDelete} style={{width: '100%'}} />
181
+ </Box>
147
182
  </Stack>
183
+
184
+ {confirming ? (
185
+ <Dialog
186
+ id="asset-delete"
187
+ header="Supprimer le média"
188
+ width={1}
189
+ onClose={() => (busy ? undefined : setConfirming(false))}
190
+ footer={
191
+ <Flex justify="flex-end" gap={2} padding={2}>
192
+ <Button text="Annuler" mode="bleed" disabled={busy} onClick={() => setConfirming(false)} />
193
+ <Button text={busy ? 'Suppression…' : 'Supprimer'} tone="critical" disabled={busy || uses === null} onClick={doDelete} />
194
+ </Flex>
195
+ }
196
+ >
197
+ <Box padding={4}>
198
+ <Stack gap={3}>
199
+ <Text size={1}>
200
+ Supprimer « {assetName(asset)} » définitivement ?
201
+ </Text>
202
+ {uses === null ? (
203
+ <Flex align="center" gap={2}>
204
+ <Spinner muted size={1} />
205
+ <Text size={1} muted>
206
+ Recherche des endroits où il est utilisé…
207
+ </Text>
208
+ </Flex>
209
+ ) : uses.length === 0 ? (
210
+ <Text size={1} muted>
211
+ Il n'est utilisé nulle part : aucune page ne sera affectée.
212
+ </Text>
213
+ ) : (
214
+ <Stack gap={2}>
215
+ <Text size={1} weight="medium">
216
+ L'image deviendra vide à {uses.length} endroit{uses.length > 1 ? 's' : ''} :
217
+ </Text>
218
+ <Card tone="caution" border radius={2} padding={3}>
219
+ <Stack gap={2} as="ul" style={{margin: 0, paddingLeft: 16}}>
220
+ {uses.slice(0, 20).map((use) => (
221
+ <Text key={use.id} size={1} as="li">
222
+ {use.title} <span style={{opacity: 0.6}}>({use.type})</span>
223
+ </Text>
224
+ ))}
225
+ {uses.length > 20 ? (
226
+ <Text size={1} muted as="li">
227
+ … et {uses.length - 20} autre{uses.length - 20 > 1 ? 's' : ''}.
228
+ </Text>
229
+ ) : null}
230
+ </Stack>
231
+ </Card>
232
+ </Stack>
233
+ )}
234
+ {deleteError ? (
235
+ <Card tone="critical" border radius={2} padding={3}>
236
+ <Text size={1}>Suppression échouée : {deleteError}</Text>
237
+ </Card>
238
+ ) : null}
239
+ </Stack>
240
+ </Box>
241
+ </Dialog>
242
+ ) : null}
148
243
  </Card>
149
244
  )
150
245
  }