@asteby/metacore-runtime-react 53.10.2 → 53.11.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.
@@ -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,16 @@ import {
62
65
  diffSelection,
63
66
  extractSelectedTargetIds,
64
67
  pickOptionLabel,
68
+ relationColumnUi,
69
+ relationDerivedValues,
70
+ relationGalleryColumn,
71
+ relationInitialValues,
72
+ relationPositionKey,
73
+ relationPositionSortable,
65
74
  relationRowKey,
75
+ sortRelationRows,
66
76
  type DynamicRelationKind,
77
+ type ImageMeta,
67
78
  } from './dynamic-relation-helpers'
68
79
 
69
80
  export type { DynamicRelationKind } from './dynamic-relation-helpers'
@@ -102,6 +113,16 @@ export interface DynamicRelationStrings {
102
113
  searchPlaceholder: string
103
114
  /** Pie de la sub-tabla: "{{loaded}} de {{total}}". */
104
115
  countLabel: string
116
+ /** Galería: toast tras eliminar una foto. Default "Foto eliminada". */
117
+ deletedToast?: string
118
+ /** Galería: acción del toast. Default "Deshacer". */
119
+ undoLabel?: string
120
+ /** Galería: falla al guardar el orden. */
121
+ reorderError?: string
122
+ /** Galería: falla al eliminar. */
123
+ deleteError?: string
124
+ /** Galería: confirmación al eliminar una foto. Default "Esta foto deja de verse en la tienda. Puedes deshacerlo unos segundos." */
125
+ confirmRemovePhotoDescription?: string
105
126
  }
106
127
 
