@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.
@@ -21,7 +21,10 @@ import { makeDefaultGetDynamicColumns } from './dynamic-columns';
21
21
  import { isColumnVisibleInLineSubtable } from './column-visibility';
22
22
  import { useOptionsResolver } from './use-options-resolver';
23
23
  import { dedupeById, useInfiniteScrollSentinel } from './use-infinite-scroll';
24
- import { buildCreatePayload, buildPivotAttachPayload, buildPivotRowIndex, buildRelationFilterParams, deriveRelationFormFields, diffSelection, extractSelectedTargetIds, pickOptionLabel, relationRowKey, } from './dynamic-relation-helpers';
24
+ import { toast } from 'sonner';
25
+ import { RelationGallery } from './relation-gallery';
26
+ import { extractUploadedValue, readImageSize } from './upload-field';
27
+ import { buildCreatePayload, buildPivotAttachPayload, buildPivotRowIndex, buildRelationFilterParams, deriveRelationFormFields, diffSelection, extractSelectedTargetIds, pickOptionLabel, relationColumnUi, relationDerivedValues, relationGalleryColumn, relationInitialValues, relationPositionKey, relationPositionSortable, relationRowKey, sortRelationRows, } from './dynamic-relation-helpers';
25
28
  export { buildCreatePayload, buildPivotAttachPayload, buildPivotRowIndex, buildRelationFilterParams, deriveRelationFormFields, diffSelection, extractSelectedTargetIds, formatRelationCell, objectLabel, pickOptionLabel, relationRowKey, } from './dynamic-relation-helpers';
