@nocode-factory/sanity-kit 2.49.1 → 2.51.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 (39) hide show
  1. package/README.md +2 -1
  2. package/dist/{finalUrl-C1kzYMzQ.js → finalUrl-CaFXmYvm.js} +3 -2
  3. package/dist/finalUrl-CaFXmYvm.js.map +1 -0
  4. package/dist/{fixCrossLanguageReferences-BZk9CkdI.js → fixCrossLanguageReferences-BeXywAAU.js} +2 -2
  5. package/dist/{fixCrossLanguageReferences-BZk9CkdI.js.map → fixCrossLanguageReferences-BeXywAAU.js.map} +1 -1
  6. package/dist/{fixCrossLanguageReferences-CjL_Xy0U.d.ts → fixCrossLanguageReferences-w3whO9xM.d.ts} +4 -2
  7. package/dist/index.d.ts +287 -5
  8. package/dist/index.js +2119 -181
  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 +3 -1
  14. package/src/config/defaults.ts +1 -0
  15. package/src/config/types.ts +3 -1
  16. package/src/context/ComponentMetaContext.tsx +23 -0
  17. package/src/form/ArrayNamesInput.tsx +25 -0
  18. package/src/form/renameArrayMembers.ts +25 -0
  19. package/src/hooks/useAssetMeta.ts +166 -0
  20. package/src/hooks/useAssets.ts +23 -0
  21. package/src/hooks/useComponentMeta.ts +159 -0
  22. package/src/hooks/useComponentNames.ts +39 -0
  23. package/src/index.ts +56 -1
  24. package/src/lib/assets.ts +161 -0
  25. package/src/lib/componentMeta.ts +70 -0
  26. package/src/schema/assetMeta.ts +65 -0
  27. package/src/schema/boardLayout.ts +5 -1
  28. package/src/schema/componentMeta.ts +54 -0
  29. package/src/tools/assets/AssetCard.tsx +86 -0
  30. package/src/tools/assets/AssetDetail.tsx +150 -0
  31. package/src/tools/assets/AssetTable.tsx +122 -0
  32. package/src/tools/assets/AssetsTool.tsx +212 -0
  33. package/src/tools/assets/AssetsToolbar.tsx +98 -0
  34. package/src/tools/assets/FolderSidebar.tsx +177 -0
  35. package/src/tools/components/BlockCard.tsx +20 -12
  36. package/src/tools/components/ComponentEditDialog.tsx +83 -0
  37. package/src/tools/components/ComponentsTool.tsx +190 -84
  38. package/src/version.ts +1 -1
  39. package/dist/finalUrl-C1kzYMzQ.js.map +0 -1
