@asteby/metacore-runtime-react 52.1.0 → 53.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 (86) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/addon-loader.d.ts +22 -1
  3. package/dist/addon-loader.d.ts.map +1 -1
  4. package/dist/addon-loader.js +23 -5
  5. package/dist/addon-page-host.d.ts +80 -0
  6. package/dist/addon-page-host.d.ts.map +1 -0
  7. package/dist/addon-page-host.js +216 -0
  8. package/dist/addon-page-loader.d.ts +40 -0
  9. package/dist/addon-page-loader.d.ts.map +1 -0
  10. package/dist/addon-page-loader.js +87 -0
  11. package/dist/dynamic-view.d.ts +20 -1
  12. package/dist/dynamic-view.d.ts.map +1 -1
  13. package/dist/dynamic-view.js +26 -3
  14. package/dist/federated-error-boundary.d.ts +46 -0
  15. package/dist/federated-error-boundary.d.ts.map +1 -0
  16. package/dist/federated-error-boundary.js +55 -0
  17. package/dist/host-api.d.ts +22 -0
  18. package/dist/host-api.d.ts.map +1 -0
  19. package/dist/host-api.js +140 -0
  20. package/dist/index.d.ts +6 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +8 -1
  23. package/dist/testing.d.ts +42 -0
  24. package/dist/testing.d.ts.map +1 -0
  25. package/dist/testing.js +53 -0
  26. package/dist/types.d.ts +13 -0
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/views/calendar-view.d.ts +23 -0
  29. package/dist/views/calendar-view.d.ts.map +1 -0
  30. package/dist/views/calendar-view.js +138 -0
  31. package/dist/views/chart-view.d.ts +14 -0
  32. package/dist/views/chart-view.d.ts.map +1 -0
  33. package/dist/views/chart-view.js +77 -0
  34. package/dist/views/data-source.d.ts +30 -0
  35. package/dist/views/data-source.d.ts.map +1 -0
  36. package/dist/views/data-source.js +103 -0
  37. package/dist/views/index.d.ts +4 -0
  38. package/dist/views/index.d.ts.map +1 -0
  39. package/dist/views/index.js +2 -0
  40. package/dist/views/map-view.d.ts +39 -0
  41. package/dist/views/map-view.d.ts.map +1 -0
  42. package/dist/views/map-view.js +143 -0
  43. package/dist/views/panels.d.ts +13 -0
  44. package/dist/views/panels.d.ts.map +1 -0
  45. package/dist/views/panels.js +119 -0
  46. package/dist/views/registry.d.ts +46 -0
  47. package/dist/views/registry.d.ts.map +1 -0
  48. package/dist/views/registry.js +139 -0
  49. package/dist/views/skeleton.d.ts +5 -0
  50. package/dist/views/skeleton.d.ts.map +1 -0
  51. package/dist/views/skeleton.js +6 -0
  52. package/dist/views/split-view.d.ts +6 -0
  53. package/dist/views/split-view.d.ts.map +1 -0
  54. package/dist/views/split-view.js +52 -0
  55. package/dist/views/timeline-view.d.ts +25 -0
  56. package/dist/views/timeline-view.d.ts.map +1 -0
  57. package/dist/views/timeline-view.js +130 -0
  58. package/dist/views/types.d.ts +87 -0
  59. package/dist/views/types.d.ts.map +1 -0
  60. package/dist/views/types.js +1 -0
  61. package/package.json +18 -6
  62. package/src/__tests__/addon-page-host.test.tsx +122 -0
  63. package/src/__tests__/addon-page-loader.test.tsx +201 -0
  64. package/src/__tests__/declarative-views.test.tsx +351 -0
  65. package/src/__tests__/host-api.test.ts +153 -0
  66. package/src/__tests__/index-static-graph.test.ts +18 -0
  67. package/src/addon-loader.tsx +51 -8
  68. package/src/addon-page-host.tsx +319 -0
  69. package/src/addon-page-loader.tsx +203 -0
  70. package/src/dynamic-view.tsx +61 -3
  71. package/src/federated-error-boundary.tsx +121 -0
  72. package/src/host-api.ts +166 -0
  73. package/src/index.ts +38 -0
  74. package/src/testing.tsx +108 -0
  75. package/src/types.ts +13 -0
  76. package/src/views/calendar-view.tsx +234 -0
  77. package/src/views/chart-view.tsx +122 -0
  78. package/src/views/data-source.ts +127 -0
  79. package/src/views/index.ts +37 -0
  80. package/src/views/map-view.tsx +217 -0
  81. package/src/views/panels.tsx +177 -0
  82. package/src/views/registry.tsx +202 -0
  83. package/src/views/skeleton.tsx +13 -0
  84. package/src/views/split-view.tsx +115 -0
  85. package/src/views/timeline-view.tsx +229 -0
  86. package/src/views/types.ts +105 -0
