@nocode-factory/sanity-kit 2.49.0 → 2.50.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 (42) hide show
  1. package/README.md +2 -1
  2. package/bin/ncf-kit.mjs +15 -0
  3. package/dist/{aiJsonLd-DiYeDzou.js → aiJsonLd-BFyxgYen.js} +15 -3
  4. package/dist/aiJsonLd-BFyxgYen.js.map +1 -0
  5. package/dist/{finalUrl-C1kzYMzQ.js → finalUrl-CaFXmYvm.js} +3 -2
  6. package/dist/finalUrl-CaFXmYvm.js.map +1 -0
  7. package/dist/{fixCrossLanguageReferences-BZk9CkdI.js → fixCrossLanguageReferences-BeXywAAU.js} +2 -2
  8. package/dist/{fixCrossLanguageReferences-BZk9CkdI.js.map → fixCrossLanguageReferences-BeXywAAU.js.map} +1 -1
  9. package/dist/{fixCrossLanguageReferences-CjL_Xy0U.d.ts → fixCrossLanguageReferences-w3whO9xM.d.ts} +4 -2
  10. package/dist/index.d.ts +237 -6
  11. package/dist/index.js +1648 -159
  12. package/dist/index.js.map +1 -1
  13. package/dist/jsonld.js +14 -7
  14. package/dist/jsonld.js.map +1 -1
  15. package/dist/schema.d.ts +1 -1
  16. package/dist/schema.js +2 -2
  17. package/package.json +3 -1
  18. package/src/config/defaults.ts +1 -0
  19. package/src/config/types.ts +3 -1
  20. package/src/context/KitContext.tsx +15 -1
  21. package/src/form/JsonLdInput.tsx +21 -6
  22. package/src/hooks/useAssetMeta.ts +166 -0
  23. package/src/hooks/useAssets.ts +23 -0
  24. package/src/hooks/useOccurrences.ts +4 -2
  25. package/src/hooks/usePageBuilder.ts +22 -0
  26. package/src/hooks/usePageContents.ts +8 -1
  27. package/src/hooks/usePages.ts +5 -1
  28. package/src/index.ts +50 -1
  29. package/src/lib/assets.ts +161 -0
  30. package/src/lib/schemaTypes.ts +105 -0
  31. package/src/schema/assetMeta.ts +65 -0
  32. package/src/schema/boardLayout.ts +3 -1
  33. package/src/tools/assets/AssetCard.tsx +86 -0
  34. package/src/tools/assets/AssetDetail.tsx +150 -0
  35. package/src/tools/assets/AssetTable.tsx +122 -0
  36. package/src/tools/assets/AssetsTool.tsx +212 -0
  37. package/src/tools/assets/AssetsToolbar.tsx +98 -0
  38. package/src/tools/assets/FolderSidebar.tsx +177 -0
  39. package/src/tools/createToolComponent.tsx +39 -10
  40. package/src/version.ts +1 -1
  41. package/dist/aiJsonLd-DiYeDzou.js.map +0 -1
  42. package/dist/finalUrl-C1kzYMzQ.js.map +0 -1
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@ import {ClockIcon} from '@sanity/icons/Clock'
5
5
  import {ComponentIcon} from '@sanity/icons/Component'
6
6
  import {DocumentsIcon} from '@sanity/icons/Documents'
7
7
  import {ColorWheelIcon} from '@sanity/icons/ColorWheel'
8
+ import {ImagesIcon} from '@sanity/icons/Images'
8
9
 
9
10
  import {resolveConfig} from './config/resolve'
10
11
  import {validateConfig} from './config/validate'
@@ -15,6 +16,7 @@ import {PagesTool} from './tools/pages/PagesTool'
15
16
  import {ComponentsTool} from './tools/components/ComponentsTool'
16
17
  import {HistoryTool} from './tools/history/HistoryTool'
17
18
  import {DesignSystemTool} from './tools/designSystem/DesignSystemTool'
19
+ import {AssetsTool} from './tools/assets/AssetsTool'
18
20
  import {BOARD_LAYOUT_TYPE, isKitType, kitSchemaTypes} from './schema/boardLayout'
19
21
  import type {NcfKitConfig, NcfToolName} from './config/types'
