@asteby/metacore-runtime-react 53.23.2 → 53.25.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 (55) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/addon-page-host.d.ts +6 -1
  3. package/dist/addon-page-host.d.ts.map +1 -1
  4. package/dist/addon-page-host.js +16 -2
  5. package/dist/dashboard-grid.d.ts +1 -1
  6. package/dist/dashboard-grid.d.ts.map +1 -1
  7. package/dist/dashboard-grid.js +19 -17
  8. package/dist/dashboard-types.d.ts +6 -0
  9. package/dist/dashboard-types.d.ts.map +1 -1
  10. package/dist/dynamic-columns.d.ts +16 -0
  11. package/dist/dynamic-columns.d.ts.map +1 -1
  12. package/dist/dynamic-columns.js +63 -8
  13. package/dist/dynamic-crud-page.d.ts.map +1 -1
  14. package/dist/dynamic-crud-page.js +10 -7
  15. package/dist/dynamic-table.d.ts +3 -1
  16. package/dist/dynamic-table.d.ts.map +1 -1
  17. package/dist/dynamic-table.js +24 -12
  18. package/dist/host-api-client.d.ts +55 -0
  19. package/dist/host-api-client.d.ts.map +1 -0
  20. package/dist/host-api-client.js +85 -0
  21. package/dist/host-api-context.d.ts +10 -0
  22. package/dist/host-api-context.d.ts.map +1 -0
  23. package/dist/host-api-context.js +10 -0
  24. package/dist/host-api.d.ts.map +1 -1
  25. package/dist/host-api.js +4 -0
  26. package/dist/index.d.ts +5 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +4 -0
  29. package/dist/model-labels.d.ts +38 -0
  30. package/dist/model-labels.d.ts.map +1 -0
  31. package/dist/model-labels.js +35 -0
  32. package/dist/types.d.ts +23 -3
  33. package/dist/types.d.ts.map +1 -1
  34. package/dist/use-host-api-client.d.ts +8 -0
  35. package/dist/use-host-api-client.d.ts.map +1 -0
  36. package/dist/use-host-api-client.js +12 -0
  37. package/package.json +9 -9
  38. package/src/__tests__/host-api-client.test.tsx +119 -0
  39. package/src/__tests__/initials-avatar-cell.test.tsx +54 -0
  40. package/src/__tests__/load-guard.test.tsx +94 -0
  41. package/src/__tests__/model-labels.test.tsx +31 -0
  42. package/src/__tests__/resolve-row-actions.test.ts +44 -0
  43. package/src/addon-page-host.tsx +18 -2
  44. package/src/dashboard-grid.tsx +49 -35
  45. package/src/dashboard-types.ts +6 -0
  46. package/src/dynamic-columns.tsx +68 -10
  47. package/src/dynamic-crud-page.tsx +10 -7
  48. package/src/dynamic-table.tsx +38 -12
  49. package/src/host-api-client.ts +137 -0
  50. package/src/host-api-context.tsx +18 -0
  51. package/src/host-api.ts +3 -0
  52. package/src/index.ts +11 -0
  53. package/src/model-labels.ts +80 -0
  54. package/src/types.ts +28 -3
  55. package/src/use-host-api-client.ts +13 -0
@@ -7,6 +7,7 @@
7
7
  import * as React from 'react'
8
8
  import { useTranslation } from 'react-i18next'
9
9
  import { cn } from '@asteby/metacore-ui/lib'
10
+ import { LoadState } from '@asteby/metacore-ui/primitives'
10
11
  import { useCan, usePermissionsActive } from './permissions-context'
