@asteby/metacore-runtime-react 49.12.0 → 50.0.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.
@@ -297,6 +297,13 @@ export interface DynamicTableProps {
297
297
  extraBulkActions?: ReactNode | ((ctx: DynamicTableBulkContext) => ReactNode)
298
298
  /** Hide the built-in bulk "Eliminar" (e.g. a model whose rows must not be deleted in batch). */
299
299
  hideBulkDelete?: boolean
300
+ /**
301
+ * Called once when a built-in bulk delete finishes, with the ids that were
302
+ * deleted and the ones refused (`message` / `status` come from the server
303
+ * response when available; a cancelled reason prompt has no message). Lets a
304
+ * host persist or log the outcome. The table's own toasts are unaffected.
305
+ */
306
+ onBulkDeleteResult?: (result: BulkDeleteResult) => void
300
307
  /**
301
308
  * First-use content shown instead of "No se encontraron resultados" when the
302
309
  * list loaded fine, is empty, and no search/filter is active. Never shown
@@ -323,6 +330,53 @@ function isForbiddenError(error: unknown): boolean {
323
330
  return e?.response?.status === 403 || e?.status === 403
324
331
  }
325
332
 
333
+ /** Outcome of a built-in bulk delete (see `onBulkDeleteResult`). */
334
+ export interface BulkDeleteResult {
335
+ succeeded: Array<string | number>
336
+ failed: Array<{ id: string | number; message?: string; status?: number }>
337
+ }
338
+
339
+ const BULK_REASON_MAX_LEN = 200
340
+ const BULK_REASON_MAX_GROUPS = 3
341
+
342
+ /** Server text -> trimmed plain string, or undefined when there is nothing usable. */
343
+ function cleanReason(v: unknown): string | undefined {
344
+ if (typeof v !== 'string') return undefined
345
+ const m = v.trim()
346
+ return m ? m : undefined
347
+ }
348
+
349
+ /**
350
+ * Axios' own technical messages ("Request failed with status code 500",
351
+ * "Network Error", "timeout of 5000ms exceeded") say nothing the user can act
352
+ * on, so they never count as a refusal reason. Real server text
353
+ * (`response.data.message`) is unaffected and always wins.
354
+ */
355
+ const GENERIC_TRANSPORT_MESSAGE = /^(request failed with status code \d+|network error|timeout of \d+ms exceeded)$/i
356
+ function cleanTransportMessage(v: unknown): string | undefined {
357
+ const m = cleanReason(v)
358
+ return m && !GENERIC_TRANSPORT_MESSAGE.test(m) ? m : undefined
359
+ }
360
+
361
+ /**
362
+ * Groups refusal reasons ("• reason (×N)", at most 3 distinct, each truncated)
363
+ * plus an "and N more" line, as a string with line breaks. It is delivered as
364
+ * the toast `description`; how line breaks are shown depends on the host's toast.
365
+ */
366
+ function groupBulkReasons(failed: BulkDeleteResult['failed'], more: (count: number) => string): string | undefined {
367
+ const counts = new Map<string, number>()
368
+ for (const f of failed) {
369
+ if (!f.message) continue
370
+ const m = f.message.length > BULK_REASON_MAX_LEN ? `${f.message.slice(0, BULK_REASON_MAX_LEN - 1)}…` : f.message
371
+ counts.set(m, (counts.get(m) ?? 0) + 1)
372
+ }
373
+ if (counts.size === 0) return undefined
374
+ const entries = Array.from(counts.entries())
375
+ const lines = entries.slice(0, BULK_REASON_MAX_GROUPS).map(([m, n]) => (n > 1 ? `• ${m} (×${n})` : `• ${m}`))
376
+ if (entries.length > BULK_REASON_MAX_GROUPS) lines.push(more(entries.length - BULK_REASON_MAX_GROUPS))
377
+ return lines.join('\n')
378
+ }
379
+
326
380
  export function DynamicTable({
327
381
  model,
328
382
  endpoint,
@@ -347,6 +401,7 @@ export function DynamicTable({
347
401
  virtualizeRows,
348
402
  extraBulkActions,
349
403
  hideBulkDelete,
404
+ onBulkDeleteResult,
350
405
  emptyState,
351
406
  }: DynamicTableProps) {
352
407
  // The org's timezone/currency: an explicit prop wins, else the app-wide
@@ -1207,14 +1262,15 @@ export function DynamicTable({
1207
1262
  setIsBulkDeleting(true)
1208
1263
  setBulkDeleteTotal(selectedRows.length)
1209
1264
  setBulkDeleteProgress(0)
1210
- let successCount = 0, errorCount = 0
1265
+ const succeeded: BulkDeleteResult['succeeded'] = []
1266
+ const failed: BulkDeleteResult['failed'] = []
1211
1267
  // One reason for the whole batch: asked the first time a row is refused
1212
1268
  // for lacking it (model declares reason_required.delete), reused after.
1213
1269
  let bulkReason: string | undefined
1214
1270
  let bulkCancelled = false
1215
1271
  for (let i = 0; i < selectedRows.length; i++) {
1216
1272
  const row = selectedRows[i]
1217
- if (bulkCancelled) { errorCount++; setBulkDeleteProgress(i + 1); continue }
1273
+ if (bulkCancelled) { failed.push({ id: row.original.id }); setBulkDeleteProgress(i + 1); continue }
1218
1274
  try {
1219
1275
  const writeBase = mutationEndpoint ?? endpoint
1220
1276
  const deleteEndpoint = writeBase ? `${writeBase}/${row.original.id}` : `/data/${model}/${row.original.id}`
@@ -1228,10 +1284,18 @@ export function DynamicTable({
1228
1284
  return api.delete(deleteEndpoint, reason ? { params: { reason } } : undefined)
1229
1285
  },
1230
1286
  })
1231
- if (!res) { bulkCancelled = true; errorCount++ }
1232
- else if (res.data.success) successCount++
1233
- else errorCount++
1234
- } catch (e) { console.error('Error al eliminar', e); errorCount++ }
1287
+ if (!res) { bulkCancelled = true; failed.push({ id: row.original.id }) }
1288
+ else if (res.data.success) succeeded.push(row.original.id)
1289
+ else failed.push({ id: row.original.id, message: cleanReason(res.data.message) })
1290
+ } catch (e) {
1291
+ console.error('Error al eliminar', e)
1292
+ const err = e as { response?: { data?: { message?: unknown }; status?: number }; message?: unknown }
1293
+ failed.push({
1294
+ id: row.original.id,
1295
+ message: cleanReason(err?.response?.data?.message) ?? cleanTransportMessage(err?.message),
1296
+ status: err?.response?.status,
1297
+ })
1298
+ }
1235
1299
  setBulkDeleteProgress(i + 1)
1236
1300
  }
1237
1301
  await new Promise(resolve => setTimeout(resolve, 500))
@@ -1240,8 +1304,21 @@ export function DynamicTable({
1240
1304
  setBulkDeleteProgress(0)
1241
1305
  setBulkDeleteTotal(0)
1242
1306
  setRowSelection({})
1307
+ const successCount = succeeded.length, errorCount = failed.length
1243
1308
  if (successCount > 0) toast.success(t('dynamic.bulk_delete_success', { count: successCount, defaultValue: '{{count}} registro(s) eliminado(s) correctamente' }))
1244
- if (errorCount > 0) toast.error(t('dynamic.bulk_delete_error', { count: errorCount, defaultValue: '{{count}} registro(s) no pudieron ser eliminados' }))
1309
+ if (errorCount > 0) {
1310
+ const reasons = groupBulkReasons(failed, (count) => t('dynamic.bulk_delete_error_more', { count, defaultValue: 'y {{count}} más' }))
1311
+ toast.error(
1312
+ t('dynamic.bulk_delete_error', { count: errorCount, defaultValue: '{{count}} registro(s) no pudieron ser eliminados' }),
1313
+ reasons ? { description: reasons, style: { whiteSpace: 'pre-line' } } : undefined,
1314
+ )
1315
+ }
1316
+ // A throwing host callback must not skip the refresh nor leave a rejected promise.
1317
+ try {
1318
+ onBulkDeleteResult?.({ succeeded, failed })
1319
+ } catch (e) {
1320
+ console.error('onBulkDeleteResult lanzó un error', e)
1321
+ }
1245
1322
  handleRefresh()
1246
1323
  }
1247
1324
 
@@ -29,6 +29,13 @@ export interface IconPickerFieldProps {
29
29
  field: ActionFieldDef
30
30
  value: any
31
31
  onChange: (v: any) => void
32
+ /**
33
+ * Icon-only mode: hide the "Imagen" tab so the field can only store a
34
+ * lucide icon name. Also read from `field.iconOnly` / `field.icon_only`
35
+ * (metadata). An existing url/path value is preserved untouched until the
36
+ * user picks an icon or clears it (shown as a non-editable current value).
37
+ */
38
+ iconOnly?: boolean
32
39
  }
33
40
 
34
41
  /** Icons rendered per "page" — grows as the user scrolls to the bottom. Keeps
@@ -42,15 +49,19 @@ export function looksLikeImageValue(value: unknown): boolean {
42
49
  return typeof value === 'string' && value !== '' && /[/.]/.test(value)
43
50
  }
44
51
 
45
- export function IconPickerField({ field, value, onChange }: IconPickerFieldProps) {
52
+ export function IconPickerField({ field, value, onChange, iconOnly }: IconPickerFieldProps) {
53
+ const onlyIcon = iconOnly ?? field.iconOnly ?? field.icon_only ?? false
46
54
  const [mode, setMode] = useState<'icon' | 'image'>(() =>
47
- looksLikeImageValue(value) ? 'image' : 'icon',
55
+ !onlyIcon && looksLikeImageValue(value) ? 'image' : 'icon',
48
56
  )
57
+ // iconOnly + a stored url/path (written before the restriction): keep it,
58
+ // render it as a read-only current value the user can clear or replace.
59
+ const legacyImageValue = onlyIcon && looksLikeImageValue(value)
49
60
  const [open, setOpen] = useState(false)
50
61
  const [query, setQuery] = useState('')
51
62
  const [limit, setLimit] = useState(PAGE)
52
63
 
53
- const selected = mode === 'icon' ? resolveLucideIconName(value) : null
64
+ const selected = mode === 'icon' && !legacyImageValue ? resolveLucideIconName(value) : null
54
65
 
55
66
  // Full match list (names only) — filtered by query, not yet capped.
56
67
  const matches = useMemo(() => {
@@ -70,6 +81,7 @@ export function IconPickerField({ field, value, onChange }: IconPickerFieldProps
70
81
 
71
82
  return (
72
83
  <div className="flex flex-col gap-2">
84
+ {!onlyIcon && (
73
85
  <div className="flex gap-1" role="tablist" aria-label="Tipo de ícono">
74
86
  <Button
75
87
  type="button"
@@ -92,7 +104,18 @@ export function IconPickerField({ field, value, onChange }: IconPickerFieldProps
92
104
  Imagen
93
105
  </Button>
94
106
  </div>
95
- {mode === 'image' ? (
107
+ )}
108
+ {legacyImageValue && (
109
+ <div className="flex items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm" data-testid="icon-legacy-value">
110
+ <span className="min-w-0 truncate text-muted-foreground" title={String(value)}>
111
+ Valor actual: {String(value)}
112
+ </span>
113
+ <Button type="button" variant="ghost" size="sm" onClick={() => onChange('')}>
114
+ Quitar
115
+ </Button>
116
+ </div>
117
+ )}
118
+ {mode === 'image' && !onlyIcon ? (
96
119
  <UploadField field={field} value={value} onChange={onChange} />
97
120
  ) : (
98
121
  <Popover
package/src/types.ts CHANGED
@@ -675,6 +675,12 @@ export interface ActionFieldDef {
675
675
  key: string
676
676
  label: string
677
677
  type: string
678
+ /**
679
+ * `icon` widget only: restrict to lucide icon names (hides the "Imagen"
680
+ * tab). snake_case alias `icon_only` accepted from metadata JSON.
681
+ */
682
+ iconOnly?: boolean
683
+ icon_only?: boolean
678
684
  required?: boolean
679
685
  /**
680
686
  * Campo de solo lectura (escrito por el servidor/sistema): `DynamicForm` lo
@@ -51,6 +51,39 @@ export function uploadedDisplayName(value: unknown): string {
51
51
  return parts[parts.length - 1] || cleaned
52
52
  }
53
53
 
54
+ /**
55
+ * True when `file` satisfies an HTML-style accept list (`"image/*,.pdf,image/png"`).
56
+ * Tokens: `type/*` (prefix), `type/sub` (exact MIME) and `.ext` (filename suffix),
57
+ * case-insensitive. An empty/absent list accepts everything. Pure — exported for tests.
58
+ */
59
+ export function fileMatchesAccept(file: { name: string; type: string }, accept?: string): boolean {
60
+ const tokens = (accept ?? '')
61
+ .split(',')
62
+ .map((x) => x.trim().toLowerCase())
63
+ .filter(Boolean)
64
+ if (tokens.length === 0) return true
65
+ const name = (file.name || '').toLowerCase()
66
+ const type = (file.type || '').toLowerCase()
67
+ return tokens.some((tok) => {
68
+ if (tok.startsWith('.')) return name.endsWith(tok)
69
+ if (tok.endsWith('/*')) return type.startsWith(tok.slice(0, -1))
70
+ return type === tok
71
+ })
72
+ }
73
+
74
+ /**
75
+ * Client-side gate shared by the upload widgets: `'type'` when the file does not
76
+ * match `accept`, `'size'` when it exceeds `maxSize` (bytes), else null. Pure.
77
+ */
78
+ export function validateUploadFile(
79
+ file: { name: string; type: string; size: number },
80
+ opts: { accept?: string; maxSize?: number },
81
+ ): 'type' | 'size' | null {
82
+ if (!fileMatchesAccept(file, opts.accept)) return 'type'
83
+ if (opts.maxSize && file.size > opts.maxSize) return 'size'
84
+ return null
85
+ }
86
+
54
87
  export function UploadField({ field, value, onChange }: UploadFieldProps) {
55
88
  const { t } = useTranslation()
56
89
  const api = useApi()
@@ -69,7 +102,16 @@ export function UploadField({ field, value, onChange }: UploadFieldProps) {
69
102
  return
70
103
  }
71
104
  setError(null)
72
- if (maxSize && file.size > maxSize) {
105
+ const rejected = validateUploadFile(file, { accept, maxSize })
106
+ if (rejected === 'type') {
107
+ setError(
108
+ t('common.upload.invalid_type', {
109
+ defaultValue: 'File type not allowed.',
110
+ }),
111
+ )
112
+ return
113
+ }
114
+ if (rejected === 'size' && maxSize) {
73
115
  const mb = (maxSize / (1024 * 1024)).toFixed(1)
74
116
  setError(
75
117
  t('common.upload.too_large', {
@@ -121,11 +163,23 @@ export function UploadField({ field, value, onChange }: UploadFieldProps) {
121
163
  setUploading(false)
122
164
  }
123
165
  },
124
- [api, endpoint, maxSize, storagePath, onChange, t],
166
+ [api, endpoint, accept, maxSize, storagePath, onChange, t],
125
167
  )
126
168
 
127
169
  return (
128
- <div className="grid gap-1.5" data-widget="upload">
170
+ <div
171
+ className="grid gap-1.5"
172
+ data-widget="upload"
173
+ onDragOver={(e) => {
174
+ e.preventDefault()
175
+ }}
176
+ onDrop={(e) => {
177
+ e.preventDefault()
178
+ const dropped = e.dataTransfer?.files?.[0]
179
+ if (!dropped || uploading) return
180
+ void handleFile(dropped)
181
+ }}
182
+ >
129
183
  <FilePickButton
130
184
  id={field.key}
131
185
  accept={accept}