@asteby/metacore-runtime-react 49.11.0 → 49.13.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +40 -0
  3. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  4. package/dist/dialogs/dynamic-record.js +8 -1
  5. package/dist/dynamic-columns.d.ts.map +1 -1
  6. package/dist/dynamic-columns.js +11 -1
  7. package/dist/dynamic-icon.d.ts +16 -1
  8. package/dist/dynamic-icon.d.ts.map +1 -1
  9. package/dist/dynamic-icon.js +36 -5
  10. package/dist/dynamic-table.d.ts +17 -1
  11. package/dist/dynamic-table.d.ts.map +1 -1
  12. package/dist/dynamic-table.js +66 -9
  13. package/dist/icon-aliases.d.ts +2 -0
  14. package/dist/icon-aliases.d.ts.map +1 -0
  15. package/dist/icon-aliases.js +594 -0
  16. package/dist/icon-resolvers.d.ts +13 -0
  17. package/dist/icon-resolvers.d.ts.map +1 -0
  18. package/dist/icon-resolvers.js +36 -0
  19. package/dist/icon-spec.d.ts +17 -0
  20. package/dist/icon-spec.d.ts.map +1 -0
  21. package/dist/icon-spec.js +165 -0
  22. package/dist/index.d.ts +3 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -0
  25. package/dist/types.d.ts +1 -1
  26. package/dist/types.d.ts.map +1 -1
  27. package/package.json +1 -1
  28. package/src/__tests__/dynamic-table-bulk-delete-reasons.test.tsx +224 -0
  29. package/src/__tests__/icon-component.test.tsx +145 -0
  30. package/src/__tests__/icon-spec.test.ts +155 -0
  31. package/src/dialogs/dynamic-record.tsx +17 -1
  32. package/src/dynamic-columns.tsx +22 -1
  33. package/src/dynamic-icon.tsx +68 -3
  34. package/src/dynamic-table.tsx +84 -7
  35. package/src/icon-aliases.ts +602 -0
  36. package/src/icon-resolvers.ts +59 -0
  37. package/src/icon-spec.ts +169 -0
  38. package/src/index.ts +3 -0
  39. package/src/types.ts +3 -0
