@nocode-factory/sanity-kit 2.52.0 → 2.53.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.52.0",
3
+ "version": "2.53.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,60 @@
1
+ import {useCallback} from 'react'
2
+ import {useKitClient} from './useKitClient'
3
+ import {assetUnsetPaths} from '../lib/assetRefs'
4
+
5
+ export interface AssetUsage {
6
+ /** Id (sans le préfixe brouillon). */
7
+ id: string
8
+ type: string
9
+ title: string
10
+ }
11
+
12
+ export interface AssetDeleteState {
13
+ /** Documents qui utilisent l'asset (dédoublonnés brouillon/publié). */
14
+ usage: (assetId: string) => Promise<AssetUsage[]>
15
+ /** Retire l'asset de tous les documents (champs vidés) puis le supprime. */
16
+ remove: (assetId: string) => Promise<void>
17
+ }
18
+
19
+ const baseId = (id: string): string => id.replace(/^drafts\./, '')
20
+
21
+ /**
22
+ * Suppression d'un asset depuis l'outil Assets. Sanity refuse de supprimer un
23
+ * asset référencé : on retire d'abord l'asset de chaque document (le champ
24
+ * devient vide), puis on supprime, dans une seule transaction.
25
+ */
26
+ export function useAssetDelete(): AssetDeleteState {
27
+ const client = useKitClient()
28
+
29
+ const usage = useCallback(
30
+ async (assetId: string): Promise<AssetUsage[]> => {
31
+ const docs = await client.fetch<{_id: string; _type: string; title?: string}[]>(
32
+ `*[references($id)]{_id, _type, "title": coalesce(title, name, originalFilename, slug.current, _id)}`,
33
+ {id: assetId},
34
+ )
35
+ const seen = new Map<string, AssetUsage>()
36
+ for (const doc of docs ?? []) {
37
+ const id = baseId(doc._id)
38
+ if (!seen.has(id)) seen.set(id, {id, type: doc._type, title: doc.title ?? id})
39
+ }
40
+ return [...seen.values()]
41
+ },
42
+ [client],
43
+ )
44
+
45
+ const remove = useCallback(
46
+ async (assetId: string): Promise<void> => {
47
+ const docs = await client.fetch<Record<string, unknown>[]>(`*[references($id)]`, {id: assetId})
48
+ const transaction = client.transaction()
49
+ for (const doc of docs ?? []) {
50
+ const paths = assetUnsetPaths(doc, assetId)
51
+ if (paths.length) transaction.patch(doc._id as string, {unset: paths})
52
+ }
53
+ transaction.delete(assetId)
54
+ await transaction.commit({visibility: 'async'})
55
+ },
56
+ [client],
57
+ )
58
+
59
+ return {usage, remove}
60
+ }
@@ -53,6 +53,9 @@ export interface BoardLayoutState {
53
53
  /** Notes et formes posées sur les canvas. */
54
54
  annotations: Annotation[]
55
55
  saveAnnotations: (next: readonly Annotation[]) => void
56
+ /** Ordre manuel des pages (liste d'ids), partagé Presentation / onglet Pages. */
57
+ pageOrder: string[]
58
+ savePageOrder: (ids: readonly string[]) => void
56
59
  /** Accès direct par identifiant de page, pour le rendu des nœuds. */
57
60
  byId: Map<string, NodeLayout>
58
61
  loading: boolean
@@ -117,6 +120,7 @@ export function useBoardLayoutState(): BoardLayoutState {
117
120
  const [columns, setColumns] = useState<NcfInternalField[]>([])
118
121
  const [columnsSet, setColumnsSet] = useState(false)
119
122
  const [annotations, setAnnotations] = useState<Annotation[]>([])
123
+ const [pageOrder, setPageOrder] = useState<string[]>([])
120
124
  const [loading, setLoading] = useState(true)
121
125
  const [saveError, setSaveError] = useState<Error | null>(null)
122
126
 
@@ -129,7 +133,8 @@ export function useBoardLayoutState(): BoardLayoutState {
129
133
  columns?: StoredColumn[]
130
134
  columnsSet?: boolean
131
135
  annotations?: StoredAnnotation[]
132
- } | null>(`*[_id == $id][0]{nodes, sections, columns, columnsSet, annotations}`, {
136
+ pageOrder?: string[]
137
+ } | null>(`*[_id == $id][0]{nodes, sections, columns, columnsSet, annotations, pageOrder}`, {
133
138
  id: BOARD_LAYOUT_ID,
134
139
  })
135
140
  .then((doc) => {
@@ -146,6 +151,7 @@ export function useBoardLayoutState(): BoardLayoutState {
146
151
  )
147
152
  setColumnsSet(Boolean(doc?.columnsSet))
148
153
  setAnnotations((doc?.annotations ?? []).map(({_key, ...rest}) => ({...rest})))
154
+ setPageOrder(Array.isArray(doc?.pageOrder) ? doc!.pageOrder.filter((id): id is string => typeof id === 'string') : [])
149
155
  })
150
156
  .catch(() => {
151
157
  // Pas de disposition lisible : on part du placement automatique
@@ -156,6 +162,7 @@ export function useBoardLayoutState(): BoardLayoutState {
156
162
  setColumns([])
157
163
  setColumnsSet(false)
158
164
  setAnnotations([])
165
+ setPageOrder([])
159
166
  }
160
167
  })
161
168
  .finally(() => {
@@ -181,11 +188,13 @@ export function useBoardLayoutState(): BoardLayoutState {
181
188
  const columnsRef = useRef<NcfInternalField[]>([])
182
189
  const columnsSetRef = useRef(false)
183
190
  const annotationsRef = useRef<Annotation[]>([])
191
+ const pageOrderRef = useRef<string[]>([])
184
192
  layoutRef.current = layout
185
193
  sectionsRef.current = sections
186
194
  columnsRef.current = columns
187
195
  columnsSetRef.current = columnsSet
188
196
  annotationsRef.current = annotations
197
+ pageOrderRef.current = pageOrder
189
198
 
190
199
  const write = useCallback(
191
200
  (next?: {
@@ -194,12 +203,14 @@ export function useBoardLayoutState(): BoardLayoutState {
194
203
  columns?: NcfInternalField[]
195
204
  columnsSet?: boolean
196
205
  annotations?: Annotation[]
206
+ pageOrder?: string[]
197
207
  }) => {
198
208
  const nodes = next?.nodes ?? layoutRef.current
199
209
  const nextSections = next?.sections ?? sectionsRef.current
200
210
  const nextColumns = next?.columns ?? columnsRef.current
201
211
  const nextColumnsSet = next?.columnsSet ?? columnsSetRef.current
202
212
  const nextAnnotations = next?.annotations ?? annotationsRef.current
213
+ const nextPageOrder = next?.pageOrder ?? pageOrderRef.current
203
214
  client
204
215
  .createOrReplace({
205
216
  _id: BOARD_LAYOUT_ID,
@@ -235,6 +246,7 @@ export function useBoardLayoutState(): BoardLayoutState {
235
246
  })),
236
247
  })),
237
248
  columnsSet: nextColumnsSet,
249
+ pageOrder: nextPageOrder,
238
250
  annotations: nextAnnotations.map((annotation) => ({
239
251
  _key: annotation.id,
240
252
  _type: 'ncfAnnotation',
@@ -364,6 +376,16 @@ export function useBoardLayoutState(): BoardLayoutState {
364
376
  write({sections: []})
365
377
  }, [write])
366
378
 
379
+ const savePageOrder = useCallback(
380
+ (ids: readonly string[]) => {
381
+ const value = [...ids]
382
+ setPageOrder(value)
383
+ if (timer.current) clearTimeout(timer.current)
384
+ timer.current = setTimeout(() => write({pageOrder: value}), 800)
385
+ },
386
+ [write],
387
+ )
388
+
367
389
  const sectionsByName = useMemo(
368
390
  () => new Map(sections.map((entry) => [entry.blockName, entry])),
369
391
  [sections],
@@ -390,6 +412,8 @@ export function useBoardLayoutState(): BoardLayoutState {
390
412
  saveColumns,
391
413
  annotations,
392
414
  saveAnnotations,
415
+ pageOrder,
416
+ savePageOrder,
393
417
  reset,
394
418
  resetSections,
395
419
  }
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@ import {HistoryTool} from './tools/history/HistoryTool'
18
18
  import {DesignSystemTool} from './tools/designSystem/DesignSystemTool'
19
19
  import {AssetsTool} from './tools/assets/AssetsTool'
20
20
  import {BOARD_LAYOUT_TYPE, isKitType, kitSchemaTypes} from './schema/boardLayout'
21
+ import {dropRedundantLanguageTemplates} from './lib/i18nTemplates'
21
22
  import type {NcfKitConfig, NcfToolName} from './config/types'
22
23
 
23
24
  /** Noms des outils dans la barre du Studio. Exportés pour filtrer `tools`. */
@@ -194,8 +195,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
194
195
  },
195
196
 
196
197
  document: {
198
+ // On masque le singleton de board, puis — en monolingue — le doublon
199
+ // « + Français Article » que document-internationalization ajoute à côté
200
+ // du « + Article » de base (voir dropRedundantLanguageTemplates).
197
201
  newDocumentOptions: (prev) =>
198
- prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
202
+ dropRedundantLanguageTemplates(prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE)),
199
203
  // Pages : « Retirer du site » (dépublication expliquée, liens listés) à la place
200
204
  // du « Unpublish » natif, caché et bloqué sans explication par les références.
201
205
  // Supprimer la version principale d'un document traduit : suppression de ses
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Trouve, dans un document, les endroits qui référencent un asset — pour les
3
+ * vider avant de supprimer l'asset (Sanity refuse de supprimer un asset encore
4
+ * référencé). Pur : testable sans Sanity.
5
+ */
6
+
7
+ type Rec = Record<string, unknown>
8
+ const isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
9
+
10
+ type PathSegment = string | number | {_key: string}
11
+
12
+ /** Chemins (segments) des objets du document qui pointent vers `assetId`. */
13
+ export function findAssetRefPaths(value: unknown, assetId: string, path: PathSegment[] = []): PathSegment[][] {
14
+ const out: PathSegment[][] = []
15
+ const walk = (node: unknown, current: PathSegment[]) => {
16
+ if (Array.isArray(node)) {
17
+ node.forEach((item, index) => {
18
+ const segment: PathSegment = isObj(item) && typeof item._key === 'string' ? {_key: item._key} : index
19
+ walk(item, [...current, segment])
20
+ })
21
+ return
22
+ }
23
+ if (!isObj(node)) return
24
+ // Objet image/fichier (`{asset: {_ref}}`) ou référence directe vers l'asset.
25
+ const assetRef = isObj(node.asset) ? node.asset._ref : undefined
26
+ if (assetRef === assetId || (node._type === 'reference' && node._ref === assetId)) {
27
+ out.push(current)
28
+ return
29
+ }
30
+ for (const [key, child] of Object.entries(node)) {
31
+ if (key.startsWith('_')) continue
32
+ walk(child, [...current, key])
33
+ }
34
+ }
35
+ walk(value, path)
36
+ return out
37
+ }
38
+
39
+ /** Chemin Sanity (`gallery[_key=="ab"].asset`) depuis des segments. */
40
+ export function toPatchPath(segments: readonly PathSegment[]): string {
41
+ let out = ''
42
+ for (const segment of segments) {
43
+ if (typeof segment === 'string') out += out ? `.${segment}` : segment
44
+ else if (typeof segment === 'number') out += `[${segment}]`
45
+ else out += `[_key=="${segment._key}"]`
46
+ }
47
+ return out
48
+ }
49
+
50
+ /** Chemins Sanity (chaînes) à retirer d'un document pour en ôter l'asset. */
51
+ export function assetUnsetPaths(doc: unknown, assetId: string): string[] {
52
+ return findAssetRefPaths(doc, assetId).map(toPatchPath).filter(Boolean)
53
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Menu « + » du Studio en situation monolingue. Pur.
3
+ *
4
+ * `@sanity/document-internationalization` ajoute, pour chaque type traduit, un
5
+ * template « paramétré » (`${type}-parameterized`) et un template statique par
6
+ * langue (`${type}-${langue}`, p. ex. `article-fr`, titré « Français Article »).
7
+ * Avec une seule langue branchée, ces deux-là font doublon avec le « + Article »
8
+ * de base : le menu de création montre « + Article » ET « + Français Article ».
9
+ *
10
+ * On ne garde alors que la base. Avec plusieurs langues on ne touche à rien
11
+ * (« + master » et « + langues » sont voulus).
12
+ *
13
+ * Détection sans connaître la liste des langues : le template `-parameterized`
14
+ * est la signature du plugin ; s'il n'existe qu'UN statique pour ce type (et que
15
+ * la base du type est bien présente), on est en monolingue pour ce type. Zéro ou
16
+ * plusieurs statiques : on laisse tout, par prudence — jamais retirer la seule
17
+ * façon de créer un document.
18
+ */
19
+ export function dropRedundantLanguageTemplates<T extends {templateId: string}>(options: readonly T[]): T[] {
20
+ const ids = new Set(options.map((option) => option.templateId))
21
+ const remove = new Set<string>()
22
+ const suffix = '-parameterized'
23
+
24
+ for (const {templateId} of options) {
25
+ if (!templateId.endsWith(suffix)) continue
26
+ const base = templateId.slice(0, -suffix.length)
27
+ // Pas de type de base dans le menu : on ne retire rien.
28
+ if (!ids.has(base)) continue
29
+ const statics = options.filter(
30
+ (option) => option.templateId !== templateId && option.templateId.startsWith(`${base}-`),
31
+ )
32
+ // Exactement une langue : monolingue → la base suffit.
33
+ const only = statics.length === 1 ? statics[0] : undefined
34
+ if (!only) continue
35
+ remove.add(templateId)
36
+ remove.add(only.templateId)
37
+ }
38
+
39
+ return options.filter((option) => !remove.has(option.templateId))
40
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Ordre manuel des pages, partagé par le navigateur de Presentation et l'onglet
3
+ * Pages. Stocké comme une liste d'ids (board singleton `pageOrder`). Pur.
4
+ */
5
+
6
+ /**
7
+ * Ordonne des éléments par la liste d'ids `order` : ceux présents d'abord (dans
8
+ * l'ordre de `order`), les autres ensuite dans leur ordre d'entrée (donc une
9
+ * page nouvelle, absente de l'ordre manuel, apparaît à la fin).
10
+ */
11
+ export function orderByIds<T extends {id: string}>(items: readonly T[], order: readonly string[]): T[] {
12
+ if (order.length === 0) return [...items]
13
+ const rank = new Map(order.map((id, index) => [id, index]))
14
+ return [...items].sort((a, b) => {
15
+ const ra = rank.get(a.id)
16
+ const rb = rank.get(b.id)
17
+ if (ra === undefined && rb === undefined) return 0
18
+ if (ra === undefined) return 1
19
+ if (rb === undefined) return -1
20
+ return ra - rb
21
+ })
22
+ }
23
+
24
+ /**
25
+ * Déplace `dragged` juste avant `target` dans la séquence d'ids `ordered`
26
+ * (l'ordre courant complet). `target` null = place en fin. Filtre-sûr : on
27
+ * travaille sur les ids, pas sur une vue filtrée.
28
+ */
29
+ export function reorderBefore(ordered: readonly string[], dragged: string, target: string | null): string[] {
30
+ if (dragged === target) return [...ordered]
31
+ const without = ordered.filter((id) => id !== dragged)
32
+ if (target === null) return [...without, dragged]
33
+ const index = without.indexOf(target)
34
+ if (index < 0) return [...without, dragged]
35
+ return [...without.slice(0, index), dragged, ...without.slice(index)]
36
+ }
package/src/lib/pages.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import {finalPath, type RedirectMap} from './finalUrl'
2
+ import {orderByIds} from './pageOrder'
2
3
  import type {ResolvedDocumentColumn, ResolvedKitConfig} from '../config/types'
3
4
  import {pageTypeFor, toPath, toUrl} from './paths'
4
5
  import {DATA_PREFIX} from './query'
@@ -99,6 +100,7 @@ export function buildPageRows(
99
100
  */
100
101
  export type SortKey =
101
102
  | 'structure'
103
+ | 'manual'
102
104
  | 'title'
103
105
  | 'type'
104
106
  | 'path'
@@ -113,9 +115,11 @@ const STATUS_ORDER: Record<PageStatus, number> = {modified: 0, draft: 1, publish
113
115
  export interface SortOptions {
114
116
  /** Ordre de déclaration des types, pour le tri « structure ». */
115
117
  typeOrder?: readonly string[]
118
+ /** Ordre manuel (liste d'ids), pour le tri « manual ». */
119
+ pageOrder?: readonly string[]
116
120
  }
117
121
 
118
- const compare = (a: PageRow, b: PageRow, key: SortKey, options: SortOptions): number => {
122
+ const compare = (a: PageRow, b: PageRow, key: Exclude<SortKey, 'manual'>, options: SortOptions): number => {
119
123
  switch (key) {
120
124
  case 'structure': {
121
125
  const order = options.typeOrder ?? []
@@ -153,6 +157,12 @@ export function sortRows(
153
157
  direction: SortDirection,
154
158
  options: SortOptions = {},
155
159
  ): PageRow[] {
160
+ // Ordre manuel : séquence d'ids stockée ; les pages hors liste après, par titre.
161
+ if (key === 'manual') {
162
+ const byTitle = [...rows].sort((a, b) => a.title.localeCompare(b.title, undefined, {sensitivity: 'base'}))
163
+ const sorted = orderByIds(byTitle, options.pageOrder ?? [])
164
+ return direction === 'asc' ? sorted : sorted.reverse()
165
+ }
156
166
  const sorted = [...rows].sort((a, b) => compare(a, b, key, options))
157
167
  return direction === 'asc' ? sorted : sorted.reverse()
158
168
  }
@@ -168,6 +168,13 @@ const boardLayoutType = defineType({
168
168
  type: 'array',
169
169
  of: [{type: SECTION_NODE_TYPE}],
170
170
  }),
171
+ // Ordre manuel des pages (liste d'ids), partagé Presentation / onglet Pages.
172
+ defineField({
173
+ name: 'pageOrder',
174
+ title: 'Manual page order',
175
+ type: 'array',
176
+ of: [{type: 'string'}],
177
+ }),
171
178
  defineField({
172
179
  name: 'updatedBy',
173
180
  title: 'Modified by',
@@ -15,20 +15,18 @@ export interface AssetCardProps {
15
15
  export function AssetCard(props: AssetCardProps) {
16
16
  const {asset, selected, onToggleSelect, onOpen} = props
17
17
  const [failed, setFailed] = useState(false)
18
- const thumb = thumbnailUrl(asset, {w: 320, h: 220})
18
+ const thumb = thumbnailUrl(asset, {w: 500})
19
19
  const unused = asset.uses === 0
20
+ // Vrai ratio de l'image (portrait / paysage visible sans cliquer). Borné pour
21
+ // éviter des tuiles absurdes ; un fichier sans image garde un ratio neutre.
22
+ const natural = asset.dimensions?.width && asset.dimensions?.height ? asset.dimensions.width / asset.dimensions.height : 4 / 3
23
+ const ratio = thumb ? Math.min(2, Math.max(0.56, natural)) : 4 / 3
20
24
  const meta = [formatBytes(asset.size), asset.dimensions?.width ? `${asset.dimensions.width}×${asset.dimensions.height}` : null, asset.extension?.toUpperCase()]
21
25
  .filter(Boolean)
22
26
  .join(' · ')
23
27
 
24
28
  return (
25
- <Card
26
- radius={3}
27
- shadow={1}
28
- padding={0}
29
- tone={selected ? 'primary' : 'default'}
30
- style={{height: '100%', overflow: 'hidden', position: 'relative'}}
31
- >
29
+ <Card radius={3} shadow={1} padding={0} tone={selected ? 'primary' : 'default'} style={{overflow: 'hidden', position: 'relative', width: '100%'}}>
32
30
  {/* Sélection : coin haut-gauche, n'ouvre pas le détail. */}
33
31
  <Box style={{position: 'absolute', top: 8, left: 8, zIndex: 1}} onClick={(e) => e.stopPropagation()}>
34
32
  <Card radius={2} padding={1} tone="default" style={{opacity: selected ? 1 : 0.85}}>
@@ -40,9 +38,9 @@ export function AssetCard(props: AssetCardProps) {
40
38
  gap={0}
41
39
  as="button"
42
40
  onClick={onOpen}
43
- style={{height: '100%', width: '100%', textAlign: 'left', cursor: 'pointer', background: 'transparent', border: 0, padding: 0}}
41
+ style={{width: '100%', textAlign: 'left', cursor: 'pointer', background: 'transparent', border: 0, padding: 0}}
44
42
  >
45
- <Box style={{aspectRatio: '16 / 11', overflow: 'hidden', background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))'}}>
43
+ <Box style={{aspectRatio: ratio, overflow: 'hidden', background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))'}}>
46
44
  {thumb && !failed ? (
47
45
  <img
48
46
  src={thumb}
@@ -1,9 +1,11 @@
1
1
  import {useEffect, useState} from 'react'
2
- import {Box, Button, Card, Flex, Grid, Label, Select, Stack, Text, TextArea, TextInput} from '@sanity/ui'
2
+ import {Box, Button, Card, Dialog, Flex, Grid, Label, Select, Spinner, Stack, Text, TextArea, TextInput} from '@sanity/ui'
3
3
  import {CloseIcon} from '@sanity/icons/Close'
4
4
  import {CopyIcon} from '@sanity/icons/Copy'
5
5
  import {LaunchIcon} from '@sanity/icons/Launch'
6
+ import {TrashIcon} from '@sanity/icons/Trash'
6
7
  import {useKitClient} from '../../hooks/useKitClient'
8
+ import {useAssetDelete, type AssetUsage} from '../../hooks/useAssetDelete'
7
9
  import {assetName, formatBytes, isImageAsset, thumbnailUrl, type AssetDoc, type AssetFolder} from '../../lib/assets'
8
10
  import {MONO} from '../../ui/tokens'
9
11
  import {formatDate} from '../../ui/formatDate'
@@ -14,6 +16,8 @@ export interface AssetDetailProps {
14
16
  folder: string | null
15
17
  onMove: (folder: string | null) => void
16
18
  onClose: () => void
19
+ /** Appelé après suppression (pour fermer le détail et rafraîchir). */
20
+ onDeleted?: () => void
17
21
  }
18
22
 
19
23
  function Metric(props: {label: string; value: string}) {
@@ -30,12 +34,39 @@ function Metric(props: {label: string; value: string}) {
30
34
  }
31
35
 
32
36
  export function AssetDetail(props: AssetDetailProps) {
33
- const {asset, folders, folder, onMove, onClose} = props
37
+ const {asset, folders, folder, onMove, onClose, onDeleted} = props
34
38
  const client = useKitClient()
39
+ const {usage, remove} = useAssetDelete()
35
40
  const [title, setTitle] = useState(asset.title ?? '')
36
41
  const [alt, setAlt] = useState(asset.altText ?? '')
37
42
  const [description, setDescription] = useState(asset.description ?? '')
38
43
  const [copied, setCopied] = useState(false)
44
+ // Suppression : null = fermé ; sinon on charge d'abord les usages, puis on confirme.
45
+ const [confirming, setConfirming] = useState(false)
46
+ const [uses, setUses] = useState<AssetUsage[] | null>(null)
47
+ const [busy, setBusy] = useState(false)
48
+ const [deleteError, setDeleteError] = useState<string | null>(null)
49
+
50
+ const openDelete = () => {
51
+ setConfirming(true)
52
+ setUses(null)
53
+ setDeleteError(null)
54
+ void usage(asset._id)
55
+ .then((list) => setUses(list))
56
+ .catch(() => setUses([]))
57
+ }
58
+ const doDelete = () => {
59
+ setBusy(true)
60
+ setDeleteError(null)
61
+ void remove(asset._id)
62
+ .then(() => {
63
+ setConfirming(false)
64
+ onDeleted?.()
65
+ onClose()
66
+ })
67
+ .catch((cause: unknown) => setDeleteError(cause instanceof Error ? cause.message : String(cause)))
68
+ .finally(() => setBusy(false))
69
+ }
39
70
 
40
71
  // Repart des valeurs de l'asset sélectionné quand il change.
41
72
  useEffect(() => {
@@ -144,7 +175,71 @@ export function AssetDetail(props: AssetDetailProps) {
144
175
  <Metric label="Usage" value={asset.uses === undefined ? '—' : `${asset.uses}`} />
145
176
  <Metric label="Ajouté" value={formatDate(asset._createdAt)} />
146
177
  </Grid>
178
+
179
+ <Box style={{borderTop: '1px solid var(--card-border-color)'}} paddingTop={3}>
180
+ <Button icon={TrashIcon} text="Supprimer le média" tone="critical" mode="ghost" fontSize={1} onClick={openDelete} style={{width: '100%'}} />
181
+ </Box>
147
182
  </Stack>
183
+
184
+ {confirming ? (
185
+ <Dialog
186
+ id="asset-delete"
187
+ header="Supprimer le média"
188
+ width={1}
189
+ onClose={() => (busy ? undefined : setConfirming(false))}
190
+ footer={
191
+ <Flex justify="flex-end" gap={2} padding={2}>
192
+ <Button text="Annuler" mode="bleed" disabled={busy} onClick={() => setConfirming(false)} />
193
+ <Button text={busy ? 'Suppression…' : 'Supprimer'} tone="critical" disabled={busy || uses === null} onClick={doDelete} />
194
+ </Flex>
195
+ }
196
+ >
197
+ <Box padding={4}>
198
+ <Stack gap={3}>
199
+ <Text size={1}>
200
+ Supprimer « {assetName(asset)} » définitivement ?
201
+ </Text>
202
+ {uses === null ? (
203
+ <Flex align="center" gap={2}>
204
+ <Spinner muted size={1} />
205
+ <Text size={1} muted>
206
+ Recherche des endroits où il est utilisé…
207
+ </Text>
208
+ </Flex>
209
+ ) : uses.length === 0 ? (
210
+ <Text size={1} muted>
211
+ Il n'est utilisé nulle part : aucune page ne sera affectée.
212
+ </Text>
213
+ ) : (
214
+ <Stack gap={2}>
215
+ <Text size={1} weight="medium">
216
+ L'image deviendra vide à {uses.length} endroit{uses.length > 1 ? 's' : ''} :
217
+ </Text>
218
+ <Card tone="caution" border radius={2} padding={3}>
219
+ <Stack gap={2} as="ul" style={{margin: 0, paddingLeft: 16}}>
220
+ {uses.slice(0, 20).map((use) => (
221
+ <Text key={use.id} size={1} as="li">
222
+ {use.title} <span style={{opacity: 0.6}}>({use.type})</span>
223
+ </Text>
224
+ ))}
225
+ {uses.length > 20 ? (
226
+ <Text size={1} muted as="li">
227
+ … et {uses.length - 20} autre{uses.length - 20 > 1 ? 's' : ''}.
228
+ </Text>
229
+ ) : null}
230
+ </Stack>
231
+ </Card>
232
+ </Stack>
233
+ )}
234
+ {deleteError ? (
235
+ <Card tone="critical" border radius={2} padding={3}>
236
+ <Text size={1}>Suppression échouée : {deleteError}</Text>
237
+ </Card>
238
+ ) : null}
239
+ </Stack>
240
+ </Box>
241
+ </Dialog>
242
+ ) : null}
148
243
  </Card>
149
244
  )
150
245
  }
@@ -1,5 +1,5 @@
1
1
  import {useCallback, useMemo, useRef, useState} from 'react'
2
- import {Box, Button, Card, Flex, Grid, Select, Spinner, Stack, Text} from '@sanity/ui'
2
+ import {Box, Button, Card, Flex, 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'
@@ -234,17 +234,19 @@ export function AssetsTool() {
234
234
  </Text>
235
235
  </Card>
236
236
  ) : view === 'grid' ? (
237
- <Grid gridTemplateColumns={[2, 3, 4, 5]} gap={3}>
237
+ // Masonry (colonnes CSS) : chaque vignette garde son vrai ratio.
238
+ <Box style={{columnWidth: 200, columnGap: 12}}>
238
239
  {visible.map((asset) => (
239
- <AssetCard
240
- key={asset._id}
241
- asset={asset}
242
- selected={selectedIds.has(asset._id)}
243
- onToggleSelect={() => toggleSelect(asset._id)}
244
- onOpen={() => setOpenedId(asset._id)}
245
- />
240
+ <Box key={asset._id} style={{breakInside: 'avoid', marginBottom: 12}}>
241
+ <AssetCard
242
+ asset={asset}
243
+ selected={selectedIds.has(asset._id)}
244
+ onToggleSelect={() => toggleSelect(asset._id)}
245
+ onOpen={() => setOpenedId(asset._id)}
246
+ />
247
+ </Box>
246
248
  ))}
247
- </Grid>
249
+ </Box>
248
250
  ) : (
249
251
  <AssetTable
250
252
  assets={visible}
@@ -265,7 +267,22 @@ export function AssetsTool() {
265
267
  </Stack>
266
268
 
267
269
  {opened ? (
268
- <AssetDetail asset={opened} folders={meta.folders} folder={folderOf(opened._id)} onMove={(folder) => meta.moveAsset(opened._id, folder)} onClose={() => setOpenedId(null)} />
270
+ <AssetDetail
271
+ asset={opened}
272
+ folders={meta.folders}
273
+ folder={folderOf(opened._id)}
274
+ onMove={(folder) => meta.moveAsset(opened._id, folder)}
275
+ onClose={() => setOpenedId(null)}
276
+ onDeleted={() => {
277
+ setSelectedIds((prev) => {
278
+ const next = new Set(prev)
279
+ next.delete(opened._id)
280
+ return next
281
+ })
282
+ setOpenedId(null)
283
+ refresh()
284
+ }}
285
+ />
269
286
  ) : null}
270
287
  </Flex>
271
288
  )