20
22
 
@@ -23,12 +25,14 @@ export const NCF_PAGES_TOOL = 'ncf-pages'
23
25
  export const NCF_COMPONENTS_TOOL = 'ncf-components'
24
26
  export const NCF_HISTORY_TOOL = 'ncf-history'
25
27
  export const NCF_DESIGN_SYSTEM_TOOL = 'ncf-design-system'
28
+ export const NCF_ASSETS_TOOL = 'ncf-assets'
26
29
 
27
30
  export const NCF_TOOL_NAMES = [
28
31
  NCF_PAGES_TOOL,
29
32
  NCF_COMPONENTS_TOOL,
30
33
  NCF_HISTORY_TOOL,
31
34
  NCF_DESIGN_SYSTEM_TOOL,
35
+ NCF_ASSETS_TOOL,
32
36
  ] as const
33
37
 
34
38
  /**
@@ -142,6 +146,22 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
142
146
  }),
143
147
  },
144
148
  },
149
+ {
150
+ // Gestionnaire de médias : tous les assets, dossiers, tri et filtres.
151
+ name: 'assets',
152
+ tool: {
153
+ name: NCF_ASSETS_TOOL,
154
+ title: 'Assets',
155
+ icon: ImagesIcon,
156
+ component: createToolComponent({
157
+ name: 'assets',
158
+ title: 'Assets',
159
+ config,
160
+ issues,
161
+ Component: AssetsTool,
162
+ }),
163
+ },
164
+ },
145
165
  ]
146
166
 
147
167
  return {
@@ -247,7 +267,7 @@ export {
247
267
  kitSchemaTypes,
248
268
  } from './schema/boardLayout'
249
269
 
250
- export {useKitConfig, useKitContext} from './context/KitContext'
270
+ export {useKitConfig, useKitContext, useOptionalKitConfig, useOptionalKitContext} from './context/KitContext'
251
271
 
252
272
  export {toPath, toUrl, segments, depth, parentPath, pageTypeFor} from './lib/paths'
253
273
  export {pageTypesFromSiteRoutes, type SiteRoutesRegistry} from './lib/siteRoutes'
@@ -268,7 +288,36 @@ export {
268
288
  blockTypesFromSchema,
269
289
  missingPageTypes,
270
290
  pageTypesWithoutBuilder,
291
+ sectionNamesFromDefaults,
292
+ detectPageBuilderField,
293
+ resolvePageBuilderField,
271
294
  } from './lib/schemaTypes'
295
+ export type {PageBuilderResolution} from './lib/schemaTypes'
296
+ export {usePageBuilder} from './hooks/usePageBuilder'
297
+ export {AssetsTool} from './tools/assets/AssetsTool'
298
+ export {useAssets} from './hooks/useAssets'
299
+ export {useAssetMeta} from './hooks/useAssetMeta'
300
+ export type {AssetMetaState} from './hooks/useAssetMeta'
301
+ export {
302
+ assetName,
303
+ formatBytes,
304
+ thumbnailUrl,
305
+ isImageAsset,
306
+ filterAssets,
307
+ sortAssets,
308
+ assignmentMap,
309
+ assetsInFolder,
310
+ countByFolder,
311
+ } from './lib/assets'
312
+ export type {
313
+ AssetDoc,
314
+ AssetFolder,
315
+ AssetAssignment,
316
+ AssetSortKey,
317
+ AssetTypeFilter,
318
+ AssetUsageFilter,
319
+ FolderSelection,
320
+ } from './lib/assets'
272
321
  export {
273
322
  buildPagesQuery,
274
323
  buildContentsQuery,
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Types et transformations pures de l'outil Assets (gestionnaire de médias).
3
+ * Rien d'ici ne dépend de React ni de Sanity : tout est testable.
4
+ */
5
+
6
+ export interface AssetDimensions {
7
+ width?: number
8
+ height?: number
9
+ aspectRatio?: number
10
+ }
11
+
12
+ /** Un asset du dataset (`sanity.imageAsset` ou `sanity.fileAsset`). */
13
+ export interface AssetDoc {
14
+ _id: string
15
+ _type: 'sanity.imageAsset' | 'sanity.fileAsset'
16
+ _createdAt: string
17
+ _updatedAt?: string
18
+ originalFilename?: string
19
+ extension?: string
20
+ mimeType?: string
21
+ size?: number
22
+ url?: string
23
+ title?: string
24
+ altText?: string
25
+ description?: string
26
+ dimensions?: AssetDimensions
27
+ lqip?: string
28
+ /** Nombre de documents qui référencent l'asset (utilisé / inutilisé). */
29
+ uses?: number
30
+ }
31
+
32
+ /** Dossier d'organisation (géré par le kit, singleton `ncfAssetMeta`). */
33
+ export interface AssetFolder {
34
+ id: string
35
+ name: string
36
+ parent?: string
37
+ }
38
+
39
+ export const isImageAsset = (asset: {_type?: string}): boolean => asset._type === 'sanity.imageAsset'
40
+
41
+ /** Nom affiché : titre saisi, sinon nom de fichier, sinon id. */
42
+ export function assetName(asset: AssetDoc): string {
43
+ return asset.title?.trim() || asset.originalFilename || asset._id
44
+ }
45
+
46
+ /** Taille lisible (o / Ko / Mo / Go). */
47
+ export function formatBytes(size: number | undefined): string {
48
+ if (!size || size <= 0) return '—'
49
+ const units = ['o', 'Ko', 'Mo', 'Go', 'To']
50
+ let value = size
51
+ let unit = 0
52
+ while (value >= 1024 && unit < units.length - 1) {
53
+ value /= 1024
54
+ unit += 1
55
+ }
56
+ const rounded = unit === 0 ? value : value < 10 ? Math.round(value * 10) / 10 : Math.round(value)
57
+ return `${rounded} ${units[unit]}`
58
+ }
59
+
60
+ /**
61
+ * URL de vignette depuis l'URL CDN de l'asset (paramètres de transformation
62
+ * Sanity). Renvoie `undefined` pour un non-image (pas de rendu).
63
+ */
64
+ export function thumbnailUrl(asset: Pick<AssetDoc, 'url' | '_type'>, opts: {w?: number; h?: number} = {}): string | undefined {
65
+ if (!asset.url || !isImageAsset(asset)) return undefined
66
+ const params = new URLSearchParams()
67
+ if (opts.w) params.set('w', String(opts.w))
68
+ if (opts.h) params.set('h', String(opts.h))
69
+ params.set('fit', 'crop')
70
+ params.set('auto', 'format')
71
+ return `${asset.url}?${params.toString()}`
72
+ }
73
+
74
+ export type AssetSortKey = 'date' | 'name' | 'size' | 'type'
75
+ export type SortDirection = 'asc' | 'desc'
76
+ export type AssetTypeFilter = 'all' | 'image' | 'file'
77
+ export type AssetUsageFilter = 'all' | 'used' | 'unused'
78
+
79
+ export interface AssetFilter {
80
+ search?: string
81
+ type?: AssetTypeFilter
82
+ usage?: AssetUsageFilter
83
+ }
84
+
85
+ function matchesSearch(asset: AssetDoc, query: string): boolean {
86
+ const haystack = [asset.title, asset.originalFilename, asset.altText, asset.description, asset.extension]
87
+ .filter(Boolean)
88
+ .join(' ')
89
+ .toLowerCase()
90
+ return haystack.includes(query)
91
+ }
92
+
93
+ /** Filtre par recherche, type (image/fichier) et usage. */
94
+ export function filterAssets(assets: readonly AssetDoc[], filter: AssetFilter = {}): AssetDoc[] {
95
+ const query = filter.search?.trim().toLowerCase() ?? ''
96
+ const type = filter.type ?? 'all'
97
+ const usage = filter.usage ?? 'all'
98
+ return assets.filter((asset) => {
99
+ if (query && !matchesSearch(asset, query)) return false
100
+ if (type === 'image' && !isImageAsset(asset)) return false
101
+ if (type === 'file' && isImageAsset(asset)) return false
102
+ if (usage === 'used' && !(asset.uses && asset.uses > 0)) return false
103
+ if (usage === 'unused' && asset.uses && asset.uses > 0) return false
104
+ return true
105
+ })
106
+ }
107
+
108
+ /** Tri stable par date / nom / taille / type. */
109
+ export function sortAssets(assets: readonly AssetDoc[], key: AssetSortKey, direction: SortDirection = 'desc'): AssetDoc[] {
110
+ const factor = direction === 'asc' ? 1 : -1
111
+ const compare = (a: AssetDoc, b: AssetDoc): number => {
112
+ switch (key) {
113
+ case 'name':
114
+ return assetName(a).localeCompare(assetName(b), 'fr', {numeric: true})
115
+ case 'size':
116
+ return (a.size ?? 0) - (b.size ?? 0)
117
+ case 'type':
118
+ return (a.extension ?? a._type).localeCompare(b.extension ?? b._type)
119
+ case 'date':
120
+ default:
121
+ return (a._createdAt < b._createdAt ? -1 : a._createdAt > b._createdAt ? 1 : 0)
122
+ }
123
+ }
124
+ return [...assets].sort((a, b) => factor * compare(a, b))
125
+ }
126
+
127
+ /* --- Dossiers (un seul emplacement par asset) --- */
128
+
129
+ export interface AssetAssignment {
130
+ /** `_id` de l'asset. */
131
+ assetId: string
132
+ /** Id du dossier, ou null (non classé). */
133
+ folder: string | null
134
+ }
135
+
136
+ /** Map assetId -> id de dossier, à partir des affectations stockées. */
137
+ export function assignmentMap(assignments: readonly AssetAssignment[]): Map<string, string> {
138
+ const map = new Map<string, string>()
139
+ for (const {assetId, folder} of assignments) if (folder) map.set(assetId, folder)
140
+ return map
141
+ }
142
+
143
+ /** Sélecteur de dossier courant. `null` = tout, `''` = non classés. */
144
+ export type FolderSelection = string | null
145
+
146
+ /** Assets du dossier sélectionné (`null` = tous, `''` = sans dossier). */
147
+ export function assetsInFolder(assets: readonly AssetDoc[], folders: Map<string, string>, selection: FolderSelection): AssetDoc[] {
148
+ if (selection === null) return [...assets]
149
+ if (selection === '') return assets.filter((asset) => !folders.has(asset._id))
150
+ return assets.filter((asset) => folders.get(asset._id) === selection)
151
+ }
152
+
153
+ /** Nombre d'assets par dossier (+ `''` pour les non classés). */
154
+ export function countByFolder(assets: readonly AssetDoc[], folders: Map<string, string>): Map<string, number> {
155
+ const counts = new Map<string, number>()
156
+ for (const asset of assets) {
157
+ const folder = folders.get(asset._id) ?? ''
158
+ counts.set(folder, (counts.get(folder) ?? 0) + 1)
159
+ }
160
+ return counts
161
+ }
@@ -73,3 +73,108 @@ export function pageTypesWithoutBuilder(
73
73
  })