@@ -0,0 +1,145 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest'
3
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
4
+
5
+ vi.mock('@tanstack/react-router', () => ({ useNavigate: () => () => {} }))
6
+ const I18N = { t: (k: string, o?: { defaultValue?: string }) => o?.defaultValue ?? k, i18n: { language: 'es' } }
7
+ vi.mock('react-i18next', () => ({ useTranslation: () => I18N }))
8
+
9
+ import { Icon, DynamicIcon } from '../dynamic-icon'
10
+ import { registerIconResolver, resolveIconSpec } from '../icon-resolvers'
11
+ import { DynamicTable } from '../dynamic-table'
12
+ import { ApiProvider, type ApiClient } from '../api-context'
13
+ import { useMetadataCache } from '../metadata-cache'
14
+ import type { TableMetadata } from '../types'
15
+
16
+ afterEach(cleanup)
17
+
18
+ describe('registerIconResolver', () => {
19
+ it('el resolutor del host gana a los built-ins y el disposer lo retira', () => {
20
+ const dispose = registerIconResolver((s) => (s === 'fas fa-brain' ? { kind: 'emoji', value: '🧠' } : null))
21
+ expect(resolveIconSpec('fas fa-brain')).toEqual({ kind: 'emoji', value: '🧠' })
22
+ expect(resolveIconSpec('fas fa-bone')).toEqual({ kind: 'lucide', name: 'Bone' })
23
+ dispose()
24
+ expect(resolveIconSpec('fas fa-brain')).toEqual({ kind: 'lucide', name: 'Brain' })
25
+ })
26
+
27
+ it('el más reciente tiene prioridad; null cede al siguiente', () => {
28
+ const a = registerIconResolver(() => ({ kind: 'emoji', value: 'A' }))
29
+ const b = registerIconResolver((s) => (s === 'x' ? { kind: 'emoji', value: 'B' } : null))
30
+ expect(resolveIconSpec('x')).toEqual({ kind: 'emoji', value: 'B' })
31
+ expect(resolveIconSpec('y')).toEqual({ kind: 'emoji', value: 'A' })
32
+ b()
33
+ expect(resolveIconSpec('x')).toEqual({ kind: 'emoji', value: 'A' })
34
+ a()
35
+ })
36
+
37
+ it('un resolutor que lanza se ignora; un ReactNode se renderiza tal cual', () => {
38
+ const a = registerIconResolver(() => {
39
+ throw new Error('boom')
40
+ })
41
+ const b = registerIconResolver((s) => (s === 'sprite:x' ? <svg data-testid="sprite" /> : null))
42
+ expect(resolveIconSpec('Brain')).toEqual({ kind: 'lucide', name: 'Brain' })
43
+ render(<Icon name="sprite:x" />)
44
+ expect(screen.getByTestId('sprite')).toBeTruthy()
45
+ a()
46
+ b()
47
+ })
48
+ })
49
+
50
+ describe('Icon', () => {
51
+ it('lucide: svg, decorativo por defecto', async () => {
52
+ const { container } = render(<Icon name="fas fa-brain" className="h-4" />)
53
+ await waitFor(() => expect(container.querySelector('svg')).toBeTruthy())
54
+ expect(container.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true')
55
+ })
56
+
57
+ it('label vuelve el icono accesible', async () => {
58
+ const { container } = render(<Icon name="Brain" label="Cerebro" />)
59
+ await waitFor(() => expect(container.querySelector('svg')).toBeTruthy())
60
+ expect(container.querySelector('svg')?.getAttribute('aria-label')).toBe('Cerebro')
61
+ })
62
+
63
+ it('emoji: span aria-hidden', () => {
64
+ const { container } = render(<Icon name="🩺" className="x" />)
65
+ const span = container.querySelector('span')!
66
+ expect(span.textContent).toBe('🩺')
67
+ expect(span.getAttribute('aria-hidden')).toBe('true')
68
+ })
69
+
70
+ it('image: img lazy con alt vacío y se oculta si falla', () => {
71
+ const { container } = render(<Icon name="https://x.test/a.png" className="h-5" />)
72
+ const img = container.querySelector('img')!
73
+ expect(img.getAttribute('src')).toBe('https://x.test/a.png')
74
+ expect(img.getAttribute('alt')).toBe('')
75
+ expect(img.getAttribute('loading')).toBe('lazy')
76
+ expect(img.getAttribute('decoding')).toBe('async')
77
+ fireEvent.error(img)
78
+ expect(container.querySelector('img')).toBeNull()
79
+ })
80
+
81
+ it('image: resolveImageSrc transforma la ruta', () => {
82
+ const { container } = render(<Icon name="/u/a.png" resolveImageSrc={(s) => `/api${s}`} />)
83
+ expect(container.querySelector('img')?.getAttribute('src')).toBe('/api/u/a.png')
84
+ })
85
+
86
+ it('unknown: nunca texto crudo; fallback opcional', () => {
87
+ const a = render(<Icon name="algo raro" />)
88
+ expect(a.container.textContent).toBe('')
89
+ a.unmount()
90
+ const b = render(<Icon name="javascript:alert(1)" fallback={<i data-testid="fb" />} />)
91
+ expect(screen.getByTestId('fb')).toBeTruthy()
92
+ expect(b.container.querySelector('img')).toBeNull()
93
+ })
94
+
95
+ it('DynamicIcon conserva su contrato con nombres Lucide', async () => {
96
+ const { container } = render(<DynamicIcon name="CreditCard" className="mr-2 h-4 w-4" />)
97
+ expect(container.firstElementChild?.getAttribute('class')).toContain('mr-2 h-4 w-4')
98
+ await waitFor(() => expect(container.querySelector('svg:not([data-glyph-pending])')).toBeTruthy())
99
+ })
100
+ })
101
+
102
+ describe('DynamicTable columna type "icon"', () => {
103
+ const metaIcon: TableMetadata = {
104
+ title: 'Specialties',
105
+ endpoint: '/data/specialty',
106
+ columns: [
107
+ { key: 'name', label: 'Nombre', type: 'text', sortable: false, filterable: false, searchable: false },
108
+ { key: 'icon', label: 'Icono', type: 'icon', sortable: false, filterable: false, searchable: false },
109
+ ],
110
+ actions: [],
111
+ perPageOptions: [10],
112
+ defaultPerPage: 10,
113
+ searchPlaceholder: 'Buscar...',
114
+ enableCRUDActions: false,
115
+ hasActions: false,
116
+ }
117
+ const rows = [
118
+ { id: 1, name: 'Neurología', icon: 'fas fa-brain' },
119
+ { id: 2, name: 'Raro', icon: 'no se entiende' },
120
+ { id: 3, name: 'Vacio', icon: '' },
121
+ ]
122
+ const api: ApiClient = {
123
+ get: vi.fn(async (url: string) => {
124
+ if (url.startsWith('/metadata/table/')) return { data: { success: true, data: metaIcon } }
125
+ if (url.endsWith('/facets')) return { data: { success: true, data: [] } }
126
+ return { data: { success: true, data: rows, meta: { total: rows.length } } }
127
+ }),
128
+ post: vi.fn(async () => ({ data: { success: true, data: null } })),
129
+ put: vi.fn(async () => ({ data: { success: true, data: null } })),
130
+ delete: vi.fn(async () => ({ data: { success: true, data: null } })),
131
+ }
132
+
133
+ it('"fas fa-brain" dibuja un glifo y nunca el texto crudo', async () => {
134
+ useMetadataCache.getState().setMetadata('specialty', metaIcon)
135
+ const { container } = render(
136
+ <ApiProvider client={api}>
137
+ <DynamicTable model="specialty" enableUrlSync={false} />
138
+ </ApiProvider>,
139
+ )
140
+ await waitFor(() => expect(screen.getAllByText('Neurología').length).toBeGreaterThan(0))
141
+ expect(container.textContent).not.toContain('fas fa-brain')
142
+ expect(container.textContent).not.toContain('no se entiende')
143
+ await waitFor(() => expect(container.querySelector('tbody svg.lucide:not([data-glyph-pending])')).toBeTruthy())
144
+ })
145
+ })
@@ -0,0 +1,155 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import dynamicIconImports from 'lucide-react/dynamicIconImports'
3
+ import { parseIconSpec } from '../icon-spec'
4
+ import { FONT_AWESOME_ALIASES } from '../icon-aliases'
5
+
6
+ const lucide = (name: string) => ({ kind: 'lucide', name })
7
+
8
+ describe('parseIconSpec', () => {
9
+ it.each([
10
+ ['CreditCard', 'CreditCard'],
11
+ ['credit-card', 'CreditCard'],
12
+ ['credit_card', 'CreditCard'],
13
+ ['CreditCardIcon', 'CreditCard'],
14
+ ['Building2', 'Building2'],
15
+ ['building-2', 'Building2'],
16
+ [' brain ', 'Brain'],
17
+ ])('Lucide %s', (input, name) => {
18
+ expect(parseIconSpec(input)).toEqual(lucide(name))
19
+ })
20
+
21
+ it.each([
22
+ // The real ones stored by doctores.lat
23
+ ['fas fa-brain', 'Brain'],
24
+ ['fas fa-female', 'Venus'],
25
+ ['fas fa-bone', 'Bone'],
26
+ ['fas fa-eye', 'Eye'],
27
+ ['fas fa-allergies', 'Flower2'],
28
+ ['fas fa-baby', 'Baby'],
29
+ ['fas fa-user-md', 'Stethoscope'],
30
+ ['fas fa-tooth', 'Toothbrush'],
31
+ // Other FA spellings
32
+ ['fa-solid fa-brain', 'Brain'],
33
+ ['far fa-heart', 'Heart'],
34
+ ['fa fa-user-md', 'Stethoscope'],
35
+ ['fa-brain', 'Brain'],
36
+ ['fa-solid fa-heart-pulse', 'HeartPulse'],
37
+ ['fas fa-heartbeat fa-2x fa-fw', 'HeartPulse'],
38
+ ['fa-regular fa-calendar-check', 'CalendarCheck'],
39
+ ['fal fa-map-marker-alt', 'MapPin'],
40
+ ])('FontAwesome %s', (input, name) => {
41
+ expect(parseIconSpec(input)).toEqual(lucide(name))
42
+ })
43
+
44
+ it.each([
45
+ ['mdi mdi-home', 'Home'],
46
+ ['mdi-home', 'Home'],
47
+ ['bi bi-house', 'House'],
48
+ ['ti ti-home', 'Home'],
49
+ ['ri-home-line', 'Home'],
50
+ ['mdi:home', 'Home'],
51
+ ['lucide:brain', 'Brain'],
52
+ ['material-icons home', 'Home'],
53
+ ])('otras librerías %s', (input, name) => {
54
+ expect(parseIconSpec(input)).toEqual(lucide(name))
55
+ })
56
+
57
+ it.each(['🩺', '👨‍⚕️', '🇲🇽', '👍🏽', '1️⃣', '❤️'])('emoji %s', (value) => {
58
+ expect(parseIconSpec(value)).toEqual({ kind: 'emoji', value })
59
+ })
60
+
61
+ it('dos emojis o emoji con texto no son un emoji', () => {
62
+ expect(parseIconSpec('🩺🩺').kind).toBe('unknown')
63
+ expect(parseIconSpec('🩺 hola').kind).toBe('unknown')
64
+ })
65
+
66
+ it.each([
67
+ 'https://cdn.example.com/a.png',
68
+ 'http://example.com/icon',
69
+ '/uploads/a.png',
70
+ './a.png',
71
+ '../a.svg',
72
+ 'uploads/a.webp',
73
+ 'data:image/png;base64,iVBORw0KGgo=',
74
+ 'data:image/svg+xml;base64,PHN2Zy8+',
75
+ 'data:image/jpeg;base64,/9j/4AAQ',
76
+ ])('imagen válida %s', (src) => {
77
+ expect(parseIconSpec(src)).toEqual({ kind: 'image', src })
78
+ })
79
+
80
+ it.each([
81
+ ['letras', 'a'.repeat(100_000)],
82
+ ['fa- encadenado', 'fa-a'.repeat(25_000)],
83
+ ['estilo repetido', 'fas '.repeat(25_000)],
84
+ ['ruta larga', '/' + 'a'.repeat(100_000)],
85
+ ['data:image enorme', 'data:image/png;base64,' + 'A'.repeat(100_000)],
86
+ ['emoji ZWJ repetido', '👨\u200d⚕️'.repeat(10_000)],
87
+ ])('entrada de 100k caracteres (%s) responde rápido y sin romper', (_n, raw) => {
88
+ const t0 = Date.now()
89
+ expect(() => parseIconSpec(raw)).not.toThrow()
90
+ expect(Date.now() - t0).toBeLessThan(500) // sin backtracking catastrófico
91
+ })
92
+
93
+ it.each([
94
+ 'javascript:alert(1)',
95
+ 'JavaScript:alert(1)',
96
+ 'vbscript:x',
97
+ 'data:text/html;base64,PHNjcmlwdD4=',
98
+ 'data:image/svg+xml;base64,AAA" onerror="x',
99
+ 'data:application/javascript,alert(1)',
100
+ 'file:///etc/passwd',
101
+ '//evil.example.com/x.png',
102
+ '<svg onload=alert(1)></svg>',
103
+ 'blob:https://x/y',
104
+ 'https://x.com/a b.png',
105
+ ])('inválido o peligroso %s -> unknown', (raw) => {
106
+ expect(parseIconSpec(raw).kind).toBe('unknown')
107
+ })
108
+
109
+ it.each(['', ' ', 'no es un icono', 'fas fa-no-existe-xyz', 'fa-solid', 'Icon', 'texto.largo'])(
110
+ 'unknown %j',
111
+ (raw) => {
112
+ expect(parseIconSpec(raw).kind).toBe('unknown')
113
+ },
114
+ )
115
+
116
+ it('valores no string', () => {
117
+ expect(parseIconSpec(null)).toEqual({ kind: 'unknown', raw: '' })
118
+ expect(parseIconSpec(undefined)).toEqual({ kind: 'unknown', raw: '' })
119
+ expect(parseIconSpec(42)).toEqual({ kind: 'unknown', raw: '42' })
120
+ expect(parseIconSpec({})).toMatchObject({ kind: 'unknown' })
121
+ })
122
+
123
+ it('es determinista', () => {
124
+ expect(parseIconSpec('fas fa-brain')).toEqual(parseIconSpec('fas fa-brain'))
125
+ })
126
+ })
127
+
128
+ describe('FONT_AWESOME_ALIASES', () => {
129
+ it('tiene una tabla amplia', () => {
130
+ expect(Object.keys(FONT_AWESOME_ALIASES).length).toBeGreaterThan(150)
131
+ })
132
+
133
+ it('todo alias apunta a un glifo Lucide real', () => {
134
+ const keys = new Set(Object.keys(dynamicIconImports))
135
+ const bad = Object.entries(FONT_AWESOME_ALIASES).filter(([, v]) => !keys.has(v))
136
+ expect(bad).toEqual([])
137
+ })
138
+
139
+ it('cada alias resuelve a lucide vía parseIconSpec', () => {
140
+ for (const name of Object.keys(FONT_AWESOME_ALIASES)) {
141
+ expect(parseIconSpec(`fas fa-${name}`).kind, name).toBe('lucide')
142
+ }
143
+ })
144
+
145
+ it('cubre los iconos médicos usados por doctores.lat', () => {
146
+ const names = [
147
+ 'brain', 'bone', 'eye', 'heart', 'heartbeat', 'stethoscope', 'user-md', 'user-nurse', 'tooth',
148
+ 'baby', 'female', 'male', 'venus-mars', 'allergies', 'lungs', 'x-ray', 'pills', 'syringe',
149
+ 'hospital', 'ambulance', 'procedures', 'dna', 'microscope', 'notes-medical', 'file-medical',
150
+ 'vial', 'thermometer', 'wheelchair', 'diagnoses', 'head-side-virus', 'child', 'clinic-medical',
151
+ 'hospital-alt', 'user-doctor', 'map-marker-alt', 'shield-heart', 'hand-sparkles',
152
+ ]
153
+ for (const n of names) expect(parseIconSpec(`fas fa-${n}`).kind, n).toBe('lucide')
154
+ })
155
+ })
@@ -71,7 +71,7 @@ import { FieldCell } from '../field-grid'
71
71
  import { isNilUuid, normalizeNilUuid } from '../nil-uuid'
72
72
  import { normalizeRefFieldsForSubmit } from './normalize-submit'
73
73
  import { validateValues, bagHasErrors, exemptUnchangedRuleIssues } from '../validator'
74
- import { DynamicIcon, isLucideIconName } from '../dynamic-icon'
74
+ import { DynamicIcon, Icon, isLucideIconName } from '../dynamic-icon'
75
75
  import { IconPickerField } from '../icon-picker-field'
76
76
  import { humanizeToken, localizeFieldLabel } from '../dynamic-columns-helpers'
77
77
  import { formatDateCell } from '../dynamic-columns'
@@ -1690,6 +1690,22 @@ export function ViewValue({
1690
1690
  )
1691
1691
  }
1692
1692
 
1693
+ // Explicit `type: 'icon'`: any stored icon format via the universal resolver.
1694
+ if (renderAs === 'icon') {
1695
+ const empty = <p className="text-sm py-1 text-muted-foreground">-</p>
1696
+ if (!value) return empty
1697
+ return (
1698
+ <div className="py-1">
1699
+ <Icon
1700
+ name={value}
1701
+ className="h-6 w-6"
1702
+ fallback={empty}
1703
+ resolveImageSrc={(src) => (/^(?:data:|https?:)/i.test(src) ? src : getImageUrl(src))}
1704
+ />
1705
+ </div>
1706
+ )
1707
+ }
1708
+
1693
1709
  if (field.type === 'image' || renderAs === 'image') {
1694
1710
  if (isLucideIconName(value)) {
1695
1711
  return <IconNameViewValue name={value} />
@@ -49,7 +49,7 @@ import {
49
49
  } from './display-value'
50
50
  import { MediaValue } from './rich-url'
51
51
  import { OptionsContext } from './options-context'
52
- import { DynamicIcon, isLucideIconName } from './dynamic-icon'
52
+ import { DynamicIcon, Icon, isLucideIconName } from './dynamic-icon'
53
53
  import { CollectionCell } from './collection-cell'
54
54
  import { isNilUuid, normalizeNilUuid } from './nil-uuid'
55
55
  import { useOptionsResolver } from './use-options-resolver'
@@ -1482,6 +1482,27 @@ export function makeDefaultGetDynamicColumns(
1482
1482
  return <ImageCell value={imageSrc} getImageUrl={getImageUrl} />
1483
1483
  }
1484
1484
 
1485
+ case 'icon': {
1486
+ // Explicit `type: 'icon'` only: any stored icon format
1487
+ // (Lucide, FontAwesome classes, emoji, image URL).
1488
+ // Uninterpretable values show the dash, never raw text.
1489
+ if (!value) return <EmptyCell />
1490
+ return (
1491
+ <Icon
1492
+ name={value}
1493
+ className="h-5 w-5 text-foreground/80"
1494
+ fallback={<EmptyCell />}
1495
+ resolveImageSrc={(src) =>
1496
+ /^(?:data:|https?:)/i.test(src)
1497
+ ? src
1498
+ : getImageUrl(
1499
+ resolveImageSrc(col, src, apiBaseUrl, normalizeImagePath),
1500
+ )
1501
+ }
1502
+ />
1503
+ )
1504
+ }
1505
+
1485
1506
  case 'image_stack': {
1486
1507
  // Defensive: normally handled above before the
1487
1508
  // switch; kept so a late `type: image_stack` without
@@ -2,14 +2,30 @@
2
2
  // set into the shared chunk. It draws through the shared glyph registry of
3
3
  // @asteby/metacore-ui: a glyph seen before renders in the first frame, and an
4
4
  // unseen one holds its box until it loads, so the label next to it stays put.
5
+ import { useState, type ReactNode } from 'react'
5
6
  import dynamicIconImports from 'lucide-react/dynamicIconImports'
6
7
  import { Glyph } from '@asteby/metacore-ui/icons'
8
+ import { resolveIconSpec } from './icon-resolvers'
7
9
 
8
10
  export interface DynamicIconProps {
9
11
  name: string
10
12
  className?: string
11
13
  }
12
14
 
15
+ export interface IconProps {
16
+ /** Any icon value: Lucide name, FontAwesome classes, emoji, image URL... */
17
+ name: unknown
18
+ className?: string
19
+ /** Accessible name. Without it the icon is decorative (aria-hidden). */
20
+ label?: string
21
+ /** Drawn when the value cannot be interpreted. Default: nothing. */
22
+ fallback?: ReactNode
23
+ /** Maps an image `src` before it reaches <img> (e.g. host `getImageUrl`). */
24
+ resolveImageSrc?: (src: string) => string
25
+ /** Render image sources (default true). DynamicIcon turns it off. */
26
+ images?: boolean
27
+ }
28
+
13
29
  type IconName = keyof typeof dynamicIconImports
14
30
 
15
31
  function pascalToKebab(pascal: string): string {
@@ -35,10 +51,59 @@ function loaderFor(pascal: string) {
35
51
  )
36
52
  }
37
53
 
54
+ function IconImage({ src, className, label }: { src: string; className?: string; label?: string }) {
55
+ const [failed, setFailed] = useState<string | null>(null)
56
+ if (failed === src) return null
57
+ return (
58
+ <img
59
+ src={src}
60
+ alt={label ?? ''}
61
+ loading="lazy"
62
+ decoding="async"
63
+ className={className}
64
+ onError={() => setFailed(src)}
65
+ />
66
+ )
67
+ }
68
+
69
+ // Icon — renders any icon value the SDK can interpret (see parseIconSpec and
70
+ // registerIconResolver): Lucide glyph, emoji, image or a host-rendered node.
71
+ // A value nobody understands renders `fallback` (default nothing), never the
72
+ // raw text. Decorative (aria-hidden) unless `label` is given.
73
+ export function Icon({ name, className, label, fallback = null, resolveImageSrc, images = true }: IconProps) {
74
+ const spec = resolveIconSpec(name)
75
+ const a11y = label ? ({ role: 'img', 'aria-label': label } as const) : ({ 'aria-hidden': true } as const)
76
+ switch (spec.kind) {
77
+ case 'lucide':
78
+ return <Glyph name={spec.name} className={className} {...a11y} />
79
+ case 'emoji':
80
+ return (
81
+ <span className={className} {...a11y}>
82
+ {spec.value}
83
+ </span>
84
+ )
85
+ case 'image':
86
+ if (!images) return <>{fallback}</>
87
+ return (
88
+ <IconImage
89
+ src={resolveImageSrc ? resolveImageSrc(spec.src) : spec.src}
90
+ className={className}
91
+ label={label}
92
+ />
93
+ )
94
+ case 'node':
95
+ return <>{spec.node}</>
96
+ default:
97
+ return <>{fallback}</>
98
+ }
99
+ }
100
+
101
+ // DynamicIcon keeps its { name, className } contract: Lucide names resolve
102
+ // exactly as before; FontAwesome classes, emoji and host resolvers now work
103
+ // too. Image paths still draw nothing here (icon slots in menus/buttons never
104
+ // showed <img>); use <Icon> or a `type: 'icon'` column for images.
38
105
  export function DynamicIcon({ name, className }: DynamicIconProps) {
39
- const resolved = resolveLucideIconName(name)
40
- if (!resolved) return null
41
- return <Glyph name={resolved} className={className} />
106
+ return <Icon name={name} className={className} images={false} />
42
107
  }
43
108
 
44
109
  // resolveLucideIconName — canonical PascalCase lucide name for a value that is
@@ -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