@nocode-factory/sanity-kit 2.51.0 → 2.52.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.51.0",
3
+ "version": "2.52.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -0,0 +1,110 @@
1
+ import {useMemo, useState} from 'react'
2
+ import {Box, Button, Card, Dialog, Flex, Grid, Spinner, Stack, Text, TextInput} from '@sanity/ui'
3
+ import {SearchIcon} from '@sanity/icons/Search'
4
+ import type {AssetSourceComponentProps} from 'sanity'
5
+ import {useAssets} from '../hooks/useAssets'
6
+ import {useAssetMeta} from '../hooks/useAssetMeta'
7
+ import {assetName, assetsInFolder, assignmentMap, countByFolder, filterAssets, isImageAsset, sortAssets, thumbnailUrl, type AssetDoc, type FolderSelection} from '../lib/assets'
8
+ import {FolderSidebar} from '../tools/assets/FolderSidebar'
9
+ import {MONO} from '../ui/tokens'
10
+
11
+ /**
12
+ * Source d'asset « NCF Médias » : le sélecteur d'image/fichier d'un champ montre
13
+ * les mêmes DOSSIERS et la même recherche que l'onglet Assets. Sans ça,
14
+ * l'organisation ne servirait qu'à l'onglet et pas au choix d'un média.
15
+ */
16
+ export function AssetSourceBrowser(props: AssetSourceComponentProps) {
17
+ const {assetType, onSelect, onClose, dialogHeaderTitle} = props
18
+ const {data, loading} = useAssets()
19
+ const meta = useAssetMeta()
20
+ const [search, setSearch] = useState('')
21
+ const [selection, setSelection] = useState<FolderSelection>(null)
22
+
23
+ // Le sélecteur d'un champ image ne propose que des images, celui d'un fichier
24
+ // que des fichiers.
25
+ const wantImages = assetType !== 'file'
26
+ const all = useMemo(() => (data ?? []).filter((asset) => (wantImages ? isImageAsset(asset) : !isImageAsset(asset))), [data, wantImages])
27
+
28
+ const folderMap = useMemo(() => assignmentMap(meta.assignments), [meta.assignments])
29
+ const counts = useMemo(() => countByFolder(all, folderMap), [all, folderMap])
30
+ const visible = useMemo(() => sortAssets(filterAssets(assetsInFolder(all, folderMap, selection), {search}), 'date', 'desc'), [all, folderMap, selection, search])
31
+
32
+ const pick = (asset: AssetDoc) => {
33
+ onSelect([{kind: 'assetDocumentId', value: asset._id}])
34
+ onClose()
35
+ }
36
+
37
+ return (
38
+ <Dialog id="ncf-asset-source" header={dialogHeaderTitle || 'NCF Médias'} width={3} onClose={onClose}>
39
+ <Flex style={{minHeight: 420}} align="stretch">
40
+ <Box padding={3} style={{width: 220, flex: 'none', borderRight: '1px solid var(--card-border-color)'}} overflow="auto">
41
+ <FolderSidebar
42
+ folders={meta.folders}
43
+ counts={counts}
44
+ total={all.length}
45
+ selection={selection}
46
+ onSelect={setSelection}
47
+ onCreate={meta.createFolder}
48
+ onRename={meta.renameFolder}
49
+ onDelete={(id) => {
50
+ if (selection === id) setSelection(null)
51
+ meta.deleteFolder(id)
52
+ }}
53
+ />
54
+ </Box>
55
+
56
+ <Stack flex={1} gap={3} padding={3} style={{minWidth: 0}}>
57
+ <TextInput
58
+ value={search}
59
+ onChange={(event) => setSearch(event.currentTarget.value)}
60
+ placeholder="Rechercher un média"
61
+ icon={SearchIcon}
62
+ clearButton={search.length > 0}
63
+ onClear={() => setSearch('')}
64
+ fontSize={1}
65
+ radius={2}
66
+ />
67
+ <Box flex={1} overflow="auto">
68
+ {loading && all.length === 0 ? (
69
+ <Flex align="center" justify="center" padding={5}>
70
+ <Spinner muted />
71
+ </Flex>
72
+ ) : visible.length === 0 ? (
73
+ <Flex align="center" justify="center" padding={5}>
74
+ <Text size={1} muted>
75
+ Aucun média{selection ? ' dans ce dossier' : ''}.
76
+ </Text>
77
+ </Flex>
78
+ ) : (
79
+ <Grid gridTemplateColumns={[2, 3, 4]} gap={3}>
80
+ {visible.map((asset) => {
81
+ const thumb = thumbnailUrl(asset, {w: 240, h: 180})
82
+ return (
83
+ <Card
84
+ key={asset._id}
85
+ radius={2}
86
+ shadow={1}
87
+ padding={0}
88
+ as="button"
89
+ onClick={() => pick(asset)}
90
+ style={{overflow: 'hidden', cursor: 'pointer', textAlign: 'left', border: 0}}
91
+ >
92
+ <Box style={{aspectRatio: '4 / 3', background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))'}}>
93
+ {thumb ? <img src={thumb} alt="" loading="lazy" style={{width: '100%', height: '100%', objectFit: 'cover', display: 'block'}} /> : null}
94
+ </Box>
95
+ <Box padding={2}>
96
+ <Text size={0} textOverflow="ellipsis" style={MONO}>
97
+ {assetName(asset)}
98
+ </Text>
99
+ </Box>
100
+ </Card>
101
+ )
102
+ })}
103
+ </Grid>
104
+ )}
105
+ </Box>
106
+ </Stack>
107
+ </Flex>
108
+ </Dialog>
109
+ )
110
+ }
@@ -0,0 +1,46 @@
1
+ import {useCallback, useState} from 'react'
2
+ import {useKitClient} from './useKitClient'
3
+
4
+ export interface AssetUploadState {
5
+ /** Téléverse des fichiers ; `onUploaded` reçoit l'id de chaque asset créé. */
6
+ upload: (files: FileList | readonly File[], onUploaded?: (assetId: string) => void) => Promise<void>
7
+ /** Nombre de fichiers en cours de téléversement. */
8
+ uploading: number
9
+ error: Error | null
10
+ }
11
+
12
+ /** Détermine le type d'asset Sanity d'après le fichier. */
13
+ const assetKind = (file: File): 'image' | 'file' => (file.type.startsWith('image/') ? 'image' : 'file')
14
+
15
+ /**
16
+ * Téléverse des assets dans le dataset depuis l'outil Assets
17
+ * (`client.assets.upload`). La liste se met à jour toute seule (écoute des
18
+ * mutations d'assets) ; `onUploaded` permet de ranger l'asset dans un dossier.
19
+ */
20
+ export function useAssetUpload(): AssetUploadState {
21
+ const client = useKitClient()
22
+ const [uploading, setUploading] = useState(0)
23
+ const [error, setError] = useState<Error | null>(null)
24
+
25
+ const upload = useCallback(
26
+ async (files: FileList | readonly File[], onUploaded?: (assetId: string) => void) => {
27
+ const list = Array.from(files)
28
+ if (!list.length) return
29
+ setError(null)
30
+ setUploading((count) => count + list.length)
31
+ for (const file of list) {
32
+ try {
33
+ const asset = await client.assets.upload(assetKind(file), file, {filename: file.name})
34
+ onUploaded?.(asset._id)
35
+ } catch (cause) {
36
+ setError(cause instanceof Error ? cause : new Error(String(cause)))
37
+ } finally {
38
+ setUploading((count) => Math.max(0, count - 1))
39
+ }
40
+ }
41
+ },
42
+ [client],
43
+ )
44
+
45
+ return {upload, uploading, error}
46
+ }
package/src/index.ts CHANGED
@@ -27,6 +27,14 @@ export const NCF_HISTORY_TOOL = 'ncf-history'
27
27
  export const NCF_DESIGN_SYSTEM_TOOL = 'ncf-design-system'