11
12
  import type {
12
13
  DashboardGridProps,
@@ -58,6 +59,7 @@ export function DashboardGrid({
58
59
  groups,
59
60
  widgets,
60
61
  loadData,
62
+ loadTimeoutMs,
61
63
  isAdmin,
62
64
  locale,
63
65
  currency,
@@ -102,6 +104,9 @@ export function DashboardGrid({
102
104
  Record<string, import('./dashboard-types').WidgetData> | null
103
105
  >(null)
104
106
  const [loading, setLoading] = React.useState(true)
107
+ // Batch failure / hung request -> actionable error with retry (not an eternal skeleton).
108
+ const [loadFailed, setLoadFailed] = React.useState(false)
109
+ const [reloadTick, setReloadTick] = React.useState(0)
105
110
 
106
111
  React.useEffect(() => {
107
112
  let cancelled = false
@@ -111,6 +116,7 @@ export function DashboardGrid({
111
116
  return
112
117
  }
113
118
  setLoading(true)
119
+ setLoadFailed(false)
114
120
  loadData(keys)
115
121
  .then((res) => {
116
122
  if (!cancelled) {
@@ -119,10 +125,9 @@ export function DashboardGrid({
119
125
  }
120
126
  })
121
127
  .catch(() => {
122
- // Batch failure: still render the grid; every widget falls to
123
- // its empty/error state rather than blanking the page.
124
128
  if (!cancelled) {
125
129
  setData({})
130
+ setLoadFailed(true)
126
131
  setLoading(false)
127
132
  }
128
133
  })
@@ -130,7 +135,7 @@ export function DashboardGrid({
130
135
  cancelled = true
131
136
  }
132
137
  // eslint-disable-next-line react-hooks/exhaustive-deps
133
- }, [keySig, loadData])
138
+ }, [keySig, loadData, reloadTick])
134
139
 
135
140
  // Flatten every group into ONE ordered list (compact KPIs before charts) for
136
141
  // the masonry grid. MUST run before any early return — it is a hook, and a
@@ -166,41 +171,50 @@ export function DashboardGrid({
166
171
  )
167
172
  }
168
173
 
174
+ const gridClass = cn(
175
+ // Masonry: balanced CSS columns. Cards take their natural height
176
+ // (compact stats, taller charts) and flow to equalize column
177
+ // height, so there are NO blank cells.
178
+ 'columns-1 gap-4 md:columns-2 xl:columns-3',
179
+ className,
180
+ )
181
+ const translated = (spec: DashboardWidgetSpec) => ({
182
+ ...spec,
183
+ title: tr(spec.title, spec.title),
184
+ subtitle: tr(spec.subtitle, spec.subtitle),
185
+ })
186
+
169
187
  return (
170
- <div
171
- data-testid="dashboard-grid"
172
- className={cn(
173
- // Masonry: balanced CSS columns. Cards take their natural height
174
- // (compact stats, taller charts) and flow to equalize column
175
- // height, so there are NO blank cells — the gaps a fixed grid
176
- // leaves around mixed 1×1 / 2×2 tiles simply don't exist here.
177
- 'columns-1 gap-4 md:columns-2 xl:columns-3',
178
- className,
179
- )}
188
+ <LoadState
189
+ loading={loading}
190
+ error={loadFailed}
191
+ timeoutMs={loadTimeoutMs}
192
+ onRetry={() => setReloadTick((n) => n + 1)}
193
+ labels={{ title: s.loadErrorTitle, hint: s.loadErrorHint, retry: s.retry }}
194
+ skeleton={
195
+ <div data-testid="dashboard-grid" className={gridClass}>
196
+ {ordered.map((spec) => (
197
+ <div key={spec.key} className="mb-4 break-inside-avoid">
198
+ <WidgetSkeleton spec={translated(spec)} />
199
+ </div>
200
+ ))}
201
+ </div>
202
+ }
180
203
  >
181
- {ordered.map((spec) => {
182
- const rspec = {
183
- ...spec,
184
- title: tr(spec.title, spec.title),
185
- subtitle: tr(spec.subtitle, spec.subtitle),
186
- }
187
- return (
204
+ <div data-testid="dashboard-grid" className={gridClass}>
205
+ {ordered.map((spec) => (
188
206
  <div key={spec.key} className="mb-4 break-inside-avoid">
189
- {loading ? (
190
- <WidgetSkeleton spec={rspec} />
191
- ) : (
192
- <WidgetRenderer
193
- spec={rspec}
194
- data={data?.[spec.key]}
195
- locale={locale}
196
- currency={currency}
197
- emptyText={spec.empty ? tr(spec.empty, spec.empty) : s.widgetEmpty}
198
- errorText={s.widgetError}
199
- />
200
- )}
207
+ <WidgetRenderer
208
+ spec={translated(spec)}
209
+ data={data?.[spec.key]}
210
+ locale={locale}
211
+ currency={currency}
212
+ emptyText={spec.empty ? tr(spec.empty, spec.empty) : s.widgetEmpty}
213
+ errorText={s.widgetError}
214
+ />
201
215
  </div>
202
- )
203
- })}
204
- </div>
216
+ ))}
217
+ </div>
218
+ </LoadState>
205
219
  )
206
220
  }
@@ -152,6 +152,8 @@ export interface DashboardGridProps {
152
152
  currency?: string
153
153
  /** Extra class on the grid root. */
154
154
  className?: string
155
+ /** Max ms the batch load may take before an error + retry replaces the skeletons. Default 15000; 0 disables. */
156
+ loadTimeoutMs?: number
155
157
  /** Optional override for empty/loading/error copy. */
156
158
  strings?: Partial<DashboardGridStrings>
157
159
  }
@@ -166,4 +168,8 @@ export interface DashboardGridStrings {
166
168
  widgetError: string
167
169
  /** Per-widget empty (no data) fallback when the spec has no `empty` key. */
168
170
  widgetEmpty: string
171
+ /** Optional overrides of the load-failure state (default: i18n `loadState.*`). */
172
+ loadErrorTitle?: string
173
+ loadErrorHint?: string
174
+ retry?: string
169
175
  }
@@ -35,6 +35,7 @@ import {
35
35
  import {
36
36
  generateBadgeStyles,
37
37
  getInitials,
38
+ optionColor,
38
39
  relationChipStyles,
39
40
  } from '@asteby/metacore-ui/lib'
40
41
  import { Progress } from './dialogs/_primitives'
@@ -287,7 +288,24 @@ export const isActionAllowedForRowState = (action: any, row: any, stageField?: s
287
288
  */
288
289
  export const isActionConditionMet = (action: any, row: any): boolean => {
289
290
  if (!action?.condition) return true
290
- const { field, operator, value } = action.condition
291
+ return evalActionCondition(action.condition, row)
292
+ }
293
+
294
+ /**
295
+ * Evaluates one ActionCondition (or an `all`/`any` composition of them) against a row.
296
+ * Besides the equality/membership/truthy family it supports numeric comparisons
297
+ * (`gt` | `gte` | `lt` | `lte`: both sides coerced with Number(); a non-numeric side never matches)
298
+ * and `all` / `any` groups (`{ operator: 'all', conditions: [...] }`), so a host can ship
299
+ * `amount > 0 && status != 4` as data instead of an unexpressible legacy string.
300
+ */
301
+ export const evalActionCondition = (cond: any, row: any): boolean => {
302
+ const { field, operator, value } = cond ?? {}
303
+ const group = String(operator ?? '').toLowerCase()
304
+ if (group === 'all' || group === 'any') {
305
+ const list: any[] = Array.isArray(cond.conditions) ? cond.conditions : []
306
+ if (list.length === 0) return true
307
+ return group === 'all' ? list.every((c) => evalActionCondition(c, row)) : list.some((c) => evalActionCondition(c, row))
308
+ }
291
309
  if (!field) return true
292
310
 
293
311
  const coerce = (v: unknown): string => {
@@ -324,6 +342,16 @@ export const isActionConditionMet = (action: any, row: any): boolean => {
324
342
  case 'blank':
325
343
  case 'empty':
326
344
  return rowValue === '' || rowValue === 'false' || rowValue === '0'
345
+ case 'gt':
346
+ case 'gte':
347
+ case 'lt':
348
+ case 'lte': {
349
+ if (rowValue === '' || values[0] === '' || values[0] === undefined) return false
350
+ const l = Number(rowValue)
351
+ const r = Number(values[0])
352
+ if (Number.isNaN(l) || Number.isNaN(r)) return false
353
+ return op === 'gt' ? l > r : op === 'gte' ? l >= r : op === 'lt' ? l < r : l <= r
354
+ }
327
355
  default:
328
356
  return true
329
357
  }
@@ -670,6 +698,21 @@ export function resolveActorDisplayName(raw: unknown): string | undefined {
670
698
  * any backend that stores just `"2.png"` next to a nested key) and the value
671
699
  * branch injected basePath into already-rooted paths (junk URLs).
672
700
  */
701
+ /**
702
+ * Whether `raw` can plausibly be an image reference (URL, data/blob URI,
703
+ * rooted/relative path or a file name with an image extension). A plain label
704
+ * such as "Ana Perez" — what a backend sends when it fills `avatar` with the
705
+ * display name instead of a file — is NOT, and must never be turned into a
706
+ * request (it used to become `apiBaseUrl + "Ana Perez"`, a 404 per row).
707
+ */
708
+ export const looksLikeImageRef = (raw: string): boolean => {
709
+ const v = raw.trim()
710
+ if (!v) return false
711
+ if (/^(https?:|data:image\/|blob:)/i.test(v) || v.startsWith('/')) return true
712
+ if (/\s/.test(v)) return false
713
+ return v.includes('/') || /\.(png|jpe?g|gif|webp|avif|svg|bmp|ico)(\?.*)?$/i.test(v)
714
+ }
715
+
673
716
  export const resolveAvatarSrc = (
674
717
  col: ColumnDefinition,
675
718
  row: any,
@@ -691,7 +734,7 @@ export const resolveAvatarSrc = (
691
734
  if (sibling) raw = String(sibling)
692
735
  }
693
736
  if (!raw && value !== undefined && value !== null && value !== '') raw = String(value)
694
- if (!raw) return undefined
737
+ if (!raw || !looksLikeImageRef(raw)) return undefined
695
738
  if (raw.startsWith('http') || raw.startsWith('/')) return raw
696
739
  const basePath = styleCfg(col, 'base_path', 'basePath') ?? col.basePath ?? ''
697
740
  return `${apiBaseUrl}${basePath}${raw}`
@@ -871,17 +914,23 @@ const AvatarCell: React.FC<{
871
914
  shape?: 'rounded' | 'circle'
872
915
  /** Per-row brand colour (hex) for the initials fallback. */
873
916
  color?: string
874
- }> = ({ name, desc, avatarSrc, getImageUrl, shape, color }) => {
917
+ /** Paint the initials fallback with a stable colour derived from `name`. */
918
+ autoColor?: boolean
919
+ }> = ({ name, desc, avatarSrc, getImageUrl, shape, color, autoColor }) => {
875
920
  const radius = shape === 'circle' ? 'rounded-full' : 'rounded-lg'
876
- const brand = brandAvatarColors(color)
921
+ // Brand colour wins; with `autoColor` a stable per-name colour (same hash as
922
+ // every other avatar in the platform) so the imageless case needs no backend colour.
923
+ const brand = brandAvatarColors(color) ?? (autoColor ? brandAvatarColors(`#${optionColor(name)}`) : undefined)
877
924
  return (
878
925
  <div className="flex items-center gap-3 min-w-0">
879
926
  <Avatar className={`h-8 w-8 ${radius} ring-1 ring-border/50`}>
880
- <AvatarImage
881
- src={avatarSrc ? getImageUrl(avatarSrc) : ''}
882
- alt={name}
883
- className={shape === 'circle' ? 'object-cover' : 'object-contain p-0.5'}
884
- />
927
+ {avatarSrc ? (
928
+ <AvatarImage
929
+ src={getImageUrl(avatarSrc)}
930
+ alt={name}
931
+ className={shape === 'circle' ? 'object-cover' : 'object-contain p-0.5'}
932
+ />
933
+ ) : null}
885
934
  <AvatarFallback
886
935
  className={`text-[10px] font-bold ${radius} ${brand ? '' : 'bg-primary/5 text-primary'}`}
887
936
  style={brand ? { backgroundColor: brand.background, color: brand.color } : undefined}
@@ -1257,6 +1306,8 @@ export function makeDefaultGetDynamicColumns(
1257
1306
  )
1258
1307
  }
1259
1308
 
1309
+ case 'initial':
1310
+ case 'initials':
1260
1311
  case 'search':
1261
1312
  case 'avatar':
1262
1313
  case 'creator':
@@ -1317,7 +1368,13 @@ export function makeDefaultGetDynamicColumns(
1317
1368
  )
1318
1369
  }
1319
1370
 
1320
- const avatarSrc = resolveAvatarSrc(col, row.original, value, apiBaseUrl)
1371
+ // `initial`/`initials`: declarative imageless avatar — never
1372
+ // resolves a source, so it can't hit the network.
1373
+ const isInitialStyle = renderAs === 'initial' || renderAs === 'initials'
1374
+ const avatarSrc =
1375
+ isInitialStyle
1376
+ ? undefined
1377
+ : resolveAvatarSrc(col, row.original, value, apiBaseUrl)
1321
1378
 
1322
1379
  return (
1323
1380
  <AvatarCell
@@ -1327,6 +1384,7 @@ export function makeDefaultGetDynamicColumns(
1327
1384
  getImageUrl={getImageUrl}
1328
1385
  shape={avatarShape}
1329
1386
  color={brandColor ? String(brandColor) : undefined}
1387
+ autoColor={isInitialStyle || styleCfg(col, 'tone') === 'auto'}
1330
1388
  />
1331
1389
  )
1332
1390
  }
@@ -42,6 +42,7 @@ import {
42
42
  } from './document-form-dialog'
43
43
  import { ExportDialog } from './dialogs/export'
44
44
  import { ImportDialog } from './dialogs/import'
45
+ import { useModelLabels } from './model-labels'
45
46
  import { getModelExtension } from './model-extension-registry'
46
47
  import { ModelActionToolbar } from './model-action-toolbar'
47
48
  import { BulkImageImportButton } from './bulk-image-dialog'
@@ -187,12 +188,14 @@ export function DynamicCRUDPage(props: DynamicCRUDPageProps) {
187
188
  }
188
189
  }, [model, cachedMeta, api])
189
190
 
190
- const title = titleOverride ?? ext?.title ?? metadata?.title ?? model
191
- const resolvedNewLabel = newLabel ?? ext?.newLabel
192
- const singular = useMemo(() => {
193
- const t = title.replace(/s$/i, '')
194
- return t.charAt(0).toUpperCase() + t.slice(1)
195
- }, [title])
191
+ const { title, newLabel: resolvedNewLabel } = useModelLabels({
192
+ model,
193
+ title: metadata?.title,
194
+ titleKey: metadata?.titleKey ?? metadata?.title_key,
195
+ titleOverride: titleOverride ?? ext?.title,
196
+ newLabelOverride: newLabel ?? ext?.newLabel,
197
+ newPrefix: strings.newPrefix,
198
+ })
196
199
 
197
200
  const enableCRUD = metadata?.enableCRUDActions ?? false
198
201
  // Una sola primaria: placement create, replaces_create, create_mode o la
@@ -310,7 +313,7 @@ export function DynamicCRUDPage(props: DynamicCRUDPageProps) {
310
313
  className='inline-flex items-center gap-2 h-9 px-3 rounded-md bg-primary text-primary-foreground hover:opacity-90 text-sm font-medium'
311
314
  >
312
315
  <Plus className='size-4' />
313
- {resolvedNewLabel ?? `${strings.newPrefix} ${singular}`}
316
+ {resolvedNewLabel}
314
317
  </button>
315
318
  )}
316
319
  </div>
@@ -37,6 +37,7 @@ import {
37
37
  } from '@tanstack/react-table'
38
38
  import { cn } from '@asteby/metacore-ui/lib'
39
39
  import { preloadGlyphs } from '@asteby/metacore-ui/icons'
40
+ import { useLoadingGuard } from '@asteby/metacore-ui/hooks'
40
41
  import {
41
42
  Table,
42
43
  TableBody,
@@ -47,6 +48,7 @@ import {
47
48
  TableRow,
48
49
  Button,
49
50
  Skeleton,
51
+ LoadState,
50
52
  AlertDialog,
51
53
  AlertDialogAction,
52
54
  AlertDialogCancel,
@@ -300,6 +302,8 @@ export interface DynamicTableProps {
300
302
  * mode exactly as before.
301
303
  */
302
304
  infiniteScroll?: boolean
305
+ /** Max ms a metadata/list request may stay loading before an error + retry replaces the skeleton. Default 15000; 0 disables. */
306
+ loadTimeoutMs?: number
303
307
  /**
304
308
  * Row virtualization. When the visible row model has at least N rows,
305
309
  * only viewport rows are mounted (helps infinite scroll and large page
@@ -424,6 +428,7 @@ export function DynamicTable({
424
428
  currency: currencyProp,
425
429
  pagination: paginationMode,
426
430
  infiniteScroll: infiniteScrollProp = false,
431
+ loadTimeoutMs,
427
432
  virtualizeRows,
428
433
  extraBulkActions,
429
434
  hideBulkDelete,
@@ -492,6 +497,12 @@ export function DynamicTable({
492
497
  // A list request that failed for a reason other than 403 (500, network,
493
498
  // `success: false`). Shown with a retry instead of a misleading "no results".
494
499
  const [loadError, setLoadError] = useState(false)
500
+ // A list request that never answers must not leave the skeleton up forever:
501
+ // after the guard's timeout it is shown as a load error with retry.
502
+ const dataGuard = useLoadingGuard(loadingData && data.length === 0, { timeoutMs: loadTimeoutMs })
503
+ const showLoadError = loadError || dataGuard.timedOut
504
+ const showDataSkeleton = loadingData && data.length === 0 && !dataGuard.timedOut
505
+ const [metaReload, setMetaReload] = useState(0)
495
506
  const infPageRef = useRef(1)
496
507
  const [optionsMap, setOptionsMap] = useState<Map<string, any[]>>(new Map())
497
508
 
@@ -896,7 +907,12 @@ export function DynamicTable({
896
907
  }
897
908
  }
898
909
  initMetadataAndOptions()
899
- }, [model]) // eslint-disable-line react-hooks/exhaustive-deps
910
+ }, [model, metaReload]) // eslint-disable-line react-hooks/exhaustive-deps
911
+
912
+ const retryMetadata = useCallback(() => {
913
+ metaInitRef.current = false
914
+ setMetaReload((n) => n + 1)
915
+ }, [])
900
916
 
901
917
  // Derived from `metadata.columns[].searchable`. `null` means the kernel
902
918
  // didn't emit the flag for any column → preserve legacy "search every
@@ -1278,6 +1294,11 @@ export function DynamicTable({
1278
1294
  fetchAggregates()
1279
1295
  }, [infiniteScroll, fetchPage, fetchData, fetchAggregates])
1280
1296
 
1297
+ const retryLoad = useCallback(() => {
1298
+ dataGuard.retry()
1299
+ handleRefresh()
1300
+ }, [dataGuard.retry, handleRefresh])
1301
+
1281
1302
  // Per-row action dispatch (view/edit/delete/link/custom) + its dialogs live
1282
1303
  // in the shared hook so DynamicKanban's card menu behaves identically.
1283
1304
  const { handleInternalAction, dialogs: rowActionDialogs } = useDynamicRowActions({
@@ -1626,8 +1647,15 @@ export function DynamicTable({
1626
1647
  </>
1627
1648
  )
1628
1649
 
1629
- if (loading) {
1650
+ if (loading || !metadata) {
1630
1651
  return (
1652
+ <LoadState
1653
+ loading={loading}
1654
+ timeoutMs={loadTimeoutMs}
1655
+ error={!loading && !metadata}
1656
+ onRetry={retryMetadata}
1657
+ className='flex flex-col h-full min-h-0 w-full'
1658
+ skeleton={
1631
1659
  <div className='flex flex-col h-full min-h-0 w-full'>
1632
1660
  <div className='pb-4 shrink-0'>
1633
1661
  <div className="flex items-center justify-between">
@@ -1653,13 +1681,11 @@ export function DynamicTable({
1653
1681
  </Table>
1654
1682
  </div>
1655
1683
  </div>
1684
+ }
1685
+ />
1656
1686
  )
1657
1687
  }
1658
1688
 
1659
- if (!metadata) {
1660
- return <div className="text-center text-muted-foreground py-8">Error al cargar la configuración de la tabla.</div>
1661
- }
1662
-
1663
1689
  return (
1664
1690
  <RowActionsModelContext.Provider value={model}>
1665
1691
  <OptionsContext.Provider value={{ optionsMap }}>
@@ -1718,7 +1744,7 @@ export function DynamicTable({
1718
1744
  ))}
1719
1745
  </TableHeader>
1720
1746
  <TableBody>
1721
- {loadingData && data.length === 0 ? (
1747
+ {showDataSkeleton ? (
1722
1748
  <TableSkeleton />
1723
1749
  ) : tableRows.length ? (
1724
1750
  <>
@@ -1829,11 +1855,11 @@ export function DynamicTable({
1829
1855
  <h3 className="text-lg font-semibold text-foreground" role="alert">{t('dynamic.forbidden_title', { defaultValue: 'Sin permiso para ver este módulo' })}</h3>
1830
1856
  <p className="text-sm text-muted-foreground">{t('dynamic.forbidden_hint', { defaultValue: 'Tu rol no tiene acceso de lectura a estos datos. Pide acceso a un administrador.' })}</p>
1831
1857
  </>
1832
- ) : loadError ? (
1858
+ ) : showLoadError ? (
1833
1859
  <>
1834
1860
  <h3 className="text-lg font-semibold text-foreground" role="alert">{t('dynamic.load_error_title', { defaultValue: 'No se pudieron cargar los datos' })}</h3>
1835
1861
  <p className="text-sm text-muted-foreground">{t('dynamic.load_error_hint', { defaultValue: 'Ocurrió un error al consultar la lista. Inténtalo de nuevo.' })}</p>
1836
- <Button variant="outline" size="sm" className="mt-2" onClick={handleRefresh}>{t('dynamic.retry', { defaultValue: 'Reintentar' })}</Button>
1862
+ <Button variant="outline" size="sm" className="mt-2" onClick={retryLoad}>{t('dynamic.retry', { defaultValue: 'Reintentar' })}</Button>
1837
1863
  </>
1838
1864
  ) : emptyState && !hasActiveFilters ? (
1839
1865
  emptyState
@@ -1910,7 +1936,7 @@ export function DynamicTable({
1910
1936
  stacks its columns as label : value pairs with the row actions
1911
1937
  pinned at the bottom. */}
1912
1938
  <div ref={infMobileRoot} className='flex flex-1 min-h-0 flex-col gap-2 overflow-y-auto sm:hidden'>
1913
- {loadingData && data.length === 0 ? (
1939
+ {showDataSkeleton ? (
1914
1940
  Array.from({ length: 5 }).map((_, i) => (
1915
1941
  <div key={i} className='rounded-lg border bg-card p-3'>
1916
1942
  <Skeleton className='h-4 w-24' />
@@ -2036,11 +2062,11 @@ export function DynamicTable({
2036
2062
  <h3 className='text-base font-semibold text-foreground' role='alert'>{t('dynamic.forbidden_title', { defaultValue: 'Sin permiso para ver este módulo' })}</h3>
2037
2063
  <p className='text-sm text-muted-foreground'>{t('dynamic.forbidden_hint', { defaultValue: 'Tu rol no tiene acceso de lectura a estos datos. Pide acceso a un administrador.' })}</p>
2038
2064
  </>
2039
- ) : loadError ? (
2065
+ ) : showLoadError ? (
2040
2066
  <>
2041
2067
  <h3 className='text-base font-semibold text-foreground' role='alert'>{t('dynamic.load_error_title', { defaultValue: 'No se pudieron cargar los datos' })}</h3>
2042
2068
  <p className='text-sm text-muted-foreground'>{t('dynamic.load_error_hint', { defaultValue: 'Ocurrió un error al consultar la lista. Inténtalo de nuevo.' })}</p>
2043
- <Button variant='outline' size='sm' onClick={handleRefresh}>{t('dynamic.retry', { defaultValue: 'Reintentar' })}</Button>
2069
+ <Button variant='outline' size='sm' onClick={retryLoad}>{t('dynamic.retry', { defaultValue: 'Reintentar' })}</Button>
2044
2070
  </>
2045
2071
  ) : emptyState && !hasActiveFilters ? (
2046
2072
  emptyState
@@ -0,0 +1,137 @@
1
+ // createHostApiClient — the ONE HTTP client for federated addons (modals,
2
+ // pickers, pages). It wraps the host-injected HostApi (see createHostApi), so:
3
+ // - baseURL, bearer token, org/branch/language headers, 401 handling and
4
+ // refresh live in the HOST transport; the addon never reads localStorage;
5
+ // - the kernel envelope `{success,data,meta}` is unwrapped here with
6
+ // @asteby/metacore-lib/envelope (success:false throws ApiError);
7
+ // - every failure is the single `ApiError` (status, code, details);
8
+ // - a cancelled request rethrows an AbortError (use isAbortError()).
9
+ import { HostApiError } from '@asteby/metacore-sdk'
10
+ import type { HostApi, HostApiParams } from '@asteby/metacore-sdk'
11
+ import {
12
+ ApiError,
13
+ isAbortError,
14
+ isEnvelope,
15
+ unwrapEnvelope,
16
+ unwrapList,
17
+ type UnwrappedList,
18
+ } from '@asteby/metacore-lib/envelope'
19
+
20
+ export { ApiError, isAbortError }
21
+
22
+ export interface HostRequestConfig {
23
+ params?: HostApiParams
24
+ signal?: AbortSignal
25
+ }
26
+
27
+ /** Minimal axios-like surface (what DynamicSelectField & co. call). */
28
+ export interface AxiosLikeClient {
29
+ get(url: string, config?: HostRequestConfig): Promise<{ data: unknown }>
30
+ post(url: string, body?: unknown, config?: HostRequestConfig): Promise<{ data: unknown }>
31
+ put(url: string, body?: unknown, config?: HostRequestConfig): Promise<{ data: unknown }>
32
+ patch(url: string, body?: unknown, config?: HostRequestConfig): Promise<{ data: unknown }>
33
+ delete(url: string, config?: HostRequestConfig): Promise<{ data: unknown }>
34
+ }
35
+
36
+ export interface HostApiClient {
37
+ /** Unwrapped `data` of the envelope (bare bodies pass through). */
38
+ get<T = unknown>(path: string, config?: HostRequestConfig): Promise<T>
39
+ post<T = unknown>(path: string, body?: unknown, config?: HostRequestConfig): Promise<T>
40
+ put<T = unknown>(path: string, body?: unknown, config?: HostRequestConfig): Promise<T>
41
+ patch<T = unknown>(path: string, body?: unknown, config?: HostRequestConfig): Promise<T>
42
+ delete<T = unknown>(path: string, config?: HostRequestConfig): Promise<T>
43
+ /** List read: `items` + `total` (meta.total) + `meta`. Never null. */
44
+ list<T = unknown>(path: string, config?: HostRequestConfig): Promise<UnwrappedList<T>>
45
+ /** Binary read (PDF, image, CSV) as a Blob. */
46
+ blob(path: string, config?: HostRequestConfig): Promise<Blob>
47
+ /**
48
+ * Multipart upload. Pass a ready FormData, or a File plus extra fields
49
+ * (`{ folder }`); the file goes under `fileField` (default `"file"`).
50
+ * The transport sets the multipart boundary; do not set Content-Type.
51
+ */
52
+ upload<T = unknown>(
53
+ path: string,
54
+ file: File | Blob | FormData,
55
+ fields?: Record<string, string>,
56
+ opts?: { fileField?: string; signal?: AbortSignal },
57
+ ): Promise<T>
58
+ /**
59
+ * Axios-like adapter for runtime-react fields that expect `{ data }` with
60
+ * the envelope still in place (`<ApiProvider client={client.axiosLike()}>`
61
+ * for a federated remote mounted outside the host provider).
62
+ */
63
+ axiosLike(): AxiosLikeClient
64
+ }
65
+
66
+ function abortError(signal: AbortSignal): Error {
67
+ const reason = signal.reason
68
+ if (reason instanceof Error && isAbortError(reason)) return reason
69
+ const e = new Error('The operation was aborted')
70
+ e.name = 'AbortError'
71
+ return e
72
+ }
73
+
74
+ function toApiError(e: unknown, signal?: AbortSignal): Error {
75
+ if (isAbortError(e)) return e as Error
76
+ if (signal?.aborted) return abortError(signal)
77
+ if (e instanceof ApiError) return e
78
+ if (e instanceof HostApiError) {
79
+ return new ApiError(e.message, { status: e.status || undefined, code: e.code, details: e.data, cause: e })
80
+ }
81
+ if (e instanceof Error) return new ApiError(e.message, { cause: e })
82
+ return new ApiError('request failed', { cause: e })
83
+ }
84
+
85
+ /** Build the client over the host-injected {@link HostApi}. */
86
+ export function createHostApiClient(api: HostApi): HostApiClient {
87
+ const run = async <R,>(p: () => Promise<R>, signal?: AbortSignal): Promise<R> => {
88
+ try {
89
+ return await p()
90
+ } catch (e) {
91
+ throw toApiError(e, signal)
92
+ }
93
+ }
94
+ const body = <T,>(p: () => Promise<unknown>, signal?: AbortSignal) =>
95
+ run(async () => unwrapEnvelope<T>(await p()), signal)
96
+
97
+ const client: HostApiClient = {
98
+ get: (path, c) => body(() => api.get(path, c), c?.signal),
99
+ post: (path, b, c) => body(() => api.post(path, b, c), c?.signal),
100
+ put: (path, b, c) => body(() => api.put(path, b, c), c?.signal),
101
+ patch: (path, b, c) => body(() => api.patch(path, b, c), c?.signal),
102
+ delete: (path, c) => body(() => api.delete(path, c), c?.signal),
103
+ list: (path, c) =>
104
+ run(async () => unwrapList(await api.get(path, c)), c?.signal),
105
+ blob: (path, c) =>
106
+ run(() => api.get<Blob>(path, { ...c, responseType: 'blob' }), c?.signal),
107
+ upload: (path, file, fields, opts) => {
108
+ let form: FormData
109
+ if (typeof FormData !== 'undefined' && file instanceof FormData) {
110
+ form = file
111
+ } else {
112
+ form = new FormData()
113
+ form.append(opts?.fileField ?? 'file', file as Blob)
114
+ for (const [k, v] of Object.entries(fields ?? {})) form.append(k, v)
115
+ }
116
+ return body(() => api.post(path, form, opts?.signal ? { signal: opts.signal } : undefined), opts?.signal)
117
+ },
118
+ axiosLike: () => {
119
+ // Envelope kept (the runtime-react fields unwrap it themselves),
120
+ // but a `success:false` body still fails as ApiError.
121
+ const raw = async (p: () => Promise<unknown>, signal?: AbortSignal) =>
122
+ run(async () => {
123
+ const data = await p()
124
+ if (isEnvelope(data)) unwrapEnvelope(data)
125
+ return { data }
126
+ }, signal)
127
+ return {
128
+ get: (u, c) => raw(() => api.get(u, c), c?.signal),
129
+ post: (u, b, c) => raw(() => api.post(u, b, c), c?.signal),
130
+ put: (u, b, c) => raw(() => api.put(u, b, c), c?.signal),
131
+ patch: (u, b, c) => raw(() => api.patch(u, b, c), c?.signal),
132
+ delete: (u, c) => raw(() => api.delete(u, c), c?.signal),
133
+ }
134
+ },
135
+ }
136
+ return client
137
+ }
@@ -0,0 +1,18 @@
1
+ // HostApiProvider — hands the host-built HostApi to federated surfaces that
2
+ // mount OUTSIDE <AddonPageHost> (action modals, record pickers, widgets).
3
+ // Pages already get it from <AddonPageHost api=…>; both resolve through
4
+ // useHostApi() / useHostApiClient().
5
+ import { createContext, type ReactNode } from 'react'
6
+ import type { HostApi } from '@asteby/metacore-sdk'
7
+
8
+ export const HostApiContext = createContext<HostApi | null>(null)
9
+
10
+ export interface HostApiProviderProps {
11
+ /** `createHostApi(hostAxios)` — the host owns baseURL, credentials and headers. */
12
+ api: HostApi
13
+ children: ReactNode
14
+ }
15
+
16
+ export function HostApiProvider({ api, children }: HostApiProviderProps) {
17
+ return <HostApiContext.Provider value={api}>{children}</HostApiContext.Provider>
18
+ }
package/src/host-api.ts CHANGED
@@ -17,6 +17,7 @@ import type {
17
17
  HostQueryPart,
18
18
  } from '@asteby/metacore-sdk'
19
19
  import type { ApiClient } from './api-context'
20
+ import { isAbortError } from '@asteby/metacore-lib/envelope'
20
21
  import { batchGet } from './query-batch'
21
22
 
22
23
  export interface CreateHostApiOptions {
@@ -111,6 +112,8 @@ async function bodyOf<T>(p: Promise<{ data: unknown }>, opts?: HostApiRequestOpt
111
112
  }
112
113
  return res.data as T
113
114
  } catch (e) {
115
+ // A cancelled request stays an abort (callers filter it with isAbortError).
116
+ if (isAbortError(e)) throw e
114
117
  throw toHostApiError(opts?.responseType === 'blob' ? await decodeBlobError(e) : e)
115
118
  }
116
119
  }