@asteby/metacore-runtime-react 51.0.0 → 52.1.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 (62) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/activity-diff.d.ts +5 -0
  3. package/dist/activity-diff.d.ts.map +1 -1
  4. package/dist/activity-timeline.d.ts.map +1 -1
  5. package/dist/activity-timeline.js +7 -2
  6. package/dist/audit-info.d.ts.map +1 -1
  7. package/dist/audit-info.js +14 -1
  8. package/dist/barcode-scanner.js +4 -4
  9. package/dist/dialogs/dynamic-record.d.ts +3 -1
  10. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  11. package/dist/dialogs/dynamic-record.js +11 -1
  12. package/dist/dynamic-columns.d.ts.map +1 -1
  13. package/dist/dynamic-columns.js +11 -0
  14. package/dist/dynamic-date-field.js +1 -1
  15. package/dist/dynamic-form.js +2 -2
  16. package/dist/index.d.ts +3 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +5 -1
  19. package/dist/org-runtime-context.d.ts +27 -0
  20. package/dist/org-runtime-context.d.ts.map +1 -1
  21. package/dist/org-runtime-context.js +6 -0
  22. package/dist/org-runtime-provider.d.ts +13 -2
  23. package/dist/org-runtime-provider.d.ts.map +1 -1
  24. package/dist/org-runtime-provider.js +3 -3
  25. package/dist/provenance.d.ts +216 -0
  26. package/dist/provenance.d.ts.map +1 -0
  27. package/dist/provenance.js +386 -0
  28. package/dist/record-history.d.ts.map +1 -1
  29. package/dist/record-history.js +3 -1
  30. package/dist/sidebar-layout-manager.js +2 -2
  31. package/dist/widgets/charts.d.ts +9 -0
  32. package/dist/widgets/charts.d.ts.map +1 -0
  33. package/dist/widgets/charts.js +55 -0
  34. package/dist/widgets/lazy-charts.d.ts +10 -0
  35. package/dist/widgets/lazy-charts.d.ts.map +1 -0
  36. package/dist/widgets/lazy-charts.js +30 -0
  37. package/dist/widgets/renderers.d.ts +5 -5
  38. package/dist/widgets/renderers.d.ts.map +1 -1
  39. package/dist/widgets/renderers.js +3 -53
  40. package/dist/widgets/widget-renderer.d.ts.map +1 -1
  41. package/dist/widgets/widget-renderer.js +2 -1
  42. package/package.json +8 -4
  43. package/src/__tests__/index-static-graph.test.ts +65 -0
  44. package/src/__tests__/provenance.test.tsx +209 -0
  45. package/src/activity-diff.tsx +5 -0
  46. package/src/activity-timeline.tsx +13 -1
  47. package/src/audit-info.tsx +17 -1
  48. package/src/barcode-scanner.tsx +4 -4
  49. package/src/dialogs/dynamic-record.tsx +18 -0
  50. package/src/dynamic-columns.tsx +14 -0
  51. package/src/dynamic-date-field.tsx +1 -1
  52. package/src/dynamic-form.tsx +2 -2
  53. package/src/index.ts +10 -4
  54. package/src/org-runtime-context.ts +36 -0
  55. package/src/org-runtime-provider.tsx +22 -1
  56. package/src/provenance.tsx +585 -0
  57. package/src/record-history.tsx +14 -3
  58. package/src/sidebar-layout-manager.tsx +2 -2
  59. package/src/widgets/charts.tsx +225 -0
  60. package/src/widgets/lazy-charts.tsx +51 -0
  61. package/src/widgets/renderers.tsx +5 -210
  62. package/src/widgets/widget-renderer.tsx +6 -4
@@ -141,7 +141,7 @@ function SortableRow({ id, depth, kind, label, hidden, collapsed, onToggleCollap
141
141
  }, children: [_jsx("option", { value: "", children: "+ \u00EDtem" }), unusedLeaves.map((l) => (_jsx("option", { value: l.ref, children: l.title }, l.ref)))] })) : null] })) : null, _jsx(Button, { type: "button", size: "icon", variant: "ghost", className: "size-6", title: "Renombrar", onClick: () => setEditing(true), children: _jsx(Pencil, { className: "size-3" }) }), _jsx(Button, { type: "button", size: "icon", variant: "ghost", className: "size-6", title: hidden ? 'Mostrar' : 'Ocultar', onClick: onToggleHidden, children: hidden ? _jsx(EyeOff, { className: "size-3" }) : _jsx(Eye, { className: "size-3" }) }), _jsx(Button, { type: "button", size: "icon", variant: "ghost", className: "text-destructive size-6", title: "Quitar", onClick: onDelete, children: _jsx(Trash2, { className: "size-3" }) })] })] }), !collapsed ? children : null] }));
142
142
  }
143
143
  // ── Manager ───────────────────────────────────────────────────────────────
