@asteby/metacore-runtime-react 53.24.0 → 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.
@@ -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'
@@ -697,6 +698,21 @@ export function resolveActorDisplayName(raw: unknown): string | undefined {
697
698
  * any backend that stores just `"2.png"` next to a nested key) and the value
698
699
  * branch injected basePath into already-rooted paths (junk URLs).
699
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
+
700
716
  export const resolveAvatarSrc = (
701
717
  col: ColumnDefinition,
702
718
  row: any,
@@ -718,7 +734,7 @@ export const resolveAvatarSrc = (
718
734
  if (sibling) raw = String(sibling)
719
735
  }
720
736
  if (!raw && value !== undefined && value !== null && value !== '') raw = String(value)
721
- if (!raw) return undefined
737
+ if (!raw || !looksLikeImageRef(raw)) return undefined
722
738
  if (raw.startsWith('http') || raw.startsWith('/')) return raw
723
739
  const basePath = styleCfg(col, 'base_path', 'basePath') ?? col.basePath ?? ''
724
740
  return `${apiBaseUrl}${basePath}${raw}`
@@ -898,17 +914,23 @@ const AvatarCell: React.FC<{
898
914
  shape?: 'rounded' | 'circle'
899
915
  /** Per-row brand colour (hex) for the initials fallback. */
900
916
  color?: string
901
- }> = ({ 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 }) => {
902
920
  const radius = shape === 'circle' ? 'rounded-full' : 'rounded-lg'
903
- 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)
904
924
  return (
905
925
  <div className="flex items-center gap-3 min-w-0">
906
926
  <Avatar className={`h-8 w-8 ${radius} ring-1 ring-border/50`}>
907
- <AvatarImage
908
- src={avatarSrc ? getImageUrl(avatarSrc) : ''}
909
- alt={name}
910
- className={shape === 'circle' ? 'object-cover' : 'object-contain p-0.5'}
911
- />
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}
912
934
  <AvatarFallback
913
935
  className={`text-[10px] font-bold ${radius} ${brand ? '' : 'bg-primary/5 text-primary'}`}
914
936
  style={brand ? { backgroundColor: brand.background, color: brand.color } : undefined}
@@ -1284,6 +1306,8 @@ export function makeDefaultGetDynamicColumns(
1284
1306
  )
1285
1307
  }
1286
1308
 
1309
+ case 'initial':
1310
+ case 'initials':
1287
1311
  case 'search':
1288
1312
  case 'avatar':
1289
1313
  case 'creator':
@@ -1344,7 +1368,13 @@ export function makeDefaultGetDynamicColumns(
1344
1368
  )
1345
1369
  }
1346
1370
 
1347
- 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)
1348
1378
 
