@asteby/metacore-runtime-react 53.7.0 → 53.8.1

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 (76) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/action-modal-dispatcher.d.ts.map +1 -1
  3. package/dist/action-modal-dispatcher.js +3 -1
  4. package/dist/api-context.d.ts.map +1 -1
  5. package/dist/api-context.js +15 -0
  6. package/dist/cache-scope.d.ts +52 -0
  7. package/dist/cache-scope.d.ts.map +1 -0
  8. package/dist/cache-scope.js +200 -0
  9. package/dist/capability-providers/index.d.ts +4 -0
  10. package/dist/capability-providers/index.d.ts.map +1 -0
  11. package/dist/capability-providers/index.js +3 -0
  12. package/dist/capability-providers/model.d.ts +201 -0
  13. package/dist/capability-providers/model.d.ts.map +1 -0
  14. package/dist/capability-providers/model.js +293 -0
  15. package/dist/capability-providers/provider-sortable-list.d.ts +86 -0
  16. package/dist/capability-providers/provider-sortable-list.d.ts.map +1 -0
  17. package/dist/capability-providers/provider-sortable-list.js +263 -0
  18. package/dist/capability-providers/reorder.d.ts +10 -0
  19. package/dist/capability-providers/reorder.d.ts.map +1 -0
  20. package/dist/capability-providers/reorder.js +31 -0
  21. package/dist/dashboard-types.d.ts +2 -4
  22. package/dist/dashboard-types.d.ts.map +1 -1
  23. package/dist/dynamic-kanban.d.ts.map +1 -1
  24. package/dist/dynamic-kanban.js +9 -4
  25. package/dist/dynamic-relation.d.ts.map +1 -1
  26. package/dist/dynamic-relation.js +5 -2
  27. package/dist/dynamic-table.d.ts +2 -0
  28. package/dist/dynamic-table.d.ts.map +1 -1
  29. package/dist/dynamic-table.js +40 -6
  30. package/dist/dynamic-view.d.ts.map +1 -1
  31. package/dist/dynamic-view.js +3 -1
  32. package/dist/index.d.ts +4 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +5 -1
  35. package/dist/metadata-cache.d.ts +22 -2
  36. package/dist/metadata-cache.d.ts.map +1 -1
  37. package/dist/metadata-cache.js +73 -13
  38. package/dist/query-batch.d.ts +12 -0
  39. package/dist/query-batch.d.ts.map +1 -1
  40. package/dist/query-batch.js +70 -29
  41. package/dist/use-option-ids.d.ts.map +1 -1
  42. package/dist/use-option-ids.js +3 -1
  43. package/dist/use-options-resolver.d.ts +4 -1
  44. package/dist/use-options-resolver.d.ts.map +1 -1
  45. package/dist/use-options-resolver.js +27 -16
  46. package/dist/widgets/charts.d.ts.map +1 -1
  47. package/dist/widgets/charts.js +11 -43
  48. package/dist/widgets/widget-format.d.ts +1 -41
  49. package/dist/widgets/widget-format.d.ts.map +1 -1
  50. package/dist/widgets/widget-format.js +3 -138
  51. package/package.json +4 -4
  52. package/src/__tests__/charts-reexport.test.ts +30 -0
  53. package/src/action-modal-dispatcher.tsx +3 -1
  54. package/src/api-context.tsx +14 -0
  55. package/src/cache-scope-inflight.test.ts +369 -0
  56. package/src/cache-scope.test.ts +234 -0
  57. package/src/cache-scope.ts +202 -0
  58. package/src/capability-providers/index.ts +46 -0
  59. package/src/capability-providers/model.test.ts +186 -0
  60. package/src/capability-providers/model.ts +464 -0
  61. package/src/capability-providers/provider-sortable-list.test.tsx +284 -0
  62. package/src/capability-providers/provider-sortable-list.tsx +452 -0
  63. package/src/capability-providers/reorder.ts +29 -0
  64. package/src/dashboard-types.ts +2 -11
  65. package/src/dynamic-kanban.tsx +9 -4
  66. package/src/dynamic-relation.tsx +5 -2
  67. package/src/dynamic-table.tsx +41 -10
  68. package/src/dynamic-view.tsx +3 -1
  69. package/src/index.ts +13 -0
  70. package/src/metadata-cache.ts +85 -15
  71. package/src/query-batch.ts +71 -30
  72. package/src/use-option-ids.ts +3 -1
  73. package/src/use-options-resolver.ts +28 -15
  74. package/src/widgets/charts.tsx +26 -189
  75. package/src/widgets/widget-format.ts +14 -181
  76. package/vitest.setup.ts +16 -0