28
28
  export const NCF_ASSETS_TOOL = 'ncf-assets'
29
29
 
30
+ /** Source d'asset « NCF Médias » (dossiers + recherche dans le sélecteur d'un champ). */
31
+ const ncfAssetSource: AssetSource = {
32
+ name: 'ncf-media',
33
+ title: 'NCF Médias',
34
+ icon: ImagesIcon,
35
+ component: AssetSourceBrowser,
36
+ }
37
+
30
38
  export const NCF_TOOL_NAMES = [
31
39
  NCF_PAGES_TOOL,
32
40
  NCF_COMPONENTS_TOOL,
@@ -51,6 +59,8 @@ import type {ConfigIssue} from './config/types'
51
59
  import {RemoveFromSiteAction, createRemoveFromSite} from './actions/RemoveFromSite'
52
60
  import {createSlugUrlInput, isSlugInput} from './form/SlugUrlInput'
53
61
  import {createArrayNamesInput} from './form/ArrayNamesInput'
62
+ import {AssetSourceBrowser} from './form/AssetSourceBrowser'
63
+ import type {AssetSource} from 'sanity'
54
64
  import {withTranslationTodo} from './form/TranslationTodoInput'
55
65
  import {withPublishedHint} from './form/PublishedHint'
56
66
  import {withLanguageMismatch} from './form/LanguageMismatch'
@@ -235,6 +245,14 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
235
245
  // Slug d'une page : son adresse complète en ligne (Copier, Ouvrir).
236
246
  form: {
237
247
  components: {input: createKitInput(config, issues)},
248
+ // Sélecteur d'un champ image/fichier : source « NCF Médias » (mêmes dossiers
249
+ // et recherche que l'onglet Assets). En tête = proposée en premier.
250
+ ...(config.tools.assets
251
+ ? {
252
+ image: {assetSources: (prev: AssetSource[]) => [ncfAssetSource, ...prev]},
253
+ file: {assetSources: (prev: AssetSource[]) => [ncfAssetSource, ...prev]},
254
+ }
255
+ : {}),
238
256
  },
239
257
  }