74
74
  .map((p) => p.type)
75
75
  }
76
+
77
+ /**
78
+ * Noms des sections déclarées via `defineComponentDefaults` (type de document
79
+ * des valeurs par défaut) : un champ par section, dont le nom est la section
80
+ * SANS son namespace (ex. `cta` pour `section.cta`). Set vide si le type est
81
+ * absent du schéma.
82
+ */
83
+ export function sectionNamesFromDefaults(schema: Schema, defaultsType: string): Set<string> {
84
+ const type = schema.get(defaultsType)
85
+ if (!isObjectType(type)) return new Set()
86
+ return new Set(type.fields.map((f) => f.name))
87
+ }
88
+
89
+ /** Nom de membre sans son namespace : `section.cta` -> `cta`, `cta` -> `cta`. */
90
+ const withoutNamespace = (name: string): string => {
91
+ const dot = name.lastIndexOf('.')
92
+ return dot >= 0 ? name.slice(dot + 1) : name
93
+ }
94
+
95
+ /**
96
+ * Vrai si `field` est un tableau dont au moins un membre est une section
97
+ * déclarée. On compare sans dépendre du namespace (les membres `of` sont par
98
+ * ex. `section.cta`, les champs de `componentDefaults` sont `cta`).
99
+ */
100
+ function isSectionArrayField(field: {type?: SchemaType} | undefined, sectionNames: Set<string>): boolean {
101
+ const type = field?.type
102
+ return (
103
+ isArrayType(type) &&
104
+ type.of.some((member) => Boolean(member.name) && (sectionNames.has(member.name as string) || sectionNames.has(withoutNamespace(member.name as string))))
105
+ )
106
+ }
107
+
108
+ /**
109
+ * Détecte le champ tableau des sections d'un type de page : le champ (hors
110
+ * `pageBuilderField` configuré) dont les membres sont les sections déclarées.
111
+ * Renvoie le nom du champ couvrant le plus de types de pages, sinon `null`.
112
+ */
113
+ export function detectPageBuilderField(
114
+ schema: Schema,
115
+ pageTypes: readonly ResolvedPageType[],
116
+ sectionNames: Set<string>,
117
+ ): string | null {
118
+ if (sectionNames.size === 0) return null
119
+ const counts = new Map<string, number>()
120
+ for (const pageType of pageTypes) {
121
+ const documentType = schema.get(pageType.type)
122
+ if (!isObjectType(documentType)) continue
123
+ for (const field of documentType.fields) {
124
+ if (isSectionArrayField(field, sectionNames)) counts.set(field.name, (counts.get(field.name) ?? 0) + 1)
125
+ }
126
+ }
127
+ let best: string | null = null
128
+ let bestCount = 0
129
+ for (const [name, count] of counts) {
130
+ if (count > bestCount) {
131
+ best = name
132
+ bestCount = count
133
+ }
134
+ }
135
+ return best
136
+ }
137
+
138
+ export interface PageBuilderResolution {
139
+ /** Champ page builder effectif (configuré s'il convient, sinon détecté). */
140
+ field: string
141
+ /** Vrai si le champ a été auto-détecté (le champ configuré ne convenait pas). */
142
+ detected: boolean
143
+ /** Faux si aucun champ tableau de sections n'a été trouvé (configuration à corriger). */
144
+ ok: boolean
145
+ }
146
+
147
+ /**
148
+ * Champ page builder à utiliser réellement :
149
+ * - le champ configuré s'il est bien un tableau de sections sur un type de page ;
150
+ * - sinon le champ auto-détecté (ses membres sont les sections déclarées) ;
151
+ * - sinon le champ configuré avec `ok: false` (rien trouvé : à corriger).
152
+ *
153
+ * Quand les sections ne sont pas connues (pas de `componentDefaults` dans le
154
+ * schéma), on garde le comportement historique : le champ configuré est réputé
155
+ * bon dès qu'il existe comme tableau sur au moins un type de page.
156
+ */
157
+ export function resolvePageBuilderField(
158
+ schema: Schema,
159
+ pageTypes: readonly ResolvedPageType[],
160
+ configuredField: string,
161
+ sectionNames: Set<string>,
162
+ ): PageBuilderResolution {
163
+ if (sectionNames.size === 0) {
164
+ const missing = pageTypesWithoutBuilder(schema, pageTypes, configuredField)
165
+ const ok = pageTypes.length === 0 || missing.length < pageTypes.length
166
+ return {field: configuredField, detected: false, ok}
167
+ }
168
+ const configuredIsSectionArray = pageTypes.some((pageType) => {
169
+ const documentType = schema.get(pageType.type)
170
+ if (!isObjectType(documentType)) return false
171
+ return isSectionArrayField(
172
+ documentType.fields.find((f) => f.name === configuredField),
173
+ sectionNames,
174
+ )
175
+ })
176
+ if (configuredIsSectionArray) return {field: configuredField, detected: false, ok: true}
177
+ const detected = detectPageBuilderField(schema, pageTypes, sectionNames)
178
+ if (detected) return {field: detected, detected: true, ok: true}
179
+ return {field: configuredField, detected: false, ok: false}
180
+ }
@@ -0,0 +1,65 @@
1
+ import {defineField, defineType} from 'sanity'
2
+
3
+ /**
4
+ * Métadonnées d'organisation des assets, propres au kit : dossiers et
5
+ * affectation d'un asset à un dossier. Document unique, écrit par l'outil
6
+ * Assets : jamais édité à la main (absent de « Créer »), comme le board.
7
+ *
8
+ * Les assets sont désignés par leur `_id` (chaîne), SANS référence Sanity :
9
+ * supprimer un asset ou vider son dossier ne doit jamais se bloquer l'un
10
+ * l'autre. Zéro schéma à déclarer côté projet : ces types arrivent par le
11
+ * plugin (kitSchemaTypes).
12
+ */
13
+ export const ASSET_META_TYPE = 'ncfAssetMeta'
14
+ export const ASSET_META_ID = 'ncfAssetMeta'
15
+ export const ASSET_FOLDER_TYPE = 'ncfAssetFolder'
16
+ export const ASSET_ASSIGNMENT_TYPE = 'ncfAssetAssignment'
17
+
18
+ const assetFolderType = defineType({
19
+ name: ASSET_FOLDER_TYPE,
20
+ title: 'Asset folder',
21
+ type: 'object',
22
+ fields: [
23
+ defineField({name: 'id', title: 'Id', type: 'string'}),
24
+ defineField({name: 'name', title: 'Name', type: 'string'}),
25
+ // Dossier parent (id) : réservé à une future arborescence ; vide = racine.
26
+ defineField({name: 'parent', title: 'Parent', type: 'string'}),
27
+ ],
28
+ preview: {select: {title: 'name', subtitle: 'id'}},
29
+ })
30
+
31
+ const assetAssignmentType = defineType({
32
+ name: ASSET_ASSIGNMENT_TYPE,
33
+ title: 'Asset folder assignment',
34
+ type: 'object',
35
+ fields: [
36
+ // `_key` de l'entrée = `_id` de l'asset (un seul dossier par asset).
37
+ defineField({name: 'folder', title: 'Folder', type: 'string'}),
38
+ ],
39
+ preview: {select: {title: 'folder'}},
40
+ })
41
+
42
+ const assetMetaType = defineType({
43
+ name: ASSET_META_TYPE,
44
+ title: 'Asset organization (NCF)',
45
+ type: 'document',
46
+ fields: [
47
+ defineField({
48
+ name: 'folders',
49
+ title: 'Folders',
50
+ type: 'array',
51
+ of: [{type: ASSET_FOLDER_TYPE}],
52
+ }),
53
+ defineField({
54
+ name: 'assignments',
55
+ title: 'Folder assignments',
56
+ type: 'array',
57
+ of: [{type: ASSET_ASSIGNMENT_TYPE}],
58
+ }),
59
+ defineField({name: 'updatedBy', title: 'Modified by', type: 'string', readOnly: true}),
60
+ ],
61
+ preview: {prepare: () => ({title: 'Asset organization (NCF)'})},
62
+ })
63
+
64
+ /** Types du singleton d'assets, à concaténer dans kitSchemaTypes. */
65
+ export const assetMetaSchemaTypes = [assetMetaType, assetFolderType, assetAssignmentType]
@@ -1,5 +1,6 @@
1
1
  import {defineField, defineType} from 'sanity'