26
29
  const DEFAULT_STRINGS = {
27
30
  title: '',
@@ -42,6 +45,7 @@ const DEFAULT_STRINGS = {
42
45
  // Tamaño de página de la sub-tabla 1:N. Antes la lista pedía el hijo COMPLETO
43
46
  // (sin page/per_page), así que abrir un almacén traía todas sus existencias y
44
47
  // traspasos. Se pagina de a 25 y el resto entra por scroll infinito.
48
+ const GALLERY_PAGE_SIZE = 200;
45
49
  const REL_PAGE_SIZE = 25;
46
50
  export function DynamicRelation(props) {
47
51
  if (props.kind === 'many_to_many') {
@@ -49,7 +53,7 @@ export function DynamicRelation(props) {
49
53
  }
50
54
  return _jsx(OneToManyRelation, { ...props });
51
55
  }
52
- function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoint, hiddenColumns = [], lineSubtable = false, canCreate = true, canDelete = true, canEdit = true, readonly, readOnly, strings, className, onChange, }) {
56
+ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoint, hiddenColumns = [], lineSubtable = false, canCreate = true, canDelete = true, canEdit = true, readonly, readOnly, strings, className, onChange, parentRecord, }) {
53
57
  // Read-only relation always wins over host-passed perms (AND). Tolerates the
54
58
  // camelCase alias the same way lock_rows/lockRows does.
55
59
  const isReadonly = readonly === true || readOnly === true;
@@ -99,6 +103,7 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
99
103
  // resolverla dispararía un segundo fetch de datos por cada montaje.
100
104
  const metadataRef = useRef(metadata);
101
105
  metadataRef.current = metadata;
106
+ const fetchPageRef = useRef(null);
102
107
  // Debounce del buscador: cada tecla no puede pegarle al servidor.
103
108
  useEffect(() => {
104
109
  const id = setTimeout(() => setDebouncedSearch(search.trim()), 300);
@@ -139,10 +144,12 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
139
144
  const optionsCtx = useMemo(() => ({ optionsMap }), [optionsMap]);
140
145
  // fetchPage REEMPLAZA (página 1) o ANEXA (scroll infinito). Antes esta lista
141
146
  // pedía el modelo hijo entero sin page/per_page.
142
- const fetchPage = useCallback(async (nextPage, append) => {
147
+ // silent: refresh page 1 without the skeleton (the gallery keeps its
148
+ // per-file upload list mounted while the new rows arrive).
149
+ const fetchPage = useCallback(async (nextPage, append, silent = false) => {
143
150
  if (append)
144
151
  setLoadingMore(true);
145
- else
152
+ else if (!silent)
146
153
  setLoading(true);
147
154
  try {
148
155
  const params = {
@@ -150,6 +157,18 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
150
157
  page: nextPage,
151
158
  per_page: REL_PAGE_SIZE,
152
159
  };
160
+ // A child model with an ordering column (`position`) lists in that
161
+ // order — the gallery's first image is the main one.
162
+ // Only when the column is declared sortable: a backend that cannot
163
+ // sort by it must not fail the whole list.
164
+ if (relationPositionSortable(metadataRef.current)) {
165
+ params.sortBy = 'position';
166
+ params.order = 'asc';
167
+ }
168
+ // A gallery shows every photo at once (no infinite scroll in the
169
+ // grid) and numbers new ones past the highest loaded position.
170
+ if (relationGalleryColumn(metadataRef.current))
171
+ params.per_page = GALLERY_PAGE_SIZE;
153
172
  if (debouncedSearch)
154
173
  params.search = debouncedSearch;
155
174
  const askedScope = cacheScope();
@@ -157,10 +176,15 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
157
176
  metadataRef.current ? Promise.resolve(null) : api.get(`/metadata/table/${model}`),
158
177
  api.get(dataEndpoint, { params }),
159
178
  ]);
179
+ let refetchOrdered = false;
160
180
  if (metaRes && metaRes.data?.success) {
161
181
  const fresh = metaRes.data.data;
162
182
  setMetadata(fresh);
183
+ metadataRef.current = fresh;
163
184
  cacheMetadata(model, fresh, { scope: askedScope });
185
+ // Cold cache: this page went out before we knew the child has a
186
+ // gallery / sortable position — ask again in that order and size.
187
+ refetchOrdered = !append && (!!relationGalleryColumn(fresh) || relationPositionSortable(fresh));
164
188
  }
165
189
  const list = dataRes.data;
166
190
  setFetchErrorStatus(null);
@@ -174,6 +198,9 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
174
198
  setTotal(fetched.length);
175
199
  setExhausted(fetched.length < REL_PAGE_SIZE);
176
200
  }
201
+ if (refetchOrdered) {
202
+ void fetchPageRef.current?.(1, false, true);
203
+ }
177
204
  }
178
205
  catch (err) {
179
206
  console.error('DynamicRelation fetch error', err);
@@ -182,15 +209,19 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
182
209
  finally {
183
210
  if (append)
184
211
  setLoadingMore(false);
185
- else
212
+ else if (!silent)
186
213
  setLoading(false);
187
214
  }
188
215
  // eslint-disable-next-line react-hooks/exhaustive-deps
189
216
  }, [api, dataEndpoint, foreignKey, parentId, filtersKey, model, cacheMetadata, debouncedSearch]);
217
+ fetchPageRef.current = fetchPage;
190
218
  // Recarga desde la primera página. Es lo que corren create/edit/delete.
191
219
  const fetchAll = useCallback(async () => {
192
220
  await fetchPage(1, false);
193
221
  }, [fetchPage]);
222
+ const refreshSilently = useCallback(async () => {
223
+ await fetchPage(1, false, true);
224
+ }, [fetchPage]);
194
225
  // Un cambio de padre/scope/búsqueda vuelve a la página 1.
195
226
  useEffect(() => { fetchPage(1, false); }, [fetchPage]);
196
227
  const canLoadMore = !loading && !loadingMore && !exhausted && rows.length < total;
@@ -202,8 +233,20 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
202
233
  // El buscador solo aparece cuando hay algo que buscar: una sub-tabla de 3
203
234
  // líneas no necesita chrome extra. Se queda visible mientras haya término
204
235
  // activo para no dejar al usuario sin forma de limpiarlo.
205
- const showSearch = debouncedSearch !== '' || search !== '' || total > REL_PAGE_SIZE;
236
+ const isGallery = !!relationGalleryColumn(metadata);
237
+ const showSearch = !isGallery && (debouncedSearch !== '' || search !== '' || total > REL_PAGE_SIZE);
206
238
  const formFields = useMemo(() => deriveRelationFormFields(metadata, foreignKey), [metadata, foreignKey]);
239
+ // Ordered view of the loaded rows (also covers the first page, fetched
240
+ // before the metadata told us there is a position column).
241
+ const positionKey = useMemo(() => relationPositionKey(metadata), [metadata]);
242
+ const orderedRows = useMemo(() => sortRelationRows(rows, positionKey), [rows, positionKey]);
243
+ const galleryColumn = useMemo(() => relationGalleryColumn(metadata), [metadata]);
244
+ const captionKey = useMemo(() => metadata?.columns?.find((c) => relationColumnUi(c).defaultFromParent)?.key, [metadata]);
245
+ const createInitialValues = useMemo(() => relationInitialValues(metadata, parentRecord), [metadata, parentRecord]);
246
+ // Size of the image uploaded in the open form (fills derived width/height).
247
+ const uploadedImageRef = useRef(null);
248
+ // Rows deleted from the gallery but still undoable.
249
+ const [pendingDelete, setPendingDelete] = useState(new Set());
207
250
  const visibleColumns = useMemo(() => {
208
251
  if (!metadata?.columns)
209
252
  return [];
@@ -249,17 +292,25 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
249
292
  id: 'actions',
250
293
  header: () => _jsx("span", { className: "sr-only", children: labels.editLabel }),
251
294
  size: 80,
252
- cell: ({ row }) => (_jsxs("div", { className: "flex items-center justify-end gap-1", children: [canEdit && (_jsx(Button, { size: "sm", variant: "ghost", onClick: () => { setEditingRow(row.original); setFormOpen(true); }, "aria-label": labels.editLabel, children: _jsx(Pencil, { className: "h-4 w-4" }) })), canDelete && (_jsx(Button, { size: "sm", variant: "ghost", onClick: () => setRowToDelete(row.original), "aria-label": labels.removeLabel, children: _jsx(Trash2, { className: "h-4 w-4" }) }))] })),
295
+ cell: ({ row }) => (_jsxs("div", { className: "flex items-center justify-end gap-1", children: [canEdit && (_jsx(Button, { size: "sm", variant: "ghost", onClick: () => { setEditingRow(row.original); uploadedImageRef.current = null; setFormOpen(true); }, "aria-label": labels.editLabel, children: _jsx(Pencil, { className: "h-4 w-4" }) })), canDelete && (_jsx(Button, { size: "sm", variant: "ghost", onClick: () => setRowToDelete(row.original), "aria-label": labels.removeLabel, children: _jsx(Trash2, { className: "h-4 w-4" }) }))] })),
253
296
  };
254
297
  return [...base, actionsCol];
255
298
  }, [metadata, visibleColumns, buildColumns, i18n?.language, timeZone, currency, showActions, canEdit, canDelete, labels.editLabel, labels.removeLabel]);
256
299
  const table = useReactTable({
257
- data: rows,
300
+ data: orderedRows,
258
301
  columns,
259
302
  getCoreRowModel: getCoreRowModel(),
260
303
  });
261
304
  const handleSubmit = useCallback(async (values) => {
262
305
  setSubmitting(true);
306
+ // Derived columns (image size, next position) travel with the row even
307
+ // though they are not form inputs.
308
+ const derived = relationDerivedValues(metadata, {
309
+ isCreate: !editingRow,
310
+ rows,
311
+ image: uploadedImageRef.current,
312
+ });
313
+ values = { ...values, ...derived };
263
314
  try {
264
315
  if (editingRow) {
265
316
  const res = await api.put(`${dataEndpoint}/${editingRow.id}`, values);
@@ -277,6 +328,7 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
277
328
  }
278
329
  setFormOpen(false);
279
330
  setEditingRow(null);
331
+ uploadedImageRef.current = null;
280
332
  await fetchAll();
281
333
  onChange?.();
282
334
  }
@@ -287,7 +339,132 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
287
339
  setSubmitting(false);
288
340
  }
289
341
  // eslint-disable-next-line react-hooks/exhaustive-deps
290
- }, [api, dataEndpoint, editingRow, fetchAll, foreignKey, filtersKey, onChange, parentId]);
342
+ }, [api, dataEndpoint, editingRow, fetchAll, foreignKey, filtersKey, onChange, parentId, metadata, rows]);
343
+ // ── Gallery (opt-in: image column with display_config.gallery) ─────────
344
+ // Same contracts as the table: POST /upload (multipart) for the file, then
345
+ // POST /data/<model> for the row. Positions are assigned in pick order.
346
+ const galleryUpload = useCallback(async (file, offset, onProgress, reuseUrl) => {
347
+ if (!galleryColumn)
348
+ return;
349
+ const size = await readImageSize(file);
350
+ let url = reuseUrl;
351
+ if (!url) {
352
+ const form = new FormData();
353
+ form.append('file', file);
354
+ const folder = galleryColumn.styleConfig?.storage_path ?? galleryColumn.styleConfig?.storagePath;
355
+ if (folder) {
356
+ form.append('folder', folder);
357
+ form.append('storage_path', folder);
358
+ }
359
+ const up = await api.post('/upload', form, {
360
+ headers: { 'Content-Type': 'multipart/form-data' },
361
+ onUploadProgress: (e) => {
362
+ if (e.total)
363
+ onProgress((e.loaded / e.total) * 0.9);
364
+ },
365
+ });
366
+ const body = up?.data;
367
+ if (body && body.success === false)
368
+ throw new Error(body.message || 'upload failed');
369
+ url = extractUploadedValue(body);
370
+ if (!url)
371
+ throw new Error('upload failed');
372
+ }
373
+ const derived = relationDerivedValues(metadata, { isCreate: true, rows, image: size });
374
+ if (positionKey && typeof derived[positionKey] === 'number')
375
+ derived[positionKey] += offset;
376
+ const payload = {
377
+ ...(filters || {}),
378
+ ...buildCreatePayload(foreignKey, parentId, {
379
+ ...createInitialValues,
380
+ ...derived,
381
+ [galleryColumn.key]: url,
382
+ }),
383
+ };
384
+ try {
385
+ const res = await api.post(dataEndpoint, payload);
386
+ if (!res.data?.success)
387
+ throw new Error(res.data?.message || 'create failed');
388
+ }
389
+ catch (err) {
390
+ // The file is already stored: a retry reuses it instead of
391
+ // uploading (and orphaning) a second copy.
392
+ throw Object.assign(err instanceof Error ? err : new Error(String(err)), { uploadedUrl: url });
393
+ }
394
+ onProgress(1);
395
+ },
396
+ // eslint-disable-next-line react-hooks/exhaustive-deps
397
+ [api, galleryColumn, metadata, rows, positionKey, filtersKey, foreignKey, parentId, createInitialValues, dataEndpoint]);
398
+ const galleryReorder = useCallback(async (ordered) => {
399
+ if (!positionKey)
400
+ return;
401
+ // Optimistic: show the new order now, persist only what changed.
402
+ setRows(ordered.map((r, i) => ({ ...r, [positionKey]: i })));
403
+ try {
404
+ await Promise.all(ordered.map((r, i) => {
405
+ const raw = r[positionKey];
406
+ const same = raw !== null && raw !== undefined && raw !== '' && Number(raw) === i;
407
+ return same ? null : api.put(`${dataEndpoint}/${r.id}`, { [positionKey]: i });
408
+ }));
409
+ onChange?.();
410
+ }
411
+ catch (err) {
412
+ console.error('DynamicRelation reorder error', err);
413
+ toast.error(labels.reorderError ?? 'No se pudo guardar el nuevo orden.');
414
+ }
415
+ finally {
416
+ await refreshSilently();
417
+ }
418
+ },
419
+ // eslint-disable-next-line react-hooks/exhaustive-deps
420
+ [api, dataEndpoint, positionKey, refreshSilently, onChange]);
421
+ // Confirmed delete → hidden at once, «Deshacer» for a few seconds, then the
422
+ // real DELETE. Closing the panel before the toast ends still deletes.
423
+ const deleteWithUndo = useCallback((row) => {
424
+ const key = String(row.id);
425
+ setPendingDelete((s) => new Set(s).add(key));
426
+ let undone = false;
427
+ const commit = async () => {
428
+ if (undone)
429
+ return;
430
+ try {
431
+ const res = await api.delete(`${dataEndpoint}/${row.id}`);
432
+ if (!res.data?.success)
433
+ throw new Error('delete failed');
434
+ onChange?.();
435
+ }
436
+ catch (err) {
437
+ console.error('DynamicRelation delete error', err);
438
+ toast.error(labels.deleteError ?? 'No se pudo eliminar.');
439
+ }
440
+ finally {
441
+ setPendingDelete((s) => {
442
+ const n = new Set(s);
443
+ n.delete(key);
444
+ return n;
445
+ });
446
+ await refreshSilently();
447
+ }
448
+ };
449
+ const timer = setTimeout(() => void commit(), 6000);
450
+ toast(labels.deletedToast ?? 'Foto eliminada', {
451
+ duration: 6000,
452
+ action: {
453
+ label: labels.undoLabel ?? 'Deshacer',
454
+ onClick: () => {
455
+ undone = true;
456
+ clearTimeout(timer);
457
+ setPendingDelete((s) => {
458
+ const n = new Set(s);
459
+ n.delete(key);
460
+ return n;
461
+ });
462
+ },
463
+ },
464
+ });
465
+ },
466
+ // eslint-disable-next-line react-hooks/exhaustive-deps
467
+ [api, dataEndpoint, refreshSilently, onChange]);
291
468
  const handleDelete = useCallback(async () => {
292
469
  if (!rowToDelete)
293
470
  return;
@@ -307,7 +484,11 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
307
484
  setSubmitting(false);
308
485
  }
309
486
  }, [api, dataEndpoint, fetchAll, onChange, rowToDelete]);
