@nocode-factory/sanity-kit 2.49.1 → 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.
package/dist/jsonld.js CHANGED
@@ -1,4 +1,4 @@
1
- import { o as pageTypeFor, t as finalPath, u as toUrl } from "./finalUrl-C1kzYMzQ.js";
1
+ import { o as pageTypeFor, t as finalPath, u as toUrl } from "./finalUrl-CaFXmYvm.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-CjL_Xy0U.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-w3whO9xM.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-C1kzYMzQ.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-BZk9CkdI.js";
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";
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.49.1",
3
+ "version": "2.50.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -79,9 +79,11 @@
79
79
  },
80
80
  "devDependencies": {
81
81
  "@sanity/pkg-utils": "13.0.1",
82
+ "@testing-library/react": "^16.3.3",
82
83
  "@types/node": "^26.6.3",
83
84
  "@types/react": "^19.2.14",
84
85
  "@types/react-dom": "^19.2.3",
86
+ "happy-dom": "^21.0.3",
85
87
  "next": "^16.3.8",
86
88
  "react": "^19.2.4",
87
89
  "react-dom": "^19.2.4",
@@ -44,6 +44,7 @@ export const DEFAULT_TOOLS: Required<NcfToolsConfig> = {
44
44
  components: true,
45
45
  history: true,
46
46
  designSystem: true,
47
+ assets: true,
47
48
  }
48
49
 
49
50
  /**
@@ -174,6 +174,8 @@ export interface NcfToolsConfig {
174
174
  history?: boolean
175
175
  /** Bouton « Design system » : ouvre la page /design-system dans Presentation. */
176
176
  designSystem?: boolean
177
+ /** Onglet « Assets » : gestionnaire de médias (dossiers, tri, filtres). */
178
+ assets?: boolean
177
179
  }
178
180
 