@@ -0,0 +1,234 @@
1
+ // `view_type: calendar`: a model's rows on a month grid. Lazy chunk, no
2
+ // calendar library: a 7-column CSS grid built from the UI kit, one request per
3
+ // visible month (`f_<start_field>=RANGE:<first>,<last>`, the list syntax the
4
+ // kernel already serves). Multi-day entries (end_field) show on each day.
5
+ import * as React from 'react'
6
+ import { useTranslation } from 'react-i18next'
7
+ import { ChevronLeft, ChevronRight } from 'lucide-react'
8
+ import { Badge, Button } from '@asteby/metacore-ui/primitives'
9
+ import type { CalendarView } from '@asteby/metacore-sdk'
10
+ import type { ViewRendererProps } from './types'
11
+ import { dayKey, displayValue, toDate } from './data-source'
12
+ import { ViewSkeleton } from './skeleton'
13
+
14
+ const MAX_ROWS = 500
15
+
16
+ export interface CalendarEntry {
17
+ key: string
18
+ title: string
19
+ start: Date
20
+ end: Date
21
+ allDay: boolean
22
+ color?: string
23
+ row: Record<string, unknown>
24
+ }
25
+
26
+ /** First and last calendar day of the month containing `d` (`YYYY-MM-DD`). */
27
+ export function monthRange(d: Date): { first: string; last: string } {
28
+ const first = new Date(d.getFullYear(), d.getMonth(), 1, 12)
29
+ const last = new Date(d.getFullYear(), d.getMonth() + 1, 0, 12)
30
+ return { first: dayKey(first), last: dayKey(last) }
31
+ }
32
+
33
+ /** Pure: rows → entries with parsed dates (rows without a start are dropped). */
34
+ export function toCalendarEntries(rows: Record<string, unknown>[], view: CalendarView): CalendarEntry[] {
35
+ const out: CalendarEntry[] = []
36
+ rows.forEach((row, i) => {
37
+ const start = toDate(row[view.start_field])
38
+ if (!start) return
39
+ const endRaw = view.end_field ? toDate(row[view.end_field]) : null
40
+ const end = endRaw && endRaw.getTime() >= start.getTime() ? endRaw : start
41
+ const allDayRaw = view.all_day_field ? row[view.all_day_field] : undefined
42
+ const allDay =
43
+ allDayRaw !== undefined
44
+ ? allDayRaw === true || allDayRaw === 'true'
45
+ : typeof row[view.start_field] === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(row[view.start_field] as string)
46
+ out.push({
47
+ key: String(row.id ?? i),
48
+ title: displayValue(view.title_field ? row[view.title_field] : row.name ?? row.title ?? row.id),
49
+ start,
50
+ end,
51
+ allDay,
52
+ color: view.color_by ? displayValue(row[view.color_by]) || undefined : undefined,
53
+ row,
54
+ })
55
+ })
56
+ return out
57
+ }
58
+
59
+ /** Pure: entries bucketed by local day key, each multi-day entry on every day it spans. */
60
+ export function bucketByDay(entries: CalendarEntry[], maxSpanDays = 62): Map<string, CalendarEntry[]> {
61
+ const map = new Map<string, CalendarEntry[]>()
62
+ for (const e of entries) {
63
+ const cur = new Date(e.start.getFullYear(), e.start.getMonth(), e.start.getDate(), 12)
64
+ const stop = new Date(e.end.getFullYear(), e.end.getMonth(), e.end.getDate(), 12)
65
+ for (let n = 0; cur.getTime() <= stop.getTime() && n < maxSpanDays; n++) {
66
+ const k = dayKey(cur)
67
+ const arr = map.get(k) ?? []
68
+ arr.push(e)
69
+ map.set(k, arr)
70
+ cur.setDate(cur.getDate() + 1)
71
+ }
72
+ }
73
+ return map
74
+ }
75
+
76
+ function weeksOf(month: Date): Date[][] {
77
+ const first = new Date(month.getFullYear(), month.getMonth(), 1, 12)
78
+ // Monday-first grid (es-MX convention); pad with the previous month.
79
+ const offset = (first.getDay() + 6) % 7
80
+ const start = new Date(first)
81
+ start.setDate(first.getDate() - offset)
82
+ const weeks: Date[][] = []
83
+ const cur = new Date(start)
84
+ do {
85
+ const week: Date[] = []
86
+ for (let i = 0; i < 7; i++) {
87
+ week.push(new Date(cur))
88
+ cur.setDate(cur.getDate() + 1)
89
+ }
90
+ weeks.push(week)
91
+ } while (cur.getMonth() === month.getMonth())
92
+ return weeks
93
+ }
94
+
95
+ export default function CalendarViewRenderer(props: ViewRendererProps<'calendar'>) {
96
+ const { model, view, data, locale, onOpenRecord, className } = props
97
+ const { t } = useTranslation()
98
+ const [month, setMonth] = React.useState(() => {
99
+ const n = new Date()
100
+ return new Date(n.getFullYear(), n.getMonth(), 1, 12)
101
+ })
102
+ const [rows, setRows] = React.useState<Record<string, unknown>[] | null>(null)
103
+ const [error, setError] = React.useState(false)
104
+ const { first, last } = monthRange(month)
105
+
106
+ React.useEffect(() => {
107
+ let cancelled = false
108
+ setRows(null)
109
+ setError(false)
110
+ data
111
+ .list(model, {
112
+ [`f_${view.start_field}`]: `RANGE:${first},${last}`,
113
+ per_page: MAX_ROWS,
114
+ sortBy: view.start_field,
115
+ order: 'asc',
116
+ })
117
+ .then((res) => !cancelled && setRows(res.rows))
118
+ .catch(() => !cancelled && setError(true))
119
+ return () => {
120
+ cancelled = true
121
+ }
122
+ }, [data, model, view.start_field, first, last])
123
+
124
+ const monthLabel = React.useMemo(() => {
125
+ try {
126
+ return new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric' }).format(month)
127
+ } catch {
128
+ return dayKey(month).slice(0, 7)
129
+ }
130
+ }, [locale, month])
131
+ const weekdayLabels = React.useMemo(() => {
132
+ const monday = new Date(2024, 0, 1, 12) // a Monday
133
+ return Array.from({ length: 7 }, (_, i) => {
134
+ const d = new Date(monday)
135
+ d.setDate(monday.getDate() + i)
136
+ try {
137
+ return new Intl.DateTimeFormat(locale, { weekday: 'short' }).format(d)
138
+ } catch {
139
+ return String(i)
140
+ }
141
+ })
142
+ }, [locale])
143
+
144
+ const byDay = React.useMemo(
145
+ () => bucketByDay(toCalendarEntries(rows ?? [], view)),
146
+ [rows, view],
147
+ )
148
+ const shift = (n: number) => setMonth((m) => new Date(m.getFullYear(), m.getMonth() + n, 1, 12))
149
+ const today = dayKey(new Date())
150
+
151
+ return (
152
+ <div className={className} data-testid="calendar-view">
153
+ <div className="mb-3 flex items-center justify-between gap-2">
154
+ <h2 className="text-base font-semibold capitalize text-foreground" aria-live="polite">
155
+ {monthLabel}
156
+ </h2>
157
+ <div className="flex gap-1">
158
+ <Button variant="outline" size="icon" aria-label={t('metacore.views.prev_month', 'Mes anterior')} onClick={() => shift(-1)}>
159
+ <ChevronLeft aria-hidden className="h-4 w-4" />
160
+ </Button>
161
+ <Button variant="outline" size="icon" aria-label={t('metacore.views.next_month', 'Mes siguiente')} onClick={() => shift(1)}>
162
+ <ChevronRight aria-hidden className="h-4 w-4" />
163
+ </Button>
164
+ </div>
165
+ </div>
166
+ {error ? (
167
+ <p role="alert" className="text-sm text-destructive">
168
+ {t('metacore.views.error', 'No se pudo cargar la información.')}
169
+ </p>
170
+ ) : !rows ? (
171
+ <ViewSkeleton height={480} />
172
+ ) : (
173
+ <div role="grid" aria-label={monthLabel} className="overflow-hidden rounded-lg border">
174
+ <div role="row" className="grid grid-cols-7 border-b bg-muted/40">
175
+ {weekdayLabels.map((w) => (
176
+ <div key={w} role="columnheader" className="px-2 py-1 text-xs font-medium text-muted-foreground">
177
+ {w}
178
+ </div>
179
+ ))}
180
+ </div>
181
+ {weeksOf(month).map((week) => (
182
+ <div key={dayKey(week[0])} role="row" className="grid grid-cols-7">
183
+ {week.map((d) => {
184
+ const k = dayKey(d)
185
+ const items = byDay.get(k) ?? []
186
+ const outside = d.getMonth() !== month.getMonth()
187
+ return (
188
+ <div
189
+ key={k}
190
+ role="gridcell"
191
+ aria-label={k}
192
+ data-day={k}
193
+ className={[
194
+ 'min-h-[6rem] border-b border-r p-1 text-xs',
195
+ outside ? 'bg-muted/20 text-muted-foreground' : '',
196
+ ].join(' ')}
197
+ >
198
+ <div className={['mb-1 text-right', k === today ? 'font-semibold text-primary' : ''].join(' ')}>
199
+ {d.getDate()}
200
+ </div>
201
+ <ul className="space-y-1">
202
+ {items.slice(0, 3).map((e) => (
203
+ <li key={e.key}>
204
+ <button
205
+ type="button"
206
+ className="w-full truncate rounded px-1 py-0.5 text-left hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
207
+ onClick={() => onOpenRecord?.(e.row)}
208
+ title={e.title}
209
+ >
210
+ {e.color ? (
211
+ <Badge variant="outline" className="mr-1 px-1 py-0 text-[10px]">
212
+ {e.color}
213
+ </Badge>
214
+ ) : null}
215
+ {e.title}
216
+ </button>
217
+ </li>
218
+ ))}
219
+ {items.length > 3 ? (
220
+ <li className="px-1 text-muted-foreground">
221
+ {t('metacore.views.more_count', '+{{count}} más', { count: items.length - 3 })}
222
+ </li>
223
+ ) : null}
224
+ </ul>
225
+ </div>
226
+ )
227
+ })}
228
+ </div>
229
+ ))}
230
+ </div>
231
+ )}
232
+ </div>
233
+ )
234
+ }
@@ -0,0 +1,122 @@
1
+ // `view_type: chart` and `kind: chart` detail panels. Reuses the dashboard
2
+ // widgets (same WidgetQuery, same aggregation engine on the host, same cards):
3
+ // no new chart code, no client-side math. This module is a lazy chunk; it is
4
+ // the only place views reach recharts (through ../widgets/charts).
5
+ import * as React from 'react'
6
+ import { useTranslation } from 'react-i18next'
7
+ import type { ChartView } from '@asteby/metacore-sdk'
8
+ import type { DashboardWidgetSpec, WidgetData, WidgetFormat } from '../dashboard-types'
9
+ import { AreaWidget, BarWidget, DonutWidget, LineWidget, PieWidget } from '../widgets/charts'
10
+ import type { WidgetRenderProps } from '../widgets/renderers'
11
+ import type { ChartRequest, PanelRendererProps, ViewDataSource, ViewRendererProps } from './types'
12
+ import { ViewSkeleton } from './skeleton'
13
+
14
+ const BY_KIND: Record<string, React.ComponentType<WidgetRenderProps>> = {
15
+ bar: BarWidget,
16
+ line: LineWidget,
17
+ area: AreaWidget,
18
+ pie: PieWidget,
19
+ donut: DonutWidget,
20
+ }
21
+
22
+ /** Load one declared chart; exposes loading/error so tests and hosts can assert. */
23
+ export function useChartData(data: ViewDataSource, req: ChartRequest | null) {
24
+ const [state, setState] = React.useState<{ loading: boolean; data?: WidgetData; error?: Error }>({
25
+ loading: true,
26
+ })
27
+ const sig = req ? JSON.stringify(req) : ''
28
+ React.useEffect(() => {
29
+ if (!req) return
30
+ let cancelled = false
31
+ setState({ loading: true })
32
+ data.chart(req).then(
33
+ (d) => !cancelled && setState({ loading: false, data: d }),
34
+ (e: unknown) => !cancelled && setState({ loading: false, error: e instanceof Error ? e : new Error(String(e)) }),
35
+ )
36
+ return () => {
37
+ cancelled = true
38
+ }
39
+ // eslint-disable-next-line react-hooks/exhaustive-deps
40
+ }, [data, sig])
41
+ return state
42
+ }
43
+
44
+ function ChartBody({
45
+ chart,
46
+ title,
47
+ req,
48
+ data,
49
+ locale,
50
+ currency,
51
+ }: {
52
+ chart: ChartView
53
+ title: string
54
+ req: ChartRequest
55
+ data: ViewDataSource
56
+ locale?: string
57
+ currency?: string
58
+ }) {
59
+ const { t } = useTranslation()
60
+ const state = useChartData(data, req)
61
+ const Widget = BY_KIND[chart.kind]
62
+ if (state.loading) return <ViewSkeleton height={260} />
63
+ if (state.error) {
64
+ return (
65
+ <p role="alert" className="text-sm text-destructive">
66
+ {t('metacore.views.error', 'No se pudo cargar la información.')}
67
+ </p>
68
+ )
69
+ }
70
+ if (!Widget) return null
71
+ const spec: DashboardWidgetSpec = {
72
+ key: req.panelKey ?? `${req.model}.chart`,
73
+ title: t(title),
74
+ kind: chart.kind as DashboardWidgetSpec['kind'],
75
+ format: chart.format as WidgetFormat | undefined,
76
+ }
77
+ return (
78
+ <div data-testid="chart-view" data-kind={chart.kind}>
79
+ <Widget
80
+ spec={spec}
81
+ data={state.data}
82
+ locale={locale}
83
+ currency={currency}
84
+ emptyText={t('metacore.views.empty', 'Sin datos todavía.')}
85
+ />
86
+ </div>
87
+ )
88
+ }
89
+
90
+ /** `view_type: chart` on a nav entry. */
91
+ export default function ChartViewRenderer(props: ViewRendererProps<'chart'>) {
92
+ const { view, model, data, metadata, locale, currency, className } = props
93
+ if (!view.query) return null
94
+ const req: ChartRequest = { model, query: view.query }
95
+ return (
96
+ <div className={className}>
97
+ <ChartBody
98
+ chart={view}
99
+ title={metadata?.title ?? model}
100
+ req={req}
101
+ data={data}
102
+ locale={locale}
103
+ currency={currency}
104
+ />
105
+ </div>
106
+ )
107
+ }
108
+
109
+ /** `kind: chart` detail panel (query scoped to the record's relation). */
110
+ export function ChartPanel({ panel, model, record, data, locale, currency }: PanelRendererProps) {
111
+ const chart = panel.chart
112
+ const id = record.id
113
+ if (!chart?.query || id === undefined || id === null) return null
114
+ const req: ChartRequest = {
115
+ model,
116
+ query: chart.query,
117
+ relation: chart.relation,
118
+ recordId: String(id),
119
+ panelKey: panel.key,
120
+ }
121
+ return <ChartBody chart={chart} title={panel.title} req={req} data={data} locale={locale} currency={currency} />
122
+ }
@@ -0,0 +1,127 @@
1
+ // Default ViewDataSource over the runtime-react ApiClient, plus the pure
2
+ // helpers renderers share (capability input mapping, item extraction, date
3
+ // grouping). Light on purpose: this module is in the static graph.
4
+ import type { ApiClient } from '../api-context'
5
+ import type { WidgetData } from '../dashboard-types'
6
+ import type { ChartRequest, ViewDataSource, ViewListParams, ViewRows } from './types'
7
+
8
+ export interface ApiViewDataSourceOptions {
9
+ /**
10
+ * Endpoint the host serves declared view/panel charts on (`POST`, body
11
+ * {@link ChartRequest} in snake_case, response `{ success, data: WidgetData }`).
12
+ * Default `/views/chart`.
13
+ */
14
+ chartPath?: string
15
+ /** Capability query endpoint (`POST { capability, input }`). Default `/capabilities/query`. */
16
+ capabilityPath?: string
17
+ }
18
+
19
+ type Envelope<T> = { success?: boolean; data?: T; meta?: { total?: number }; message?: string }
20
+
21
+ function unwrap<T>(body: unknown): { data: T | undefined; total?: number } {
22
+ const env = body as Envelope<T>
23
+ if (env && typeof env === 'object' && 'success' in env) {
24
+ if (env.success === false) throw new Error(env.message || 'request failed')
25
+ return { data: env.data, total: env.meta?.total }
26
+ }
27
+ return { data: body as T }
28
+ }
29
+
30
+ export function createApiViewDataSource(
31
+ api: ApiClient,
32
+ opts: ApiViewDataSourceOptions = {},
33
+ ): ViewDataSource {
34
+ const chartPath = opts.chartPath ?? '/views/chart'
35
+ const capabilityPath = opts.capabilityPath ?? '/capabilities/query'
36
+ return {
37
+ async list(model: string, params?: ViewListParams): Promise<ViewRows> {
38
+ const res = await api.get(`/data/${encodeURIComponent(model)}`, params ? { params } : undefined)
39
+ const { data, total } = unwrap<Record<string, unknown>[]>(res.data)
40
+ return { rows: Array.isArray(data) ? data : [], total }
41
+ },
42
+ async record(model: string, id: string) {
43
+ const res = await api.get(`/data/${encodeURIComponent(model)}/${encodeURIComponent(id)}`)
44
+ return unwrap<Record<string, unknown>>(res.data).data ?? null
45
+ },
46
+ async chart(req: ChartRequest): Promise<WidgetData> {
47
+ const res = await api.post(chartPath, {
48
+ model: req.model,
49
+ query: req.query,
50
+ relation: req.relation,
51
+ record_id: req.recordId,
52
+ panel_key: req.panelKey,
53
+ })
54
+ return unwrap<WidgetData>(res.data).data ?? {}
55
+ },
56
+ async capability(key: string, input: Record<string, unknown>) {
57
+ const res = await api.post(capabilityPath, { capability: key, input })
58
+ return unwrap<unknown>(res.data).data
59
+ },
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Map a timeline source `input` (`record.<column>` | `const:<literal>`) onto
65
+ * the record. Unknown forms are rejected (the kernel validates them; a host
66
+ * serving something else is a bug, not something to guess at).
67
+ */
68
+ export function resolveCapabilityInput(
69
+ input: Record<string, string> | undefined,
70
+ record: Record<string, unknown>,
71
+ ): Record<string, unknown> {
72
+ const out: Record<string, unknown> = {}
73
+ for (const [key, ref] of Object.entries(input ?? {})) {
74
+ if (ref.startsWith('record.')) out[key] = record[ref.slice('record.'.length)]
75
+ else if (ref.startsWith('const:')) out[key] = ref.slice('const:'.length)
76
+ else throw new Error(`timeline source input "${key}": unsupported reference "${ref}"`)
77
+ }
78
+ return out
79
+ }
80
+
81
+ /** Read the `items` array (dot path) out of a capability output. */
82
+ export function pickItems(output: unknown, path: string | undefined): Record<string, unknown>[] {
83
+ let cur: unknown = output
84
+ for (const seg of (path ?? '').split('.').filter(Boolean)) {
85
+ cur = cur && typeof cur === 'object' ? (cur as Record<string, unknown>)[seg] : undefined
86
+ }
87
+ return Array.isArray(cur) ? (cur.filter((x) => x && typeof x === 'object') as Record<string, unknown>[]) : []
88
+ }
89
+
90
+ /** Parse a date-ish value (ISO string, epoch ms, Date). */
91
+ export function toDate(v: unknown): Date | null {
92
+ if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v
93
+ if (typeof v === 'number') return new Date(v)
94
+ if (typeof v === 'string' && v) {
95
+ // Date-only values are calendar days: anchor at local noon so a time
96
+ // zone offset never moves them to the previous day.
97
+ const d = /^\d{4}-\d{2}-\d{2}$/.test(v) ? new Date(`${v}T12:00:00`) : new Date(v)
98
+ return Number.isNaN(d.getTime()) ? null : d
99
+ }
100
+ return null
101
+ }
102
+
103
+ /** `YYYY-MM-DD` of a date in local time. */
104
+ export function dayKey(d: Date): string {
105
+ const p = (n: number) => String(n).padStart(2, '0')
106
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
107
+ }
108
+
109
+ /** Sort entries by a date field, newest first (stable for equal dates). */
110
+ export function sortByDate<T extends Record<string, unknown>>(rows: T[], field: string, dir: 'asc' | 'desc' = 'desc'): T[] {
111
+ const k = dir === 'desc' ? -1 : 1
112
+ return rows
113
+ .map((r, i) => ({ r, i, t: toDate(r[field])?.getTime() ?? Number.NEGATIVE_INFINITY }))
114
+ .sort((a, b) => (a.t === b.t ? a.i - b.i : (a.t - b.t) * k))
115
+ .map((x) => x.r)
116
+ }
117
+
118
+ /** Display string of a cell value (renderers show what the server sent). */
119
+ export function displayValue(v: unknown): string {
120
+ if (v === null || v === undefined) return ''
121
+ if (typeof v === 'object') {
122
+ const o = v as Record<string, unknown>
123
+ for (const k of ['label', 'name', 'title', 'display']) if (typeof o[k] === 'string') return o[k] as string
124
+ return JSON.stringify(v)
125
+ }
126
+ return String(v)
127
+ }
@@ -0,0 +1,37 @@
1
+ // Declarative views (view_type map/timeline/calendar/chart/split) and detail
2
+ // panels. This entry is light: the renderers are lazy chunks loaded by type
3
+ // through the registry; nothing here imports recharts or a map library.
4
+ export type {
5
+ DeclarativeViewType,
6
+ DeclarativeViewConfig,
7
+ ViewDataSource,
8
+ ViewRows,
9
+ ViewListParams,
10
+ ChartRequest,
11
+ ViewRendererProps,
12
+ PanelRendererProps,
13
+ ViewRendererComponent,
14
+ PanelRendererComponent,
15
+ ViewRendererLoader,
16
+ PanelRendererLoader,
17
+ } from './types'
18
+ export {
19
+ DECLARATIVE_VIEW_TYPES,
20
+ isDeclarativeViewType,
21
+ registerViewRenderer,
22
+ registerPanelRenderer,
23
+ hasViewRenderer,
24
+ hasPanelRenderer,
25
+ preloadViewRenderer,
26
+ DeclarativeView,
27
+ DetailPanels,
28
+ ViewSkeleton,
29
+ type DeclarativeViewProps,
30
+ type DetailPanelsProps,
31
+ } from './registry'
32
+ export {
33
+ createApiViewDataSource,
34
+ resolveCapabilityInput,
35
+ pickItems,
36
+ type ApiViewDataSourceOptions,
37
+ } from './data-source'