310
- return (_jsxs("div", { className: className, "data-relation-kind": kind, "data-relation-model": model, children: [(labels.title || canCreate || showSearch) && (_jsxs("div", { className: "flex items-center justify-between gap-2 pb-3", children: [labels.title ? _jsx("h3", { className: "text-sm font-medium", children: labels.title }) : _jsx("span", {}), _jsxs("div", { className: "flex items-center gap-2", children: [showSearch && (_jsxs("div", { className: "relative", children: [_jsx(Search, { className: "absolute start-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" }), _jsx(Input, { value: search, onChange: (e) => setSearch(e.target.value), placeholder: labels.searchPlaceholder, className: "h-8 w-40 ps-7 sm:w-56" })] })), canCreate && (_jsxs(Button, { size: "sm", variant: "outline", onClick: () => { setEditingRow(null); setFormOpen(true); }, children: [_jsx(Plus, { className: "h-4 w-4 mr-1" }), labels.addLabel] }))] })] })), loading ? (_jsx("div", { className: "space-y-2", children: Array.from({ length: 3 }).map((_, i) => (_jsx(Skeleton, { className: "h-10 w-full" }, `rel-skeleton-${i}`))) })) : rows.length === 0 ? (_jsx("div", { className: "text-center text-sm text-muted-foreground py-8 border rounded-md bg-muted/30", children: fetchErrorStatus === 403
487
+ return (_jsxs("div", { className: className, "data-relation-kind": kind, "data-relation-model": model, children: [(labels.title || canCreate || showSearch) && (_jsxs("div", { className: "flex items-center justify-between gap-2 pb-3", children: [labels.title ? _jsx("h3", { className: "text-sm font-medium", children: labels.title }) : _jsx("span", {}), _jsxs("div", { className: "flex items-center gap-2", children: [showSearch && (_jsxs("div", { className: "relative", children: [_jsx(Search, { className: "absolute start-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" }), _jsx(Input, { value: search, onChange: (e) => setSearch(e.target.value), placeholder: labels.searchPlaceholder, className: "h-8 w-40 ps-7 sm:w-56" })] })), canCreate && !galleryColumn && (_jsxs(Button, { size: "sm", variant: "outline", onClick: () => { setEditingRow(null); uploadedImageRef.current = null; setFormOpen(true); }, children: [_jsx(Plus, { className: "h-4 w-4 mr-1" }), labels.addLabel] }))] })] })), loading ? (_jsx("div", { className: "space-y-2", children: Array.from({ length: 3 }).map((_, i) => (_jsx(Skeleton, { className: "h-10 w-full" }, `rel-skeleton-${i}`))) })) : galleryColumn && fetchErrorStatus === null ? (_jsx(RelationGallery, { rows: orderedRows, rowKey: (row, i) => relationRowKey(row, i, foreignKey), imageKey: galleryColumn.key, captionKey: captionKey, getImageUrl: (p) => getImageUrl(p), accept: galleryColumn.accept || 'image/*', maxSize: (() => {
488
+ const sc = (galleryColumn.styleConfig ?? {});
489
+ const n = Number(sc.max_size ?? sc.maxSize);
490
+ return Number.isFinite(n) && n > 0 ? n : undefined;
491
+ })(), canCreate: canCreate, canEdit: canEdit, canReorder: canEdit && !!positionKey, canDelete: canDelete, hiddenKeys: pendingDelete, onUpload: galleryUpload, onUploadsSettled: () => { void refreshSilently(); onChange?.(); }, onReorder: galleryReorder, onEdit: canEdit ? (row) => { setEditingRow(row); uploadedImageRef.current = null; setFormOpen(true); } : undefined, onDelete: canDelete ? (row) => setRowToDelete(row) : undefined })) : rows.length === 0 ? (_jsx("div", { className: "text-center text-sm text-muted-foreground py-8 border rounded-md bg-muted/30", children: fetchErrorStatus === 403
311
492
  ? (labels.forbiddenState ?? 'Sin permiso para ver estos registros.')
312
493
  : fetchErrorStatus !== null
313
494
  ? (labels.errorState ?? 'No se pudieron cargar los registros relacionados.')
@@ -316,8 +497,20 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
316
497
  return (_jsx(TableHead, { colSpan: header.colSpan, style: header.column.columnDef.size ? { width: header.column.columnDef.size } : undefined, className: cn('bg-card border-b h-10', isActions && 'text-right'), children: header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext()) }, header.id));
317
498
  }) }, headerGroup.id))) }), _jsx(TableBody, { children: table.getRowModel().rows.map((row, idx) => (_jsx(TableRow, { children: row.getVisibleCells().map((cell) => (_jsx(TableCell, { style: cell.column.columnDef.size ? { width: cell.column.columnDef.size } : undefined, className: "py-2", children: flexRender(cell.column.columnDef.cell, cell.getContext()) }, cell.id))) }, relationRowKey(row.original, idx, foreignKey)))) })] }), loadingMore && (_jsx("div", { className: "p-2", children: _jsx(Skeleton, { className: "h-8 w-full" }) })), _jsx("div", { ref: sentinelRef, "aria-hidden": true, className: "h-px w-full" })] }) })), !loading && rows.length > 0 && total > rows.length && (_jsx("div", { className: "pt-2 text-end text-xs text-muted-foreground", children: labels.countLabel
318
499
  .replace('{{loaded}}', String(rows.length))
319
- .replace('{{total}}', String(total)) })), _jsx(Dialog, { open: formOpen, onOpenChange: (open) => { setFormOpen(open); if (!open)
320
- setEditingRow(null); }, children: _jsxs(DialogContent, { className: "flex max-h-[90dvh] flex-col overflow-hidden", children: [_jsx(DialogHeader, { className: "shrink-0", children: _jsx(DialogTitle, { children: editingRow ? labels.editLabel : labels.addLabel }) }), _jsx(DynamicForm, { scrollableBody: true, fields: formFields, initialValues: editingRow || undefined, onSubmit: handleSubmit, onCancel: () => { setFormOpen(false); setEditingRow(null); }, submitLabel: labels.saveLabel, cancelLabel: labels.cancelLabel, disabled: submitting }, editingRow ? `edit-${editingRow.id ?? ''}` : 'new')] }) }), _jsx(AlertDialog, { open: !!rowToDelete, onOpenChange: (open) => !open && setRowToDelete(null), children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: labels.confirmRemoveTitle }), _jsx(AlertDialogDescription, { children: labels.confirmRemoveDescription })] }), _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: submitting, children: labels.cancelLabel }), _jsx(AlertDialogAction, { onClick: (e) => { e.preventDefault(); handleDelete(); }, className: "bg-red-600 hover:bg-red-700", disabled: submitting, children: labels.removeLabel })] })] }) })] }));
500
+ .replace('{{total}}', String(total)) })), _jsx(Dialog, { open: formOpen, onOpenChange: (open) => { setFormOpen(open); if (!open) {
501
+ setEditingRow(null);
502
+ uploadedImageRef.current = null;
503
+ } }, children: _jsxs(DialogContent, { className: "flex max-h-[90dvh] flex-col overflow-hidden", children: [_jsx(DialogHeader, { className: "shrink-0", children: _jsx(DialogTitle, { children: editingRow ? labels.editLabel : labels.addLabel }) }), _jsx(DynamicForm, { scrollableBody: true, fields: formFields, initialValues: editingRow || (Object.keys(createInitialValues).length ? createInitialValues : undefined), onFieldMeta: (_key, meta) => { uploadedImageRef.current = meta; }, onSubmit: handleSubmit, onCancel: () => { setFormOpen(false); setEditingRow(null); uploadedImageRef.current = null; }, submitLabel: labels.saveLabel, cancelLabel: labels.cancelLabel, disabled: submitting }, editingRow ? `edit-${editingRow.id ?? ''}` : 'new')] }) }), _jsx(AlertDialog, { open: !!rowToDelete, onOpenChange: (open) => !open && setRowToDelete(null), children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: labels.confirmRemoveTitle }), _jsx(AlertDialogDescription, { children: galleryColumn
504
+ ? (labels.confirmRemovePhotoDescription ?? 'Esta foto deja de verse en la tienda. Puedes deshacerlo unos segundos.')
505
+ : labels.confirmRemoveDescription })] }), _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: submitting, children: labels.cancelLabel }), _jsx(AlertDialogAction, { onClick: (e) => {
506
+ e.preventDefault();
507
+ if (galleryColumn && rowToDelete) {
508
+ deleteWithUndo(rowToDelete);
509
+ setRowToDelete(null);
510
+ return;
511
+ }
512
+ handleDelete();
513
+ }, className: "bg-red-600 hover:bg-red-700", disabled: submitting, children: labels.removeLabel })] })] }) })] }));
321
514
  }