@@ -12,6 +12,7 @@
12
12
  // free; legacy callers that still ship `searchEndpoint` keep working.
13
13
  import { useEffect, useMemo, useRef, useState } from 'react'
14
14
  import { useApi } from './api-context'
15
+ import { cacheScope, onCacheScopeChange } from './cache-scope'
15
16
  import { applyOptionFilter, type OptionFilterRule } from './option-filter'
16
17
  import { loadQueryPart, optionsBatchToken, optionsModelFromUrl } from './query-batch'
17
18
  import type { OptionDisplayData } from './option-display'
@@ -157,6 +158,9 @@ export function invalidateOptionsCache(): void {
157
158
 
158
159
  const invalidationListeners = new Set<() => void>()
159
160
 
161
+ // Options are shaped by who asks (permissions, org): drop them with the scope.
162
+ onCacheScopeChange(() => invalidateOptionsCache())
163
+
160
164
  /** Runs `fn` on every invalidateOptionsCache (id-label lookups drop with it). */
161
165
  export function onOptionsCacheInvalidated(fn: () => void): () => void {
162
166
  invalidationListeners.add(fn)
@@ -200,18 +204,20 @@ function contextKey(context: Record<string, string> | undefined): string {
200
204
  .join('&')
201
205
  }
202
206
 
203
- /** Org + branch of the host session: part of every options cache key. */
207
+ /**
208
+ * `org:user:lang` scope + branch of the host session: part of every options
209
+ * cache key. Empty when the identity is unknown (callers then skip the cache).
210
+ */
204
211
  export function optionsScope(): string {
205
- if (typeof localStorage === 'undefined') return ''
206
- let org = ''
212
+ const scope = cacheScope()
213
+ if (!scope) return ''
214
+ let branch = ''
207
215
  try {
208
- const raw = localStorage.getItem('auth_user')
209
- if (raw) org = String((JSON.parse(raw) as { organization_id?: string }).organization_id ?? '')
216
+ branch = typeof localStorage === 'undefined' ? '' : (localStorage.getItem('active_branch_id') ?? '')
210
217
  } catch {
211
- org = ''
218
+ branch = ''
212
219
  }
213
- const branch = localStorage.getItem('active_branch_id') ?? ''
214
- return `${org}|${branch}`
220
+ return `${scope}|${branch}`
215
221
  }
216
222
 
217
223
  function readOptionsEnvelope(body: any): OptionsPayload {
@@ -285,8 +291,11 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
285
291
  return
286
292
  }
287
293
 
294
+ const askedScope = optionsScope()
295
+ // Unknown identity: no cache, no shared in-flight request.
296
+ const scoped = askedScope !== ''
288
297
  const key = optionsRequestKey(
289
- optionsScope(),
298
+ askedScope,
290
299
  url,
291
300
  effectiveField,
292
301
  query ?? '',
@@ -302,7 +311,7 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
302
311
  }
303
312
  const epoch = optionsEpoch.get(key) ?? 0
304
313
  const generation = optionsGeneration
305
- const cached = optionsCache.get(key)
314
+ const cached = scoped ? optionsCache.get(key) : undefined
306
315
  if (cached && Date.now() - cached.at < OPTIONS_TTL_MS) {
307
316
  setOptions(cached.payload.options)
308
317
  setMeta(cached.payload.meta)
@@ -314,7 +323,7 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
314
323
  setLoading(true)
315
324
  setError(null)
316
325
 
317
- let pending = optionsInflight.get(key)
326
+ let pending = scoped ? optionsInflight.get(key) : undefined
318
327
  if (!pending) {
319
328
  const params: Record<string, string | number> = { field: effectiveField }
320
329
  if (query) params.q = query
@@ -337,13 +346,17 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
337
346
  data: part.data,
338
347
  meta: part.meta,
339
348
  })
340
- if ((optionsEpoch.get(key) ?? 0) === epoch && optionsGeneration === generation) {
349
+ if (scoped && optionsScope() === askedScope && (optionsEpoch.get(key) ?? 0) === epoch && optionsGeneration === generation) {
341
350
  optionsCache.set(key, { payload, at: Date.now() })
342
351
  }
343
352
  return payload
344
353
  } catch (err) {
345
354
  const msg = err instanceof Error ? err.message : ''
346
- const batchMiss = msg === 'batch unavailable' || msg === 'batch part missing'
355
+ const batchMiss =
356
+ msg === 'batch unavailable' ||
357
+ msg === 'batch part missing' ||
358
+ msg === 'batch scope changed' ||
359
+ msg === 'batch cache cleared'
347
360
  if (!batchMiss) throw err
348
361
  }
349
362
  }
@@ -353,14 +366,14 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
353
366
  throw new Error(body?.message || 'options resolver: unsuccessful response')
354
367
  }