package/dist/jsonld.js CHANGED
@@ -1,4 +1,4 @@
1
- import { o as pageTypeFor, t as finalPath, u as toUrl } from "./finalUrl-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.51.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,23 @@
1
+ import {createContext, useContext, type ReactNode} from 'react'
2
+ import {useComponentMetaState, type ComponentMetaState} from '../hooks/useComponentMeta'
3
+
4
+ const ComponentMetaContext = createContext<ComponentMetaState | null>(null)
5
+
6
+ /**
7
+ * Une seule instance de l'organisation des composants dans l'onglet.
8
+ *
9
+ * Le document `ncfComponentMeta` est réécrit en entier à chaque enregistrement :
10
+ * deux instances s'écraseraient (renommer effacerait un groupe, etc.).
11
+ */
12
+ export function ComponentMetaProvider(props: {children: ReactNode}) {
13
+ const value = useComponentMetaState()
14
+ return <ComponentMetaContext.Provider value={value}>{props.children}</ComponentMetaContext.Provider>
15
+ }
16
+
17
+ export function useComponentMeta(): ComponentMetaState {
18
+ const value = useContext(ComponentMetaContext)
19
+ if (!value) {
20
+ throw new Error('useComponentMeta must be called inside ComponentMetaProvider.')
21
+ }
22
+ return value
23
+ }
@@ -0,0 +1,25 @@
1
+ import {createElement, useMemo, type ComponentType} from 'react'
2
+ import type {InputProps} from 'sanity'
3
+ import {useComponentNames} from '../hooks/useComponentNames'
4
+ import {renameArrayMembers} from './renameArrayMembers'
5
+
6
+ /**
7
+ * Input d'un champ tableau : si ses membres portent un nom marketing (groupes /
8
+ * renommage des composants), réécrit leurs titres pour que le menu d'insertion
9
+ * les affiche. Sinon, délègue au comportement normal du kit (`Fallback`).
10
+ *
11
+ * Cible naturellement le page builder (et tout tableau qui accepte des sections
12
+ * renommées) sans avoir à l'identifier : seuls les membres réellement renommés
13
+ * changent.
14
+ */
15
+ export function createArrayNamesInput(Fallback: ComponentType<InputProps>): ComponentType<InputProps> {
16
+ return function ArrayNamesInput(props: InputProps) {
17
+ const names = useComponentNames()
18
+ const schemaType = useMemo(
19
+ () => renameArrayMembers(props.schemaType as never, names),
20
+ [props.schemaType, names],
21
+ )
22
+ if (schemaType === (props.schemaType as never)) return createElement(Fallback, props)
23
+ return props.renderDefault({...props, schemaType} as InputProps)
24
+ }
25
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Réécrit le `title` des membres `of` d'un type tableau à partir des noms
3
+ * marketing (type -> nom). Sert à ce que le menu d'insertion du page builder
4
+ * affiche le nom donné par le marketing au lieu du titre du schéma.
5
+ *
6
+ * Renvoie le MÊME objet si rien n'est à renommer (aucun membre concerné) :
7
+ * l'appelant peut comparer par identité pour ne rien changer au rendu.
8
+ * Le clone préserve le prototype du type de schéma (l'input d'array peut en
9
+ * dépendre) et ne remplace que `title`.
10
+ */
11
+ type ArrayMember = {name?: string; title?: string} & Record<string, unknown>
12
+ type ArrayLikeType = {of?: ArrayMember[]} & Record<string, unknown>
13
+
14
+ export function renameArrayMembers<T extends ArrayLikeType>(schemaType: T, names: ReadonlyMap<string, string>): T {
15
+ const members = schemaType.of
16
+ if (names.size === 0 || !Array.isArray(members) || !members.some((member) => member?.name && names.has(member.name))) {
17
+ return schemaType
18
+ }
19
+ const of = members.map((member) =>
20
+ member?.name && names.has(member.name)
21
+ ? (Object.assign(Object.create(Object.getPrototypeOf(member)), member, {title: names.get(member.name)}) as ArrayMember)
22
+ : member,
23
+ )
24
+ return {...schemaType, of}
25
+ }
@@ -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
+ }
@@ -0,0 +1,159 @@
1
+ import {useCallback, useEffect, useMemo, useRef, useState} from 'react'
2
+ import {useCurrentUser} from 'sanity'
3
+ import {useKitClient} from './useKitClient'
4
+ import {COMPONENT_META_ID, COMPONENT_META_TYPE, COMPONENT_GROUP_TYPE, COMPONENT_ENTRY_TYPE} from '../schema/componentMeta'
5
+ import {groupMap, nameMap, type ComponentEntry, type ComponentGroup} from '../lib/componentMeta'
6
+
7
+ export interface ComponentMetaState {
8
+ groups: ComponentGroup[]
9
+ entries: ComponentEntry[]
10
+ names: Map<string, string>
11
+ groupOf: Map<string, string>
12
+ loading: boolean
13
+ saveError: Error | null
14
+ createGroup: (name: string) => string
15
+ renameGroup: (id: string, name: string) => void
16
+ deleteGroup: (id: string) => void
17
+ /** Nom marketing d'un composant (`''`/null = retour au titre du schéma). */
18
+ renameComponent: (type: string, name: string | null) => void
19
+ /** Range un composant dans un groupe (`null` = sans groupe). */
20
+ setGroup: (type: string, group: string | null) => void
21
+ }
22
+
23
+ type StoredGroup = {id?: string; name?: string}
24
+ type StoredEntry = {_key?: string; name?: string; group?: string}
25
+
26
+ const newId = (): string => `g${Math.random().toString(36).slice(2, 10)}`
27
+
28
+ /**
29
+ * Lit et écrit l'organisation des composants (groupes + noms marketing) dans le
30
+ * singleton du kit `ncfComponentMeta`. Même principe que l'organisation des
31
+ * assets : document unique réécrit en entier, écriture débouncée, optimiste.
32
+ * À appeler UNE fois (via `ComponentMetaProvider`).
33
+ */
34
+ export function useComponentMetaState(): ComponentMetaState {
35
+ const client = useKitClient()
36
+ const user = useCurrentUser()
37
+
38
+ const [groups, setGroups] = useState<ComponentGroup[]>([])
39
+ const [entries, setEntries] = useState<ComponentEntry[]>([])
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<{groups?: StoredGroup[]; components?: StoredEntry[]} | null>(`*[_id == $id][0]{groups, components}`, {id: COMPONENT_META_ID})
47
+ .then((doc) => {
48
+ if (cancelled) return
49
+ setGroups((doc?.groups ?? []).filter((g) => g.id && g.name).map((g) => ({id: g.id as string, name: g.name as string})))
50
+ setEntries(
51
+ (doc?.components ?? [])
52
+ .filter((c) => Boolean(c._key))
53
+ .map((c) => ({type: c._key as string, ...(c.name ? {name: c.name} : {}), ...(c.group ? {group: c.group} : {})})),
54
+ )
55
+ })
56
+ .catch(() => {
57
+ if (!cancelled) {
58
+ setGroups([])
59
+ setEntries([])
60
+ }
61
+ })
62
+ .finally(() => {
63
+ if (!cancelled) setLoading(false)
64
+ })
65
+ return () => {
66
+ cancelled = true
67
+ }
68
+ }, [client])
69
+
70
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
71
+ useEffect(
72
+ () => () => {
73
+ if (timer.current) clearTimeout(timer.current)
74
+ },
75
+ [],
76
+ )
77
+
78
+ const groupsRef = useRef<ComponentGroup[]>([])
79
+ const entriesRef = useRef<ComponentEntry[]>([])
80
+ groupsRef.current = groups
81
+ entriesRef.current = entries
82
+
83
+ const write = useCallback(
84
+ (next?: {groups?: ComponentGroup[]; entries?: ComponentEntry[]}) => {
85
+ const nextGroups = next?.groups ?? groupsRef.current
86
+ const nextEntries = next?.entries ?? entriesRef.current
87
+ if (timer.current) clearTimeout(timer.current)
88
+ timer.current = setTimeout(() => {
89
+ client
90
+ .createOrReplace({
91
+ _id: COMPONENT_META_ID,
92
+ _type: COMPONENT_META_TYPE,
93
+ groups: nextGroups.map((group) => ({_key: group.id, _type: COMPONENT_GROUP_TYPE, id: group.id, name: group.name})),
94
+ // Entrées sans nom ni groupe : inutiles, on ne les stocke pas. `_key` = type.
95
+ components: nextEntries
96
+ .filter((entry) => entry.name || entry.group)
97
+ .map((entry) => ({_key: entry.type, _type: COMPONENT_ENTRY_TYPE, ...(entry.name ? {name: entry.name} : {}), ...(entry.group ? {group: entry.group} : {})})),
98
+ updatedBy: user?.id ?? null,
99
+ })
100
+ .then(() => setSaveError(null))
101
+ .catch((cause: unknown) => setSaveError(cause instanceof Error ? cause : new Error(String(cause))))
102
+ }, 800)
103
+ },
104
+ [client, user?.id],
105
+ )
106
+
107
+ // Modifie l'entrée d'un type (crée/supprime au besoin), puis écrit.
108
+ const patchEntry = useCallback(
109
+ (type: string, patch: Partial<ComponentEntry>) => {
110
+ const current = entriesRef.current.find((entry) => entry.type === type) ?? {type}
111
+ const merged: ComponentEntry = {...current, ...patch}
112
+ const cleaned: ComponentEntry = {type, ...(merged.name ? {name: merged.name} : {}), ...(merged.group ? {group: merged.group} : {})}
113
+ const others = entriesRef.current.filter((entry) => entry.type !== type)
114
+ const next = cleaned.name || cleaned.group ? [...others, cleaned] : others
115
+ setEntries(next)
116
+ write({entries: next})
117
+ },
118
+ [write],
119
+ )
120
+
121
+ const createGroup = useCallback(
122
+ (name: string): string => {
123
+ const id = newId()
124
+ const next = [...groupsRef.current, {id, name: name.trim() || 'Groupe'}]
125
+ setGroups(next)
126
+ write({groups: next})
127
+ return id
128
+ },
129
+ [write],
130
+ )
131
+
132
+ const renameGroup = useCallback(
133
+ (id: string, name: string) => {
134
+ const next = groupsRef.current.map((group) => (group.id === id ? {...group, name: name.trim() || group.name} : group))
135
+ setGroups(next)
136
+ write({groups: next})
137
+ },
138
+ [write],
139
+ )
140
+
141
+ const deleteGroup = useCallback(
142
+ (id: string) => {
143
+ const nextGroups = groupsRef.current.filter((group) => group.id !== id)
144
+ const nextEntries = entriesRef.current.map((entry) => (entry.group === id ? {...entry, group: undefined} : entry)).filter((entry) => entry.name || entry.group)
145
+ setGroups(nextGroups)
146
+ setEntries(nextEntries)
147
+ write({groups: nextGroups, entries: nextEntries})
148
+ },
149
+ [write],
150
+ )
151
+
152
+ const renameComponent = useCallback((type: string, name: string | null) => patchEntry(type, {name: name?.trim() || undefined}), [patchEntry])
153
+ const setGroup = useCallback((type: string, group: string | null) => patchEntry(type, {group: group ?? undefined}), [patchEntry])
154
+
155
+ const names = useMemo(() => nameMap(entries), [entries])
156
+ const groupOf = useMemo(() => groupMap(entries), [entries])
157
+
158
+ return {groups, entries, names, groupOf, loading, saveError, createGroup, renameGroup, deleteGroup, renameComponent, setGroup}
159
+ }
@@ -0,0 +1,39 @@
1
+ import {useEffect, useState} from 'react'
2
+ import {useKitClient} from './useKitClient'
3
+ import {COMPONENT_META_ID} from '../schema/componentMeta'
4
+
5
+ type StoredEntry = {_key?: string; name?: string}
6
+
7
+ /**
8
+ * Noms marketing des composants (type -> nom), en LECTURE SEULE et en direct.
9
+ * Pour les surfaces hors onglet (ex. l'input du page builder qui réécrit les
10
+ * libellés du menu d'insertion) : pas d'écriture, donc pas de provider unique.
11
+ */
12
+ export function useComponentNames(): Map<string, string> {
13
+ const client = useKitClient()
14
+ const [names, setNames] = useState<Map<string, string>>(() => new Map())
15
+
16
+ useEffect(() => {
17
+ let cancelled = false
18
+ const load = () =>
19
+ client
20
+ .fetch<{components?: StoredEntry[]} | null>(`*[_id == $id][0]{components}`, {id: COMPONENT_META_ID})
21
+ .then((doc) => {
22
+ if (cancelled) return
23
+ const map = new Map<string, string>()
24
+ for (const entry of doc?.components ?? []) if (entry._key && entry.name?.trim()) map.set(entry._key, entry.name.trim())
25
+ setNames(map)
26
+ })
27
+ .catch(() => {})
28
+ void load()
29
+ const subscription = client
30
+ .listen(`*[_id == $id]`, {id: COMPONENT_META_ID}, {visibility: 'query', events: ['mutation']})
31
+ .subscribe({next: () => void load(), error: () => {}})
32
+ return () => {
33
+ cancelled = true
34
+ subscription.unsubscribe()
35
+ }
36
+ }, [client])
37
+
38
+ return names
39
+ }
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
  /**
@@ -46,6 +50,7 @@ import {KitProvider} from './context/KitContext'
46
50
  import type {ConfigIssue} from './config/types'
47
51
  import {RemoveFromSiteAction, createRemoveFromSite} from './actions/RemoveFromSite'
48
52
  import {createSlugUrlInput, isSlugInput} from './form/SlugUrlInput'
53
+ import {createArrayNamesInput} from './form/ArrayNamesInput'
49
54
  import {withTranslationTodo} from './form/TranslationTodoInput'
50
55
  import {withPublishedHint} from './form/PublishedHint'
51
56
  import {withLanguageMismatch} from './form/LanguageMismatch'
@@ -58,11 +63,18 @@ import {withTranslationRedirects} from './actions/TranslationRedirects'
58
63
  function createKitInput(config: Parameters<typeof createOverrideInput>[0], issues: ConfigIssue[]): ComponentType<InputProps> {
59
64
  const Override = createOverrideInput(config)
60
65
  const SlugUrl = createSlugUrlInput(config)
66
+ // Tableaux : réécrit les libellés du menu d'insertion avec les noms marketing
67
+ // des composants (sinon, comportement normal via Override).
68
+ const ArrayNames = createArrayNamesInput(Override)
61
69
  function KitInput(props: InputProps) {
62
70
  // Configuration du kit fournie au formulaire : les champs du kit (ex. JSON-LD,
63
71
  // useKitConfig) la lisent comme les outils. Sans elle : « useKitContext must be
64
72
  // called inside a tool ».
65
- const children = isSlugInput(props) ? createElement(SlugUrl, props) : createElement(Override, props)
73
+ const children = isSlugInput(props)
74
+ ? createElement(SlugUrl, props)
75
+ : props.schemaType.jsonType === 'array'
76
+ ? createElement(ArrayNames, props)
77
+ : createElement(Override, props)
66
78
  return createElement(KitProvider, {config, issues, children})
67
79
  }
68
80
  // Traductions : pastille « À traduire » sur les champs modifiés dans la version principale.
@@ -142,6 +154,22 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
142
154
  }),
143
155
  },
144
156
  },
157
+ {
158
+ // Gestionnaire de médias : tous les assets, dossiers, tri et filtres.
159
+ name: 'assets',
160
+ tool: {
161
+ name: NCF_ASSETS_TOOL,
162
+ title: 'Assets',
163
+ icon: ImagesIcon,
164
+ component: createToolComponent({
165
+ name: 'assets',
166
+ title: 'Assets',
167
+ config,
168
+ issues,
169
+ Component: AssetsTool,
170
+ }),
171
+ },
172
+ },
145
173
  ]
146
174
 
147
175
  return {
@@ -274,6 +302,33 @@ export {
274
302
  } from './lib/schemaTypes'
275
303
  export type {PageBuilderResolution} from './lib/schemaTypes'
276
304
  export {usePageBuilder} from './hooks/usePageBuilder'
305
+ export {AssetsTool} from './tools/assets/AssetsTool'
306
+ export {useAssets} from './hooks/useAssets'
307
+ export {useAssetMeta} from './hooks/useAssetMeta'
308
+ export type {AssetMetaState} from './hooks/useAssetMeta'
309
+ export {
310
+ assetName,
311
+ formatBytes,
312
+ thumbnailUrl,
313
+ isImageAsset,
314
+ filterAssets,
315
+ sortAssets,
316
+ assignmentMap,
317
+ assetsInFolder,
318
+ countByFolder,
319
+ } from './lib/assets'
320
+ export type {
321
+ AssetDoc,
322
+ AssetFolder,
323
+ AssetAssignment,
324
+ AssetSortKey,
325
+ AssetTypeFilter,
326
+ AssetUsageFilter,
327
+ FolderSelection,
328
+ } from './lib/assets'
329
+ export {nameMap, groupMap, withCustomNames, groupComponents} from './lib/componentMeta'
330
+ export type {ComponentGroup, ComponentEntry, ComponentGrouping} from './lib/componentMeta'
331
+ export {useComponentNames} from './hooks/useComponentNames'
277
332
  export {
278
333
  buildPagesQuery,
279
334
  buildContentsQuery,