@asteby/metacore-runtime-react 53.11.0 → 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.
@@ -67,6 +67,7 @@ import {
67
67
  pickOptionLabel,
68
68
  relationColumnUi,
69
69
  relationDerivedValues,
70
+ contiguousPositionUpdates,
70
71
  relationGalleryColumn,
71
72
  relationInitialValues,
72
73
  relationPositionKey,
@@ -595,11 +596,73 @@ function OneToManyRelation({
595
596
  // eslint-disable-next-line react-hooks/exhaustive-deps
596
597
  }, [api, dataEndpoint, editingRow, fetchAll, foreignKey, filtersKey, onChange, parentId, metadata, rows])
597
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
+
598
661
  // ── Gallery (opt-in: image column with display_config.gallery) ─────────
599
662
  // Same contracts as the table: POST /upload (multipart) for the file, then
600
663
  // POST /data/<model> for the row. Positions are assigned in pick order.
601
664
  const galleryUpload = useCallback(
602
- async (file: File, offset: number, onProgress: (f: number) => void, reuseUrl?: string) => {
665
+ async (file: File, _offset: number, onProgress: (f: number) => void, reuseUrl?: string) => {
603
666
  if (!galleryColumn) return
604
667
  const size = await readImageSize(file)
605
668
  let url = reuseUrl
@@ -623,7 +686,10 @@ function OneToManyRelation({
623
686
  if (!url) throw new Error('upload failed')
624
687
  }
625
688
  const derived = relationDerivedValues(metadata, { isCreate: true, rows, image: size })
626
- if (positionKey && typeof derived[positionKey] === 'number') derived[positionKey] += offset
689
+ if (positionKey && typeof derived[positionKey] === 'number') {
690
+ derived[positionKey] = Math.max(derived[positionKey], createdMaxPositionRef.current + 1)
691
+ createdMaxPositionRef.current = derived[positionKey]
692
+ }
627
693
  const payload = {
628
694
  ...(filters || {}),
629
695
  ...buildCreatePayload(foreignKey, parentId, {
@@ -651,24 +717,26 @@ function OneToManyRelation({
651
717
  if (!positionKey) return
652
718
  // Optimistic: show the new order now, persist only what changed.
653
719
  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
- }
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
+ })
669
737
  },
670
738
  // eslint-disable-next-line react-hooks/exhaustive-deps
671
- [api, dataEndpoint, positionKey, refreshSilently, onChange],
739
+ [api, dataEndpoint, positionKey, refreshSilently, onChange, enqueuePositions],
672
740
  )
673
741
 
674
742
  // Confirmed delete → hidden at once, «Deshacer» for a few seconds, then the
@@ -683,6 +751,7 @@ function OneToManyRelation({
683
751
  try {
684
752
  const res = await api.delete(`${dataEndpoint}/${row.id}`)
685
753
  if (!(res as any).data?.success) throw new Error('delete failed')
754
+ await normalizePositions()
686
755
  onChange?.()
687
756
  } catch (err) {
688
757
  console.error('DynamicRelation delete error', err)
@@ -704,6 +773,7 @@ function OneToManyRelation({
704
773
  onClick: () => {
705
774
  undone = true
706
775
  clearTimeout(timer)
776
+ void normalizePositions().then(() => refreshSilently())
707
777
  setPendingDelete((s) => {
708
778
  const n = new Set(s)
709
779
  n.delete(key)
@@ -714,7 +784,7 @@ function OneToManyRelation({
714
784
  })
715
785
  },
716
786
  // eslint-disable-next-line react-hooks/exhaustive-deps
717
- [api, dataEndpoint, refreshSilently, onChange],
787
+ [api, dataEndpoint, refreshSilently, onChange, normalizePositions],
718
788
  )
719
789
 
720
790
  const handleDelete = useCallback(async () => {
@@ -725,13 +795,14 @@ function OneToManyRelation({
725
795
  if (!(res as any).data?.success) throw new Error('delete failed')
726
796
  setRowToDelete(null)
727
797
  await fetchAll()
798
+ void normalizePositions().then(() => refreshSilently())
728
799
  onChange?.()
729
800
  } catch (err) {
730
801
  console.error('DynamicRelation delete error', err)
731
802
  } finally {
732
803
  setSubmitting(false)
733
804
  }
734
- }, [api, dataEndpoint, fetchAll, onChange, rowToDelete])
805
+ }, [api, dataEndpoint, fetchAll, onChange, rowToDelete, normalizePositions, refreshSilently])
735
806
 
736
807
  return (
737
808
  <div className={className} data-relation-kind={kind} data-relation-model={model}>
@@ -789,7 +860,7 @@ function OneToManyRelation({
789
860
  canDelete={canDelete}
790
861
  hiddenKeys={pendingDelete}
791
862
  onUpload={galleryUpload}
792
- onUploadsSettled={() => { void refreshSilently(); onChange?.() }}
863
+ onUploadsSettled={() => { void normalizePositions().then(() => refreshSilently()); onChange?.() }}
793
864
  onReorder={galleryReorder}
794
865
  onEdit={canEdit ? (row) => { setEditingRow(row); uploadedImageRef.current = null; setFormOpen(true) } : undefined}
795
866
  onDelete={canDelete ? (row) => setRowToDelete(row) : undefined}
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'
@@ -404,7 +404,7 @@ function GalleryTile({
404
404
  ref={setNodeRef}
405
405
  style={{ transform: CSS.Transform.toString(transform), transition }}
406
406
  className={cn(
407
- 'group relative overflow-hidden rounded-lg border bg-card',
407
+ 'group relative min-w-0 overflow-hidden rounded-lg border bg-card',
408
408
  isMain && 'ring-2 ring-primary',
409
409
  isDragging && 'z-10 opacity-80 shadow-lg',
410
410
  )}
@@ -428,8 +428,9 @@ function GalleryTile({
428
428
  {mainLabel}
429
429
  </span>
430
430
  )}
431
- <div className="flex items-center justify-between gap-1 border-t bg-card px-1 py-1">
432
- <div className="flex items-center">
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">
433
434
  {canReorder && (
434
435
  <>
435
436
  <Button
@@ -470,7 +471,7 @@ function GalleryTile({
470
471
  </>
471
472
  )}
472
473
  </div>
473
- <div className="flex items-center">
474
+ <div className="flex flex-wrap items-center">
474
475
  {canEdit && onEdit && (
475
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' })}>
476
477
  <Pencil className="h-4 w-4" />