@asteby/metacore-runtime-react 53.10.2 → 53.12.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/CHANGELOG.md +42 -0
- package/dist/bulk-image-dialog.d.ts +31 -0
- package/dist/bulk-image-dialog.d.ts.map +1 -0
- package/dist/bulk-image-dialog.js +339 -0
- package/dist/bulk-image-import.d.ts +158 -0
- package/dist/bulk-image-import.d.ts.map +1 -0
- package/dist/bulk-image-import.js +310 -0
- package/dist/dynamic-crud-page.d.ts.map +1 -1
- package/dist/dynamic-crud-page.js +2 -1
- package/dist/dynamic-form.d.ts +10 -1
- package/dist/dynamic-form.d.ts.map +1 -1
- package/dist/dynamic-form.js +6 -6
- package/dist/dynamic-relation-helpers.d.ts +65 -0
- package/dist/dynamic-relation-helpers.d.ts.map +1 -1
- package/dist/dynamic-relation-helpers.js +178 -2
- package/dist/dynamic-relation.d.ts +16 -0
- package/dist/dynamic-relation.d.ts.map +1 -1
- package/dist/dynamic-relation.js +277 -13
- package/dist/dynamic-relations.d.ts.map +1 -1
- package/dist/dynamic-relations.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/relation-gallery.d.ts +31 -0
- package/dist/relation-gallery.d.ts.map +1 -0
- package/dist/relation-gallery.js +154 -0
- package/dist/upload-field.d.ts +19 -1
- package/dist/upload-field.d.ts.map +1 -1
- package/dist/upload-field.js +50 -3
- package/package.json +2 -1
- package/src/__tests__/bulk-image-dialog.test.tsx +127 -0
- package/src/__tests__/bulk-image-import.test.ts +129 -0
- package/src/__tests__/relation-gallery-helpers.test.ts +154 -0
- package/src/__tests__/relation-gallery.test.tsx +229 -0
- package/src/bulk-image-dialog.tsx +594 -0
- package/src/bulk-image-import.ts +456 -0
- package/src/dynamic-crud-page.tsx +2 -0
- package/src/dynamic-form.tsx +20 -2
- package/src/dynamic-relation-helpers.ts +210 -2
- package/src/dynamic-relation.tsx +329 -15
- package/src/dynamic-relations.tsx +1 -0
- package/src/index.ts +12 -0
- package/src/relation-gallery.tsx +489 -0
- package/src/upload-field.tsx +60 -2
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
// RelationGallery — the thumbnail-grid view of a one_to_many relation whose
|
|
2
|
+
// image column declares `display_config.gallery: true` (e.g. a product's
|
|
3
|
+
// ProductImage rows). Opt-in: DynamicRelation keeps its table for every other
|
|
4
|
+
// relation. Pure UI over callbacks — DynamicRelation owns the API calls, so the
|
|
5
|
+
// `/upload` and `/data` contracts are the ones the table already uses.
|
|
6
|
+
//
|
|
7
|
+
// - Add several photos at once (picker or drag & drop), one progress bar,
|
|
8
|
+
// preview, error and retry per file; type/size limits with clear messages.
|
|
9
|
+
// - Reorder by dragging (pointer or keyboard: Space to lift, arrows to move)
|
|
10
|
+
// or with the explicit move buttons; the first image is the main one.
|
|
11
|
+
// - Delete asks for confirmation, then offers «Deshacer» for a few seconds.
|
|
12
|
+
// - Theme tokens only (bg-card, border, muted…) so it follows dark mode.
|
|
13
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
14
|
+
import { useTranslation } from 'react-i18next'
|
|
15
|
+
import {
|
|
16
|
+
DndContext,
|
|
17
|
+
KeyboardSensor,
|
|
18
|
+
PointerSensor,
|
|
19
|
+
closestCenter,
|
|
20
|
+
useSensor,
|
|
21
|
+
useSensors,
|
|
22
|
+
type DragEndEvent,
|
|
23
|
+
} from '@dnd-kit/core'
|
|
24
|
+
import {
|
|
25
|
+
SortableContext,
|
|
26
|
+
arrayMove,
|
|
27
|
+
rectSortingStrategy,
|
|
28
|
+
sortableKeyboardCoordinates,
|
|
29
|
+
useSortable,
|
|
30
|
+
} from '@dnd-kit/sortable'
|
|
31
|
+
import { CSS } from '@dnd-kit/utilities'
|
|
32
|
+
import { cn } from '@asteby/metacore-ui/lib'
|
|
33
|
+
import { Button } from '@asteby/metacore-ui/primitives'
|
|
34
|
+
import { ArrowLeft, ArrowRight, ImagePlus, Loader2, Pencil, RotateCcw, Star, Trash2, X } from 'lucide-react'
|
|
35
|
+
import { validateUploadFile } from './upload-field'
|
|
36
|
+
|
|
37
|
+
export interface GalleryUploadProgress {
|
|
38
|
+
(fraction: number): void
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface RelationGalleryProps {
|
|
42
|
+
rows: Record<string, any>[]
|
|
43
|
+
rowKey: (row: Record<string, any>, index: number) => string
|
|
44
|
+
imageKey: string
|
|
45
|
+
/** Optional caption column (alt text). */
|
|
46
|
+
captionKey?: string
|
|
47
|
+
getImageUrl: (path: string) => string
|
|
48
|
+
accept?: string
|
|
49
|
+
maxSize?: number
|
|
50
|
+
canCreate?: boolean
|
|
51
|
+
canEdit?: boolean
|
|
52
|
+
/** Reorder / «Hacer principal» (needs a position column). Default = canEdit. */
|
|
53
|
+
canReorder?: boolean
|
|
54
|
+
canDelete?: boolean
|
|
55
|
+
/** Uploads one file and creates its row at gallery index `offset` past the end. */
|
|
56
|
+
onUpload: (file: File, offset: number, onProgress: GalleryUploadProgress, reuseUrl?: string) => Promise<void>
|
|
57
|
+
/** All uploads of one batch finished (refresh the list). */
|
|
58
|
+
onUploadsSettled?: () => void
|
|
59
|
+
/** New order of the rows (persist positions). */
|
|
60
|
+
onReorder: (ordered: Record<string, any>[]) => Promise<void> | void
|
|
61
|
+
onEdit?: (row: Record<string, any>) => void
|
|
62
|
+
/** Asks for confirmation and deletes (with undo) — owned by the host. */
|
|
63
|
+
onDelete?: (row: Record<string, any>) => void
|
|
64
|
+
/** Keys of rows pending deletion (hidden while «Deshacer» is offered). */
|
|
65
|
+
hiddenKeys?: Set<string>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface UploadItem {
|
|
69
|
+
id: string
|
|
70
|
+
file: File
|
|
71
|
+
preview: string
|
|
72
|
+
progress: number
|
|
73
|
+
status: 'uploading' | 'error' | 'done'
|
|
74
|
+
error?: string
|
|
75
|
+
offset: number
|
|
76
|
+
/** Stored file of a failed row create — a retry reuses it. */
|
|
77
|
+
uploadedUrl?: string
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let uploadSeq = 0
|
|
81
|
+
|
|
82
|
+
export function RelationGallery({
|
|
83
|
+
rows,
|
|
84
|
+
rowKey,
|
|
85
|
+
imageKey,
|
|
86
|
+
captionKey,
|
|
87
|
+
getImageUrl,
|
|
88
|
+
accept = 'image/*',
|
|
89
|
+
maxSize,
|
|
90
|
+
canCreate = true,
|
|
91
|
+
canEdit = true,
|
|
92
|
+
canReorder,
|
|
93
|
+
canDelete = true,
|
|
94
|
+
onUpload,
|
|
95
|
+
onUploadsSettled,
|
|
96
|
+
onReorder,
|
|
97
|
+
onEdit,
|
|
98
|
+
onDelete,
|
|
99
|
+
hiddenKeys,
|
|
100
|
+
}: RelationGalleryProps) {
|
|
101
|
+
const { t } = useTranslation()
|
|
102
|
+
const inputRef = useRef<HTMLInputElement>(null)
|
|
103
|
+
const [dragOver, setDragOver] = useState(false)
|
|
104
|
+
const [uploads, setUploads] = useState<UploadItem[]>([])
|
|
105
|
+
const reorderable = canReorder ?? canEdit
|
|
106
|
+
// Every local preview is released when its item goes away or on unmount.
|
|
107
|
+
const uploadsRef = useRef<UploadItem[]>([])
|
|
108
|
+
uploadsRef.current = uploads
|
|
109
|
+
const releasePreview = (u: UploadItem) => {
|
|
110
|
+
if (u.preview) URL.revokeObjectURL?.(u.preview)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const keyed = useMemo(
|
|
114
|
+
() =>
|
|
115
|
+
rows
|
|
116
|
+
.map((row, i) => ({ row, key: rowKey(row, i) }))
|
|
117
|
+
.filter((r) => !hiddenKeys?.has(r.key)),
|
|
118
|
+
[rows, rowKey, hiddenKeys],
|
|
119
|
+
)
|
|
120
|
+
const ids = useMemo(() => keyed.map((k) => k.key), [keyed])
|
|
121
|
+
|
|
122
|
+
useEffect(() => () => uploadsRef.current.forEach(releasePreview), [])
|
|
123
|
+
|
|
124
|
+
const sensors = useSensors(
|
|
125
|
+
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
|
|
126
|
+
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
const move = useCallback(
|
|
130
|
+
(from: number, to: number) => {
|
|
131
|
+
if (from === to || to < 0 || to >= keyed.length) return
|
|
132
|
+
void onReorder(arrayMove(keyed, from, to).map((k) => k.row))
|
|
133
|
+
},
|
|
134
|
+
[keyed, onReorder],
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
const handleDragEnd = useCallback(
|
|
138
|
+
(e: DragEndEvent) => {
|
|
139
|
+
if (!e.over || e.active.id === e.over.id) return
|
|
140
|
+
move(ids.indexOf(String(e.active.id)), ids.indexOf(String(e.over.id)))
|
|
141
|
+
},
|
|
142
|
+
[ids, move],
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
const runUpload = useCallback(
|
|
146
|
+
async (item: UploadItem) => {
|
|
147
|
+
setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'uploading', progress: 0, error: undefined } : u)))
|
|
148
|
+
try {
|
|
149
|
+
await onUpload(
|
|
150
|
+
item.file,
|
|
151
|
+
item.offset,
|
|
152
|
+
(fraction) =>
|
|
153
|
+
setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, progress: Math.max(0, Math.min(1, fraction)) } : u))),
|
|
154
|
+
item.uploadedUrl,
|
|
155
|
+
)
|
|
156
|
+
setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'done', progress: 1 } : u)))
|
|
157
|
+
return true
|
|
158
|
+
} catch (err: any) {
|
|
159
|
+
const msg =
|
|
160
|
+
err?.response?.data?.message ||
|
|
161
|
+
err?.message ||
|
|
162
|
+
t('dynamic.gallery.upload_failed', { defaultValue: 'No se pudo subir la foto.' })
|
|
163
|
+
const stored = typeof err?.uploadedUrl === 'string' ? err.uploadedUrl : item.uploadedUrl
|
|
164
|
+
setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'error', error: String(msg), uploadedUrl: stored } : u)))
|
|
165
|
+
return false
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
[onUpload, t],
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
const addFiles = useCallback(
|
|
172
|
+
async (files: FileList | File[] | null | undefined) => {
|
|
173
|
+
const picked = Array.from(files ?? [])
|
|
174
|
+
if (picked.length === 0) return
|
|
175
|
+
const accepted: UploadItem[] = []
|
|
176
|
+
const rejected: UploadItem[] = []
|
|
177
|
+
for (const file of picked) {
|
|
178
|
+
const item: UploadItem = {
|
|
179
|
+
id: `up-${++uploadSeq}`,
|
|
180
|
+
file,
|
|
181
|
+
preview: typeof URL !== 'undefined' && URL.createObjectURL ? URL.createObjectURL(file) : '',
|
|
182
|
+
progress: 0,
|
|
183
|
+
status: 'uploading',
|
|
184
|
+
offset: accepted.length,
|
|
185
|
+
}
|
|
186
|
+
const bad = validateUploadFile(file, { accept, maxSize })
|
|
187
|
+
if (bad === 'type') {
|
|
188
|
+
rejected.push({ ...item, status: 'error', error: t('dynamic.gallery.invalid_type', { defaultValue: 'Formato no permitido. Usa JPG, PNG o WebP.' }) })
|
|
189
|
+
} else if (bad === 'size') {
|
|
190
|
+
const mb = ((maxSize ?? 0) / (1024 * 1024)).toFixed(1)
|
|
191
|
+
rejected.push({ ...item, status: 'error', error: t('dynamic.gallery.too_large', { mb, defaultValue: `La foto pesa más de ${mb} MB.` }) })
|
|
192
|
+
} else {
|
|
193
|
+
accepted.push(item)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
setUploads((list) => {
|
|
197
|
+
list.filter((u) => u.status === 'done').forEach(releasePreview)
|
|
198
|
+
return [...list.filter((u) => u.status !== 'done'), ...accepted, ...rejected]
|
|
199
|
+
})
|
|
200
|
+
// Sequential: keeps positions in pick order and spares the server.
|
|
201
|
+
let any = false
|
|
202
|
+
for (const item of accepted) {
|
|
203
|
+
if (await runUpload(item)) any = true
|
|
204
|
+
}
|
|
205
|
+
if (any) onUploadsSettled?.()
|
|
206
|
+
},
|
|
207
|
+
[accept, maxSize, runUpload, onUploadsSettled, t],
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
const retry = useCallback(
|
|
211
|
+
async (item: UploadItem) => {
|
|
212
|
+
if (await runUpload({ ...item, offset: 0 })) onUploadsSettled?.()
|
|
213
|
+
},
|
|
214
|
+
[runUpload, onUploadsSettled],
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
const dismiss = useCallback((id: string) => {
|
|
218
|
+
setUploads((list) => {
|
|
219
|
+
const gone = list.find((u) => u.id === id)
|
|
220
|
+
if (gone) releasePreview(gone)
|
|
221
|
+
return list.filter((u) => u.id !== id)
|
|
222
|
+
})
|
|
223
|
+
}, [])
|
|
224
|
+
|
|
225
|
+
const pending = uploads.filter((u) => u.status !== 'done')
|
|
226
|
+
// A retry numbers its photo past the rows already refreshed; while a batch
|
|
227
|
+
// is still uploading that list is stale, so retry waits for it.
|
|
228
|
+
const busy = uploads.some((u) => u.status === 'uploading')
|
|
229
|
+
const hintId = useMemo(() => `gallery-hint-${++uploadSeq}`, [])
|
|
230
|
+
const mainLabel = t('dynamic.gallery.main', { defaultValue: 'Principal' })
|
|
231
|
+
|
|
232
|
+
return (
|
|
233
|
+
<div className="grid gap-3" data-relation-view="gallery">
|
|
234
|
+
{canCreate && (
|
|
235
|
+
<div
|
|
236
|
+
role="button"
|
|
237
|
+
tabIndex={0}
|
|
238
|
+
aria-label={t('dynamic.gallery.add', { defaultValue: 'Agregar fotos' })}
|
|
239
|
+
aria-describedby={hintId}
|
|
240
|
+
onClick={() => inputRef.current?.click()}
|
|
241
|
+
onKeyDown={(e) => {
|
|
242
|
+
if (e.key === 'Enter' || e.key === ' ') {
|
|
243
|
+
e.preventDefault()
|
|
244
|
+
inputRef.current?.click()
|
|
245
|
+
}
|
|
246
|
+
}}
|
|
247
|
+
onDragOver={(e) => {
|
|
248
|
+
e.preventDefault()
|
|
249
|
+
setDragOver(true)
|
|
250
|
+
}}
|
|
251
|
+
onDragLeave={() => setDragOver(false)}
|
|
252
|
+
onDrop={(e) => {
|
|
253
|
+
e.preventDefault()
|
|
254
|
+
setDragOver(false)
|
|
255
|
+
void addFiles(e.dataTransfer?.files)
|
|
256
|
+
}}
|
|
257
|
+
className={cn(
|
|
258
|
+
'flex cursor-pointer flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed border-muted-foreground/30 px-4 py-6 text-center text-sm text-muted-foreground transition-colors hover:border-primary/50 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
|
259
|
+
dragOver && 'border-primary/60 bg-muted/50',
|
|
260
|
+
)}
|
|
261
|
+
data-testid="gallery-dropzone"
|
|
262
|
+
>
|
|
263
|
+
<ImagePlus className="h-6 w-6" aria-hidden />
|
|
264
|
+
<span className="font-medium text-foreground">
|
|
265
|
+
{t('dynamic.gallery.add', { defaultValue: 'Agregar fotos' })}
|
|
266
|
+
</span>
|
|
267
|
+
<span className="text-xs" id={hintId}>
|
|
268
|
+
{maxSize
|
|
269
|
+
? t('dynamic.gallery.hint_size', {
|
|
270
|
+
mb: (maxSize / (1024 * 1024)).toFixed(0),
|
|
271
|
+
defaultValue: `Arrastra aquí o elige varias a la vez · JPG, PNG o WebP · hasta ${(maxSize / (1024 * 1024)).toFixed(0)} MB`,
|
|
272
|
+
})
|
|
273
|
+
: t('dynamic.gallery.hint', { defaultValue: 'Arrastra aquí o elige varias a la vez · JPG, PNG o WebP' })}
|
|
274
|
+
</span>
|
|
275
|
+
<input
|
|
276
|
+
ref={inputRef}
|
|
277
|
+
type="file"
|
|
278
|
+
accept={accept}
|
|
279
|
+
multiple
|
|
280
|
+
className="hidden"
|
|
281
|
+
data-testid="gallery-input"
|
|
282
|
+
onChange={(e) => {
|
|
283
|
+
void addFiles(e.target.files)
|
|
284
|
+
e.target.value = ''
|
|
285
|
+
}}
|
|
286
|
+
/>
|
|
287
|
+
</div>
|
|
288
|
+
)}
|
|
289
|
+
|
|
290
|
+
{pending.length > 0 && (
|
|
291
|
+
<ul className="grid gap-2" aria-live="polite" data-testid="gallery-uploads">
|
|
292
|
+
{pending.map((u) => (
|
|
293
|
+
<li key={u.id} className="flex items-center gap-3 rounded-md border bg-card p-2">
|
|
294
|
+
{u.preview ? (
|
|
295
|
+
<img src={u.preview} alt="" className="h-12 w-12 shrink-0 rounded object-cover" />
|
|
296
|
+
) : (
|
|
297
|
+
<div className="h-12 w-12 shrink-0 rounded bg-muted" />
|
|
298
|
+
)}
|
|
299
|
+
<div className="min-w-0 flex-1">
|
|
300
|
+
<div className="truncate text-sm">{u.file.name}</div>
|
|
301
|
+
{u.status === 'error' ? (
|
|
302
|
+
<div className="text-xs text-destructive" role="alert">
|
|
303
|
+
{u.error}
|
|
304
|
+
</div>
|
|
305
|
+
) : (
|
|
306
|
+
<div
|
|
307
|
+
className="mt-1 h-1.5 w-full overflow-hidden rounded bg-muted"
|
|
308
|
+
role="progressbar"
|
|
309
|
+
aria-label={u.file.name}
|
|
310
|
+
aria-valuemin={0}
|
|
311
|
+
aria-valuemax={100}
|
|
312
|
+
aria-valuenow={Math.round(u.progress * 100)}
|
|
313
|
+
>
|
|
314
|
+
<div className="h-full bg-primary transition-all" style={{ width: `${Math.round(u.progress * 100)}%` }} />
|
|
315
|
+
</div>
|
|
316
|
+
)}
|
|
317
|
+
</div>
|
|
318
|
+
{u.status === 'uploading' && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden />}
|
|
319
|
+
{u.status === 'error' && !validateUploadFile(u.file, { accept, maxSize }) && (
|
|
320
|
+
<Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => void retry(u)} aria-label={t('dynamic.gallery.retry', { defaultValue: 'Reintentar' })}>
|
|
321
|
+
<RotateCcw className="h-4 w-4" />
|
|
322
|
+
</Button>
|
|
323
|
+
)}
|
|
324
|
+
{u.status === 'error' && (
|
|
325
|
+
<Button type="button" size="sm" variant="ghost" onClick={() => dismiss(u.id)} aria-label={t('dynamic.gallery.dismiss', { defaultValue: 'Quitar' })}>
|
|
326
|
+
<X className="h-4 w-4" />
|
|
327
|
+
</Button>
|
|
328
|
+
)}
|
|
329
|
+
</li>
|
|
330
|
+
))}
|
|
331
|
+
</ul>
|
|
332
|
+
)}
|
|
333
|
+
|
|
334
|
+
{keyed.length === 0 && !canCreate && pending.length === 0 && (
|
|
335
|
+
<div className="rounded-md border bg-muted/30 py-8 text-center text-sm text-muted-foreground">
|
|
336
|
+
{t('dynamic.gallery.empty', { defaultValue: 'Sin fotos.' })}
|
|
337
|
+
</div>
|
|
338
|
+
)}
|
|
339
|
+
|
|
340
|
+
{keyed.length > 0 && (
|
|
341
|
+
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
|
342
|
+
<SortableContext items={ids} strategy={rectSortingStrategy}>
|
|
343
|
+
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4" data-testid="gallery-grid">
|
|
344
|
+
{keyed.map(({ row, key }, index) => (
|
|
345
|
+
<GalleryTile
|
|
346
|
+
key={key}
|
|
347
|
+
id={key}
|
|
348
|
+
src={row[imageKey] ? getImageUrl(String(row[imageKey])) : ''}
|
|
349
|
+
caption={captionKey ? String(row[captionKey] ?? '') : ''}
|
|
350
|
+
index={index}
|
|
351
|
+
total={keyed.length}
|
|
352
|
+
isMain={index === 0}
|
|
353
|
+
mainLabel={mainLabel}
|
|
354
|
+
canEdit={canEdit}
|
|
355
|
+
canReorder={reorderable}
|
|
356
|
+
canDelete={canDelete}
|
|
357
|
+
onMove={(to) => move(index, to)}
|
|
358
|
+
onEdit={onEdit ? () => onEdit(row) : undefined}
|
|
359
|
+
onDelete={onDelete ? () => onDelete(row) : undefined}
|
|
360
|
+
/>
|
|
361
|
+
))}
|
|
362
|
+
</ul>
|
|
363
|
+
</SortableContext>
|
|
364
|
+
</DndContext>
|
|
365
|
+
)}
|
|
366
|
+
</div>
|
|
367
|
+
)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function GalleryTile({
|
|
371
|
+
id,
|
|
372
|
+
src,
|
|
373
|
+
caption,
|
|
374
|
+
index,
|
|
375
|
+
total,
|
|
376
|
+
isMain,
|
|
377
|
+
mainLabel,
|
|
378
|
+
canEdit,
|
|
379
|
+
canReorder,
|
|
380
|
+
canDelete,
|
|
381
|
+
onMove,
|
|
382
|
+
onEdit,
|
|
383
|
+
onDelete,
|
|
384
|
+
}: {
|
|
385
|
+
id: string
|
|
386
|
+
src: string
|
|
387
|
+
caption: string
|
|
388
|
+
index: number
|
|
389
|
+
total: number
|
|
390
|
+
isMain: boolean
|
|
391
|
+
mainLabel: string
|
|
392
|
+
canEdit: boolean
|
|
393
|
+
canReorder: boolean
|
|
394
|
+
canDelete: boolean
|
|
395
|
+
onMove: (to: number) => void
|
|
396
|
+
onEdit?: () => void
|
|
397
|
+
onDelete?: () => void
|
|
398
|
+
}) {
|
|
399
|
+
const { t } = useTranslation()
|
|
400
|
+
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, disabled: !canReorder })
|
|
401
|
+
const label = caption || t('dynamic.gallery.photo', { n: index + 1, defaultValue: `Foto ${index + 1}` })
|
|
402
|
+
return (
|
|
403
|
+
<li
|
|
404
|
+
ref={setNodeRef}
|
|
405
|
+
style={{ transform: CSS.Transform.toString(transform), transition }}
|
|
406
|
+
className={cn(
|
|
407
|
+
'group relative min-w-0 overflow-hidden rounded-lg border bg-card',
|
|
408
|
+
isMain && 'ring-2 ring-primary',
|
|
409
|
+
isDragging && 'z-10 opacity-80 shadow-lg',
|
|
410
|
+
)}
|
|
411
|
+
data-testid="gallery-tile"
|
|
412
|
+
data-main={isMain ? 'true' : undefined}
|
|
413
|
+
>
|
|
414
|
+
<div
|
|
415
|
+
className="aspect-square w-full touch-none bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
|
416
|
+
{...attributes}
|
|
417
|
+
{...listeners}
|
|
418
|
+
aria-roledescription={t('dynamic.gallery.sortable', { defaultValue: 'foto reordenable' })}
|
|
419
|
+
aria-label={`${label}${isMain ? ` · ${mainLabel}` : ''}`}
|
|
420
|
+
>
|
|
421
|
+
{src ? (
|
|
422
|
+
<img src={src} alt={caption} className="h-full w-full min-h-24 object-cover" draggable={false} />
|
|
423
|
+
) : null}
|
|
424
|
+
</div>
|
|
425
|
+
{isMain && (
|
|
426
|
+
<span className="absolute start-2 top-2 inline-flex items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs font-medium text-primary-foreground">
|
|
427
|
+
<Star className="h-3 w-3" aria-hidden />
|
|
428
|
+
{mainLabel}
|
|
429
|
+
</span>
|
|
430
|
+
)}
|
|
431
|
+
{/* Wraps instead of clipping: a 140 px tile (or a phone) holds up to five icons. */}
|
|
432
|
+
<div className="flex flex-wrap items-center justify-between gap-x-1 border-t bg-card px-1 py-0.5" data-testid="gallery-tile-actions">
|
|
433
|
+
<div className="flex flex-wrap items-center">
|
|
434
|
+
{canReorder && (
|
|
435
|
+
<>
|
|
436
|
+
<Button
|
|
437
|
+
type="button"
|
|
438
|
+
size="sm"
|
|
439
|
+
variant="ghost"
|
|
440
|
+
className="h-8 w-8 p-0"
|
|
441
|
+
disabled={index === 0}
|
|
442
|
+
onClick={() => onMove(index - 1)}
|
|
443
|
+
aria-label={t('dynamic.gallery.move_before', { defaultValue: 'Mover antes' })}
|
|
444
|
+
>
|
|
445
|
+
<ArrowLeft className="h-4 w-4 rtl:rotate-180" />
|
|
446
|
+
</Button>
|
|
447
|
+
<Button
|
|
448
|
+
type="button"
|
|
449
|
+
size="sm"
|
|
450
|
+
variant="ghost"
|
|
451
|
+
className="h-8 w-8 p-0"
|
|
452
|
+
disabled={index === total - 1}
|
|
453
|
+
onClick={() => onMove(index + 1)}
|
|
454
|
+
aria-label={t('dynamic.gallery.move_after', { defaultValue: 'Mover después' })}
|
|
455
|
+
>
|
|
456
|
+
<ArrowRight className="h-4 w-4 rtl:rotate-180" />
|
|
457
|
+
</Button>
|
|
458
|
+
{!isMain && (
|
|
459
|
+
<Button
|
|
460
|
+
type="button"
|
|
461
|
+
size="sm"
|
|
462
|
+
variant="ghost"
|
|
463
|
+
className="h-8 w-8 p-0"
|
|
464
|
+
onClick={() => onMove(0)}
|
|
465
|
+
aria-label={t('dynamic.gallery.make_main', { defaultValue: 'Hacer principal' })}
|
|
466
|
+
title={t('dynamic.gallery.make_main', { defaultValue: 'Hacer principal' })}
|
|
467
|
+
>
|
|
468
|
+
<Star className="h-4 w-4" />
|
|
469
|
+
</Button>
|
|
470
|
+
)}
|
|
471
|
+
</>
|
|
472
|
+
)}
|
|
473
|
+
</div>
|
|
474
|
+
<div className="flex flex-wrap items-center">
|
|
475
|
+
{canEdit && onEdit && (
|
|
476
|
+
<Button type="button" size="sm" variant="ghost" className="h-8 w-8 p-0" onClick={onEdit} aria-label={t('dynamic.gallery.edit', { defaultValue: 'Editar foto' })}>
|
|
477
|
+
<Pencil className="h-4 w-4" />
|
|
478
|
+
</Button>
|
|
479
|
+
)}
|
|
480
|
+
{canDelete && onDelete && (
|
|
481
|
+
<Button type="button" size="sm" variant="ghost" className="h-8 w-8 p-0 text-destructive" onClick={onDelete} aria-label={t('dynamic.gallery.delete', { defaultValue: 'Eliminar foto' })}>
|
|
482
|
+
<Trash2 className="h-4 w-4" />
|
|
483
|
+
</Button>
|
|
484
|
+
)}
|
|
485
|
+
</div>
|
|
486
|
+
</div>
|
|
487
|
+
</li>
|
|
488
|
+
)
|
|
489
|
+
}
|
package/src/upload-field.tsx
CHANGED
|
@@ -15,12 +15,56 @@ import { useTranslation } from 'react-i18next'
|
|
|
15
15
|
import { getUploadConfig } from './dynamic-form-schema'
|
|
16
16
|
import { FilePickButton } from './file-pick-button'
|
|
17
17
|
import { useApi } from './api-context'
|
|
18
|
+
import { useImageUrl } from './image-url-context'
|
|
18
19
|
import type { ActionFieldDef } from './types'
|
|
19
20
|
|
|
20
21
|
export interface UploadFieldProps {
|
|
21
22
|
field: ActionFieldDef
|
|
22
23
|
value: any
|
|
23
24
|
onChange: (v: any) => void
|
|
25
|
+
/**
|
|
26
|
+
* Called after a successful upload of an image with its natural size,
|
|
27
|
+
* measured in the browser (no server round-trip, `/upload` contract
|
|
28
|
+
* unchanged). Lets a form fill derived width/height columns.
|
|
29
|
+
*/
|
|
30
|
+
onFileMeta?: (meta: { width?: number; height?: number }) => void
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Natural pixel size of an image file, measured client-side. Resolves `{}` for
|
|
35
|
+
* a non-image or when the browser cannot decode it — never throws, never
|
|
36
|
+
* guesses.
|
|
37
|
+
*/
|
|
38
|
+
export async function readImageSize(file: Blob): Promise<{ width?: number; height?: number }> {
|
|
39
|
+
if (!file || !String((file as File).type || '').startsWith('image/')) return {}
|
|
40
|
+
try {
|
|
41
|
+
if (typeof createImageBitmap === 'function') {
|
|
42
|
+
const bmp = await createImageBitmap(file)
|
|
43
|
+
const out = { width: bmp.width, height: bmp.height }
|
|
44
|
+
bmp.close?.()
|
|
45
|
+
if (out.width > 0 && out.height > 0) return out
|
|
46
|
+
}
|
|
47
|
+
} catch {
|
|
48
|
+
// fall through to <img>
|
|
49
|
+
}
|
|
50
|
+
if (typeof Image === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL) return {}
|
|
51
|
+
return new Promise((resolve) => {
|
|
52
|
+
const url = URL.createObjectURL(file)
|
|
53
|
+
const img = new Image()
|
|
54
|
+
img.onload = () => {
|
|
55
|
+
URL.revokeObjectURL(url)
|
|
56
|
+
resolve(img.naturalWidth > 0 ? { width: img.naturalWidth, height: img.naturalHeight } : {})
|
|
57
|
+
}
|
|
58
|
+
img.onerror = () => {
|
|
59
|
+
URL.revokeObjectURL(url)
|
|
60
|
+
resolve({})
|
|
61
|
+
}
|
|
62
|
+
img.src = url
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isImageField(field: ActionFieldDef, accept?: string): boolean {
|
|
67
|
+
return field.type === 'image' || (accept ?? '').toLowerCase().split(',').some((t) => t.trim().startsWith('image/'))
|
|
24
68
|
}
|
|
25
69
|
|
|
26
70
|
/** Default host upload endpoint. Overridable per-field via `searchEndpoint`. */
|
|
@@ -84,9 +128,10 @@ export function validateUploadFile(
|
|
|
84
128
|
return null
|
|
85
129
|
}
|
|
86
130
|
|
|
87
|
-
export function UploadField({ field, value, onChange }: UploadFieldProps) {
|
|
131
|
+
export function UploadField({ field, value, onChange, onFileMeta }: UploadFieldProps) {
|
|
88
132
|
const { t } = useTranslation()
|
|
89
133
|
const api = useApi()
|
|
134
|
+
const getImageUrl = useImageUrl()
|
|
90
135
|
const [uploading, setUploading] = useState(false)
|
|
91
136
|
const [error, setError] = useState<string | null>(null)
|
|
92
137
|
|
|
@@ -154,6 +199,11 @@ export function UploadField({ field, value, onChange }: UploadFieldProps) {
|
|
|
154
199
|
return
|
|
155
200
|
}
|
|
156
201
|
onChange(stored)
|
|
202
|
+
if (onFileMeta && isImageField(field, accept)) {
|
|
203
|
+
void readImageSize(file).then((meta) => {
|
|
204
|
+
if (meta.width && meta.height) onFileMeta(meta)
|
|
205
|
+
})
|
|
206
|
+
}
|
|
157
207
|
} catch (err: any) {
|
|
158
208
|
setError(
|
|
159
209
|
err?.response?.data?.message ||
|
|
@@ -163,7 +213,7 @@ export function UploadField({ field, value, onChange }: UploadFieldProps) {
|
|
|
163
213
|
setUploading(false)
|
|
164
214
|
}
|
|
165
215
|
},
|
|
166
|
-
[api, endpoint, accept, maxSize, storagePath, onChange, t],
|
|
216
|
+
[api, endpoint, accept, maxSize, storagePath, onChange, onFileMeta, field, t],
|
|
167
217
|
)
|
|
168
218
|
|
|
169
219
|
return (
|
|
@@ -180,6 +230,14 @@ export function UploadField({ field, value, onChange }: UploadFieldProps) {
|
|
|
180
230
|
void handleFile(dropped)
|
|
181
231
|
}}
|
|
182
232
|
>
|
|
233
|
+
{hasValue && isImageField(field, accept) && (
|
|
234
|
+
<img
|
|
235
|
+
src={getImageUrl(String(value))}
|
|
236
|
+
alt=""
|
|
237
|
+
className="h-24 w-24 rounded-md border bg-muted object-cover"
|
|
238
|
+
data-testid="upload-preview"
|
|
239
|
+
/>
|
|
240
|
+
)}
|
|
183
241
|
<FilePickButton
|
|
184
242
|
id={field.key}
|
|
185
243
|
accept={accept}
|