144
- export function SidebarLayoutManager({ loadLayout, saveLayout, resetLayout, catalog, currentGroups, resolveLabel = (s) => s, title = 'Menú lateral', description = 'Arrastrá, renombrá y agrupá como en Discord. Así lo verá toda la organización.', }) {
144
+ export function SidebarLayoutManager({ loadLayout, saveLayout, resetLayout, catalog, currentGroups, resolveLabel = (s) => s, title = 'Menú lateral', description = 'Arrastra, renombra y agrupa como en Discord. Así lo verá toda la organización.', }) {
145
145
  const [tree, setTree] = React.useState([]);
146
146
  const [baseline, setBaseline] = React.useState('[]');
147
147
  const [loading, setLoading] = React.useState(true);
@@ -357,7 +357,7 @@ export function SidebarLayoutManager({ loadLayout, saveLayout, resetLayout, cata
357
357
  toast.message('Árbol recargado desde el menú actual');
358
358
  }, children: "Recargar men\u00FA actual" }), _jsxs(Button, { type: "button", variant: "outline", size: "sm", disabled: saving, onClick: () => void handleReset(), children: [_jsx(RotateCcw, { className: "mr-1 size-3.5" }), "Restaurar default"] }), _jsxs(Button, { type: "button", size: "sm", disabled: !dirty || saving, onClick: () => void handleSave(), children: [_jsx(Save, { className: "mr-1 size-3.5" }), saving ? 'Guardando…' : dirty ? 'Guardar cambios' : 'Guardado'] })] })] }), loading ? (_jsx("p", { className: "text-muted-foreground text-sm", children: "Cargando men\u00FA\u2026" })) : (_jsxs("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_240px]", children: [_jsxs("div", { className: "bg-muted/20 border-border overflow-hidden rounded-xl border", children: [_jsxs("div", { className: "border-border/60 flex items-center justify-between border-b px-3 py-2", children: [_jsx("span", { className: "text-muted-foreground text-[11px] font-semibold uppercase tracking-wider", children: "Vista del men\u00FA" }), baseline === '[]' && dirty ? (_jsx("span", { className: "text-amber-600 text-[11px]", children: "Sin guardar \u00B7 borrador del men\u00FA actual" })) : dirty ? (_jsx("span", { className: "text-amber-600 text-[11px]", children: "Cambios sin guardar" })) : (_jsx("span", { className: "text-muted-foreground text-[11px]", children: folderKeys.length
359
359
  ? `${folderKeys.length} carpeta(s) con permiso`
360
- : 'Layout activo' }))] }), _jsx(ScrollArea, { className: "h-[min(70vh,640px)]", children: _jsxs("div", { className: "p-2 pb-4", children: [_jsxs(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragStart: handleDragStart, onDragEnd: handleDragEnd, children: [tree.length === 0 ? (_jsx("p", { className: "text-muted-foreground px-3 py-8 text-center text-sm", children: "Men\u00FA vac\u00EDo. Cre\u00E1 una secci\u00F3n o recarg\u00E1 el men\u00FA actual." })) : (renderList(tree, [])), _jsx(PortalDragOverlay, { children: activeLabel ? (_jsx("div", { className: "bg-background border-border rounded-md border px-3 py-1.5 text-sm shadow-lg", children: activeLabel })) : null })] }), _jsxs("div", { className: "mt-3 flex gap-2 px-2", children: [_jsx(Input, { value: newCategory, onChange: (e) => setNewCategory(e.target.value), placeholder: "Nombre de secci\u00F3n\u2026", className: "h-8 text-sm", onKeyDown: (e) => {
360
+ : 'Layout activo' }))] }), _jsx(ScrollArea, { className: "h-[min(70vh,640px)]", children: _jsxs("div", { className: "p-2 pb-4", children: [_jsxs(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragStart: handleDragStart, onDragEnd: handleDragEnd, children: [tree.length === 0 ? (_jsx("p", { className: "text-muted-foreground px-3 py-8 text-center text-sm", children: "Men\u00FA vac\u00EDo. Crea una secci\u00F3n o recarga el men\u00FA actual." })) : (renderList(tree, [])), _jsx(PortalDragOverlay, { children: activeLabel ? (_jsx("div", { className: "bg-background border-border rounded-md border px-3 py-1.5 text-sm shadow-lg", children: activeLabel })) : null })] }), _jsxs("div", { className: "mt-3 flex gap-2 px-2", children: [_jsx(Input, { value: newCategory, onChange: (e) => setNewCategory(e.target.value), placeholder: "Nombre de secci\u00F3n\u2026", className: "h-8 text-sm", onKeyDown: (e) => {
361
361
  if (e.key === 'Enter')
362
362
  addRootCategory();
363
363
  } }), _jsxs(Button, { type: "button", size: "sm", className: "h-8 shrink-0", onClick: addRootCategory, children: [_jsx(Plus, { className: "mr-1 size-3.5" }), "Secci\u00F3n"] })] })] }) })] }), _jsxs("div", { className: "bg-muted/10 border-border flex flex-col overflow-hidden rounded-xl border", children: [_jsxs("div", { className: "border-border/60 border-b px-3 py-2", children: [_jsx("p", { className: "text-muted-foreground text-[11px] font-semibold uppercase tracking-wider", children: "Sin colocar" }), _jsx("p", { className: "text-muted-foreground mt-0.5 text-[11px]", children: "Agregalos desde el men\u00FA + de cada secci\u00F3n" })] }), _jsx(ScrollArea, { className: "flex-1", children: _jsx("ul", { className: "space-y-1 p-2", children: unused.length === 0 ? (_jsx("li", { className: "text-muted-foreground px-1 py-4 text-center text-xs", children: "Todo est\u00E1 en el men\u00FA" })) : (unused.map((l) => (_jsx("li", { children: _jsxs("button", { type: "button", className: "hover:bg-muted/60 flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs", title: l.ref, onClick: () => {
@@ -0,0 +1,9 @@
1
+ import * as React from 'react';
2
+ import { type WidgetRenderProps } from './renderers';
3
+ export type { WidgetRenderProps };
4
+ export declare function BarWidget(p: WidgetRenderProps): React.JSX.Element;
5
+ export declare function LineWidget(p: WidgetRenderProps): React.JSX.Element;
6
+ export declare function AreaWidget(p: WidgetRenderProps): React.JSX.Element;
7
+ export declare function PieWidget(p: WidgetRenderProps): React.JSX.Element;
8
+ export declare function DonutWidget(p: WidgetRenderProps): React.JSX.Element;
9
+ //# sourceMappingURL=charts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"charts.d.ts","sourceRoot":"","sources":["../../src/widgets/charts.tsx"],"names":[],"mappings":"AAOA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AA4B9B,OAAO,EAAqB,KAAK,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAEvE,YAAY,EAAE,iBAAiB,EAAE,CAAA;AAoCjC,wBAAgB,SAAS,CAAC,CAAC,EAAE,iBAAiB,qBAsC7C;AAgDD,wBAAgB,UAAU,CAAC,CAAC,EAAE,iBAAiB,qBAE9C;AACD,wBAAgB,UAAU,CAAC,CAAC,EAAE,iBAAiB,qBAE9C;AAuDD,wBAAgB,SAAS,CAAC,CAAC,EAAE,iBAAiB,qBAE7C;AACD,wBAAgB,WAAW,CAAC,CAAC,EAAE,iBAAiB,qBAE/C"}
@@ -0,0 +1,55 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Area, AreaChart, Bar, BarChart, CartesianGrid, Cell, Line, LineChart, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis, } from 'recharts';
3
+ import { cn } from '@asteby/metacore-ui/lib';
4
+ import { WidgetCard, WidgetEmpty } from './widget-card';
5
+ import { accentClasses, paletteColor, formatWidgetValue, formatAxisTick, CHART_GRID, CHART_MUTED, } from './widget-format';
6
+ import { fmtCtx, hasSeries } from './renderers';
7
+ // Fixed-height chart body. In the masonry (CSS columns) layout cards take their
8
+ // natural height, so charts need a definite height for ResponsiveContainer to
9
+ // resolve. This height + the card chrome gives every chart card a consistent,
10
+ // taller footprint that balances cleanly against compact stat cards.
11
+ const CHART_H = 'h-[190px]';
12
+ function ChartArea({ children }) {
13
+ return (_jsx("div", { className: cn(CHART_H, 'w-full'), children: _jsx(ResponsiveContainer, { width: "100%", height: "100%", children: children }) }));
14
+ }
15
+ // Compact recharts tooltip styled with theme tokens.
16
+ function ChartTooltip({ ctx }) {
17
+ return (_jsx(Tooltip, { cursor: { fill: 'var(--muted, rgba(148,163,184,0.12))', opacity: 0.4 }, contentStyle: {
18
+ background: 'var(--popover, #fff)',
19
+ border: '1px solid var(--border, #e2e8f0)',
20
+ borderRadius: 8,
21
+ fontSize: 12,
22
+ color: 'var(--popover-foreground, #0f172a)',
23
+ boxShadow: '0 4px 16px rgba(0,0,0,0.08)',
24
+ }, labelStyle: { color: 'var(--muted-foreground, #64748b)', marginBottom: 2 }, formatter: (v) => formatWidgetValue(Number(v), ctx) }));
25
+ }
26
+ // --- bar ------------------------------------------------------------------
27
+ export function BarWidget(p) {
28
+ const ctx = fmtCtx(p.spec, p.locale, p.currency);
29
+ const a = accentClasses(p.spec.accent);
30
+ return (_jsx(WidgetCard, { "data-testid": `widget-${p.spec.key}`, title: p.spec.title, subtitle: p.spec.subtitle, icon: p.spec.icon, accent: p.spec.accent, children: hasSeries(p.data) ? (_jsx(ChartArea, { children: _jsxs(BarChart, { data: p.data.series, margin: { top: 4, right: 4, left: -16, bottom: 0 }, children: [_jsx(CartesianGrid, { vertical: false, stroke: CHART_GRID, strokeDasharray: "3 3" }), _jsx(XAxis, { dataKey: "label", tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, interval: "preserveStartEnd" }), _jsx(YAxis, { tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, width: 44, tickFormatter: (v) => formatAxisTick(v, ctx) }), _jsx(ChartTooltip, { ctx: ctx }), _jsx(Bar, { dataKey: "value", fill: a.chartVar, radius: [4, 4, 0, 0], maxBarSize: 48 })] }) })) : (_jsx(WidgetEmpty, { message: p.emptyText })) }));
31
+ }
32
+ // --- line / area (shared) -------------------------------------------------
33
+ function TimeSeriesWidget(p) {
34
+ const ctx = fmtCtx(p.spec, p.locale, p.currency);
35
+ const a = accentClasses(p.spec.accent);
36
+ const gradId = `wg-grad-${p.spec.key}`;
37
+ return (_jsx(WidgetCard, { "data-testid": `widget-${p.spec.key}`, title: p.spec.title, subtitle: p.spec.subtitle, icon: p.spec.icon, accent: p.spec.accent, children: hasSeries(p.data) ? (_jsx(ChartArea, { children: p.variant === 'area' ? (_jsxs(AreaChart, { data: p.data.series, margin: { top: 4, right: 6, left: -16, bottom: 0 }, children: [_jsx("defs", { children: _jsxs("linearGradient", { id: gradId, x1: "0", y1: "0", x2: "0", y2: "1", children: [_jsx("stop", { offset: "0%", stopColor: a.chartVar, stopOpacity: 0.35 }), _jsx("stop", { offset: "100%", stopColor: a.chartVar, stopOpacity: 0.02 })] }) }), _jsx(CartesianGrid, { vertical: false, stroke: CHART_GRID, strokeDasharray: "3 3" }), _jsx(XAxis, { dataKey: "label", tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, interval: "preserveStartEnd" }), _jsx(YAxis, { tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, width: 44, tickFormatter: (v) => formatAxisTick(v, ctx) }), _jsx(ChartTooltip, { ctx: ctx }), _jsx(Area, { type: "monotone", dataKey: "value", stroke: a.chartVar, strokeWidth: 2, fill: `url(#${gradId})` })] })) : (_jsxs(LineChart, { data: p.data.series, margin: { top: 4, right: 6, left: -16, bottom: 0 }, children: [_jsx(CartesianGrid, { vertical: false, stroke: CHART_GRID, strokeDasharray: "3 3" }), _jsx(XAxis, { dataKey: "label", tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, interval: "preserveStartEnd" }), _jsx(YAxis, { tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, width: 44, tickFormatter: (v) => formatAxisTick(v, ctx) }), _jsx(ChartTooltip, { ctx: ctx }), _jsx(Line, { type: "monotone", dataKey: "value", stroke: a.chartVar, strokeWidth: 2, dot: false, activeDot: { r: 4 } })] })) })) : (_jsx(WidgetEmpty, { message: p.emptyText })) }));
38
+ }
39
+ export function LineWidget(p) {
40
+ return _jsx(TimeSeriesWidget, { ...p, variant: "line" });
41
+ }
42
+ export function AreaWidget(p) {
43
+ return _jsx(TimeSeriesWidget, { ...p, variant: "area" });
44
+ }
45
+ // --- pie / donut (shared) -------------------------------------------------
46
+ function CircularWidget(p) {
47
+ const ctx = fmtCtx(p.spec, p.locale, p.currency);
48
+ return (_jsx(WidgetCard, { "data-testid": `widget-${p.spec.key}`, title: p.spec.title, subtitle: p.spec.subtitle, icon: p.spec.icon, accent: p.spec.accent, children: hasSeries(p.data) ? (_jsxs("div", { className: cn(CHART_H, 'flex items-center gap-3'), children: [_jsx("div", { className: "h-full min-h-0 w-[46%] shrink-0", children: _jsx(ResponsiveContainer, { width: "100%", height: "100%", children: _jsxs(PieChart, { children: [_jsx(ChartTooltip, { ctx: ctx }), _jsx(Pie, { data: p.data.series, dataKey: "value", nameKey: "label", innerRadius: p.variant === 'donut' ? '55%' : 0, outerRadius: "92%", paddingAngle: p.variant === 'donut' ? 2 : 0, stroke: "var(--background, #fff)", strokeWidth: 2, children: p.data.series.map((_, i) => (_jsx(Cell, { fill: paletteColor(i) }, i))) })] }) }) }), _jsx("ul", { className: "flex min-w-0 flex-1 flex-col gap-1.5", children: p.data.series.slice(0, 6).map((pt, i) => (_jsxs("li", { className: "flex items-center gap-2 text-xs", children: [_jsx("span", { className: "size-2.5 shrink-0 rounded-sm", style: { background: paletteColor(i) } }), _jsx("span", { className: "truncate text-muted-foreground", children: pt.label }), _jsx("span", { className: "ml-auto shrink-0 font-medium tabular-nums text-foreground", children: formatWidgetValue(pt.value, ctx) })] }, pt.key))) })] })) : (_jsx(WidgetEmpty, { message: p.emptyText })) }));
49
+ }
50
+ export function PieWidget(p) {
51
+ return _jsx(CircularWidget, { ...p, variant: "pie" });
52
+ }
53
+ export function DonutWidget(p) {
54
+ return _jsx(CircularWidget, { ...p, variant: "donut" });
55
+ }
@@ -0,0 +1,10 @@
1
+ import * as React from 'react';
2
+ import type { WidgetRenderProps } from './renderers';
3
+ /** Warm the charts chunk (e.g. on hover of a dashboard link). Idempotent. */
4
+ export declare function preloadWidgetCharts(): Promise<unknown>;
5
+ export declare const BarWidget: (p: WidgetRenderProps) => React.JSX.Element;
6
+ export declare const LineWidget: (p: WidgetRenderProps) => React.JSX.Element;
7
+ export declare const AreaWidget: (p: WidgetRenderProps) => React.JSX.Element;
8
+ export declare const PieWidget: (p: WidgetRenderProps) => React.JSX.Element;
9
+ export declare const DonutWidget: (p: WidgetRenderProps) => React.JSX.Element;
10
+ //# sourceMappingURL=lazy-charts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lazy-charts.d.ts","sourceRoot":"","sources":["../../src/widgets/lazy-charts.tsx"],"names":[],"mappings":"AAKA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAIpD,6EAA6E;AAC7E,wBAAgB,mBAAmB,IAAI,OAAO,CAAC,OAAO,CAAC,CAEtD;AAgCD,eAAO,MAAM,SAAS,MATiB,iBAAiB,sBASV,CAAA;AAC9C,eAAO,MAAM,UAAU,MAVgB,iBAAiB,sBAUR,CAAA;AAChD,eAAO,MAAM,UAAU,MAXgB,iBAAiB,sBAWR,CAAA;AAChD,eAAO,MAAM,SAAS,MAZiB,iBAAiB,sBAYV,CAAA;AAC9C,eAAO,MAAM,WAAW,MAbe,iBAAiB,sBAaN,CAAA"}
@@ -0,0 +1,30 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // Lazy facades for the recharts-backed widgets. The package index and
3
+ // WidgetRenderer import these instead of ./charts, so recharts becomes its own
4
+ // async chunk: it downloads only when a dashboard actually renders a
5
+ // bar/line/area/pie/donut widget. Public names stay the same as before.
6
+ import * as React from 'react';
7
+ import { WidgetCard } from './widget-card';
8
+ const loadCharts = () => import('./charts');
9
+ /** Warm the charts chunk (e.g. on hover of a dashboard link). Idempotent. */
10
+ export function preloadWidgetCharts() {
11
+ return loadCharts();
12
+ }
13
+ const LazyBar = React.lazy(() => loadCharts().then((m) => ({ default: m.BarWidget })));
14
+ const LazyLine = React.lazy(() => loadCharts().then((m) => ({ default: m.LineWidget })));
15
+ const LazyArea = React.lazy(() => loadCharts().then((m) => ({ default: m.AreaWidget })));
16
+ const LazyPie = React.lazy(() => loadCharts().then((m) => ({ default: m.PieWidget })));
17
+ const LazyDonut = React.lazy(() => loadCharts().then((m) => ({ default: m.DonutWidget })));
18
+ function ChartFallback(p) {
19
+ return (_jsx(WidgetCard, { "data-testid": `widget-skeleton-${p.spec.key}`, title: p.spec.title, subtitle: p.spec.subtitle, icon: p.spec.icon, accent: p.spec.accent, children: _jsx("div", { className: "h-[190px] w-full animate-pulse rounded-md bg-muted" }) }));
20
+ }
21
+ function withSuspense(Lazy) {
22
+ return function LazyChartWidget(p) {
23
+ return (_jsx(React.Suspense, { fallback: _jsx(ChartFallback, { ...p }), children: _jsx(Lazy, { ...p }) }));
24
+ };
25
+ }
26
+ export const BarWidget = withSuspense(LazyBar);
27
+ export const LineWidget = withSuspense(LazyLine);
28
+ export const AreaWidget = withSuspense(LazyArea);
29
+ export const PieWidget = withSuspense(LazyPie);
30
+ export const DonutWidget = withSuspense(LazyDonut);
@@ -1,5 +1,6 @@
1
1
  import * as React from 'react';
2
2
  import type { DashboardWidgetSpec, WidgetData } from '../dashboard-types';
3
+ import { type WidgetFormatCtx } from './widget-format';
3
4
  export interface WidgetRenderProps {
4
5
  spec: DashboardWidgetSpec;
5
6
  data?: WidgetData;
@@ -8,12 +9,11 @@ export interface WidgetRenderProps {
8
9
  /** i18n: per-widget empty fallback (already translated). */
9
10
  emptyText: string;
10
11
  }
12
+ export declare const fmtCtx: (spec: DashboardWidgetSpec, locale?: string, currency?: string) => WidgetFormatCtx;
13
+ export declare const hasSeries: (d?: WidgetData) => d is WidgetData & {
14
+ series: NonNullable<WidgetData["series"]>;
15
+ };
11
16
  export declare function StatWidget(p: WidgetRenderProps): React.JSX.Element;
12
- export declare function BarWidget(p: WidgetRenderProps): React.JSX.Element;
13
- export declare function LineWidget(p: WidgetRenderProps): React.JSX.Element;
14
- export declare function AreaWidget(p: WidgetRenderProps): React.JSX.Element;
15
- export declare function PieWidget(p: WidgetRenderProps): React.JSX.Element;
16
- export declare function DonutWidget(p: WidgetRenderProps): React.JSX.Element;
17
17
  export declare function ListWidget(p: WidgetRenderProps): React.JSX.Element;
18
18
  export declare function ProgressWidget(p: WidgetRenderProps): React.JSX.Element;
19
19
  //# sourceMappingURL=renderers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"renderers.d.ts","sourceRoot":"","sources":["../../src/widgets/renderers.tsx"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAkB9B,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAA;AAazE,MAAM,WAAW,iBAAiB;IAC9B,IAAI,EAAE,mBAAmB,CAAA;IACzB,IAAI,CAAC,EAAE,UAAU,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,4DAA4D;IAC5D,SAAS,EAAE,MAAM,CAAA;CACpB;AA8CD,wBAAgB,UAAU,CAAC,CAAC,EAAE,iBAAiB,qBA+B9C;AAGD,wBAAgB,SAAS,CAAC,CAAC,EAAE,iBAAiB,qBAsC7C;AAgDD,wBAAgB,UAAU,CAAC,CAAC,EAAE,iBAAiB,qBAE9C;AACD,wBAAgB,UAAU,CAAC,CAAC,EAAE,iBAAiB,qBAE9C;AAuDD,wBAAgB,SAAS,CAAC,CAAC,EAAE,iBAAiB,qBAE7C;AACD,wBAAgB,WAAW,CAAC,CAAC,EAAE,iBAAiB,qBAE/C;AAGD,wBAAgB,UAAU,CAAC,CAAC,EAAE,iBAAiB,qBAqC9C;AAKD,wBAAgB,cAAc,CAAC,CAAC,EAAE,iBAAiB,qBAkClD"}
1
+ {"version":3,"file":"renderers.d.ts","sourceRoot":"","sources":["../../src/widgets/renderers.tsx"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAA;AAEzE,OAAO,EAQH,KAAK,eAAe,EACvB,MAAM,iBAAiB,CAAA;AAExB,MAAM,WAAW,iBAAiB;IAC9B,IAAI,EAAE,mBAAmB,CAAA;IACzB,IAAI,CAAC,EAAE,UAAU,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,4DAA4D;IAC5D,SAAS,EAAE,MAAM,CAAA;CACpB;AAED,eAAO,MAAM,MAAM,GACf,MAAM,mBAAmB,EACzB,SAAS,MAAM,EACf,WAAW,MAAM,KAClB,eAA8D,CAAA;AAEjE,eAAO,MAAM,SAAS,GAAI,IAAI,UAAU,KAAG,CAAC,IAAI,UAAU,GAAG;IAAE,MAAM,EAAE,WAAW,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAA;CACnD,CAAA;AAGrD,wBAAgB,UAAU,CAAC,CAAC,EAAE,iBAAiB,qBA+B9C;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,iBAAiB,qBAqC9C;AAKD,wBAAgB,cAAc,CAAC,CAAC,EAAE,iBAAiB,qBAkClD"}
@@ -1,29 +1,9 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Area, AreaChart, Bar, BarChart, CartesianGrid, Cell, Line, LineChart, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis, } from 'recharts';
3
2
  import { cn } from '@asteby/metacore-ui/lib';
4
3
  import { WidgetCard, DeltaChip, WidgetEmpty } from './widget-card';
5
- import { accentClasses, paletteColor, formatWidgetValue, formatAxisTick, formatDelta, CHART_GRID, CHART_MUTED, } from './widget-format';
6
- const fmtCtx = (spec, locale, currency) => ({ format: spec.format, locale, currency });
7
- const hasSeries = (d) => Array.isArray(d?.series) && d.series.length > 0;
8
- // Fixed-height chart body. In the masonry (CSS columns) layout cards take their
9
- // natural height, so charts need a definite height for ResponsiveContainer to
10
- // resolve. This height + the card chrome gives every chart card a consistent,
11
- // taller footprint that balances cleanly against compact stat cards.
12
- const CHART_H = 'h-[190px]';
13
- function ChartArea({ children }) {
14
- return (_jsx("div", { className: cn(CHART_H, 'w-full'), children: _jsx(ResponsiveContainer, { width: "100%", height: "100%", children: children }) }));
15
- }
16
- // Compact recharts tooltip styled with theme tokens.
17
- function ChartTooltip({ ctx }) {
18
- return (_jsx(Tooltip, { cursor: { fill: 'var(--muted, rgba(148,163,184,0.12))', opacity: 0.4 }, contentStyle: {
19
- background: 'var(--popover, #fff)',
20
- border: '1px solid var(--border, #e2e8f0)',
21
- borderRadius: 8,
22
- fontSize: 12,
23
- color: 'var(--popover-foreground, #0f172a)',
24
- boxShadow: '0 4px 16px rgba(0,0,0,0.08)',
25
- }, labelStyle: { color: 'var(--muted-foreground, #64748b)', marginBottom: 2 }, formatter: (v) => formatWidgetValue(Number(v), ctx) }));
26
- }
4
+ import { accentClasses, formatWidgetValue, formatDelta, } from './widget-format';
5
+ export const fmtCtx = (spec, locale, currency) => ({ format: spec.format, locale, currency });
6
+ export const hasSeries = (d) => Array.isArray(d?.series) && d.series.length > 0;
27
7
  // --- stat -----------------------------------------------------------------
28
8
  export function StatWidget(p) {
29
9
  const ctx = fmtCtx(p.spec, p.locale, p.currency);
@@ -32,36 +12,6 @@ export function StatWidget(p) {
32
12
  const hasValue = typeof value === 'number' && !Number.isNaN(value);
33
13
  return (_jsx(WidgetCard, { "data-testid": `widget-${p.spec.key}`, title: p.spec.title, subtitle: p.spec.subtitle, icon: p.spec.icon, accent: p.spec.accent, headerExtra: typeof delta === 'number' ? (_jsx(DeltaChip, { delta: delta, text: formatDelta(delta, p.locale) })) : undefined, children: hasValue ? (_jsx("div", { className: "flex min-h-[2.5rem] items-end", children: _jsx("div", { className: "text-[2rem] font-semibold leading-none tabular-nums tracking-tight text-foreground", children: formatWidgetValue(value, ctx) }) })) : (_jsx("div", { className: "flex min-h-[2.5rem] items-center text-sm text-muted-foreground", children: p.emptyText })) }));
34
14
  }
35
- // --- bar ------------------------------------------------------------------
36
- export function BarWidget(p) {
37
- const ctx = fmtCtx(p.spec, p.locale, p.currency);
38
- const a = accentClasses(p.spec.accent);
39
- return (_jsx(WidgetCard, { "data-testid": `widget-${p.spec.key}`, title: p.spec.title, subtitle: p.spec.subtitle, icon: p.spec.icon, accent: p.spec.accent, children: hasSeries(p.data) ? (_jsx(ChartArea, { children: _jsxs(BarChart, { data: p.data.series, margin: { top: 4, right: 4, left: -16, bottom: 0 }, children: [_jsx(CartesianGrid, { vertical: false, stroke: CHART_GRID, strokeDasharray: "3 3" }), _jsx(XAxis, { dataKey: "label", tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, interval: "preserveStartEnd" }), _jsx(YAxis, { tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, width: 44, tickFormatter: (v) => formatAxisTick(v, ctx) }), _jsx(ChartTooltip, { ctx: ctx }), _jsx(Bar, { dataKey: "value", fill: a.chartVar, radius: [4, 4, 0, 0], maxBarSize: 48 })] }) })) : (_jsx(WidgetEmpty, { message: p.emptyText })) }));
40
- }
41
- // --- line / area (shared) -------------------------------------------------
42
- function TimeSeriesWidget(p) {
43
- const ctx = fmtCtx(p.spec, p.locale, p.currency);
44
- const a = accentClasses(p.spec.accent);
45
- const gradId = `wg-grad-${p.spec.key}`;
46
- return (_jsx(WidgetCard, { "data-testid": `widget-${p.spec.key}`, title: p.spec.title, subtitle: p.spec.subtitle, icon: p.spec.icon, accent: p.spec.accent, children: hasSeries(p.data) ? (_jsx(ChartArea, { children: p.variant === 'area' ? (_jsxs(AreaChart, { data: p.data.series, margin: { top: 4, right: 6, left: -16, bottom: 0 }, children: [_jsx("defs", { children: _jsxs("linearGradient", { id: gradId, x1: "0", y1: "0", x2: "0", y2: "1", children: [_jsx("stop", { offset: "0%", stopColor: a.chartVar, stopOpacity: 0.35 }), _jsx("stop", { offset: "100%", stopColor: a.chartVar, stopOpacity: 0.02 })] }) }), _jsx(CartesianGrid, { vertical: false, stroke: CHART_GRID, strokeDasharray: "3 3" }), _jsx(XAxis, { dataKey: "label", tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, interval: "preserveStartEnd" }), _jsx(YAxis, { tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, width: 44, tickFormatter: (v) => formatAxisTick(v, ctx) }), _jsx(ChartTooltip, { ctx: ctx }), _jsx(Area, { type: "monotone", dataKey: "value", stroke: a.chartVar, strokeWidth: 2, fill: `url(#${gradId})` })] })) : (_jsxs(LineChart, { data: p.data.series, margin: { top: 4, right: 6, left: -16, bottom: 0 }, children: [_jsx(CartesianGrid, { vertical: false, stroke: CHART_GRID, strokeDasharray: "3 3" }), _jsx(XAxis, { dataKey: "label", tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, interval: "preserveStartEnd" }), _jsx(YAxis, { tick: { fontSize: 10, fill: CHART_MUTED }, tickLine: false, axisLine: false, width: 44, tickFormatter: (v) => formatAxisTick(v, ctx) }), _jsx(ChartTooltip, { ctx: ctx }), _jsx(Line, { type: "monotone", dataKey: "value", stroke: a.chartVar, strokeWidth: 2, dot: false, activeDot: { r: 4 } })] })) })) : (_jsx(WidgetEmpty, { message: p.emptyText })) }));
47
- }
48
- export function LineWidget(p) {
49
- return _jsx(TimeSeriesWidget, { ...p, variant: "line" });
50
- }
51
- export function AreaWidget(p) {
52
- return _jsx(TimeSeriesWidget, { ...p, variant: "area" });
53
- }
54
- // --- pie / donut (shared) -------------------------------------------------
55
- function CircularWidget(p) {
56
- const ctx = fmtCtx(p.spec, p.locale, p.currency);
57
- return (_jsx(WidgetCard, { "data-testid": `widget-${p.spec.key}`, title: p.spec.title, subtitle: p.spec.subtitle, icon: p.spec.icon, accent: p.spec.accent, children: hasSeries(p.data) ? (_jsxs("div", { className: cn(CHART_H, 'flex items-center gap-3'), children: [_jsx("div", { className: "h-full min-h-0 w-[46%] shrink-0", children: _jsx(ResponsiveContainer, { width: "100%", height: "100%", children: _jsxs(PieChart, { children: [_jsx(ChartTooltip, { ctx: ctx }), _jsx(Pie, { data: p.data.series, dataKey: "value", nameKey: "label", innerRadius: p.variant === 'donut' ? '55%' : 0, outerRadius: "92%", paddingAngle: p.variant === 'donut' ? 2 : 0, stroke: "var(--background, #fff)", strokeWidth: 2, children: p.data.series.map((_, i) => (_jsx(Cell, { fill: paletteColor(i) }, i))) })] }) }) }), _jsx("ul", { className: "flex min-w-0 flex-1 flex-col gap-1.5", children: p.data.series.slice(0, 6).map((pt, i) => (_jsxs("li", { className: "flex items-center gap-2 text-xs", children: [_jsx("span", { className: "size-2.5 shrink-0 rounded-sm", style: { background: paletteColor(i) } }), _jsx("span", { className: "truncate text-muted-foreground", children: pt.label }), _jsx("span", { className: "ml-auto shrink-0 font-medium tabular-nums text-foreground", children: formatWidgetValue(pt.value, ctx) })] }, pt.key))) })] })) : (_jsx(WidgetEmpty, { message: p.emptyText })) }));
58
- }
59
- export function PieWidget(p) {
60
- return _jsx(CircularWidget, { ...p, variant: "pie" });
61
- }
62
- export function DonutWidget(p) {
63
- return _jsx(CircularWidget, { ...p, variant: "donut" });
64
- }
65
15
  // --- list (top-N with proportion bars) ------------------------------------
66
16
  export function ListWidget(p) {
67
17
  const ctx = fmtCtx(p.spec, p.locale, p.currency);
@@ -1 +1 @@
1
- {"version":3,"file":"widget-renderer.d.ts","sourceRoot":"","sources":["../../src/widgets/widget-renderer.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAA;AAcrF,+DAA+D;AAC/D,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAKhD,CAAA;AAED;6EAC6E;AAC7E,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAKjD,CAAA;AAMD;kFACkF;AAClF,wBAAgB,WAAW,CAAC,IAAI,EAAE,mBAAmB,GAAG,UAAU,CAGjE;AAED;4EAC4E;AAC5E,wBAAgB,SAAS,CAAC,IAAI,EAAE,mBAAmB,GAAG,MAAM,CAG3D;AAED;0EAC0E;AAC1E,wBAAgB,YAAY,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAE/D;AAiDD,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,mBAAmB,CAAA;IACzB,IAAI,CAAC,EAAE,UAAU,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,iDAAiD;IACjD,SAAS,EAAE,MAAM,CAAA;IACjB,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAA;CACpB;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,EAC3B,IAAI,EACJ,IAAI,EACJ,MAAM,EACN,QAAQ,EACR,SAAS,EACT,SAAS,GACZ,EAAE,mBAAmB,qBAkDrB;AAED,8DAA8D;AAC9D,wBAAgB,cAAc,CAAC,EAAE,IAAI,EAAE,EAAE;IAAE,IAAI,EAAE,mBAAmB,CAAA;CAAE,qBAqBrE"}
1
+ {"version":3,"file":"widget-renderer.d.ts","sourceRoot":"","sources":["../../src/widgets/widget-renderer.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAA;AAgBrF,+DAA+D;AAC/D,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAKhD,CAAA;AAED;6EAC6E;AAC7E,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAKjD,CAAA;AAMD;kFACkF;AAClF,wBAAgB,WAAW,CAAC,IAAI,EAAE,mBAAmB,GAAG,UAAU,CAGjE;AAED;4EAC4E;AAC5E,wBAAgB,SAAS,CAAC,IAAI,EAAE,mBAAmB,GAAG,MAAM,CAG3D;AAED;0EAC0E;AAC1E,wBAAgB,YAAY,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAE/D;AAiDD,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,mBAAmB,CAAA;IACzB,IAAI,CAAC,EAAE,UAAU,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,iDAAiD;IACjD,SAAS,EAAE,MAAM,CAAA;IACjB,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAA;CACpB;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,EAC3B,IAAI,EACJ,IAAI,EACJ,MAAM,EACN,QAAQ,EACR,SAAS,EACT,SAAS,GACZ,EAAE,mBAAmB,qBAkDrB;AAED,8DAA8D;AAC9D,wBAAgB,cAAc,CAAC,EAAE,IAAI,EAAE,EAAE;IAAE,IAAI,EAAE,mBAAmB,CAAA;CAAE,qBAqBrE"}
@@ -5,7 +5,8 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
5
5
  import * as React from 'react';
6
6
  import { Slot } from '../slot';
7
7
  import { WidgetCard, WidgetError } from './widget-card';
8
- import { StatWidget, BarWidget, LineWidget, AreaWidget, PieWidget, DonutWidget, ListWidget, ProgressWidget, } from './renderers';
8
+ import { StatWidget, ListWidget, ProgressWidget, } from './renderers';
9
+ import { BarWidget, LineWidget, AreaWidget, PieWidget, DonutWidget, } from './lazy-charts';
9
10
  /** Maps a widget size to its column span in the 4-col grid. */
10
11
  export const SIZE_SPAN = {
11
12
  sm: 1,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asteby/metacore-runtime-react",
3
- "version": "51.0.0",
3
+ "version": "52.1.0",
4
4
  "description": "React runtime for metacore hosts — renders addon contributions dynamically",
5
5
  "repository": {
6
6
  "type": "git",
@@ -14,6 +14,10 @@
14
14
  ".": {
15
15
  "types": "./dist/index.d.ts",
16
16
  "import": "./dist/index.js"
17
+ },
18
+ "./charts": {
19
+ "types": "./dist/widgets/charts.d.ts",
20
+ "import": "./dist/widgets/charts.js"
17
21
  }
18
22
  },
19
23
  "dependencies": {
@@ -21,12 +25,12 @@
21
25
  "@dnd-kit/sortable": "^10.0.0",
22
26
  "@dnd-kit/utilities": "^3.2.2",
23
27
  "@tanstack/react-virtual": "^3.14.13",
24
- "recharts": "^2.15.0",
28
+ "recharts": "^3.8.1",
25
29
  "zod": "^4.3.0"
26
30
  },
27
31
  "peerDependencies": {
28
32
  "@asteby/metacore-sdk": "^3.14.0",
29
- "@asteby/metacore-ui": "^2.27.0",
33
+ "@asteby/metacore-ui": "^2.28.0",
30
34
  "@tanstack/react-query": ">=5",
31
35
  "@tanstack/react-router": ">=1.100",
32
36
  "@tanstack/react-table": ">=8",
@@ -54,7 +58,7 @@
54
58
  },
55
59
  "devDependencies": {
56
60
  "@asteby/metacore-sdk": "3.14.0",
57
- "@asteby/metacore-ui": "2.27.0",
61
+ "@asteby/metacore-ui": "2.28.0",
58
62
  "@tanstack/react-query": "^5.95.0",
59
63
  "@tanstack/react-router": "^1.168.0",
60
64
  "@tanstack/react-table": "^8.20.0",
@@ -0,0 +1,65 @@
1
+ // Guards the host's first paint: the package index must not reach recharts (or
2
+ // any other heavy charting/map library) through STATIC imports. Dynamic
3
+ // `import()` is allowed — that is how ./widgets/lazy-charts defers it.
4
+ import { describe, expect, it } from 'vitest'
5
+ import { existsSync, readFileSync, statSync } from 'node:fs'
6
+ import { dirname, join, resolve } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+
9
+ const SRC = resolve(dirname(fileURLToPath(import.meta.url)), '..')
10
+ const HEAVY = ['recharts', 'maplibre-gl', 'leaflet', 'echarts', 'd3', '@visx']
11
+
12
+ function resolveLocal(from: string, spec: string): string | null {
13
+ const base = resolve(dirname(from), spec)
14
+ for (const c of [base, `${base}.ts`, `${base}.tsx`, join(base, 'index.ts'), join(base, 'index.tsx')]) {
15
+ if (existsSync(c) && statSync(c).isFile()) return c
16
+ }
17
+ return null
18
+ }
19
+
20
+ // Static specifiers: `import ... from 'x'`, `import 'x'`, `export ... from 'x'`.
21
+ // `import type` / `export type` are erased and skipped.
22
+ function staticSpecifiers(code: string): string[] {
23
+ const out: string[] = []
24
+ const re = /(?:^|\n)\s*(?:import|export)\s+(type\s+)?(?:[^'";]*?\sfrom\s+)?['"]([^'"]+)['"]/g
25
+ for (const m of code.matchAll(re)) if (!m[1]) out.push(m[2])
26
+ return out
27
+ }
28
+
29
+ function staticGraph(entry: string) {
30
+ const seen = new Set<string>()
31
+ const external = new Map<string, string>() // pkg -> first importer
32
+ const walk = (file: string) => {
33
+ if (seen.has(file)) return
34
+ seen.add(file)
35
+ for (const spec of staticSpecifiers(readFileSync(file, 'utf8'))) {
36
+ if (spec.startsWith('.')) {
37
+ const next = resolveLocal(file, spec)
38
+ if (next) walk(next)
39
+ } else if (!external.has(spec)) {
40
+ external.set(spec, file.slice(SRC.length + 1))
41
+ }
42
+ }
43
+ }
44
+ walk(entry)
45
+ return { seen, external }
46
+ }
47
+
48
+ describe('runtime-react index static graph', () => {
49
+ const { seen, external } = staticGraph(join(SRC, 'index.ts'))
50
+
51
+ it('walks a non-trivial graph (guards against a broken walker)', () => {
52
+ expect(seen.size).toBeGreaterThan(50)
53
+ expect(external.has('react')).toBe(true)
54
+ })
55
+
56
+ it.each(HEAVY)('does not statically reach %s', (lib) => {
57
+ const hit = [...external].find(([spec]) => spec === lib || spec.startsWith(`${lib}/`))
58
+ expect(hit && `${hit[0]} imported from ${hit[1]}`).toBeUndefined()
59
+ })
60
+
61
+ it('keeps the recharts-backed module out of the static graph', () => {
62
+ expect(seen.has(join(SRC, 'widgets/charts.tsx'))).toBe(false)
63
+ expect(seen.has(join(SRC, 'widgets/lazy-charts.tsx'))).toBe(true)
64
+ })
65
+ })
@@ -0,0 +1,209 @@
1
+ // @vitest-environment happy-dom
2
+ // Provenance badges: human, agent (Gobi), system/integration with origin and
3
+ // "person with agent" with the authorizer, the proposal and the date.
4
+ import { afterEach, describe, expect, it, vi } from 'vitest'
5
+ import { cleanup, render, screen } from '@testing-library/react'
6
+ import type { ReactNode } from 'react'
7
+
8
+ let language = 'es'
9
+ vi.mock('react-i18next', () => {
10
+ const t = (k: string, o?: Record<string, string>) =>
11
+ (o?.defaultValue ?? k).replace(/\{\{(\w+)\}\}/g, (_: string, v: string) => o?.[v] ?? '')
12
+ return { useTranslation: () => ({ t, i18n: { language } }) }
13
+ })
14
+
15
+ import { OrgRuntimeProvider } from '../org-runtime-provider'
16
+ import {
17
+ AuthorshipCell,
18
+ classifyProvenance,
19
+ hasSpecialAuthorship,
20
+ isSystemCreated,
21
+ notificationProvenance,
22
+ parseProvenance,
23
+ ProvenanceActorChip,
24
+ ProvenanceBadge,
25
+ readProvenance,
26
+ type ProvenanceData,
27
+ } from '../provenance'
28
+ import { AuditInfo } from '../audit-info'
29
+
30
+ afterEach(() => {
31
+ cleanup()
32
+ language = 'es'
33
+ })
34
+
35
+ const gobi = { name: 'Gobi', avatarUrl: '/images/gobi.svg' }
36
+ const wrap = (ui: ReactNode, extra: Record<string, unknown> = {}) =>
37
+ render(
38
+ <OrgRuntimeProvider agentActor={gobi} timeZone="America/Mexico_City" {...extra}>
39
+ {ui}
40
+ </OrgRuntimeProvider>,
41
+ )
42
+
43
+ const assisted: ProvenanceData = {
44
+ actor_kind: 'agent',
45
+ actor_name: 'Gobi',
46
+ mode: 'assisted',
47
+ authorized_by: 'u-1',
48
+ authorized_by_name: 'Ana Pérez',
49
+ authorized_at: '2026-10-12T16:30:00Z',
50
+ via: 'chat',
51
+ origin: 'Borrador aprobado en el chat',
52
+ summary: 'Propuso crear la acción «Recorrido en Tecomán»',
53
+ }
54
+
55
+ describe('provenance model', () => {
56
+ it('classifies the four presentations', () => {
57
+ expect(classifyProvenance({ actor_kind: 'human', mode: 'manual' })).toBe('human')
58
+ expect(classifyProvenance(assisted)).toBe('assisted')
59
+ expect(classifyProvenance({ actor_kind: 'agent', mode: 'automated', on_behalf_of: 'u-1' })).toBe('agent')
60
+ expect(classifyProvenance({ actor_kind: 'agent', mode: 'automated', proposed: true })).toBe('agent')
61
+ expect(classifyProvenance({ actor_kind: 'system', mode: 'automated' })).toBe('system')
62
+ expect(classifyProvenance({ actor_kind: 'integration', mode: 'automated' })).toBe('system')
63
+ })
64
+
65
+ it('reads provenance from created_by, the row or JSON strings', () => {
66
+ expect(readProvenance({ created_by: { name: 'Ana', provenance: assisted } })?.mode).toBe('assisted')
67
+ expect(readProvenance({ provenance: JSON.stringify(assisted) })?.actor_kind).toBe('agent')
68
+ expect(readProvenance({ provenance: { actor_kind: 'robot' } })).toBeUndefined()
69
+ expect(parseProvenance('{bad')).toBeUndefined()
70
+ expect(notificationProvenance({ metadata: JSON.stringify({ provenance: { actor_kind: 'agent' } }) })?.actor_kind).toBe('agent')
71
+ })
72
+
73
+ it('legacy system rows: null, nil and the kernel actor', () => {
74
+ expect(isSystemCreated({ created_by_id: null })).toBe(true)
75
+ expect(isSystemCreated({ created_by_id: '00000000-0000-0000-0000-000000000001' })).toBe(true)
76
+ expect(isSystemCreated({ created_by_id: 'abc', created_by: { name: 'Ana' } })).toBe(false)
77
+ expect(hasSpecialAuthorship({ created_by_id: 'abc', created_by: { name: 'Ana' } })).toBe(false)
78
+ expect(hasSpecialAuthorship({ created_by: { name: 'Ana', provenance: assisted } })).toBe(true)
79
+ })
80
+ })
81
+
82
+ describe('<ProvenanceBadge>', () => {
83
+ it('person with agent: label, overlay avatar and accessible description', () => {
84
+ const { container } = wrap(<ProvenanceBadge provenance={assisted} />)
85
+ expect(screen.getByText('Ana Pérez con Gobi')).toBeTruthy()
86
+ expect(screen.getByText('Borrador aprobado en el chat')).toBeTruthy()
87
+ const trigger = container.querySelector('[data-provenance="assisted"]') as HTMLElement
88
+ expect(trigger.tabIndex).toBe(0)
89
+ const desc = document.getElementById(trigger.getAttribute('aria-describedby') as string)
90
+ expect(desc?.textContent).toContain('Autorizó: Ana Pérez')
91
+ expect(desc?.textContent).toContain('Gobi propuso: Propuso crear la acción')
92
+ expect(desc?.textContent).toMatch(/12 oct 2026/)
93
+ expect(container.querySelector('[data-provenance-overlay] img[src="/images/gobi.svg"]')).toBeTruthy()
94
+ })
95
+
96
+ it('agent alone uses the app agent and its origin; pending proposals say so', () => {
97
+ const { rerender } = wrap(<ProvenanceBadge provenance={{ actor_kind: 'agent', mode: 'automated', origin: 'Briefing automático' }} />)
98
+ expect(screen.getByText('Gobi')).toBeTruthy()
99
+ expect(screen.getByText('Briefing automático')).toBeTruthy()
100
+ rerender(
101
+ <OrgRuntimeProvider agentActor={gobi}>
102
+ <ProvenanceBadge provenance={{ actor_kind: 'agent', mode: 'automated', proposed: true, via: 'chat' }} />
103
+ </OrgRuntimeProvider>,
104
+ )
105
+ expect(screen.getByText('Propuesta pendiente')).toBeTruthy()
106
+ })
107
+
108
+ it('system and integration show their origin, never the agent', () => {
109
+ const { container } = wrap(
110
+ <>
111
+ <ProvenanceBadge provenance={{ actor_kind: 'system', mode: 'automated', via: 'seed' }} />
112
+ <ProvenanceBadge provenance={{ actor_kind: 'integration', actor_name: 'gobiernos-intel', mode: 'automated', origin: 'Plano de datos' }} />
113
+ </>,
114
+ )
115
+ expect(screen.getByText('Sistema')).toBeTruthy()
116
+ expect(screen.getByText('Datos iniciales')).toBeTruthy()
117
+ expect(screen.getByText('gobiernos-intel')).toBeTruthy()
118
+ expect(screen.getByText('Plano de datos')).toBeTruthy()
119
+ expect(container.querySelectorAll('[data-provenance="system"]').length).toBe(2)
120
+ expect(screen.queryByText('Gobi')).toBeNull()
121
+ })
122
+
123
+ it('human alone', () => {
124
+ wrap(<ProvenanceBadge provenance={{ actor_kind: 'human', mode: 'manual', actor_person_name: 'Luis Gómez' }} />)
125
+ expect(screen.getByText('Luis Gómez')).toBeTruthy()
126
+ })
127
+
128
+ it('English copy', () => {
129
+ language = 'en'
130
+ wrap(<ProvenanceBadge provenance={assisted} />)
131
+ expect(screen.getByText('Ana Pérez with Gobi')).toBeTruthy()
132
+ })
133
+
134
+ it('without agentActor falls back to the stored agent name', () => {
135
+ render(<ProvenanceBadge provenance={{ ...assisted, actor_name: 'Llantonio' }} />)
136
+ expect(screen.getByText('Ana Pérez con Llantonio')).toBeTruthy()
137
+ })
138
+ })
139
+
140
+ describe('<AuthorshipCell>', () => {
141
+ it('legacy system row gets the host origin', () => {
142
+ const origin = vi.fn(() => 'Importación de investigación pública')
143
+ wrap(<AuthorshipCell row={{ id: 'r', created_by_id: null }} model="findings" />, { provenanceOrigin: origin, systemActor: { name: 'Sistema' } })
144
+ expect(origin).toHaveBeenCalledWith('findings', { id: 'r', created_by_id: null })
145
+ expect(screen.getByText('Importación de investigación pública')).toBeTruthy()
146
+ })
147
+
148
+ it('stored provenance wins over the legacy rule', () => {
149
+ wrap(<AuthorshipCell row={{ created_by_id: 'u-1', created_by: { name: 'Ana Pérez', provenance: assisted } }} />)
150
+ expect(screen.getByText('Ana Pérez con Gobi')).toBeTruthy()
151
+ })
152
+
153
+ it('a plain person renders the person', () => {
154
+ wrap(<AuthorshipCell row={{ created_by_id: 'u-2', created_by: { name: 'Luis' } }} variant="inline" />)
155
+ expect(screen.getByText('Luis')).toBeTruthy()
156
+ })
157
+ })
158
+
159
+ describe('history and audit', () => {
160
+ it('ProvenanceActorChip names the actor with the full sentence for screen readers', () => {
161
+ wrap(<ProvenanceActorChip provenance={assisted} />)
162
+ expect(screen.getByText('Ana Pérez con Gobi')).toBeTruthy()
163
+ expect(screen.getByText(/Autorizó: Ana Pérez/)).toBeTruthy()
164
+ })
165
+
166
+ it('AuditInfo "Creado por" uses the provenance label', () => {
167
+ wrap(
168
+ <AuditInfo
169
+ defaultOpen
170
+ record={{ created_at: '2026-10-12T16:30:00Z', created_by_id: 'u-1', created_by: { name: 'Ana Pérez', provenance: assisted } }}
171
+ audit={{ created_at: 'created_at', created_by: 'created_by_id' }}
172
+ />,
173
+ )
174
+ expect(screen.getByText('Creado por Ana Pérez con Gobi')).toBeTruthy()
175
+ })
176
+ })
177
+
178
+ describe('dynamic table created_by column', () => {
179
+ it('renders the provenance badge by default', async () => {
180
+ const { defaultGetDynamicColumns } = await import('../dynamic-columns')
181
+ const cols = defaultGetDynamicColumns(
182
+ {
183
+ title: 'Acciones',
184
+ endpoint: '/data/actions',
185
+ columns: [{ key: 'created_by.avatar', label: 'Creado por', type: 'avatar', tooltip: 'created_by.name' }],
186
+ actions: [],
187
+ perPageOptions: [10],
188
+ defaultPerPage: 10,
189
+ searchPlaceholder: '',
190
+ enableCRUDActions: false,
191
+ hasActions: false,
192
+ } as never,
193
+ () => {},
194
+ (k: string, o?: { defaultValue?: string }) => o?.defaultValue ?? k,
195
+ 'es',
196
+ new Map(),
197
+ )
198
+ const col = cols.find((c) => (c as { accessorKey?: string }).accessorKey === 'created_by.avatar' || c.id === 'created_by.avatar')
199
+ expect(col).toBeTruthy()
200
+ const original = { id: 'r1', created_by_id: 'u-1', created_by: { name: 'Ana Pérez', provenance: assisted } }
201
+ const cell = (col!.cell as (ctx: unknown) => ReactNode)({
202
+ row: { original, getValue: () => undefined },
203
+ getValue: () => undefined,
204
+ column: { id: 'created_by.avatar' },
205
+ })
206
+ wrap(<>{cell}</>)
207
+ expect(screen.getByText('Ana Pérez con Gobi')).toBeTruthy()
208
+ })
209
+ })
@@ -35,6 +35,11 @@ export interface ActivityEvent {
35
35
  correlation_id?: string | null
36
36
  actor_id?: string | null
37
37
  actor_label?: string | null
38
+ /**
39
+ * Provenance of the change (kernel `provenance`, JSON string or object):
40
+ * person, agent, system or integration, and the mode. Optional.
41
+ */
42
+ provenance?: unknown
38
43
  /** Storage path of the actor's avatar image, when the backend resolves one. */
39
44
  actor_avatar?: string | null
40
45
  addon_key: string