107
128
  const DEFAULT_STRINGS: DynamicRelationStrings = {
@@ -124,6 +145,7 @@ const DEFAULT_STRINGS: DynamicRelationStrings = {
124
145
  // Tamaño de página de la sub-tabla 1:N. Antes la lista pedía el hijo COMPLETO
125
146
  // (sin page/per_page), así que abrir un almacén traía todas sus existencias y
126
147
  // traspasos. Se pagina de a 25 y el resto entra por scroll infinito.
148
+ const GALLERY_PAGE_SIZE = 200
127
149
  const REL_PAGE_SIZE = 25
128
150
 
129
151
  interface CommonProps {
@@ -180,6 +202,12 @@ export interface DynamicRelationOneToManyProps extends CommonProps {
180
202
  foreignKey: string
181
203
  /** Endpoint override; default `/data/${model}`. */
182
204
  endpoint?: string
205
+ /**
206
+ * El registro padre. Solo lo leen los campos que declaran
207
+ * `display_config.default_from_parent` (p. ej. el nombre del producto como
208
+ * texto alternativo sugerido de una foto). Opcional.
209
+ */
210
+ parentRecord?: Record<string, unknown> | null
183
211
  }
184
212
 
185
213
  export interface DynamicRelationManyToManyProps extends CommonProps {
@@ -231,6 +259,7 @@ function OneToManyRelation({
231
259
  strings,
232
260
  className,
233
261
  onChange,
262
+ parentRecord,
234
263
  }: DynamicRelationOneToManyProps) {
235
264
  // Read-only relation always wins over host-passed perms (AND). Tolerates the
236
265
  // camelCase alias the same way lock_rows/lockRows does.
@@ -284,6 +313,7 @@ function OneToManyRelation({
284
313
  // resolverla dispararía un segundo fetch de datos por cada montaje.
285
314
  const metadataRef = useRef<TableMetadata | null>(metadata)
286
315
  metadataRef.current = metadata
316
+ const fetchPageRef = useRef<((p: number, append: boolean, silent?: boolean) => Promise<void>) | null>(null)
287
317
 
288
318
  // Debounce del buscador: cada tecla no puede pegarle al servidor.
289
319
  useEffect(() => {
@@ -329,25 +359,43 @@ function OneToManyRelation({
329
359
 
330
360
  // fetchPage REEMPLAZA (página 1) o ANEXA (scroll infinito). Antes esta lista
331
361
  // pedía el modelo hijo entero sin page/per_page.
332
- const fetchPage = useCallback(async (nextPage: number, append: boolean) => {
362
+ // silent: refresh page 1 without the skeleton (the gallery keeps its
363
+ // per-file upload list mounted while the new rows arrive).
364
+ const fetchPage = useCallback(async (nextPage: number, append: boolean, silent = false) => {
333
365
  if (append) setLoadingMore(true)
334
- else setLoading(true)
366
+ else if (!silent) setLoading(true)
335
367
  try {
336
368
  const params: Record<string, any> = {
337
369
  ...buildRelationFilterParams(foreignKey, parentId, filters),
338
370
  page: nextPage,
339
371
  per_page: REL_PAGE_SIZE,
340
372
  }
373
+ // A child model with an ordering column (`position`) lists in that
374
+ // order — the gallery's first image is the main one.
375
+ // Only when the column is declared sortable: a backend that cannot
376
+ // sort by it must not fail the whole list.
377
+ if (relationPositionSortable(metadataRef.current)) {
378
+ params.sortBy = 'position'
379
+ params.order = 'asc'
380
+ }
381
+ // A gallery shows every photo at once (no infinite scroll in the
382
+ // grid) and numbers new ones past the highest loaded position.
383
+ if (relationGalleryColumn(metadataRef.current)) params.per_page = GALLERY_PAGE_SIZE
341
384
  if (debouncedSearch) params.search = debouncedSearch
342
385
  const askedScope = cacheScope()
343
386
  const [metaRes, dataRes] = await Promise.all([
344
387
  metadataRef.current ? Promise.resolve(null) : api.get(`/metadata/table/${model}`),
345
388
  api.get(dataEndpoint, { params }),
346
389
  ])
390
+ let refetchOrdered = false
347
391
  if (metaRes && (metaRes as any).data?.success) {
348
392
  const fresh = (metaRes as { data: ApiResponse<TableMetadata> }).data.data
349
393
  setMetadata(fresh)
394
+ metadataRef.current = fresh
350
395
  cacheMetadata(model, fresh, { scope: askedScope })
396
+ // Cold cache: this page went out before we knew the child has a
397
+ // gallery / sortable position — ask again in that order and size.
398
+ refetchOrdered = !append && (!!relationGalleryColumn(fresh) || relationPositionSortable(fresh))
351
399
  }
352
400
  const list = (dataRes as { data: ApiResponse<any[]> }).data
353
401
  setFetchErrorStatus(null)
@@ -359,20 +407,28 @@ function OneToManyRelation({
359
407
  else if (!append) setTotal(fetched.length)
360
408
  setExhausted(fetched.length < REL_PAGE_SIZE)
361
409
  }
410
+ if (refetchOrdered) {
411
+ void fetchPageRef.current?.(1, false, true)
412
+ }
362
413
  } catch (err) {
363
414
  console.error('DynamicRelation fetch error', err)
364
415
  setFetchErrorStatus((err as { response?: { status?: number } })?.response?.status ?? 0)
365
416
  } finally {
366
417
  if (append) setLoadingMore(false)
367
- else setLoading(false)
418
+ else if (!silent) setLoading(false)
368
419
  }
369
420
  // eslint-disable-next-line react-hooks/exhaustive-deps
370
421
  }, [api, dataEndpoint, foreignKey, parentId, filtersKey, model, cacheMetadata, debouncedSearch])
371
422
 
423
+ fetchPageRef.current = fetchPage
424
+
372
425
  // Recarga desde la primera página. Es lo que corren create/edit/delete.
373
426
  const fetchAll = useCallback(async () => {
374
427
  await fetchPage(1, false)
375
428
  }, [fetchPage])
429
+ const refreshSilently = useCallback(async () => {
430
+ await fetchPage(1, false, true)
431
+ }, [fetchPage])
376
432
 
377
433
  // Un cambio de padre/scope/búsqueda vuelve a la página 1.
378
434
  useEffect(() => { fetchPage(1, false) }, [fetchPage])
@@ -386,13 +442,32 @@ function OneToManyRelation({
386
442
  // El buscador solo aparece cuando hay algo que buscar: una sub-tabla de 3
387
443
  // líneas no necesita chrome extra. Se queda visible mientras haya término
388
444
  // activo para no dejar al usuario sin forma de limpiarlo.
389
- const showSearch = debouncedSearch !== '' || search !== '' || total > REL_PAGE_SIZE
445
+ const isGallery = !!relationGalleryColumn(metadata)
446
+ const showSearch = !isGallery && (debouncedSearch !== '' || search !== '' || total > REL_PAGE_SIZE)
390
447
 
391
448
  const formFields = useMemo(
392
449
  () => deriveRelationFormFields(metadata, foreignKey),
393
450
  [metadata, foreignKey],
394
451
  )
395
452
 
453
+ // Ordered view of the loaded rows (also covers the first page, fetched
454
+ // before the metadata told us there is a position column).
455
+ const positionKey = useMemo(() => relationPositionKey(metadata), [metadata])
456
+ const orderedRows = useMemo(() => sortRelationRows(rows, positionKey), [rows, positionKey])
457
+ const galleryColumn = useMemo(() => relationGalleryColumn(metadata), [metadata])
458
+ const captionKey = useMemo(
459
+ () => metadata?.columns?.find((c) => relationColumnUi(c).defaultFromParent)?.key,
460
+ [metadata],
461
+ )
462
+ const createInitialValues = useMemo(
463
+ () => relationInitialValues(metadata, parentRecord),
464
+ [metadata, parentRecord],
465
+ )
466
+ // Size of the image uploaded in the open form (fills derived width/height).
467
+ const uploadedImageRef = useRef<ImageMeta | null>(null)
468
+ // Rows deleted from the gallery but still undoable.
469
+ const [pendingDelete, setPendingDelete] = useState<Set<string>>(new Set())
470
+
396
471
  const visibleColumns = useMemo(() => {
397
472
  if (!metadata?.columns) return []
398
473
  // Hide the FK and every scope column — they're fixed for this parent and
@@ -457,7 +532,7 @@ function OneToManyRelation({
457
532
  <Button
458
533
  size="sm"
459
534
  variant="ghost"
460
- onClick={() => { setEditingRow(row.original); setFormOpen(true) }}
535
+ onClick={() => { setEditingRow(row.original); uploadedImageRef.current = null; setFormOpen(true) }}
461
536
  aria-label={labels.editLabel}
462
537
  >
463
538
  <Pencil className="h-4 w-4" />
@@ -480,13 +555,21 @@ function OneToManyRelation({
480
555
  }, [metadata, visibleColumns, buildColumns, i18n?.language, timeZone, currency, showActions, canEdit, canDelete, labels.editLabel, labels.removeLabel])
481
556
 
482
557
  const table = useReactTable({
483
- data: rows,
558
+ data: orderedRows,
484
559
  columns,
485
560
  getCoreRowModel: getCoreRowModel(),
486
561
  })
487
562
 
488
563
  const handleSubmit = useCallback(async (values: Record<string, any>) => {
489
564
  setSubmitting(true)
565
+ // Derived columns (image size, next position) travel with the row even
566
+ // though they are not form inputs.
567
+ const derived = relationDerivedValues(metadata, {
568
+ isCreate: !editingRow,
569
+ rows,
570
+ image: uploadedImageRef.current,
571
+ })
572
+ values = { ...values, ...derived }
490
573
  try {
491
574
  if (editingRow) {
492
575
  const res = await api.put(`${dataEndpoint}/${editingRow.id}`, values)
@@ -501,6 +584,7 @@ function OneToManyRelation({
501
584
  }
502
585
  setFormOpen(false)
503
586
  setEditingRow(null)
587
+ uploadedImageRef.current = null
504
588
  await fetchAll()
505
589
  onChange?.()
506
590
  } catch (err) {
@@ -509,7 +593,129 @@ function OneToManyRelation({
509
593
  setSubmitting(false)
510
594
  }
511
595
  // eslint-disable-next-line react-hooks/exhaustive-deps
512
- }, [api, dataEndpoint, editingRow, fetchAll, foreignKey, filtersKey, onChange, parentId])
596
+ }, [api, dataEndpoint, editingRow, fetchAll, foreignKey, filtersKey, onChange, parentId, metadata, rows])
597
+
598
+ // ── Gallery (opt-in: image column with display_config.gallery) ─────────
599
+ // Same contracts as the table: POST /upload (multipart) for the file, then
600
+ // POST /data/<model> for the row. Positions are assigned in pick order.
601
+ const galleryUpload = useCallback(
602
+ async (file: File, offset: number, onProgress: (f: number) => void, reuseUrl?: string) => {
603
+ if (!galleryColumn) return
604
+ const size = await readImageSize(file)
605
+ let url = reuseUrl
606
+ if (!url) {
607
+ const form = new FormData()
608
+ form.append('file', file)
609
+ const folder = (galleryColumn.styleConfig as any)?.storage_path ?? (galleryColumn.styleConfig as any)?.storagePath
610
+ if (folder) {
611
+ form.append('folder', folder)
612
+ form.append('storage_path', folder)
613
+ }
614
+ const up = await api.post('/upload', form, {
615
+ headers: { 'Content-Type': 'multipart/form-data' },
616
+ onUploadProgress: (e: { loaded: number; total?: number }) => {
617
+ if (e.total) onProgress((e.loaded / e.total) * 0.9)
618
+ },
619
+ } as any)
620
+ const body = (up as { data?: any })?.data
621
+ if (body && body.success === false) throw new Error(body.message || 'upload failed')
622
+ url = extractUploadedValue(body)
623
+ if (!url) throw new Error('upload failed')
624
+ }
625
+ const derived = relationDerivedValues(metadata, { isCreate: true, rows, image: size })
626
+ if (positionKey && typeof derived[positionKey] === 'number') derived[positionKey] += offset
627
+ const payload = {
628
+ ...(filters || {}),
629
+ ...buildCreatePayload(foreignKey, parentId, {
630
+ ...createInitialValues,
631
+ ...derived,
632
+ [galleryColumn.key]: url,
633
+ }),
634
+ }
635
+ try {
636
+ const res = await api.post(dataEndpoint, payload)
637
+ if (!(res as any).data?.success) throw new Error((res as any).data?.message || 'create failed')
638
+ } catch (err: any) {
639
+ // The file is already stored: a retry reuses it instead of
640
+ // uploading (and orphaning) a second copy.
641
+ throw Object.assign(err instanceof Error ? err : new Error(String(err)), { uploadedUrl: url })
642
+ }
643
+ onProgress(1)
644
+ },
645
+ // eslint-disable-next-line react-hooks/exhaustive-deps
646
+ [api, galleryColumn, metadata, rows, positionKey, filtersKey, foreignKey, parentId, createInitialValues, dataEndpoint],
647
+ )
648
+
649
+ const galleryReorder = useCallback(
650
+ async (ordered: Record<string, any>[]) => {
651
+ if (!positionKey) return
652
+ // Optimistic: show the new order now, persist only what changed.
653
+ setRows(ordered.map((r, i) => ({ ...r, [positionKey]: i })))
654
+ try {
655
+ await Promise.all(
656
+ ordered.map((r, i) => {
657
+ const raw = r[positionKey]
658
+ const same = raw !== null && raw !== undefined && raw !== '' && Number(raw) === i
659
+ return same ? null : api.put(`${dataEndpoint}/${r.id}`, { [positionKey]: i })
660
+ }),
661
+ )
662
+ onChange?.()
663
+ } catch (err) {
664
+ console.error('DynamicRelation reorder error', err)
665
+ toast.error(labels.reorderError ?? 'No se pudo guardar el nuevo orden.')
666
+ } finally {
667
+ await refreshSilently()
668
+ }
669
+ },
670
+ // eslint-disable-next-line react-hooks/exhaustive-deps
671
+ [api, dataEndpoint, positionKey, refreshSilently, onChange],
672
+ )
673
+
674
+ // Confirmed delete → hidden at once, «Deshacer» for a few seconds, then the
675
+ // real DELETE. Closing the panel before the toast ends still deletes.
676
+ const deleteWithUndo = useCallback(
677
+ (row: any) => {
678
+ const key = String(row.id)
679
+ setPendingDelete((s) => new Set(s).add(key))
680
+ let undone = false
681
+ const commit = async () => {
682
+ if (undone) return
683
+ try {
684
+ const res = await api.delete(`${dataEndpoint}/${row.id}`)
685
+ if (!(res as any).data?.success) throw new Error('delete failed')
686
+ onChange?.()
687
+ } catch (err) {
688
+ console.error('DynamicRelation delete error', err)
689
+ toast.error(labels.deleteError ?? 'No se pudo eliminar.')
690
+ } finally {
691
+ setPendingDelete((s) => {
692
+ const n = new Set(s)
693
+ n.delete(key)
694
+ return n
695
+ })
696
+ await refreshSilently()
697
+ }
698
+ }
699
+ const timer = setTimeout(() => void commit(), 6000)
700
+ toast(labels.deletedToast ?? 'Foto eliminada', {
701
+ duration: 6000,
702
+ action: {
703
+ label: labels.undoLabel ?? 'Deshacer',
704
+ onClick: () => {
705
+ undone = true
706
+ clearTimeout(timer)
707
+ setPendingDelete((s) => {
708
+ const n = new Set(s)
709
+ n.delete(key)
710
+ return n
711
+ })
712
+ },
713
+ },
714
+ })
715
+ },
716
+ // eslint-disable-next-line react-hooks/exhaustive-deps
717
+ [api, dataEndpoint, refreshSilently, onChange],
718
+ )
513
719
 
514
720
  const handleDelete = useCallback(async () => {
515
721
  if (!rowToDelete) return
@@ -544,11 +750,11 @@ function OneToManyRelation({
544
750
  />
545
751
  </div>
546
752
  )}
547
- {canCreate && (
753
+ {canCreate && !galleryColumn && (
548
754
  <Button
549
755
  size="sm"
550
756
  variant="outline"
551
- onClick={() => { setEditingRow(null); setFormOpen(true) }}
757
+ onClick={() => { setEditingRow(null); uploadedImageRef.current = null; setFormOpen(true) }}
552
758
  >
553
759
  <Plus className="h-4 w-4 mr-1" />
554
760
  {labels.addLabel}
@@ -564,6 +770,30 @@ function OneToManyRelation({
564
770
  <Skeleton key={`rel-skeleton-${i}`} className="h-10 w-full" />
565
771
  ))}
566
772
  </div>
773
+ ) : galleryColumn && fetchErrorStatus === null ? (
774
+ <RelationGallery
775
+ rows={orderedRows}
776
+ rowKey={(row, i) => relationRowKey(row, i, foreignKey)}
777
+ imageKey={galleryColumn.key}
778
+ captionKey={captionKey}
779
+ getImageUrl={(p) => getImageUrl(p)}
780
+ accept={(galleryColumn as any).accept || 'image/*'}
781
+ maxSize={(() => {
782
+ const sc = (galleryColumn.styleConfig ?? {}) as any
783
+ const n = Number(sc.max_size ?? sc.maxSize)
784
+ return Number.isFinite(n) && n > 0 ? n : undefined
785
+ })()}
786
+ canCreate={canCreate}
787
+ canEdit={canEdit}
788
+ canReorder={canEdit && !!positionKey}
789
+ canDelete={canDelete}
790
+ hiddenKeys={pendingDelete}
791
+ onUpload={galleryUpload}
792
+ onUploadsSettled={() => { void refreshSilently(); onChange?.() }}
793
+ onReorder={galleryReorder}
794
+ onEdit={canEdit ? (row) => { setEditingRow(row); uploadedImageRef.current = null; setFormOpen(true) } : undefined}
795
+ onDelete={canDelete ? (row) => setRowToDelete(row) : undefined}
796
+ />
567
797
  ) : rows.length === 0 ? (
568
798
  <div className="text-center text-sm text-muted-foreground py-8 border rounded-md bg-muted/30">
569
799
  {fetchErrorStatus === 403
@@ -637,7 +867,7 @@ function OneToManyRelation({
637
867
  </div>
638
868
  )}
639
869
 
640
- <Dialog open={formOpen} onOpenChange={(open: boolean) => { setFormOpen(open); if (!open) setEditingRow(null) }}>
870
+ <Dialog open={formOpen} onOpenChange={(open: boolean) => { setFormOpen(open); if (!open) { setEditingRow(null); uploadedImageRef.current = null } }}>
641
871
  {/* Alto acotado al viewport: el cuerpo del form hace scroll y el
642
872
  footer (Guardar) queda fijo, para que un renglón con muchos
643
873
  campos no deje el botón fuera de pantalla. */}
@@ -649,9 +879,10 @@ function OneToManyRelation({
649
879
  key={editingRow ? `edit-${editingRow.id ?? ''}` : 'new'}
650
880
  scrollableBody
651
881
  fields={formFields}
652
- initialValues={editingRow || undefined}
882
+ initialValues={editingRow || (Object.keys(createInitialValues).length ? createInitialValues : undefined)}
883
+ onFieldMeta={(_key, meta) => { uploadedImageRef.current = meta }}
653
884
  onSubmit={handleSubmit}
654
- onCancel={() => { setFormOpen(false); setEditingRow(null) }}
885
+ onCancel={() => { setFormOpen(false); setEditingRow(null); uploadedImageRef.current = null }}
655
886
  submitLabel={labels.saveLabel}
656
887
  cancelLabel={labels.cancelLabel}
657
888
  disabled={submitting}
@@ -663,12 +894,24 @@ function OneToManyRelation({
663
894
  <AlertDialogContent>
664
895
  <AlertDialogHeader>
665
896
  <AlertDialogTitle>{labels.confirmRemoveTitle}</AlertDialogTitle>
666
- <AlertDialogDescription>{labels.confirmRemoveDescription}</AlertDialogDescription>
897
+ <AlertDialogDescription>
898
+ {galleryColumn
899
+ ? (labels.confirmRemovePhotoDescription ?? 'Esta foto deja de verse en la tienda. Puedes deshacerlo unos segundos.')
900
+ : labels.confirmRemoveDescription}
901
+ </AlertDialogDescription>
667
902
  </AlertDialogHeader>
668
903
  <AlertDialogFooter>
669
904
  <AlertDialogCancel disabled={submitting}>{labels.cancelLabel}</AlertDialogCancel>
670
905
  <AlertDialogAction
671
- onClick={(e: React.MouseEvent) => { e.preventDefault(); handleDelete() }}
906
+ onClick={(e: React.MouseEvent) => {
907
+ e.preventDefault()
908
+ if (galleryColumn && rowToDelete) {
909
+ deleteWithUndo(rowToDelete)
910
+ setRowToDelete(null)
911
+ return
912
+ }
913
+ handleDelete()
914
+ }}
672
915
  className="bg-red-600 hover:bg-red-700"
673
916
  disabled={submitting}
674
917
  >
@@ -204,6 +204,7 @@ export function DynamicRelations({
204
204
  canEdit={canEdit}
205
205
  readonly={relReadonly}
206
206
  strings={panelStrings}
207
+ parentRecord={record}
207
208
  onChange={onChange ? () => onChange(rel) : undefined}
208
209
  />
209
210
  )