355
368
  const payload = readOptionsEnvelope(body)
356
- if ((optionsEpoch.get(key) ?? 0) === epoch && optionsGeneration === generation) {
369
+ if (scoped && optionsScope() === askedScope && (optionsEpoch.get(key) ?? 0) === epoch && optionsGeneration === generation) {
357
370
  optionsCache.set(key, { payload, at: Date.now() })
358
371
  }
359
372
  return payload
360
373
  })().finally(() => {
361
374
  if (optionsInflight.get(key) === pending) optionsInflight.delete(key)
362
375
  })
363
- optionsInflight.set(key, pending)
376
+ if (scoped) optionsInflight.set(key, pending)
364
377
  }
365
378
 
366
379
  let cancelled = false
@@ -2,78 +2,25 @@
2
2
  // the package index on purpose: recharts is ~100 KB gzip and must not ride in
3
3
  // the host's first paint. `WidgetRenderer` loads this module with React.lazy;
4
4
  // hosts that want the components directly import
5
- // `@asteby/metacore-runtime-react/charts`. Colors come from theme CSS vars
6
- // (dark-mode safe), curves are smooth, axes/legends compact, tooltips on.
5
+ // `@asteby/metacore-runtime-react/charts`. The chart bodies live in
6
+ // `@asteby/metacore-charts/recharts`; this file only adds the WidgetCard chrome.
7
7
 
8
8
  import * as React from 'react'
9
9
  import {
10
- Area,
11
- AreaChart,
12
- Bar,
13
- BarChart,
14
- CartesianGrid,
15
- Cell,
16
- Line,
17
- LineChart,
18
- Pie,
19
- PieChart,
20
- ResponsiveContainer,
21
- Tooltip,
22
- XAxis,
23
- YAxis,
24
- } from 'recharts'
25
- import { cn } from '@asteby/metacore-ui/lib'
10
+ AreaChartBody,
11
+ BarChartBody,
12
+ DonutChartBody,
13
+ LineChartBody,
14
+ PieChartBody,
15
+ type ChartBodyProps,
16
+ } from '@asteby/metacore-charts/recharts'
26
17
  import { WidgetCard, WidgetEmpty } from './widget-card'