322
515
  function ManyToManyRelation({ kind, through, references, foreignKey, referencesKey, parentId, filters, pivotEndpoint, referencesEndpoint, displayKey, canCreate = true, canDelete = true, readonly, readOnly, strings, className, onChange, }) {
323
516
  // Read-only relation always wins over host-passed perms (AND).
@@ -1 +1 @@
1
- {"version":3,"file":"dynamic-relations.d.ts","sourceRoot":"","sources":["../src/dynamic-relations.tsx"],"names":[],"mappings":"AAcA,OAAO,EAAmB,KAAK,sBAAsB,EAAE,MAAM,oBAAoB,CAAA;AACjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAE3C,MAAM,WAAW,qBAAqB;IAClC;;;OAGG;IACH,MAAM,EAAE;QAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;QAAC,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,GAAG,IAAI,GAAG,SAAS,CAAA;IACzE,gEAAgE;IAChE,SAAS,EAAE,YAAY,EAAE,GAAG,IAAI,GAAG,SAAS,CAAA;IAC5C;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,6CAA6C;IAC7C,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,mCAAmC;IACnC,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB;;;OAGG;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,CAAC,CAUxB;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,EAAE,OAAO,CAAC,GAAG,OAAO,CAEpE;AAOD,wBAAgB,gBAAgB,CAAC,EAC7B,MAAM,EACN,SAAS,EACT,WAAkB,EAClB,SAAS,EACT,cAAc,EACd,SAAgB,EAChB,SAAgB,EAChB,OAAc,EACd,OAAO,EACP,YAAoB,EACpB,SAAiB,EACjB,QAAQ,GACX,EAAE,qBAAqB,sCA+EvB"}
@@ -89,6 +89,6 @@ export function DynamicRelations({ record, relations, parentIdKey = 'id', classN
89
89
  // directly. (one_to_many is the common detail-page case.)
90
90
  references: rel.through, foreignKey: rel.foreign_key, parentId: parentId, filters: filters, className: panelClassName, lineSubtable: lineSubtable, canCreate: canCreate, canDelete: canDelete, readonly: relReadonly, strings: panelStrings, onChange: onChange ? () => onChange(rel) : undefined }, relationKey(rel, idx)));