240
258
  })
@@ -329,6 +347,9 @@ export type {
329
347
  export {nameMap, groupMap, withCustomNames, groupComponents} from './lib/componentMeta'
330
348
  export type {ComponentGroup, ComponentEntry, ComponentGrouping} from './lib/componentMeta'
331
349
  export {useComponentNames} from './hooks/useComponentNames'
350
+ export {useAssetUpload} from './hooks/useAssetUpload'
351
+ export type {AssetUploadState} from './hooks/useAssetUpload'
352
+ export {AssetSourceBrowser} from './form/AssetSourceBrowser'
332
353
  export {
333
354
  buildPagesQuery,
334
355
  buildContentsQuery,
@@ -1,8 +1,9 @@
1
- import {useCallback, useMemo, useState} from 'react'
1
+ import {useCallback, useMemo, useRef, useState} from 'react'
2
2
  import {Box, Button, Card, Flex, Grid, Select, Spinner, Stack, Text} from '@sanity/ui'
3
3
  import {QueryError} from '../../ui/QueryError'
4
4
  import {useAssets} from '../../hooks/useAssets'
5
5
  import {useAssetMeta} from '../../hooks/useAssetMeta'
6
+ import {useAssetUpload} from '../../hooks/useAssetUpload'
6
7
  import {
7
8
  assignmentMap,
8
9
  assetsInFolder,
@@ -25,6 +26,9 @@ import {AssetDetail} from './AssetDetail'
25
26
  export function AssetsTool() {
26
27
  const {data, loading, error, refresh} = useAssets()
27
28
  const meta = useAssetMeta()
29
+ const {upload, uploading, error: uploadError} = useAssetUpload()
30
+ const fileInputRef = useRef<HTMLInputElement>(null)
31
+ const [dragging, setDragging] = useState(false)
28
32
  const assets = useMemo(() => data ?? [], [data])
29
33
 
30
34
  const [search, setSearch] = useState('')
@@ -80,6 +84,16 @@ export function AssetsTool() {
80
84
  [meta, selectedIds, clearSelection],
81
85
  )
82
86
 
87
+ // Import : téléverse, et range dans le dossier courant (si un vrai dossier est ouvert).
88
+ const handleFiles = useCallback(
89
+ (files: FileList | null) => {
90
+ if (!files || !files.length) return
91
+ const folder = typeof selection === 'string' && selection !== '' ? selection : null
92
+ void upload(files, folder ? (assetId) => meta.moveAsset(assetId, folder) : undefined).then(() => refresh())
93
+ },
94
+ [upload, selection, meta, refresh],
95
+ )
96
+
83
97
  if (loading && assets.length === 0) {
84
98
  return (
85
99
  <Flex align="center" justify="center" padding={6}>
@@ -90,7 +104,45 @@ export function AssetsTool() {
90
104
  if (error) return <QueryError error={error} onRetry={refresh} />
91
105
 
92
106
  return (
93
- <Flex gap={4} align="stretch" style={{minHeight: 420}}>
107
+ <Flex
108
+ gap={4}
109
+ align="stretch"
110
+ style={{minHeight: 420, position: 'relative'}}
111
+ onDragOver={(event) => {
112
+ event.preventDefault()
113
+ if (!dragging) setDragging(true)
114
+ }}
115
+ onDragLeave={(event) => {
116
+ if (event.currentTarget === event.target) setDragging(false)
117
+ }}
118
+ onDrop={(event) => {
119
+ event.preventDefault()
120
+ setDragging(false)
121
+ handleFiles(event.dataTransfer.files)
122
+ }}
123
+ >
124
+ <input
125
+ ref={fileInputRef}
126
+ type="file"
127
+ multiple
128
+ hidden
129
+ onChange={(event) => {
130
+ handleFiles(event.currentTarget.files)
131
+ event.currentTarget.value = ''
132
+ }}
133
+ />
134
+ {dragging ? (
135
+ <Flex
136
+ align="center"
137
+ justify="center"
138
+ style={{position: 'absolute', inset: 0, zIndex: 5, borderRadius: 6, border: '2px dashed var(--card-focus-ring-color, #2276fc)', background: 'var(--card-bg-color, rgba(255,255,255,0.85))', pointerEvents: 'none'}}
139
+ >
140
+ <Text size={2} weight="medium">
141
+ Déposer pour importer
142
+ </Text>
143
+ </Flex>
144
+ ) : null}
145
+
94
146
  <Box style={{width: 220, flex: 'none'}}>
95
147
  <FolderSidebar
96
148
  folders={meta.folders}
@@ -125,8 +177,16 @@ export function AssetsTool() {
125
177
  onView={setView}
126
178
  onRefresh={refresh}
127
179
  busy={loading}
180
+ onImport={() => fileInputRef.current?.click()}
181
+ uploading={uploading}
128
182
  />
129
183
 
184
+ {uploadError ? (
185
+ <Card tone="critical" border radius={2} padding={3}>
186
+ <Text size={1}>Import échoué : {uploadError.message}</Text>
187
+ </Card>
188
+ ) : null}
189
+
130
190
  {selectedIds.size > 0 ? (
131
191
  <Card tone="primary" border radius={2} padding={2}>
132
192
  <Flex align="center" gap={3} wrap="wrap">
@@ -3,6 +3,7 @@ import {SearchIcon} from '@sanity/icons/Search'
3
3
  import {SyncIcon} from '@sanity/icons/Sync'
4
4
  import {ThLargeIcon} from '@sanity/icons/ThLarge'
5
5
  import {ThListIcon} from '@sanity/icons/ThList'
6
+ import {UploadIcon} from '@sanity/icons/Upload'
6
7
  import type {AssetSortKey, AssetTypeFilter, AssetUsageFilter, SortDirection} from '../../lib/assets'
7
8
 
8
9
  export type AssetView = 'grid' | 'table'
@@ -21,11 +22,27 @@ export interface AssetsToolbarProps {
21
22
  onView: (view: AssetView) => void
22
23
  onRefresh: () => void
23
24
  busy: boolean
25
+ /** Ouvre le sélecteur de fichiers pour importer. */
26
+ onImport?: () => void
27
+ /** Nombre de fichiers en cours d'import. */
28
+ uploading?: number
24
29
  }
25
30
 
26
31
  export function AssetsToolbar(props: AssetsToolbarProps) {
27
32
  return (
28
33
  <Flex gap={2} align="center" wrap="wrap">
34
+ {props.onImport ? (
35
+ <Button
36
+ icon={UploadIcon}
37
+ text={props.uploading ? `Import… (${props.uploading})` : 'Importer'}
38
+ tone="primary"
39
+ fontSize={1}
40
+ padding={2}
41
+ disabled={Boolean(props.uploading)}
42
+ onClick={props.onImport}
43
+ style={{flex: 'none'}}
44
+ />
45
+ ) : null}
29
46
  <Box flex={1} style={{minWidth: 180}}>
30
47
  <TextInput
31
48
  value={props.search}
@@ -237,7 +237,12 @@ function ComponentsToolInner() {
237
237
  value={groupDialog.name}
238
238
  autoFocus
239
239
  placeholder="Nom du groupe"
240
- onChange={(event) => setGroupDialog((d) => (d ? {...d, name: event.currentTarget.value} : d))}
240
+ onChange={(event) => {
241
+ // `currentTarget` n'est lisible que pendant l'événement : on capture
242
+ // la valeur AVANT l'updater d'état (sinon il vaut null → crash).
243
+ const value = event.currentTarget.value
244
+ setGroupDialog((d) => (d ? {...d, name: value} : d))
245
+ }}
241
246
  onKeyDown={(event) => {
242
247
  if (event.key === 'Enter' && groupDialog.name.trim()) {
243
248
  if (groupDialog.mode === 'rename' && groupDialog.id) meta.renameGroup(groupDialog.id, groupDialog.name)
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
4
4
  * le vérifie.
5
5
  */
6
- export const KIT_VERSION = '2.51.0'
6
+ export const KIT_VERSION = '2.52.0'