@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
package/src/dynamic-relation.tsx
CHANGED
|
@@ -52,6 +52,9 @@ import { makeDefaultGetDynamicColumns } from './dynamic-columns'
|
|
|
52
52
|
import { isColumnVisibleInLineSubtable } from './column-visibility'
|
|
53
53
|
import { useOptionsResolver } from './use-options-resolver'
|
|
54
54
|
import { dedupeById, useInfiniteScrollSentinel } from './use-infinite-scroll'
|
|
55
|
+
import { toast } from 'sonner'
|
|
56
|
+
import { RelationGallery } from './relation-gallery'
|
|
57
|
+
import { extractUploadedValue, readImageSize } from './upload-field'
|
|
55
58
|
import type { ApiResponse, ColumnDefinition, TableMetadata } from './types'
|
|
56
59
|
import {
|
|
57
60
|
buildCreatePayload,
|
|
@@ -62,8 +65,17 @@ import {
|
|
|
62
65
|
diffSelection,
|
|
63
66
|
extractSelectedTargetIds,
|
|
64
67
|
pickOptionLabel,
|
|
68
|
+
relationColumnUi,
|
|
69
|
+
relationDerivedValues,
|
|
70
|
+
contiguousPositionUpdates,
|
|
71
|
+
relationGalleryColumn,
|
|
72
|
+
relationInitialValues,
|
|
73
|
+
relationPositionKey,
|
|
74
|
+
relationPositionSortable,
|
|
65
75
|
relationRowKey,
|
|
76
|
+
sortRelationRows,
|
|
66
77
|
type DynamicRelationKind,
|
|
78
|
+
type ImageMeta,
|
|
67
79
|
} from './dynamic-relation-helpers'
|
|
68
80
|
|
|
69
81
|
export type { DynamicRelationKind } from './dynamic-relation-helpers'
|
|
@@ -102,6 +114,16 @@ export interface DynamicRelationStrings {
|
|
|
102
114
|
searchPlaceholder: string
|
|
103
115
|
/** Pie de la sub-tabla: "{{loaded}} de {{total}}". */
|
|
104
116
|
countLabel: string
|
|
117
|
+
/** Galería: toast tras eliminar una foto. Default "Foto eliminada". */
|
|
118
|
+
deletedToast?: string
|
|
119
|
+
/** Galería: acción del toast. Default "Deshacer". */
|
|
120
|
+
undoLabel?: string
|
|
121
|
+
/** Galería: falla al guardar el orden. */
|
|
122
|
+
reorderError?: string
|
|
123
|
+
/** Galería: falla al eliminar. */
|
|
124
|
+
deleteError?: string
|
|
125
|
+
/** Galería: confirmación al eliminar una foto. Default "Esta foto deja de verse en la tienda. Puedes deshacerlo unos segundos." */
|
|
126
|
+
confirmRemovePhotoDescription?: string
|
|
105
127
|
}
|
|
106
128
|
|
|
107
129
|
const DEFAULT_STRINGS: DynamicRelationStrings = {
|
|
@@ -124,6 +146,7 @@ const DEFAULT_STRINGS: DynamicRelationStrings = {
|
|
|
124
146
|
// Tamaño de página de la sub-tabla 1:N. Antes la lista pedía el hijo COMPLETO
|
|
125
147
|
// (sin page/per_page), así que abrir un almacén traía todas sus existencias y
|
|
126
148
|
// traspasos. Se pagina de a 25 y el resto entra por scroll infinito.
|
|
149
|
+
const GALLERY_PAGE_SIZE = 200
|
|
127
150
|
const REL_PAGE_SIZE = 25
|
|
128
151
|
|
|
129
152
|
interface CommonProps {
|
|
@@ -180,6 +203,12 @@ export interface DynamicRelationOneToManyProps extends CommonProps {
|
|
|
180
203
|
foreignKey: string
|
|
181
204
|
/** Endpoint override; default `/data/${model}`. */
|
|
182
205
|
endpoint?: string
|
|
206
|
+
/**
|
|
207
|
+
* El registro padre. Solo lo leen los campos que declaran
|
|
208
|
+
* `display_config.default_from_parent` (p. ej. el nombre del producto como
|
|
209
|
+
* texto alternativo sugerido de una foto). Opcional.
|
|
210
|
+
*/
|
|
211
|
+
parentRecord?: Record<string, unknown> | null
|
|
183
212
|
}
|
|
184
213
|
|
|
185
214
|
export interface DynamicRelationManyToManyProps extends CommonProps {
|
|
@@ -231,6 +260,7 @@ function OneToManyRelation({
|
|
|
231
260
|
strings,
|
|
232
261
|
className,
|
|
233
262
|
onChange,
|
|
263
|
+
parentRecord,
|
|
234
264
|
}: DynamicRelationOneToManyProps) {
|
|
235
265
|
// Read-only relation always wins over host-passed perms (AND). Tolerates the
|
|
236
266
|
// camelCase alias the same way lock_rows/lockRows does.
|
|
@@ -284,6 +314,7 @@ function OneToManyRelation({
|
|
|
284
314
|
// resolverla dispararía un segundo fetch de datos por cada montaje.
|
|
285
315
|
const metadataRef = useRef<TableMetadata | null>(metadata)
|
|
286
316
|
metadataRef.current = metadata
|
|
317
|
+
const fetchPageRef = useRef<((p: number, append: boolean, silent?: boolean) => Promise<void>) | null>(null)
|
|
287
318
|
|
|
288
319
|
// Debounce del buscador: cada tecla no puede pegarle al servidor.
|
|
289
320
|
useEffect(() => {
|
|
@@ -329,25 +360,43 @@ function OneToManyRelation({
|
|
|
329
360
|
|
|
330
361
|
// fetchPage REEMPLAZA (página 1) o ANEXA (scroll infinito). Antes esta lista
|
|
331
362
|
// pedía el modelo hijo entero sin page/per_page.
|
|
332
|
-
|
|
363
|
+
// silent: refresh page 1 without the skeleton (the gallery keeps its
|
|
364
|
+
// per-file upload list mounted while the new rows arrive).
|
|
365
|
+
const fetchPage = useCallback(async (nextPage: number, append: boolean, silent = false) => {
|
|
333
366
|
if (append) setLoadingMore(true)
|
|
334
|
-
else setLoading(true)
|
|
367
|
+
else if (!silent) setLoading(true)
|
|
335
368
|
try {
|
|
336
369
|
const params: Record<string, any> = {
|
|
337
370
|
...buildRelationFilterParams(foreignKey, parentId, filters),
|
|
338
371
|
page: nextPage,
|
|
339
372
|
per_page: REL_PAGE_SIZE,
|
|
340
373
|
}
|
|
374
|
+
// A child model with an ordering column (`position`) lists in that
|
|
375
|
+
// order — the gallery's first image is the main one.
|
|
376
|
+
// Only when the column is declared sortable: a backend that cannot
|
|
377
|
+
// sort by it must not fail the whole list.
|
|
378
|
+
if (relationPositionSortable(metadataRef.current)) {
|
|
379
|
+
params.sortBy = 'position'
|
|
380
|
+
params.order = 'asc'
|
|
381
|
+
}
|
|
382
|
+
// A gallery shows every photo at once (no infinite scroll in the
|
|
383
|
+
// grid) and numbers new ones past the highest loaded position.
|
|
384
|
+
if (relationGalleryColumn(metadataRef.current)) params.per_page = GALLERY_PAGE_SIZE
|
|
341
385
|
if (debouncedSearch) params.search = debouncedSearch
|
|
342
386
|
const askedScope = cacheScope()
|
|
343
387
|
const [metaRes, dataRes] = await Promise.all([
|
|
344
388
|
metadataRef.current ? Promise.resolve(null) : api.get(`/metadata/table/${model}`),
|
|
345
389
|
api.get(dataEndpoint, { params }),
|
|
346
390
|
])
|
|
391
|
+
let refetchOrdered = false
|
|
347
392
|
if (metaRes && (metaRes as any).data?.success) {
|
|
348
393
|
const fresh = (metaRes as { data: ApiResponse<TableMetadata> }).data.data
|
|
349
394
|
setMetadata(fresh)
|
|
395
|
+
metadataRef.current = fresh
|
|
350
396
|
cacheMetadata(model, fresh, { scope: askedScope })
|
|
397
|
+
// Cold cache: this page went out before we knew the child has a
|
|
398
|
+
// gallery / sortable position — ask again in that order and size.
|
|
399
|
+
refetchOrdered = !append && (!!relationGalleryColumn(fresh) || relationPositionSortable(fresh))
|
|
351
400
|
}
|
|
352
401
|
const list = (dataRes as { data: ApiResponse<any[]> }).data
|
|
353
402
|
setFetchErrorStatus(null)
|
|
@@ -359,20 +408,28 @@ function OneToManyRelation({
|
|
|
359
408
|
else if (!append) setTotal(fetched.length)
|
|
360
409
|
setExhausted(fetched.length < REL_PAGE_SIZE)
|
|
361
410
|
}
|
|
411
|
+
if (refetchOrdered) {
|
|
412
|
+
void fetchPageRef.current?.(1, false, true)
|
|
413
|
+
}
|
|
362
414
|
} catch (err) {
|
|
363
415
|
console.error('DynamicRelation fetch error', err)
|
|
364
416
|
setFetchErrorStatus((err as { response?: { status?: number } })?.response?.status ?? 0)
|
|
365
417
|
} finally {
|
|
366
418
|
if (append) setLoadingMore(false)
|
|
367
|
-
else setLoading(false)
|
|
419
|
+
else if (!silent) setLoading(false)
|
|
368
420
|
}
|
|
369
421
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
370
422
|
}, [api, dataEndpoint, foreignKey, parentId, filtersKey, model, cacheMetadata, debouncedSearch])
|
|
371
423
|
|
|
424
|
+
fetchPageRef.current = fetchPage
|
|
425
|
+
|
|
372
426
|
// Recarga desde la primera página. Es lo que corren create/edit/delete.
|
|
373
427
|
const fetchAll = useCallback(async () => {
|
|
374
428
|
await fetchPage(1, false)
|
|
375
429
|
}, [fetchPage])
|
|
430
|
+
const refreshSilently = useCallback(async () => {
|
|
431
|
+
await fetchPage(1, false, true)
|
|
432
|
+
}, [fetchPage])
|
|
376
433
|
|
|
377
434
|
// Un cambio de padre/scope/búsqueda vuelve a la página 1.
|
|
378
435
|
useEffect(() => { fetchPage(1, false) }, [fetchPage])
|
|
@@ -386,13 +443,32 @@ function OneToManyRelation({
|
|
|
386
443
|
// El buscador solo aparece cuando hay algo que buscar: una sub-tabla de 3
|
|
387
444
|
// líneas no necesita chrome extra. Se queda visible mientras haya término
|
|
388
445
|
// activo para no dejar al usuario sin forma de limpiarlo.
|
|
389
|
-
const
|
|
446
|
+
const isGallery = !!relationGalleryColumn(metadata)
|
|
447
|
+
const showSearch = !isGallery && (debouncedSearch !== '' || search !== '' || total > REL_PAGE_SIZE)
|
|
390
448
|
|
|
391
449
|
const formFields = useMemo(
|
|
392
450
|
() => deriveRelationFormFields(metadata, foreignKey),
|
|
393
451
|
[metadata, foreignKey],
|
|
394
452
|
)
|
|
395
453
|
|
|
454
|
+
// Ordered view of the loaded rows (also covers the first page, fetched
|
|
455
|
+
// before the metadata told us there is a position column).
|
|
456
|
+
const positionKey = useMemo(() => relationPositionKey(metadata), [metadata])
|
|
457
|
+
const orderedRows = useMemo(() => sortRelationRows(rows, positionKey), [rows, positionKey])
|
|
458
|
+
const galleryColumn = useMemo(() => relationGalleryColumn(metadata), [metadata])
|
|
459
|
+
const captionKey = useMemo(
|
|
460
|
+
() => metadata?.columns?.find((c) => relationColumnUi(c).defaultFromParent)?.key,
|
|
461
|
+
[metadata],
|
|
462
|
+
)
|
|
463
|
+
const createInitialValues = useMemo(
|
|
464
|
+
() => relationInitialValues(metadata, parentRecord),
|
|
465
|
+
[metadata, parentRecord],
|
|
466
|
+
)
|
|
467
|
+
// Size of the image uploaded in the open form (fills derived width/height).
|
|
468
|
+
const uploadedImageRef = useRef<ImageMeta | null>(null)
|
|
469
|
+
// Rows deleted from the gallery but still undoable.
|
|
470
|
+
const [pendingDelete, setPendingDelete] = useState<Set<string>>(new Set())
|
|
471
|
+
|
|
396
472
|
const visibleColumns = useMemo(() => {
|
|
397
473
|
if (!metadata?.columns) return []
|
|
398
474
|
// Hide the FK and every scope column — they're fixed for this parent and
|
|
@@ -457,7 +533,7 @@ function OneToManyRelation({
|
|
|
457
533
|
<Button
|
|
458
534
|
size="sm"
|
|
459
535
|
variant="ghost"
|
|
460
|
-
onClick={() => { setEditingRow(row.original); setFormOpen(true) }}
|
|
536
|
+
onClick={() => { setEditingRow(row.original); uploadedImageRef.current = null; setFormOpen(true) }}
|
|
461
537
|
aria-label={labels.editLabel}
|
|
462
538
|
>
|
|
463
539
|
<Pencil className="h-4 w-4" />
|
|
@@ -480,13 +556,21 @@ function OneToManyRelation({
|
|
|
480
556
|
}, [metadata, visibleColumns, buildColumns, i18n?.language, timeZone, currency, showActions, canEdit, canDelete, labels.editLabel, labels.removeLabel])
|
|
481
557
|
|
|
482
558
|
const table = useReactTable({
|
|
483
|
-
data:
|
|
559
|
+
data: orderedRows,
|
|
484
560
|
columns,
|
|
485
561
|
getCoreRowModel: getCoreRowModel(),
|
|
486
562
|
})
|
|
487
563
|
|
|
488
564
|
const handleSubmit = useCallback(async (values: Record<string, any>) => {
|
|
489
565
|
setSubmitting(true)
|
|
566
|
+
// Derived columns (image size, next position) travel with the row even
|
|
567
|
+
// though they are not form inputs.
|
|
568
|
+
const derived = relationDerivedValues(metadata, {
|
|
569
|
+
isCreate: !editingRow,
|
|
570
|
+
rows,
|
|
571
|
+
image: uploadedImageRef.current,
|
|
572
|
+
})
|
|
573
|
+
values = { ...values, ...derived }
|
|
490
574
|
try {
|
|
491
575
|
if (editingRow) {
|
|
492
576
|
const res = await api.put(`${dataEndpoint}/${editingRow.id}`, values)
|
|
@@ -501,6 +585,7 @@ function OneToManyRelation({
|
|
|
501
585
|
}
|
|
502
586
|
setFormOpen(false)
|
|
503
587
|
setEditingRow(null)
|
|
588
|
+
uploadedImageRef.current = null
|
|
504
589
|
await fetchAll()
|
|
505
590
|
onChange?.()
|
|
506
591
|
} catch (err) {
|
|
@@ -509,7 +594,198 @@ function OneToManyRelation({
|
|
|
509
594
|
setSubmitting(false)
|
|
510
595
|
}
|
|
511
596
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
512
|
-
}, [api, dataEndpoint, editingRow, fetchAll, foreignKey, filtersKey, onChange, parentId])
|
|
597
|
+
}, [api, dataEndpoint, editingRow, fetchAll, foreignKey, filtersKey, onChange, parentId, metadata, rows])
|
|
598
|
+
|
|
599
|
+
// Highest position this panel created itself. `rows` can lag behind the
|
|
600
|
+
// rows just created (the list refreshes after the batch), so two uploads in
|
|
601
|
+
// a row must not both read the same stale maximum. Reset per parent.
|
|
602
|
+
const createdMaxPositionRef = useRef(-1)
|
|
603
|
+
useEffect(() => { createdMaxPositionRef.current = -1 }, [parentId])
|
|
604
|
+
|
|
605
|
+
// Position writes (reorder and renumber) run one after another, never
|
|
606
|
+
// interleaved: a renumber that read the server before a drag would
|
|
607
|
+
// otherwise overwrite the order the user just chose.
|
|
608
|
+
const positionQueueRef = useRef<Promise<unknown>>(Promise.resolve())
|
|
609
|
+
const enqueuePositions = useCallback(<T,>(fn: () => Promise<T>): Promise<T> => {
|
|
610
|
+
const run = positionQueueRef.current.then(fn, fn)
|
|
611
|
+
positionQueueRef.current = run.catch(() => undefined)
|
|
612
|
+
return run
|
|
613
|
+
}, [])
|
|
614
|
+
|
|
615
|
+
// Renumbers the gallery 0..n-1 from what the SERVER holds (read when the
|
|
616
|
+
// job runs, not from state): heals duplicated positions left by older
|
|
617
|
+
// clients and closes the gap a deleted photo leaves. Reads every page;
|
|
618
|
+
// writes only the rows that differ; a failed write does not stop the rest.
|
|
619
|
+
const normalizePositions = useCallback(
|
|
620
|
+
() =>
|
|
621
|
+
enqueuePositions(async () => {
|
|
622
|
+
if (!positionKey || !relationGalleryColumn(metadataRef.current)) return
|
|
623
|
+
try {
|
|
624
|
+
const fresh: any[] = []
|
|
625
|
+
for (let page = 1; page <= 20; page++) {
|
|
626
|
+
const res = (await api.get(dataEndpoint, {
|
|
627
|
+
params: {
|
|
628
|
+
...buildRelationFilterParams(foreignKey, parentId, filters),
|
|
629
|
+
page,
|
|
630
|
+
per_page: GALLERY_PAGE_SIZE,
|
|
631
|
+
sortBy: positionKey,
|
|
632
|
+
order: 'asc',
|
|
633
|
+
},
|
|
634
|
+
})) as { data?: ApiResponse<any[]> }
|
|
635
|
+
if (!res?.data?.success) return
|
|
636
|
+
const got = res.data.data ?? []
|
|
637
|
+
fresh.push(...got)
|
|
638
|
+
if (got.length < GALLERY_PAGE_SIZE) break
|
|
639
|
+
if (page === 20) return // too many to renumber safely
|
|
640
|
+
}
|
|
641
|
+
const { updates } = contiguousPositionUpdates(dedupeById([], fresh), positionKey)
|
|
642
|
+
let failed = 0
|
|
643
|
+
for (const u of updates) {
|
|
644
|
+
try {
|
|
645
|
+
const r = (await api.put(`${dataEndpoint}/${u.id}`, { [positionKey]: u.position })) as any
|
|
646
|
+
if (r?.data?.success === false) failed++
|
|
647
|
+
} catch {
|
|
648
|
+
failed++
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
createdMaxPositionRef.current = Math.max(createdMaxPositionRef.current, fresh.length - 1)
|
|
652
|
+
if (failed) toast.error(labels.reorderError ?? 'No se pudo guardar el nuevo orden.')
|
|
653
|
+
} catch (err) {
|
|
654
|
+
console.error('DynamicRelation normalize positions error', err)
|
|
655
|
+
}
|
|
656
|
+
}),
|
|
657
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
658
|
+
[api, dataEndpoint, positionKey, foreignKey, parentId, filtersKey, enqueuePositions],
|
|
659
|
+
)
|
|
660
|
+
|
|
661
|
+
// ── Gallery (opt-in: image column with display_config.gallery) ─────────
|
|
662
|
+
// Same contracts as the table: POST /upload (multipart) for the file, then
|
|
663
|
+
// POST /data/<model> for the row. Positions are assigned in pick order.
|
|
664
|
+
const galleryUpload = useCallback(
|
|
665
|
+
async (file: File, _offset: number, onProgress: (f: number) => void, reuseUrl?: string) => {
|
|
666
|
+
if (!galleryColumn) return
|
|
667
|
+
const size = await readImageSize(file)
|
|
668
|
+
let url = reuseUrl
|
|
669
|
+
if (!url) {
|
|
670
|
+
const form = new FormData()
|
|
671
|
+
form.append('file', file)
|
|
672
|
+
const folder = (galleryColumn.styleConfig as any)?.storage_path ?? (galleryColumn.styleConfig as any)?.storagePath
|
|
673
|
+
if (folder) {
|
|
674
|
+
form.append('folder', folder)
|
|
675
|
+
form.append('storage_path', folder)
|
|
676
|
+
}
|
|
677
|
+
const up = await api.post('/upload', form, {
|
|
678
|
+
headers: { 'Content-Type': 'multipart/form-data' },
|
|
679
|
+
onUploadProgress: (e: { loaded: number; total?: number }) => {
|
|
680
|
+
if (e.total) onProgress((e.loaded / e.total) * 0.9)
|
|
681
|
+
},
|
|
682
|
+
} as any)
|
|
683
|
+
const body = (up as { data?: any })?.data
|
|
684
|
+
if (body && body.success === false) throw new Error(body.message || 'upload failed')
|
|
685
|
+
url = extractUploadedValue(body)
|
|
686
|
+
if (!url) throw new Error('upload failed')
|
|
687
|
+
}
|
|
688
|
+
const derived = relationDerivedValues(metadata, { isCreate: true, rows, image: size })
|
|
689
|
+
if (positionKey && typeof derived[positionKey] === 'number') {
|
|
690
|
+
derived[positionKey] = Math.max(derived[positionKey], createdMaxPositionRef.current + 1)
|
|
691
|
+
createdMaxPositionRef.current = derived[positionKey]
|
|
692
|
+
}
|
|
693
|
+
const payload = {
|
|
694
|
+
...(filters || {}),
|
|
695
|
+
...buildCreatePayload(foreignKey, parentId, {
|
|
696
|
+
...createInitialValues,
|
|
697
|
+
...derived,
|
|
698
|
+
[galleryColumn.key]: url,
|
|
699
|
+
}),
|
|
700
|
+
}
|
|
701
|
+
try {
|
|
702
|
+
const res = await api.post(dataEndpoint, payload)
|
|
703
|
+
if (!(res as any).data?.success) throw new Error((res as any).data?.message || 'create failed')
|
|
704
|
+
} catch (err: any) {
|
|
705
|
+
// The file is already stored: a retry reuses it instead of
|
|
706
|
+
// uploading (and orphaning) a second copy.
|
|
707
|
+
throw Object.assign(err instanceof Error ? err : new Error(String(err)), { uploadedUrl: url })
|
|
708
|
+
}
|
|
709
|
+
onProgress(1)
|
|
710
|
+
},
|
|
711
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
712
|
+
[api, galleryColumn, metadata, rows, positionKey, filtersKey, foreignKey, parentId, createInitialValues, dataEndpoint],
|
|
713
|
+
)
|
|
714
|
+
|
|
715
|
+
const galleryReorder = useCallback(
|
|
716
|
+
async (ordered: Record<string, any>[]) => {
|
|
717
|
+
if (!positionKey) return
|
|
718
|
+
// Optimistic: show the new order now, persist only what changed.
|
|
719
|
+
setRows(ordered.map((r, i) => ({ ...r, [positionKey]: i })))
|
|
720
|
+
await enqueuePositions(async () => {
|
|
721
|
+
try {
|
|
722
|
+
await Promise.all(
|
|
723
|
+
ordered.map((r, i) => {
|
|
724
|
+
const raw = r[positionKey]
|
|
725
|
+
const same = raw !== null && raw !== undefined && raw !== '' && Number(raw) === i
|
|
726
|
+
return same ? null : api.put(`${dataEndpoint}/${r.id}`, { [positionKey]: i })
|
|
727
|
+
}),
|
|
728
|
+
)
|
|
729
|
+
onChange?.()
|
|
730
|
+
} catch (err) {
|
|
731
|
+
console.error('DynamicRelation reorder error', err)
|
|
732
|
+
toast.error(labels.reorderError ?? 'No se pudo guardar el nuevo orden.')
|
|
733
|
+
} finally {
|
|
734
|
+
await refreshSilently()
|
|
735
|
+
}
|
|
736
|
+
})
|
|
737
|
+
},
|
|
738
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
739
|
+
[api, dataEndpoint, positionKey, refreshSilently, onChange, enqueuePositions],
|
|
740
|
+
)
|
|
741
|
+
|
|
742
|
+
// Confirmed delete → hidden at once, «Deshacer» for a few seconds, then the
|
|
743
|
+
// real DELETE. Closing the panel before the toast ends still deletes.
|
|
744
|
+
const deleteWithUndo = useCallback(
|
|
745
|
+
(row: any) => {
|
|
746
|
+
const key = String(row.id)
|
|
747
|
+
setPendingDelete((s) => new Set(s).add(key))
|
|
748
|
+
let undone = false
|
|
749
|
+
const commit = async () => {
|
|
750
|
+
if (undone) return
|
|
751
|
+
try {
|
|
752
|
+
const res = await api.delete(`${dataEndpoint}/${row.id}`)
|
|
753
|
+
if (!(res as any).data?.success) throw new Error('delete failed')
|
|
754
|
+
await normalizePositions()
|
|
755
|
+
onChange?.()
|
|
756
|
+
} catch (err) {
|
|
757
|
+
console.error('DynamicRelation delete error', err)
|
|
758
|
+
toast.error(labels.deleteError ?? 'No se pudo eliminar.')
|
|
759
|
+
} finally {
|
|
760
|
+
setPendingDelete((s) => {
|
|
761
|
+
const n = new Set(s)
|
|
762
|
+
n.delete(key)
|
|
763
|
+
return n
|
|
764
|
+
})
|
|
765
|
+
await refreshSilently()
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
const timer = setTimeout(() => void commit(), 6000)
|
|
769
|
+
toast(labels.deletedToast ?? 'Foto eliminada', {
|
|
770
|
+
duration: 6000,
|
|
771
|
+
action: {
|
|
772
|
+
label: labels.undoLabel ?? 'Deshacer',
|
|
773
|
+
onClick: () => {
|
|
774
|
+
undone = true
|
|
775
|
+
clearTimeout(timer)
|
|
776
|
+
void normalizePositions().then(() => refreshSilently())
|
|
777
|
+
setPendingDelete((s) => {
|
|
778
|
+
const n = new Set(s)
|
|
779
|
+
n.delete(key)
|
|
780
|
+
return n
|
|
781
|
+
})
|
|
782
|
+
},
|
|
783
|
+
},
|
|
784
|
+
})
|
|
785
|
+
},
|
|
786
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
787
|
+
[api, dataEndpoint, refreshSilently, onChange, normalizePositions],
|
|
788
|
+
)
|
|
513
789
|
|
|
514
790
|
const handleDelete = useCallback(async () => {
|
|
515
791
|
if (!rowToDelete) return
|
|
@@ -519,13 +795,14 @@ function OneToManyRelation({
|
|
|
519
795
|
if (!(res as any).data?.success) throw new Error('delete failed')
|
|
520
796
|
setRowToDelete(null)
|
|
521
797
|
await fetchAll()
|
|
798
|
+
void normalizePositions().then(() => refreshSilently())
|
|
522
799
|
onChange?.()
|
|
523
800
|
} catch (err) {
|
|
524
801
|
console.error('DynamicRelation delete error', err)
|
|
525
802
|
} finally {
|
|
526
803
|
setSubmitting(false)
|
|
527
804
|
}
|
|
528
|
-
}, [api, dataEndpoint, fetchAll, onChange, rowToDelete])
|
|
805
|
+
}, [api, dataEndpoint, fetchAll, onChange, rowToDelete, normalizePositions, refreshSilently])
|
|
529
806
|
|
|
530
807
|
return (
|
|
531
808
|
<div className={className} data-relation-kind={kind} data-relation-model={model}>
|
|
@@ -544,11 +821,11 @@ function OneToManyRelation({
|
|
|
544
821
|
/>
|
|
545
822
|
</div>
|
|
546
823
|
)}
|
|
547
|
-
{canCreate && (
|
|
824
|
+
{canCreate && !galleryColumn && (
|
|
548
825
|
<Button
|
|
549
826
|
size="sm"
|
|
550
827
|
variant="outline"
|
|
551
|
-
onClick={() => { setEditingRow(null); setFormOpen(true) }}
|
|
828
|
+
onClick={() => { setEditingRow(null); uploadedImageRef.current = null; setFormOpen(true) }}
|
|
552
829
|
>
|
|
553
830
|
<Plus className="h-4 w-4 mr-1" />
|
|
554
831
|
{labels.addLabel}
|
|
@@ -564,6 +841,30 @@ function OneToManyRelation({
|
|
|
564
841
|
<Skeleton key={`rel-skeleton-${i}`} className="h-10 w-full" />
|
|
565
842
|
))}
|
|
566
843
|
</div>
|
|
844
|
+
) : galleryColumn && fetchErrorStatus === null ? (
|
|
845
|
+
<RelationGallery
|
|
846
|
+
rows={orderedRows}
|
|
847
|
+
rowKey={(row, i) => relationRowKey(row, i, foreignKey)}
|
|
848
|
+
imageKey={galleryColumn.key}
|
|
849
|
+
captionKey={captionKey}
|
|
850
|
+
getImageUrl={(p) => getImageUrl(p)}
|
|
851
|
+
accept={(galleryColumn as any).accept || 'image/*'}
|
|
852
|
+
maxSize={(() => {
|
|
853
|
+
const sc = (galleryColumn.styleConfig ?? {}) as any
|
|
854
|
+
const n = Number(sc.max_size ?? sc.maxSize)
|
|
855
|
+
return Number.isFinite(n) && n > 0 ? n : undefined
|
|
856
|
+
})()}
|
|
857
|
+
canCreate={canCreate}
|
|
858
|
+
canEdit={canEdit}
|
|
859
|
+
canReorder={canEdit && !!positionKey}
|
|
860
|
+
canDelete={canDelete}
|
|
861
|
+
hiddenKeys={pendingDelete}
|
|
862
|
+
onUpload={galleryUpload}
|
|
863
|
+
onUploadsSettled={() => { void normalizePositions().then(() => refreshSilently()); onChange?.() }}
|
|
864
|
+
onReorder={galleryReorder}
|
|
865
|
+
onEdit={canEdit ? (row) => { setEditingRow(row); uploadedImageRef.current = null; setFormOpen(true) } : undefined}
|
|
866
|
+
onDelete={canDelete ? (row) => setRowToDelete(row) : undefined}
|
|
867
|
+
/>
|
|
567
868
|
) : rows.length === 0 ? (
|
|
568
869
|
<div className="text-center text-sm text-muted-foreground py-8 border rounded-md bg-muted/30">
|
|
569
870
|
{fetchErrorStatus === 403
|
|
@@ -637,7 +938,7 @@ function OneToManyRelation({
|
|
|
637
938
|
</div>
|
|
638
939
|
)}
|
|
639
940
|
|
|
640
|
-
<Dialog open={formOpen} onOpenChange={(open: boolean) => { setFormOpen(open); if (!open) setEditingRow(null) }}>
|
|
941
|
+
<Dialog open={formOpen} onOpenChange={(open: boolean) => { setFormOpen(open); if (!open) { setEditingRow(null); uploadedImageRef.current = null } }}>
|
|
641
942
|
{/* Alto acotado al viewport: el cuerpo del form hace scroll y el
|
|
642
943
|
footer (Guardar) queda fijo, para que un renglón con muchos
|
|
643
944
|
campos no deje el botón fuera de pantalla. */}
|
|
@@ -649,9 +950,10 @@ function OneToManyRelation({
|
|
|
649
950
|
key={editingRow ? `edit-${editingRow.id ?? ''}` : 'new'}
|
|
650
951
|
scrollableBody
|
|
651
952
|
fields={formFields}
|
|
652
|
-
initialValues={editingRow || undefined}
|
|
953
|
+
initialValues={editingRow || (Object.keys(createInitialValues).length ? createInitialValues : undefined)}
|
|
954
|
+
onFieldMeta={(_key, meta) => { uploadedImageRef.current = meta }}
|
|
653
955
|
onSubmit={handleSubmit}
|
|
654
|
-
onCancel={() => { setFormOpen(false); setEditingRow(null) }}
|
|
956
|
+
onCancel={() => { setFormOpen(false); setEditingRow(null); uploadedImageRef.current = null }}
|
|
655
957
|
submitLabel={labels.saveLabel}
|
|
656
958
|
cancelLabel={labels.cancelLabel}
|
|
657
959
|
disabled={submitting}
|
|
@@ -663,12 +965,24 @@ function OneToManyRelation({
|
|
|
663
965
|
<AlertDialogContent>
|
|
664
966
|
<AlertDialogHeader>
|
|
665
967
|
<AlertDialogTitle>{labels.confirmRemoveTitle}</AlertDialogTitle>
|
|
666
|
-
<AlertDialogDescription>
|
|
968
|
+
<AlertDialogDescription>
|
|
969
|
+
{galleryColumn
|
|
970
|
+
? (labels.confirmRemovePhotoDescription ?? 'Esta foto deja de verse en la tienda. Puedes deshacerlo unos segundos.')
|
|
971
|
+
: labels.confirmRemoveDescription}
|
|
972
|
+
</AlertDialogDescription>
|
|
667
973
|
</AlertDialogHeader>
|
|
668
974
|
<AlertDialogFooter>
|
|
669
975
|
<AlertDialogCancel disabled={submitting}>{labels.cancelLabel}</AlertDialogCancel>
|
|
670
976
|
<AlertDialogAction
|
|
671
|
-
onClick={(e: React.MouseEvent) => {
|
|
977
|
+
onClick={(e: React.MouseEvent) => {
|
|
978
|
+
e.preventDefault()
|
|
979
|
+
if (galleryColumn && rowToDelete) {
|
|
980
|
+
deleteWithUndo(rowToDelete)
|
|
981
|
+
setRowToDelete(null)
|
|
982
|
+
return
|
|
983
|
+
}
|
|
984
|
+
handleDelete()
|
|
985
|
+
}}
|
|
672
986
|
className="bg-red-600 hover:bg-red-700"
|
|
673
987
|
disabled={submitting}
|
|
674
988
|
>
|
package/src/index.ts
CHANGED
|
@@ -890,3 +890,15 @@ export {
|
|
|
890
890
|
type SplitActions,
|
|
891
891
|
} from './record-actions'
|
|
892
892
|
export * from './capability-providers'
|
|
893
|
+
export {
|
|
894
|
+
BulkImageImportButton,
|
|
895
|
+
BulkImageDialog,
|
|
896
|
+
type BulkImageImportButtonProps,
|
|
897
|
+
} from './bulk-image-dialog'
|
|
898
|
+
export {
|
|
899
|
+
buildPreview as buildBulkImagePreview,
|
|
900
|
+
parseImageName as parseBulkImageName,
|
|
901
|
+
deriveBulkImageTarget,
|
|
902
|
+
type BulkImageTarget,
|
|
903
|
+
type BatchLog as BulkImageBatchLog,
|
|
904
|
+
} from './bulk-image-import'
|