91
91
  }
92
- return (_jsx(DynamicRelation, { kind: "one_to_many", model: rel.through, foreignKey: rel.foreign_key, parentId: parentId, filters: filters, className: panelClassName, lineSubtable: lineSubtable, canCreate: canCreate, canDelete: canDelete, canEdit: canEdit, readonly: relReadonly, strings: panelStrings, onChange: onChange ? () => onChange(rel) : undefined }, relationKey(rel, idx)));
92
+ return (_jsx(DynamicRelation, { kind: "one_to_many", model: rel.through, foreignKey: rel.foreign_key, parentId: parentId, filters: filters, className: panelClassName, lineSubtable: lineSubtable, canCreate: canCreate, canDelete: canDelete, canEdit: canEdit, readonly: relReadonly, strings: panelStrings, parentRecord: record, onChange: onChange ? () => onChange(rel) : undefined }, relationKey(rel, idx)));
93
93
  }) }));
94
94
  }
@@ -0,0 +1,31 @@
1
+ export interface GalleryUploadProgress {
2
+ (fraction: number): void;
3
+ }
4
+ export interface RelationGalleryProps {
5
+ rows: Record<string, any>[];
6
+ rowKey: (row: Record<string, any>, index: number) => string;
7
+ imageKey: string;
8
+ /** Optional caption column (alt text). */
9
+ captionKey?: string;
10
+ getImageUrl: (path: string) => string;
11
+ accept?: string;
12
+ maxSize?: number;
13
+ canCreate?: boolean;
14
+ canEdit?: boolean;
15
+ /** Reorder / «Hacer principal» (needs a position column). Default = canEdit. */
16
+ canReorder?: boolean;
17
+ canDelete?: boolean;
18
+ /** Uploads one file and creates its row at gallery index `offset` past the end. */
19
+ onUpload: (file: File, offset: number, onProgress: GalleryUploadProgress, reuseUrl?: string) => Promise<void>;
20
+ /** All uploads of one batch finished (refresh the list). */
21
+ onUploadsSettled?: () => void;
22
+ /** New order of the rows (persist positions). */
23
+ onReorder: (ordered: Record<string, any>[]) => Promise<void> | void;
24
+ onEdit?: (row: Record<string, any>) => void;
25
+ /** Asks for confirmation and deletes (with undo) — owned by the host. */
26
+ onDelete?: (row: Record<string, any>) => void;
27
+ /** Keys of rows pending deletion (hidden while «Deshacer» is offered). */
28
+ hiddenKeys?: Set<string>;
29
+ }
30
+ export declare function RelationGallery({ rows, rowKey, imageKey, captionKey, getImageUrl, accept, maxSize, canCreate, canEdit, canReorder, canDelete, onUpload, onUploadsSettled, onReorder, onEdit, onDelete, hiddenKeys, }: RelationGalleryProps): import("react").JSX.Element;
31
+ //# sourceMappingURL=relation-gallery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relation-gallery.d.ts","sourceRoot":"","sources":["../src/relation-gallery.tsx"],"names":[],"mappings":"AAoCA,MAAM,WAAW,qBAAqB;IAClC,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;CAC3B;AAED,MAAM,WAAW,oBAAoB;IACjC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,CAAA;IAC3B,MAAM,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;IAC3D,QAAQ,EAAE,MAAM,CAAA;IAChB,0CAA0C;IAC1C,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB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1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ // RelationGallery — the thumbnail-grid view of a one_to_many relation whose
3
+ // image column declares `display_config.gallery: true` (e.g. a product's
4
+ // ProductImage rows). Opt-in: DynamicRelation keeps its table for every other
5
+ // relation. Pure UI over callbacks — DynamicRelation owns the API calls, so the
6
+ // `/upload` and `/data` contracts are the ones the table already uses.
7
+ //
8
+ // - Add several photos at once (picker or drag & drop), one progress bar,
9
+ // preview, error and retry per file; type/size limits with clear messages.
10
+ // - Reorder by dragging (pointer or keyboard: Space to lift, arrows to move)
11
+ // or with the explicit move buttons; the first image is the main one.
12
+ // - Delete asks for confirmation, then offers «Deshacer» for a few seconds.
13
+ // - Theme tokens only (bg-card, border, muted…) so it follows dark mode.
14
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
15
+ import { useTranslation } from 'react-i18next';
16
+ import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, } from '@dnd-kit/core';
17
+ import { SortableContext, arrayMove, rectSortingStrategy, sortableKeyboardCoordinates, useSortable, } from '@dnd-kit/sortable';
18
+ import { CSS } from '@dnd-kit/utilities';
19
+ import { cn } from '@asteby/metacore-ui/lib';
20
+ import { Button } from '@asteby/metacore-ui/primitives';
21
+ import { ArrowLeft, ArrowRight, ImagePlus, Loader2, Pencil, RotateCcw, Star, Trash2, X } from 'lucide-react';
22
+ import { validateUploadFile } from './upload-field';
23
+ let uploadSeq = 0;
24
+ export function RelationGallery({ rows, rowKey, imageKey, captionKey, getImageUrl, accept = 'image/*', maxSize, canCreate = true, canEdit = true, canReorder, canDelete = true, onUpload, onUploadsSettled, onReorder, onEdit, onDelete, hiddenKeys, }) {
25
+ const { t } = useTranslation();
26
+ const inputRef = useRef(null);
27
+ const [dragOver, setDragOver] = useState(false);
28
+ const [uploads, setUploads] = useState([]);
29
+ const reorderable = canReorder ?? canEdit;
30
+ // Every local preview is released when its item goes away or on unmount.
31
+ const uploadsRef = useRef([]);
32
+ uploadsRef.current = uploads;
33
+ const releasePreview = (u) => {
34
+ if (u.preview)
35
+ URL.revokeObjectURL?.(u.preview);
36
+ };
37
+ const keyed = useMemo(() => rows
38
+ .map((row, i) => ({ row, key: rowKey(row, i) }))
39
+ .filter((r) => !hiddenKeys?.has(r.key)), [rows, rowKey, hiddenKeys]);
40
+ const ids = useMemo(() => keyed.map((k) => k.key), [keyed]);
41
+ useEffect(() => () => uploadsRef.current.forEach(releasePreview), []);
42
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }));
43
+ const move = useCallback((from, to) => {
44
+ if (from === to || to < 0 || to >= keyed.length)
45
+ return;
46
+ void onReorder(arrayMove(keyed, from, to).map((k) => k.row));
47
+ }, [keyed, onReorder]);
48
+ const handleDragEnd = useCallback((e) => {
49
+ if (!e.over || e.active.id === e.over.id)
50
+ return;
51
+ move(ids.indexOf(String(e.active.id)), ids.indexOf(String(e.over.id)));
52
+ }, [ids, move]);
53
+ const runUpload = useCallback(async (item) => {
54
+ setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'uploading', progress: 0, error: undefined } : u)));
55
+ try {
56
+ await onUpload(item.file, item.offset, (fraction) => setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, progress: Math.max(0, Math.min(1, fraction)) } : u))), item.uploadedUrl);
57
+ setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'done', progress: 1 } : u)));
58
+ return true;
59
+ }
60
+ catch (err) {
61
+ const msg = err?.response?.data?.message ||
62
+ err?.message ||
63
+ t('dynamic.gallery.upload_failed', { defaultValue: 'No se pudo subir la foto.' });
64
+ const stored = typeof err?.uploadedUrl === 'string' ? err.uploadedUrl : item.uploadedUrl;
65
+ setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'error', error: String(msg), uploadedUrl: stored } : u)));
66
+ return false;
67
+ }
68
+ }, [onUpload, t]);
69
+ const addFiles = useCallback(async (files) => {
70
+ const picked = Array.from(files ?? []);
71
+ if (picked.length === 0)
72
+ return;
73
+ const accepted = [];
74
+ const rejected = [];
75
+ for (const file of picked) {
76
+ const item = {
77
+ id: `up-${++uploadSeq}`,
78
+ file,
79
+ preview: typeof URL !== 'undefined' && URL.createObjectURL ? URL.createObjectURL(file) : '',
80
+ progress: 0,
81
+ status: 'uploading',
82
+ offset: accepted.length,
83
+ };
84
+ const bad = validateUploadFile(file, { accept, maxSize });
85
+ if (bad === 'type') {
86
+ rejected.push({ ...item, status: 'error', error: t('dynamic.gallery.invalid_type', { defaultValue: 'Formato no permitido. Usa JPG, PNG o WebP.' }) });
87
+ }
88
+ else if (bad === 'size') {
89
+ const mb = ((maxSize ?? 0) / (1024 * 1024)).toFixed(1);
90
+ rejected.push({ ...item, status: 'error', error: t('dynamic.gallery.too_large', { mb, defaultValue: `La foto pesa más de ${mb} MB.` }) });
91
+ }
92
+ else {
93
+ accepted.push(item);
94
+ }
95
+ }
96
+ setUploads((list) => {
97
+ list.filter((u) => u.status === 'done').forEach(releasePreview);
98
+ return [...list.filter((u) => u.status !== 'done'), ...accepted, ...rejected];
99
+ });
100
+ // Sequential: keeps positions in pick order and spares the server.
101
+ let any = false;
102
+ for (const item of accepted) {
103
+ if (await runUpload(item))
104
+ any = true;
105
+ }
106
+ if (any)
107
+ onUploadsSettled?.();
108
+ }, [accept, maxSize, runUpload, onUploadsSettled, t]);
109
+ const retry = useCallback(async (item) => {
110
+ if (await runUpload({ ...item, offset: 0 }))
111
+ onUploadsSettled?.();
112
+ }, [runUpload, onUploadsSettled]);
113
+ const dismiss = useCallback((id) => {
114
+ setUploads((list) => {
115
+ const gone = list.find((u) => u.id === id);
116
+ if (gone)
117
+ releasePreview(gone);
118
+ return list.filter((u) => u.id !== id);
119
+ });
120
+ }, []);
121
+ const pending = uploads.filter((u) => u.status !== 'done');
122
+ // A retry numbers its photo past the rows already refreshed; while a batch
123
+ // is still uploading that list is stale, so retry waits for it.
124
+ const busy = uploads.some((u) => u.status === 'uploading');
125
+ const hintId = useMemo(() => `gallery-hint-${++uploadSeq}`, []);
126
+ const mainLabel = t('dynamic.gallery.main', { defaultValue: 'Principal' });
127
+ return (_jsxs("div", { className: "grid gap-3", "data-relation-view": "gallery", children: [canCreate && (_jsxs("div", { role: "button", tabIndex: 0, "aria-label": t('dynamic.gallery.add', { defaultValue: 'Agregar fotos' }), "aria-describedby": hintId, onClick: () => inputRef.current?.click(), onKeyDown: (e) => {
128
+ if (e.key === 'Enter' || e.key === ' ') {
129
+ e.preventDefault();
130
+ inputRef.current?.click();
131
+ }
132
+ }, onDragOver: (e) => {
133
+ e.preventDefault();
134
+ setDragOver(true);
135
+ }, onDragLeave: () => setDragOver(false), onDrop: (e) => {
136
+ e.preventDefault();
137
+ setDragOver(false);
138
+ void addFiles(e.dataTransfer?.files);
139
+ }, className: cn('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', dragOver && 'border-primary/60 bg-muted/50'), "data-testid": "gallery-dropzone", children: [_jsx(ImagePlus, { className: "h-6 w-6", "aria-hidden": true }), _jsx("span", { className: "font-medium text-foreground", children: t('dynamic.gallery.add', { defaultValue: 'Agregar fotos' }) }), _jsx("span", { className: "text-xs", id: hintId, children: maxSize
140
+ ? t('dynamic.gallery.hint_size', {
141
+ mb: (maxSize / (1024 * 1024)).toFixed(0),
142
+ defaultValue: `Arrastra aquí o elige varias a la vez · JPG, PNG o WebP · hasta ${(maxSize / (1024 * 1024)).toFixed(0)} MB`,
143
+ })
144
+ : t('dynamic.gallery.hint', { defaultValue: 'Arrastra aquí o elige varias a la vez · JPG, PNG o WebP' }) }), _jsx("input", { ref: inputRef, type: "file", accept: accept, multiple: true, className: "hidden", "data-testid": "gallery-input", onChange: (e) => {
145
+ void addFiles(e.target.files);
146
+ e.target.value = '';
147
+ } })] })), pending.length > 0 && (_jsx("ul", { className: "grid gap-2", "aria-live": "polite", "data-testid": "gallery-uploads", children: pending.map((u) => (_jsxs("li", { className: "flex items-center gap-3 rounded-md border bg-card p-2", children: [u.preview ? (_jsx("img", { src: u.preview, alt: "", className: "h-12 w-12 shrink-0 rounded object-cover" })) : (_jsx("div", { className: "h-12 w-12 shrink-0 rounded bg-muted" })), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "truncate text-sm", children: u.file.name }), u.status === 'error' ? (_jsx("div", { className: "text-xs text-destructive", role: "alert", children: u.error })) : (_jsx("div", { className: "mt-1 h-1.5 w-full overflow-hidden rounded bg-muted", role: "progressbar", "aria-label": u.file.name, "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": Math.round(u.progress * 100), children: _jsx("div", { className: "h-full bg-primary transition-all", style: { width: `${Math.round(u.progress * 100)}%` } }) }))] }), u.status === 'uploading' && _jsx(Loader2, { className: "h-4 w-4 animate-spin text-muted-foreground", "aria-hidden": true }), u.status === 'error' && !validateUploadFile(u.file, { accept, maxSize }) && (_jsx(Button, { type: "button", size: "sm", variant: "ghost", disabled: busy, onClick: () => void retry(u), "aria-label": t('dynamic.gallery.retry', { defaultValue: 'Reintentar' }), children: _jsx(RotateCcw, { className: "h-4 w-4" }) })), u.status === 'error' && (_jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => dismiss(u.id), "aria-label": t('dynamic.gallery.dismiss', { defaultValue: 'Quitar' }), children: _jsx(X, { className: "h-4 w-4" }) }))] }, u.id))) })), keyed.length === 0 && !canCreate && pending.length === 0 && (_jsx("div", { className: "rounded-md border bg-muted/30 py-8 text-center text-sm text-muted-foreground", children: t('dynamic.gallery.empty', { defaultValue: 'Sin fotos.' }) })), keyed.length > 0 && (_jsx(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragEnd: handleDragEnd, children: _jsx(SortableContext, { items: ids, strategy: rectSortingStrategy, children: _jsx("ul", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4", "data-testid": "gallery-grid", children: keyed.map(({ row, key }, index) => (_jsx(GalleryTile, { id: key, src: row[imageKey] ? getImageUrl(String(row[imageKey])) : '', caption: captionKey ? String(row[captionKey] ?? '') : '', index: index, total: keyed.length, isMain: index === 0, mainLabel: mainLabel, canEdit: canEdit, canReorder: reorderable, canDelete: canDelete, onMove: (to) => move(index, to), onEdit: onEdit ? () => onEdit(row) : undefined, onDelete: onDelete ? () => onDelete(row) : undefined }, key))) }) }) }))] }));
148
+ }
149
+ function GalleryTile({ id, src, caption, index, total, isMain, mainLabel, canEdit, canReorder, canDelete, onMove, onEdit, onDelete, }) {
150
+ const { t } = useTranslation();
151
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, disabled: !canReorder });
152
+ const label = caption || t('dynamic.gallery.photo', { n: index + 1, defaultValue: `Foto ${index + 1}` });
153
+ return (_jsxs("li", { ref: setNodeRef, style: { transform: CSS.Transform.toString(transform), transition }, className: cn('group relative overflow-hidden rounded-lg border bg-card', isMain && 'ring-2 ring-primary', isDragging && 'z-10 opacity-80 shadow-lg'), "data-testid": "gallery-tile", "data-main": isMain ? 'true' : undefined, children: [_jsx("div", { className: "aspect-square w-full touch-none bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring", ...attributes, ...listeners, "aria-roledescription": t('dynamic.gallery.sortable', { defaultValue: 'foto reordenable' }), "aria-label": `${label}${isMain ? ` · ${mainLabel}` : ''}`, children: src ? (_jsx("img", { src: src, alt: caption, className: "h-full w-full min-h-24 object-cover", draggable: false })) : null }), isMain && (_jsxs("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", children: [_jsx(Star, { className: "h-3 w-3", "aria-hidden": true }), mainLabel] })), _jsxs("div", { className: "flex items-center justify-between gap-1 border-t bg-card px-1 py-1", children: [_jsx("div", { className: "flex items-center", children: canReorder && (_jsxs(_Fragment, { children: [_jsx(Button, { type: "button", size: "sm", variant: "ghost", className: "h-8 w-8 p-0", disabled: index === 0, onClick: () => onMove(index - 1), "aria-label": t('dynamic.gallery.move_before', { defaultValue: 'Mover antes' }), children: _jsx(ArrowLeft, { className: "h-4 w-4 rtl:rotate-180" }) }), _jsx(Button, { type: "button", size: "sm", variant: "ghost", className: "h-8 w-8 p-0", disabled: index === total - 1, onClick: () => onMove(index + 1), "aria-label": t('dynamic.gallery.move_after', { defaultValue: 'Mover después' }), children: _jsx(ArrowRight, { className: "h-4 w-4 rtl:rotate-180" }) }), !isMain && (_jsx(Button, { type: "button", size: "sm", variant: "ghost", className: "h-8 w-8 p-0", onClick: () => onMove(0), "aria-label": t('dynamic.gallery.make_main', { defaultValue: 'Hacer principal' }), title: t('dynamic.gallery.make_main', { defaultValue: 'Hacer principal' }), children: _jsx(Star, { className: "h-4 w-4" }) }))] })) }), _jsxs("div", { className: "flex items-center", children: [canEdit && onEdit && (_jsx(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' }), children: _jsx(Pencil, { className: "h-4 w-4" }) })), canDelete && onDelete && (_jsx(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' }), children: _jsx(Trash2, { className: "h-4 w-4" }) }))] })] })] }));
154
+ }
@@ -3,7 +3,25 @@ export interface UploadFieldProps {
3
3
  field: ActionFieldDef;
4
4
  value: any;
5
5
  onChange: (v: any) => void;
6
+ /**
7
+ * Called after a successful upload of an image with its natural size,
8
+ * measured in the browser (no server round-trip, `/upload` contract
9
+ * unchanged). Lets a form fill derived width/height columns.
10
+ */
11
+ onFileMeta?: (meta: {
12
+ width?: number;
13
+ height?: number;
14
+ }) => void;
6
15
  }