2
2
  import {TRANSLATION_TODO_TYPE, translationTodoType} from './translationTodo'
3
+ import {ASSET_META_TYPE, assetMetaSchemaTypes} from './assetMeta'
3
4
 
4
5
  /** Type et identifiant du singleton portant la disposition du board. */
5
6
  export const BOARD_LAYOUT_TYPE = 'ncfBoardLayout'
@@ -12,7 +13,7 @@ export const COLUMN_OPTION_TYPE = 'ncfColumnOption'
12
13
  export const ANNOTATION_TYPE = 'ncfAnnotation'
13
14
 
14
15
  /** Types déclarés par le kit : à masquer de la structure du Studio hôte. */
15
- export const NCF_HIDDEN_TYPES = [BOARD_LAYOUT_TYPE, TRANSLATION_TODO_TYPE] as const
16
+ export const NCF_HIDDEN_TYPES = [BOARD_LAYOUT_TYPE, TRANSLATION_TODO_TYPE, ASSET_META_TYPE] as const
16
17
 
17
18
  const boardNodeType = defineType({
18
19
  name: BOARD_NODE_TYPE,
@@ -185,6 +186,7 @@ export const kitSchemaTypes = [
185
186
  columnType,
186
187
  columnOptionType,
187
188
  annotationType,
189
+ ...assetMetaSchemaTypes,
188
190
  ]
189
191
 
190
192
  /** Vrai pour les types techniques du kit. */
@@ -0,0 +1,86 @@
1
+ import {useState} from 'react'
2
+ import {Badge, Box, Card, Checkbox, Flex, Stack, Text} from '@sanity/ui'
3
+ import {DocumentIcon} from '@sanity/icons/Document'
4
+ import {assetName, formatBytes, isImageAsset, thumbnailUrl, type AssetDoc} from '../../lib/assets'
5
+ import {MONO} from '../../ui/tokens'
6
+
7
+ export interface AssetCardProps {
8
+ asset: AssetDoc
9
+ selected: boolean
10
+ onToggleSelect: () => void
11
+ onOpen: () => void
12
+ }
13
+
14
+ /** Tuile d'un asset dans la grille : aperçu, nom, taille, type, usage. */
15
+ export function AssetCard(props: AssetCardProps) {
16
+ const {asset, selected, onToggleSelect, onOpen} = props
17
+ const [failed, setFailed] = useState(false)
18
+ const thumb = thumbnailUrl(asset, {w: 320, h: 220})
19
+ const unused = asset.uses === 0
20
+ const meta = [formatBytes(asset.size), asset.dimensions?.width ? `${asset.dimensions.width}×${asset.dimensions.height}` : null, asset.extension?.toUpperCase()]
21
+ .filter(Boolean)
22
+ .join(' · ')
23
+
24
+ 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
+ >
32
+ {/* Sélection : coin haut-gauche, n'ouvre pas le détail. */}
33
+ <Box style={{position: 'absolute', top: 8, left: 8, zIndex: 1}} onClick={(e) => e.stopPropagation()}>
34
+ <Card radius={2} padding={1} tone="default" style={{opacity: selected ? 1 : 0.85}}>
35
+ <Checkbox checked={selected} onChange={onToggleSelect} aria-label="Sélectionner" />
36
+ </Card>
37
+ </Box>
38
+
39
+ <Stack
40
+ gap={0}
41
+ as="button"
42
+ onClick={onOpen}
43
+ style={{height: '100%', width: '100%', textAlign: 'left', cursor: 'pointer', background: 'transparent', border: 0, padding: 0}}
44
+ >
45
+ <Box style={{aspectRatio: '16 / 11', overflow: 'hidden', background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))'}}>
46
+ {thumb && !failed ? (
47
+ <img
48
+ src={thumb}
49
+ alt=""
50
+ loading="lazy"
51
+ onError={() => setFailed(true)}
52
+ style={{width: '100%', height: '100%', objectFit: 'cover', display: 'block'}}
53
+ />
54
+ ) : (
55
+ <Flex align="center" justify="center" direction="column" gap={2} style={{height: '100%'}} padding={3}>
56
+ <Text size={3} muted>
57
+ <DocumentIcon />
58
+ </Text>
59
+ <Text size={0} muted>
60
+ {asset.extension?.toUpperCase() || (isImageAsset(asset) ? 'IMAGE' : 'FICHIER')}
61
+ </Text>
62
+ </Flex>
63
+ )}
64
+ </Box>
65
+
66
+ <Box padding={3}>
67
+ <Stack gap={2}>
68
+ <Flex align="center" gap={2} justify="space-between">
69
+ <Text size={1} weight="medium" textOverflow="ellipsis" style={{minWidth: 0}}>
70
+ {assetName(asset)}
71
+ </Text>
72
+ {unused ? (
73
+ <Badge tone="caution" fontSize={0} style={{flex: 'none'}} title="Aucun document ne l’utilise">
74
+ inutilisé
75
+ </Badge>
76
+ ) : null}
77
+ </Flex>
78
+ <Text size={0} muted textOverflow="ellipsis" style={MONO}>
79
+ {meta}
80
+ </Text>
81
+ </Stack>
82
+ </Box>
83
+ </Stack>
84
+ </Card>
85
+ )
86
+ }