27
- import {
28
- accentClasses,
29
- paletteColor,
30
- formatWidgetValue,
31
- formatAxisTick,
32
- CHART_GRID,
33
- CHART_MUTED,
34
- type WidgetFormatCtx,
35
- } from './widget-format'
36
- import { fmtCtx, hasSeries, type WidgetRenderProps } from './renderers'
18
+ import { hasSeries, type WidgetRenderProps } from './renderers'
37
19
 
38
20
  export type { WidgetRenderProps }
39
21
 
40
- // Fixed-height chart body. In the masonry (CSS columns) layout cards take their
41
- // natural height, so charts need a definite height for ResponsiveContainer to
42
- // resolve. This height + the card chrome gives every chart card a consistent,
43
- // taller footprint that balances cleanly against compact stat cards.
44
- const CHART_H = 'h-[190px]'
45
- function ChartArea({ children }: { children: React.ReactElement }) {
46
- return (
47
- <div className={cn(CHART_H, 'w-full')}>
48
- <ResponsiveContainer width="100%" height="100%">
49
- {children}
50
- </ResponsiveContainer>
51
- </div>
52
- )
53
- }
54
-
55
- // Compact recharts tooltip styled with theme tokens.
56
- function ChartTooltip({ ctx }: { ctx: WidgetFormatCtx }) {
57
- return (
58
- <Tooltip
59
- cursor={{ fill: 'var(--muted, rgba(148,163,184,0.12))', opacity: 0.4 }}
60
- contentStyle={{
61
- background: 'var(--popover, #fff)',
62
- border: '1px solid var(--border, #e2e8f0)',
63
- borderRadius: 8,
64
- fontSize: 12,
65
- color: 'var(--popover-foreground, #0f172a)',
66
- boxShadow: '0 4px 16px rgba(0,0,0,0.08)',
67
- }}
68
- labelStyle={{ color: 'var(--muted-foreground, #64748b)', marginBottom: 2 }}
69
- formatter={(v) => formatWidgetValue(Number(v), ctx)}
70
- />
71
- )
72
- }
73
- // --- bar ------------------------------------------------------------------
74
- export function BarWidget(p: WidgetRenderProps) {
75
- const ctx = fmtCtx(p.spec, p.locale, p.currency)
76
- const a = accentClasses(p.spec.accent)
22
+ function ChartWidget(p: WidgetRenderProps & { Body: React.ComponentType<ChartBodyProps> }) {
23
+ const { Body } = p
77
24
  return (
78
25
  <WidgetCard
79
26
  data-testid={`widget-${p.spec.key}`}
@@ -83,27 +30,14 @@ export function BarWidget(p: WidgetRenderProps) {
83
30
  accent={p.spec.accent}
84
31
  >
85
32
  {hasSeries(p.data) ? (
86
- <ChartArea>
87
- <BarChart data={p.data.series} margin={{ top: 4, right: 4, left: -16, bottom: 0 }}>
88
- <CartesianGrid vertical={false} stroke={CHART_GRID} strokeDasharray="3 3" />
89
- <XAxis
90
- dataKey="label"
91
- tick={{ fontSize: 10, fill: CHART_MUTED }}
92
- tickLine={false}
93
- axisLine={false}
94
- interval="preserveStartEnd"
95
- />
96
- <YAxis
97
- tick={{ fontSize: 10, fill: CHART_MUTED }}
98
- tickLine={false}
99
- axisLine={false}
100
- width={44}
101
- tickFormatter={(v: number) => formatAxisTick(v, ctx)}
102
- />
103
- <ChartTooltip ctx={ctx} />
104
- <Bar dataKey="value" fill={a.chartVar} radius={[4, 4, 0, 0]} maxBarSize={48} />
105
- </BarChart>
106
- </ChartArea>
33
+ <Body
34
+ series={p.data.series}
35
+ accent={p.spec.accent}
36
+ format={p.spec.format}
37
+ locale={p.locale}
38
+ currency={p.currency}
39
+ id={p.spec.key}
40
+ />
107
41
  ) : (
108
42
  <WidgetEmpty message={p.emptyText} />
109
43
  )}
@@ -111,115 +45,18 @@ export function BarWidget(p: WidgetRenderProps) {
111
45
  )
112
46
  }
113
47
 
114
- // --- line / area (shared) -------------------------------------------------
115
- function TimeSeriesWidget(p: WidgetRenderProps & { variant: 'line' | 'area' }) {
116
- const ctx = fmtCtx(p.spec, p.locale, p.currency)
117
- const a = accentClasses(p.spec.accent)
118
- const gradId = `wg-grad-${p.spec.key}`
119
- return (
120
- <WidgetCard
121
- data-testid={`widget-${p.spec.key}`}
122
- title={p.spec.title}
123
- subtitle={p.spec.subtitle}
124
- icon={p.spec.icon}
125
- accent={p.spec.accent}
126
- >
127
- {hasSeries(p.data) ? (
128
- <ChartArea>
129
- {p.variant === 'area' ? (
130
- <AreaChart data={p.data.series} margin={{ top: 4, right: 6, left: -16, bottom: 0 }}>
131
- <defs>
132
- <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
133
- <stop offset="0%" stopColor={a.chartVar} stopOpacity={0.35} />
134
- <stop offset="100%" stopColor={a.chartVar} stopOpacity={0.02} />
135
- </linearGradient>
136
- </defs>
137
- <CartesianGrid vertical={false} stroke={CHART_GRID} strokeDasharray="3 3" />
138
- <XAxis dataKey="label" tick={{ fontSize: 10, fill: CHART_MUTED }} tickLine={false} axisLine={false} interval="preserveStartEnd" />
139
- <YAxis tick={{ fontSize: 10, fill: CHART_MUTED }} tickLine={false} axisLine={false} width={44} tickFormatter={(v: number) => formatAxisTick(v, ctx)} />
140
- <ChartTooltip ctx={ctx} />
141
- <Area type="monotone" dataKey="value" stroke={a.chartVar} strokeWidth={2} fill={`url(#${gradId})`} />
142
- </AreaChart>
143
- ) : (
144
- <LineChart data={p.data.series} margin={{ top: 4, right: 6, left: -16, bottom: 0 }}>
145
- <CartesianGrid vertical={false} stroke={CHART_GRID} strokeDasharray="3 3" />
146
- <XAxis dataKey="label" tick={{ fontSize: 10, fill: CHART_MUTED }} tickLine={false} axisLine={false} interval="preserveStartEnd" />
147
- <YAxis tick={{ fontSize: 10, fill: CHART_MUTED }} tickLine={false} axisLine={false} width={44} tickFormatter={(v: number) => formatAxisTick(v, ctx)} />
148
- <ChartTooltip ctx={ctx} />
149
- <Line type="monotone" dataKey="value" stroke={a.chartVar} strokeWidth={2} dot={false} activeDot={{ r: 4 }} />
150
- </LineChart>
151
- )}
152
- </ChartArea>
153
- ) : (
154
- <WidgetEmpty message={p.emptyText} />
155
- )}
156
- </WidgetCard>
157
- )
48
+ export function BarWidget(p: WidgetRenderProps) {
49
+ return <ChartWidget {...p} Body={BarChartBody} />
158
50
  }
159
-
160
51
  export function LineWidget(p: WidgetRenderProps) {
161
- return <TimeSeriesWidget {...p} variant="line" />
52
+ return <ChartWidget {...p} Body={LineChartBody} />
162
53
  }
163
54
  export function AreaWidget(p: WidgetRenderProps) {
164
- return <TimeSeriesWidget {...p} variant="area" />
55
+ return <ChartWidget {...p} Body={AreaChartBody} />
165
56
  }
166
-
167
- // --- pie / donut (shared) -------------------------------------------------
168
- function CircularWidget(p: WidgetRenderProps & { variant: 'pie' | 'donut' }) {
169
- const ctx = fmtCtx(p.spec, p.locale, p.currency)
170
- return (
171
- <WidgetCard
172
- data-testid={`widget-${p.spec.key}`}
173
- title={p.spec.title}
174
- subtitle={p.spec.subtitle}
175
- icon={p.spec.icon}
176
- accent={p.spec.accent}
177
- >
178
- {hasSeries(p.data) ? (
179
- <div className={cn(CHART_H, 'flex items-center gap-3')}>
180
- <div className="h-full min-h-0 w-[46%] shrink-0">
181
- <ResponsiveContainer width="100%" height="100%">
182
- <PieChart>
183
- <ChartTooltip ctx={ctx} />
184
- <Pie
185
- data={p.data.series}
186
- dataKey="value"
187
- nameKey="label"
188
- innerRadius={p.variant === 'donut' ? '55%' : 0}
189
- outerRadius="92%"
190
- paddingAngle={p.variant === 'donut' ? 2 : 0}
191
- stroke="var(--background, #fff)"
192
- strokeWidth={2}
193
- >
194
- {p.data.series.map((_, i) => (
195
- <Cell key={i} fill={paletteColor(i)} />
196
- ))}
197
- </Pie>
198
- </PieChart>
199
- </ResponsiveContainer>
200
- </div>
201
- <ul className="flex min-w-0 flex-1 flex-col gap-1.5">
202
- {p.data.series.slice(0, 6).map((pt, i) => (
203
- <li key={pt.key} className="flex items-center gap-2 text-xs">
204
- <span className="size-2.5 shrink-0 rounded-sm" style={{ background: paletteColor(i) }} />
205
- <span className="truncate text-muted-foreground">{pt.label}</span>
206
- <span className="ml-auto shrink-0 font-medium tabular-nums text-foreground">
207
- {formatWidgetValue(pt.value, ctx)}
208
- </span>
209
- </li>
210
- ))}
211
- </ul>
212
- </div>
213
- ) : (
214
- <WidgetEmpty message={p.emptyText} />
215
- )}
216
- </WidgetCard>
217
- )
218
- }
219
-
220
57
  export function PieWidget(p: WidgetRenderProps) {
221
- return <CircularWidget {...p} variant="pie" />
58
+ return <ChartWidget {...p} Body={PieChartBody} />
222
59
  }
223
60
  export function DonutWidget(p: WidgetRenderProps) {
224
- return <CircularWidget {...p} variant="donut" />
61
+ return <ChartWidget {...p} Body={DonutChartBody} />
225
62
  }
@@ -1,181 +1,14 @@
1
- // Shared widget formatting + accent theming. Reuses the same Intl-based
2
- // approach as the table cells (dynamic-columns) so dashboard numbers read
3
- // identically to the grids: org currency + locale, compact notation, percent.
4
-
5
- import type { WidgetAccent, WidgetFormat } from '../dashboard-types'
6
-
7
- export interface WidgetFormatCtx {
8
- format?: WidgetFormat
9
- locale?: string
10
- currency?: string
11
- }
12
-
13
- /**
14
- * Formats a scalar/series value with the widget's declared format. `currency`
15
- * uses the org currency + locale (same fallback chain as table cells); `percent`
16
- * treats the value as a fraction (0.142 → "14.2%"); `compact` uses Intl compact
17
- * notation (1_200 → "1.2K").
18
- */
19
- export function formatWidgetValue(
20
- value: number,
21
- { format = 'number', locale, currency }: WidgetFormatCtx,
22
- ): string {
23
- if (value === null || value === undefined || Number.isNaN(value)) return '—'
24
- const loc = locale || undefined
25
- switch (format) {
26
- case 'currency':
27
- return new Intl.NumberFormat(loc, {
28
- style: 'currency',
29
- currency: currency || 'USD',
30
- maximumFractionDigits: 2,
31
- }).format(value)
32
- case 'percent':
33
- return new Intl.NumberFormat(loc, {
34
- style: 'percent',
35
- minimumFractionDigits: 0,
36
- maximumFractionDigits: 1,
37
- }).format(value)
38
- case 'compact':
39
- return new Intl.NumberFormat(loc, {
40
- notation: 'compact',
41
- maximumFractionDigits: 1,
42
- }).format(value)
43
- case 'number':
44
- default:
45
- return new Intl.NumberFormat(loc, {
46
- maximumFractionDigits: 2,
47
- }).format(value)
48
- }
49
- }
50
-
51
- /** Axis-tick formatter — always compact so charts stay legible. */
52
- export function formatAxisTick(
53
- value: number,
54
- { format, locale, currency }: WidgetFormatCtx,
55
- ): string {
56
- const loc = locale || undefined
57
- if (format === 'currency') {
58
- return new Intl.NumberFormat(loc, {
59
- style: 'currency',
60
- currency: currency || 'USD',
61
- notation: 'compact',
62
- maximumFractionDigits: 1,
63
- }).format(value)
64
- }
65
- if (format === 'percent') {
66
- return new Intl.NumberFormat(loc, {
67
- style: 'percent',
68
- maximumFractionDigits: 0,
69
- }).format(value)
70
- }
71
- return new Intl.NumberFormat(loc, {
72
- notation: 'compact',
73
- maximumFractionDigits: 1,
74
- }).format(value)
75
- }
76
-
77
- /** Formats the compare delta fraction (0.142 → "+14.2%"). */
78
- export function formatDelta(delta: number, locale?: string): string {
79
- const sign = delta > 0 ? '+' : ''
80
- return (
81
- sign +
82
- new Intl.NumberFormat(locale || undefined, {
83
- style: 'percent',
84
- minimumFractionDigits: 0,
85
- maximumFractionDigits: 1,
86
- }).format(delta)
87
- )
88
- }
89
-
90
- // --- Accent theming -------------------------------------------------------
91
- // Tailwind tokens scanned in THIS package's build (the renderers live in the
92
- // SDK, not the federated host), so static utility classes are safe. We avoid
93
- // host-dependent arbitrary values. Each accent maps to a small bundle of
94
- // classes for the icon chip, the chart stroke/fill and the progress/list bar.
95
-
96
- export interface AccentClasses {
97
- /** Icon chip background + foreground. */
98
- chip: string
99
- /** Text color for accented labels. */
100
- text: string
101
- /** Solid bar/fill background (progress, list proportion). */
102
- bar: string
103
- /** Soft track background behind a bar. */
104
- track: string
105
- /** Hex-ish CSS color used for recharts stroke/fill (var-based). */
106
- chartVar: string
107
- }
108
-
109
- const ACCENTS: Record<WidgetAccent, AccentClasses> = {
110
- emerald: {
111
- chip: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
112
- text: 'text-emerald-600 dark:text-emerald-400',
113
- bar: 'bg-emerald-500',
114
- track: 'bg-emerald-500/15',
115
- chartVar: 'var(--color-widget-emerald, #10b981)',
116
- },
117
- sky: {
118
- chip: 'bg-sky-500/10 text-sky-600 dark:text-sky-400',
119
- text: 'text-sky-600 dark:text-sky-400',
120
- bar: 'bg-sky-500',
121
- track: 'bg-sky-500/15',
122
- chartVar: 'var(--color-widget-sky, #0ea5e9)',
123
- },
124
- violet: {
125
- chip: 'bg-violet-500/10 text-violet-600 dark:text-violet-400',
126
- text: 'text-violet-600 dark:text-violet-400',
127
- bar: 'bg-violet-500',
128
- track: 'bg-violet-500/15',
129
- chartVar: 'var(--color-widget-violet, #8b5cf6)',
130
- },
131
- amber: {
132
- chip: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',
133
- text: 'text-amber-600 dark:text-amber-400',
134
- bar: 'bg-amber-500',
135
- track: 'bg-amber-500/15',
136
- chartVar: 'var(--color-widget-amber, #f59e0b)',
137
- },
138
- rose: {
139
- chip: 'bg-rose-500/10 text-rose-600 dark:text-rose-400',
140
- text: 'text-rose-600 dark:text-rose-400',
141
- bar: 'bg-rose-500',
142
- track: 'bg-rose-500/15',
143
- chartVar: 'var(--color-widget-rose, #f43f5e)',
144
- },
145
- slate: {
146
- chip: 'bg-slate-500/10 text-slate-600 dark:text-slate-300',
147
- text: 'text-slate-600 dark:text-slate-300',
148
- bar: 'bg-slate-500',
149
- track: 'bg-slate-500/15',
150
- chartVar: 'var(--color-widget-slate, #64748b)',
151
- },
152
- }
153
-
154
- const DEFAULT_ACCENT: WidgetAccent = 'sky'
155
-
156
- /** Resolves the accent class bundle, defaulting to `sky`. */
157
- export function accentClasses(accent?: WidgetAccent): AccentClasses {
158
- return ACCENTS[accent ?? DEFAULT_ACCENT] ?? ACCENTS[DEFAULT_ACCENT]
159
- }
160
-
161
- /**
162
- * A categorical palette for multi-series charts (pie/donut/bar by bucket).
163
- * Cycles the accent chart vars so slices stay theme-aware + dark-mode safe.
164
- */
165
- export const CHART_PALETTE: string[] = [
166
- ACCENTS.sky.chartVar,
167
- ACCENTS.emerald.chartVar,
168
- ACCENTS.violet.chartVar,
169
- ACCENTS.amber.chartVar,
170
- ACCENTS.rose.chartVar,
171
- ACCENTS.slate.chartVar,
172
- ]
173
-
174
- /** Picks a palette color by index, wrapping around. */
175
- export function paletteColor(index: number): string {
176
- return CHART_PALETTE[index % CHART_PALETTE.length]
177
- }
178
-
179
- /** Grid/axis muted color from the theme (works in light + dark). */
180
- export const CHART_MUTED = 'var(--muted-foreground, #94a3b8)'
181
- export const CHART_GRID = 'var(--border, #e2e8f0)'
1
+ // Moved to @asteby/metacore-charts (shared palette + formatting). Re-exported
2
+ // here so existing imports keep compiling.
3
+ export {
4
+ formatWidgetValue,
5
+ formatAxisTick,
6
+ formatDelta,
7
+ accentClasses,
8
+ paletteColor,
9
+ CHART_PALETTE,
10
+ CHART_GRID,
11
+ CHART_MUTED,
12
+ type AccentClasses,
13
+ type WidgetFormatCtx,
14
+ } from '@asteby/metacore-charts'
package/vitest.setup.ts CHANGED
@@ -34,3 +34,19 @@ installMemoryStorage('sessionStorage')
34
34
  import { configure } from '@testing-library/react'
35
35
 
36
36
  configure({ asyncUtilTimeout: 5000 })
37
+
38
+ // Scoped caches (metadata store, query batch) fail closed without an
39
+ // org:user:lang identity. Give every test one by default; the cache-scope
40
+ // suites remove or change it explicitly.
41
+ import { beforeEach } from 'vitest'
42
+
43
+ beforeEach(() => {
44
+ try {
45
+ if (!localStorage.getItem('auth_user')) {
46
+ localStorage.setItem('auth_user', JSON.stringify({ id: 'u-test', organization_id: 'o-test' }))
47
+ }
48
+ if (!localStorage.getItem('i18nextLng')) localStorage.setItem('i18nextLng', 'en')
49
+ } catch {
50
+ /* storage unavailable */
51
+ }
52
+ })