16
+ /**
17
+ * Natural pixel size of an image file, measured client-side. Resolves `{}` for
18
+ * a non-image or when the browser cannot decode it — never throws, never
19
+ * guesses.
20
+ */
21
+ export declare function readImageSize(file: Blob): Promise<{
22
+ width?: number;
23
+ height?: number;
24
+ }>;
7
25
  /**
8
26
  * Pulls the stored file url/path out of an upload response envelope, tolerating
9
27
  * the common key shapes a host might return. Pure — exported for tests.
@@ -32,5 +50,5 @@ export declare function validateUploadFile(file: {
32
50
  accept?: string;
33
51
  maxSize?: number;
34
52
  }): 'type' | 'size' | null;
35
- export declare function UploadField({ field, value, onChange }: UploadFieldProps): import("react").JSX.Element;
53
+ export declare function UploadField({ field, value, onChange, onFileMeta }: UploadFieldProps): import("react").JSX.Element;
36
54
  //# sourceMappingURL=upload-field.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upload-field.d.ts","sourceRoot":"","sources":["../src/upload-field.tsx"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,MAAM,WAAW,gBAAgB;IAC7B,KAAK,EAAE,cAAc,CAAA;IACrB,KAAK,EAAE,GAAG,CAAA;IACV,QAAQ,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,IAAI,CAAA;CAC7B;AAKD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,GAAG,GAAG,MAAM,CAWzD;AAED,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAK1D;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAahG;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAC9B,IAAI,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;C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