1349
1379
  return (
1350
1380
  <AvatarCell
@@ -1354,6 +1384,7 @@ export function makeDefaultGetDynamicColumns(
1354
1384
  getImageUrl={getImageUrl}
1355
1385
  shape={avatarShape}
1356
1386
  color={brandColor ? String(brandColor) : undefined}
1387
+ autoColor={isInitialStyle || styleCfg(col, 'tone') === 'auto'}
1357
1388
  />
1358
1389
  )
1359
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
package/src/index.ts CHANGED
@@ -910,3 +910,6 @@ export type { BulkImageTarget } from './bulk-image-target'
910
910
  export type { BatchLog as BulkImageBatchLog } from './bulk-image-import'
911
911
  export * from './attention'
912
912
  export * from './view-system'
913
+
914
+ export { useModelLabels, resolveModelLabels, defaultSingular } from './model-labels'
915
+ export type { ModelLabels, ModelLabelInput, ModelLabelT } from './model-labels'
@@ -0,0 +1,80 @@
1
+ import { useMemo } from 'react'
2
+ import { useTranslation } from 'react-i18next'
3
+
4
+ /**
5
+ * Model-driven labels. A backend often ships generic/English titles
6
+ * ("Clients", "New Client"); the SDK resolves them through i18n from the model
7
+ * key so the host can translate (or rebrand) per model without touching code:
8
+ *
9
+ * models.<model>.title -> list/page title ("Clientes")
10
+ * models.<model>.singular -> singular name ("Cliente")
11
+ * models.<model>.new -> create button label ("Nuevo cliente")
12
+ *
13
+ * Every key is looked up in the host's i18n resources (also addon namespaces
14
+ * merged by `I18nProvider`). Order: explicit override > `titleKey` from
15
+ * metadata > `models.<model>.*` > backend text > generic fallback. When no
16
+ * `models.<model>.new` exists the label is `common.new_model` interpolated
17
+ * with the singular name (`{{prefix}} {{name}}`), prefix overridable via
18
+ * `common.new`.
19
+ */
20
+ export type ModelLabelT = (key: string, opts?: Record<string, unknown>) => string
21
+
22
+ export interface ModelLabelInput {
23
+ model: string
24
+ /** Backend title (already possibly localized). */
25
+ title?: string
26
+ /** Backend i18n key for the title (`titleKey`/`title_key`). */
27
+ titleKey?: string
28
+ /** Prefix fallback for the create label when nothing translates (default "New"). */
29
+ newPrefix?: string
30
+ titleOverride?: string
31
+ newLabelOverride?: string
32
+ }
33
+
34
+ export interface ModelLabels {
35
+ title: string
36
+ singular: string
37
+ newLabel: string
38
+ }
39
+
40
+ const MISSING = '\u0000'
41
+
42
+ /** Returns the translation or undefined when the key has no value. */
43
+ function tryKey(t: ModelLabelT, key: string | undefined): string | undefined {
44
+ if (!key) return undefined
45
+ const v = t(key, { defaultValue: MISSING })
46
+ return v && v !== MISSING && v !== key ? v : undefined
47
+ }
48
+
49
+ export function defaultSingular(title: string): string {
50
+ const s = title.replace(/s$/i, '')
51
+ return s.charAt(0).toUpperCase() + s.slice(1)
52
+ }
53
+
54
+ export function resolveModelLabels(t: ModelLabelT, input: ModelLabelInput): ModelLabels {
55
+ const { model } = input
56
+ const title =
57
+ input.titleOverride ??
58
+ tryKey(t, input.titleKey) ??
59
+ tryKey(t, `models.${model}.title`) ??
60
+ input.title ??
61
+ model
62
+ const singular =
63
+ tryKey(t, `models.${model}.singular`) ?? defaultSingular(title)
64
+ const newLabel =
65
+ input.newLabelOverride ??
66
+ tryKey(t, `models.${model}.new`) ??
67
+ `${tryKey(t, 'common.new') ?? input.newPrefix ?? 'New'} ${singular}`
68
+ return { title, singular, newLabel }
69
+ }
70
+
71
+ /** Hook form of {@link resolveModelLabels}, bound to the active i18n instance. */
72
+ export function useModelLabels(input: ModelLabelInput): ModelLabels {
73
+ const { t, i18n } = useTranslation()
74
+ const { model, title, titleKey, newPrefix, titleOverride, newLabelOverride } = input
75
+ return useMemo(
76
+ () => resolveModelLabels(t as unknown as ModelLabelT, { model, title, titleKey, newPrefix, titleOverride, newLabelOverride }),
77
+ // eslint-disable-next-line react-hooks/exhaustive-deps
78
+ [t, i18n?.language, model, title, titleKey, newPrefix, titleOverride, newLabelOverride],
79
+ )
80
+ }
package/src/types.ts CHANGED
@@ -198,6 +198,9 @@ export interface AuditMeta {
198
198
  }
199
199
 
200
200
  export interface TableMetadata {
201
+ /** i18n key for `title` (host resources win over the raw backend text). */
202
+ titleKey?: string
203
+ title_key?: string
201
204
  title: string
202
205
  endpoint: string
203
206
  columns: ColumnDefinition[]