179
181
  export interface NcfKitConfig {
@@ -364,7 +366,7 @@ export interface ConfigIssue {
364
366
  tools?: NcfToolName[]
365
367
  }
366
368
 
367
- export type NcfToolName = 'pages' | 'components' | 'history' | 'designSystem'
369
+ export type NcfToolName = 'pages' | 'components' | 'history' | 'designSystem' | 'assets'
368
370
 
369
371
  export interface KitContextValue {
370
372
  config: ResolvedKitConfig
@@ -0,0 +1,166 @@
1
+ import {useCallback, useEffect, useRef, useState} from 'react'
2
+ import {useCurrentUser} from 'sanity'
3
+ import {useKitClient} from './useKitClient'
4
+ import {ASSET_META_ID, ASSET_META_TYPE, ASSET_FOLDER_TYPE, ASSET_ASSIGNMENT_TYPE} from '../schema/assetMeta'
5
+ import type {AssetAssignment, AssetFolder} from '../lib/assets'
6
+
7
+ export interface AssetMetaState {
8
+ folders: AssetFolder[]
9
+ assignments: AssetAssignment[]
10
+ loading: boolean
11
+ saveError: Error | null
12
+ /** Crée un dossier et renvoie son id. */
13
+ createFolder: (name: string) => string
14
+ renameFolder: (id: string, name: string) => void
15
+ /** Supprime le dossier ; ses assets redeviennent non classés. */
16
+ deleteFolder: (id: string) => void
17
+ /** Range un asset dans un dossier (`null` = non classé). */
18
+ moveAsset: (assetId: string, folder: string | null) => void
19
+ /** Range plusieurs assets d'un coup. */
20
+ moveAssets: (assetIds: readonly string[], folder: string | null) => void
21
+ }
22
+
23
+ type StoredFolder = {id?: string; name?: string; parent?: string}
24
+ type StoredAssignment = {_key?: string; folder?: string}
25
+
26
+ const newId = (): string => `f${Math.random().toString(36).slice(2, 10)}`
27
+
28
+ /**
29
+ * Lit et écrit l'organisation des assets (dossiers + affectations) dans le
30
+ * singleton du kit `ncfAssetMeta`. Même principe que la disposition du board :
31
+ * document unique réécrit en entier, écriture directe (pas de brouillon),
32
+ * débouncée. À appeler UNE fois (outil Assets) : deux instances s'écraseraient.
33
+ */
34
+ export function useAssetMeta(): AssetMetaState {
35
+ const client = useKitClient()
36
+ const user = useCurrentUser()
37
+
38
+ const [folders, setFolders] = useState<AssetFolder[]>([])
39
+ const [assignments, setAssignments] = useState<AssetAssignment[]>([])
40
+ const [loading, setLoading] = useState(true)
41
+ const [saveError, setSaveError] = useState<Error | null>(null)
42
+
43
+ useEffect(() => {
44
+ let cancelled = false
45
+ client
46
+ .fetch<{folders?: StoredFolder[]; assignments?: StoredAssignment[]} | null>(
47
+ `*[_id == $id][0]{folders, assignments}`,
48
+ {id: ASSET_META_ID},
49
+ )
50
+ .then((doc) => {
51
+ if (cancelled) return
52
+ setFolders((doc?.folders ?? []).filter((f): f is Required<Pick<StoredFolder, 'id' | 'name'>> & StoredFolder => Boolean(f.id && f.name)).map((f) => ({id: f.id as string, name: f.name as string, ...(f.parent ? {parent: f.parent} : {})})))
53
+ setAssignments(
54
+ (doc?.assignments ?? [])
55
+ .filter((a) => Boolean(a._key && a.folder))
56
+ .map((a) => ({assetId: a._key as string, folder: a.folder as string})),
57
+ )
58
+ })
59
+ .catch(() => {
60
+ if (!cancelled) {
61
+ setFolders([])
62
+ setAssignments([])
63
+ }
64
+ })
65
+ .finally(() => {
66
+ if (!cancelled) setLoading(false)
67
+ })
68
+ return () => {
69
+ cancelled = true
70
+ }
71
+ }, [client])
72
+
73
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
74
+ useEffect(
75
+ () => () => {
76
+ if (timer.current) clearTimeout(timer.current)
77
+ },
78
+ [],
79
+ )
80
+
81
+ const foldersRef = useRef<AssetFolder[]>([])
82
+ const assignmentsRef = useRef<AssetAssignment[]>([])
83
+ foldersRef.current = folders
84
+ assignmentsRef.current = assignments
85
+
86
+ const write = useCallback(
87
+ (next?: {folders?: AssetFolder[]; assignments?: AssetAssignment[]}) => {
88
+ const nextFolders = next?.folders ?? foldersRef.current
89
+ const nextAssignments = next?.assignments ?? assignmentsRef.current
90
+ if (timer.current) clearTimeout(timer.current)
91
+ timer.current = setTimeout(() => {
92
+ client
93
+ .createOrReplace({
94
+ _id: ASSET_META_ID,
95
+ _type: ASSET_META_TYPE,
96
+ folders: nextFolders.map((folder) => ({
97
+ _key: folder.id,
98
+ _type: ASSET_FOLDER_TYPE,
99
+ id: folder.id,
100
+ name: folder.name,
101
+ ...(folder.parent ? {parent: folder.parent} : {}),
102
+ })),
103
+ // Seules les affectations à un dossier sont stockées ; `_key` = id de l'asset.
104
+ assignments: nextAssignments
105
+ .filter((assignment) => assignment.folder)
106
+ .map((assignment) => ({
107
+ _key: assignment.assetId,
108
+ _type: ASSET_ASSIGNMENT_TYPE,
109
+ folder: assignment.folder,
110
+ })),
111
+ updatedBy: user?.id ?? null,
112
+ })
113
+ .then(() => setSaveError(null))
114
+ .catch((cause: unknown) => setSaveError(cause instanceof Error ? cause : new Error(String(cause))))
115
+ }, 800)
116
+ },
117
+ [client, user?.id],
118
+ )
119
+
120
+ const createFolder = useCallback(
121
+ (name: string): string => {
122
+ const id = newId()
123
+ const next = [...foldersRef.current, {id, name: name.trim() || 'Dossier'}]
124
+ setFolders(next)
125
+ write({folders: next})
126
+ return id
127
+ },
128
+ [write],
129
+ )
130
+
131
+ const renameFolder = useCallback(
132
+ (id: string, name: string) => {
133
+ const next = foldersRef.current.map((folder) => (folder.id === id ? {...folder, name: name.trim() || folder.name} : folder))
134
+ setFolders(next)
135
+ write({folders: next})
136
+ },
137
+ [write],
138
+ )
139
+
140
+ const deleteFolder = useCallback(
141
+ (id: string) => {
142
+ const nextFolders = foldersRef.current.filter((folder) => folder.id !== id)
143
+ const nextAssignments = assignmentsRef.current.filter((assignment) => assignment.folder !== id)
144
+ setFolders(nextFolders)
145
+ setAssignments(nextAssignments)
146
+ write({folders: nextFolders, assignments: nextAssignments})
147
+ },
148
+ [write],
149
+ )
150
+
151
+ const moveAssets = useCallback(
152
+ (assetIds: readonly string[], folder: string | null) => {
153
+ const ids = new Set(assetIds)
154
+ const kept = assignmentsRef.current.filter((assignment) => !ids.has(assignment.assetId))
155
+ const added = folder ? assetIds.map((assetId) => ({assetId, folder})) : []
156
+ const next = [...kept, ...added]
157
+ setAssignments(next)
158
+ write({assignments: next})
159
+ },
160
+ [write],
161
+ )
162
+
163
+ const moveAsset = useCallback((assetId: string, folder: string | null) => moveAssets([assetId], folder), [moveAssets])
164
+
165
+ return {folders, assignments, loading, saveError, createFolder, renameFolder, deleteFolder, moveAsset, moveAssets}
166
+ }
@@ -0,0 +1,23 @@
1
+ import {useQueryData} from './useQueryData'
2
+ import type {AssetDoc} from '../lib/assets'
3
+
4
+ const ASSET_TYPES = ['sanity.imageAsset', 'sanity.fileAsset']
5
+
6
+ /**
7
+ * Tous les assets du dataset (images et fichiers), en direct. `uses` compte les
8
+ * documents qui référencent l'asset (utilisé / inutilisé) : il suit les
9
+ * mutations d'assets ; un changement de contenu qui (dé)référence un asset est
10
+ * pris au prochain rafraîchissement.
11
+ */
12
+ export function useAssets() {
13
+ return useQueryData<AssetDoc[]>(
14
+ `*[_type in $types]{
15
+ _id, _type, _createdAt, _updatedAt, originalFilename, extension, mimeType, size, url,
16
+ title, altText, description,
17
+ "dimensions": metadata.dimensions, "lqip": metadata.lqip,
18
+ "uses": count(*[references(^._id)])
19
+ } | order(_createdAt desc)`,
20
+ {types: ASSET_TYPES},
21
+ {listenTypes: ASSET_TYPES},
22
+ )
23
+ }
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 {
@@ -274,6 +294,30 @@ export {
274
294
  } from './lib/schemaTypes'
275
295
  export type {PageBuilderResolution} from './lib/schemaTypes'
276
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'
277
321
  export {
278
322
  buildPagesQuery,
279
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
+ }
@@ -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. */