@asteby/metacore-runtime-react 52.0.0 → 53.0.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.
- package/CHANGELOG.md +26 -0
- package/dist/addon-loader.d.ts +22 -1
- package/dist/addon-loader.d.ts.map +1 -1
- package/dist/addon-loader.js +23 -5
- package/dist/addon-page-host.d.ts +80 -0
- package/dist/addon-page-host.d.ts.map +1 -0
- package/dist/addon-page-host.js +216 -0
- package/dist/addon-page-loader.d.ts +40 -0
- package/dist/addon-page-loader.d.ts.map +1 -0
- package/dist/addon-page-loader.js +87 -0
- package/dist/dynamic-view.d.ts +20 -1
- package/dist/dynamic-view.d.ts.map +1 -1
- package/dist/dynamic-view.js +26 -3
- package/dist/federated-error-boundary.d.ts +46 -0
- package/dist/federated-error-boundary.d.ts.map +1 -0
- package/dist/federated-error-boundary.js +55 -0
- package/dist/host-api.d.ts +22 -0
- package/dist/host-api.d.ts.map +1 -0
- package/dist/host-api.js +113 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -2
- package/dist/testing.d.ts +42 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +53 -0
- package/dist/types.d.ts +13 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/views/calendar-view.d.ts +23 -0
- package/dist/views/calendar-view.d.ts.map +1 -0
- package/dist/views/calendar-view.js +138 -0
- package/dist/views/chart-view.d.ts +14 -0
- package/dist/views/chart-view.d.ts.map +1 -0
- package/dist/views/chart-view.js +77 -0
- package/dist/views/data-source.d.ts +30 -0
- package/dist/views/data-source.d.ts.map +1 -0
- package/dist/views/data-source.js +103 -0
- package/dist/views/index.d.ts +4 -0
- package/dist/views/index.d.ts.map +1 -0
- package/dist/views/index.js +2 -0
- package/dist/views/map-view.d.ts +39 -0
- package/dist/views/map-view.d.ts.map +1 -0
- package/dist/views/map-view.js +143 -0
- package/dist/views/panels.d.ts +13 -0
- package/dist/views/panels.d.ts.map +1 -0
- package/dist/views/panels.js +119 -0
- package/dist/views/registry.d.ts +46 -0
- package/dist/views/registry.d.ts.map +1 -0
- package/dist/views/registry.js +139 -0
- package/dist/views/skeleton.d.ts +5 -0
- package/dist/views/skeleton.d.ts.map +1 -0
- package/dist/views/skeleton.js +6 -0
- package/dist/views/split-view.d.ts +6 -0
- package/dist/views/split-view.d.ts.map +1 -0
- package/dist/views/split-view.js +52 -0
- package/dist/views/timeline-view.d.ts +25 -0
- package/dist/views/timeline-view.d.ts.map +1 -0
- package/dist/views/timeline-view.js +130 -0
- package/dist/views/types.d.ts +87 -0
- package/dist/views/types.d.ts.map +1 -0
- package/dist/views/types.js +1 -0
- package/dist/widgets/charts.d.ts +9 -0
- package/dist/widgets/charts.d.ts.map +1 -0
- package/dist/widgets/charts.js +55 -0
- package/dist/widgets/lazy-charts.d.ts +10 -0
- package/dist/widgets/lazy-charts.d.ts.map +1 -0
- package/dist/widgets/lazy-charts.js +30 -0
- package/dist/widgets/renderers.d.ts +5 -5
- package/dist/widgets/renderers.d.ts.map +1 -1
- package/dist/widgets/renderers.js +3 -53
- package/dist/widgets/widget-renderer.d.ts.map +1 -1
- package/dist/widgets/widget-renderer.js +2 -1
- package/package.json +21 -5
- package/src/__tests__/addon-page-host.test.tsx +122 -0
- package/src/__tests__/addon-page-loader.test.tsx +201 -0
- package/src/__tests__/declarative-views.test.tsx +351 -0
- package/src/__tests__/host-api.test.ts +87 -0
- package/src/__tests__/index-static-graph.test.ts +83 -0
- package/src/addon-loader.tsx +51 -8
- package/src/addon-page-host.tsx +319 -0
- package/src/addon-page-loader.tsx +203 -0
- package/src/dynamic-view.tsx +61 -3
- package/src/federated-error-boundary.tsx +121 -0
- package/src/host-api.ts +143 -0
- package/src/index.ts +47 -4
- package/src/testing.tsx +108 -0
- package/src/types.ts +13 -0
- package/src/views/calendar-view.tsx +234 -0
- package/src/views/chart-view.tsx +122 -0
- package/src/views/data-source.ts +127 -0
- package/src/views/index.ts +37 -0
- package/src/views/map-view.tsx +217 -0
- package/src/views/panels.tsx +177 -0
- package/src/views/registry.tsx +202 -0
- package/src/views/skeleton.tsx +13 -0
- package/src/views/split-view.tsx +115 -0
- package/src/views/timeline-view.tsx +229 -0
- package/src/views/types.ts +105 -0
- package/src/widgets/charts.tsx +225 -0
- package/src/widgets/lazy-charts.tsx +51 -0
- package/src/widgets/renderers.tsx +5 -210
- package/src/widgets/widget-renderer.tsx +6 -4
package/src/testing.tsx
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Test helpers for federated pages and panels (`@asteby/metacore-runtime-react/testing`).
|
|
2
|
+
//
|
|
3
|
+
// import { renderWithHost, createMockHostApi } from '@asteby/metacore-runtime-react/testing'
|
|
4
|
+
//
|
|
5
|
+
// const api = createMockHostApi({ get: { '/data/Shipment': { success: true, data: [] } } })
|
|
6
|
+
// const { navigate, chrome } = renderWithHost(<ControlTower {...props} />, {
|
|
7
|
+
// api,
|
|
8
|
+
// basePath: '/a/shipping/control-tower',
|
|
9
|
+
// })
|
|
10
|
+
// expect(chrome.get().title).toBe('Torre de envíos')
|
|
11
|
+
//
|
|
12
|
+
// Never imported by the package index (it pulls @testing-library/react).
|
|
13
|
+
import type { ReactElement } from 'react'
|
|
14
|
+
import { render, type RenderResult } from '@testing-library/react'
|
|
15
|
+
import type { AddonHostContext, HostApi } from '@asteby/metacore-sdk'
|
|
16
|
+
import { HostApiError } from '@asteby/metacore-sdk'
|
|
17
|
+
import {
|
|
18
|
+
AddonPageHost,
|
|
19
|
+
createPageChromeStore,
|
|
20
|
+
type AddonNavigateOptions,
|
|
21
|
+
type PageChromeStore,
|
|
22
|
+
} from './addon-page-host'
|
|
23
|
+
|
|
24
|
+
type Responder = unknown | ((path: string, body?: unknown) => unknown)
|
|
25
|
+
|
|
26
|
+
export interface MockHostApiRoutes {
|
|
27
|
+
get?: Record<string, Responder>
|
|
28
|
+
post?: Record<string, Responder>
|
|
29
|
+
put?: Record<string, Responder>
|
|
30
|
+
patch?: Record<string, Responder>
|
|
31
|
+
delete?: Record<string, Responder>
|
|
32
|
+
capability?: Record<string, Responder>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface MockHostApi extends HostApi {
|
|
36
|
+
/** Every call, in order: `[method, path, body?]`. */
|
|
37
|
+
calls: Array<[string, string, unknown?]>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* In-memory {@link HostApi}. Unknown routes reject with a 404
|
|
42
|
+
* {@link HostApiError}, like a real host would.
|
|
43
|
+
*/
|
|
44
|
+
export function createMockHostApi(routes: MockHostApiRoutes = {}): MockHostApi {
|
|
45
|
+
const calls: MockHostApi['calls'] = []
|
|
46
|
+
const answer = async (method: keyof MockHostApiRoutes, path: string, body?: unknown) => {
|
|
47
|
+
calls.push([method, path, body])
|
|
48
|
+
const table = routes[method] ?? {}
|
|
49
|
+
const key = path.split('?')[0]
|
|
50
|
+
if (!(key in table)) throw new HostApiError(`No mock for ${method.toUpperCase()} ${key}`, 404)
|
|
51
|
+
const r = table[key]
|
|
52
|
+
return typeof r === 'function' ? (r as (p: string, b?: unknown) => unknown)(path, body) : r
|
|
53
|
+
}
|
|
54
|
+
const api: MockHostApi = {
|
|
55
|
+
calls,
|
|
56
|
+
get: (p) => answer('get', p) as Promise<never>,
|
|
57
|
+
post: (p, b) => answer('post', p, b) as Promise<never>,
|
|
58
|
+
put: (p, b) => answer('put', p, b) as Promise<never>,
|
|
59
|
+
patch: (p, b) => answer('patch', p, b) as Promise<never>,
|
|
60
|
+
delete: (p) => answer('delete', p) as Promise<never>,
|
|
61
|
+
q: async (p) => {
|
|
62
|
+
const body = (await answer('get', p)) as { success?: boolean; data?: unknown; meta?: unknown }
|
|
63
|
+
return { success: body?.success !== false, data: body?.data as never, meta: body?.meta }
|
|
64
|
+
},
|
|
65
|
+
capability: (key, input) => answer('capability', key, input) as Promise<never>,
|
|
66
|
+
}
|
|
67
|
+
return api
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface RenderWithHostOptions {
|
|
71
|
+
host?: AddonHostContext
|
|
72
|
+
api?: HostApi
|
|
73
|
+
basePath?: string
|
|
74
|
+
/** Initial path (absolute) and search of the simulated router. */
|
|
75
|
+
pathname?: string
|
|
76
|
+
search?: string
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface RenderWithHostResult extends RenderResult {
|
|
80
|
+
api: HostApi
|
|
81
|
+
chrome: PageChromeStore
|
|
82
|
+
/** Spy of host navigations: `[to, opts]`. */
|
|
83
|
+
navigate: { calls: Array<[string, AddonNavigateOptions | undefined]> }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Render `ui` inside an `<AddonPageHost>` with a simulated host. */
|
|
87
|
+
export function renderWithHost(ui: ReactElement, opts: RenderWithHostOptions = {}): RenderWithHostResult {
|
|
88
|
+
const basePath = opts.basePath ?? '/a/test/page'
|
|
89
|
+
const api = opts.api ?? createMockHostApi()
|
|
90
|
+
const chrome = createPageChromeStore()
|
|
91
|
+
const navCalls: Array<[string, AddonNavigateOptions | undefined]> = []
|
|
92
|
+
const host: AddonHostContext = opts.host ?? {
|
|
93
|
+
org: { id: 'org_test', name: 'Org de prueba', currency: 'MXN', timezone: 'America/Mexico_City', taxLabel: 'IVA' },
|
|
94
|
+
user: { id: 'user_test', name: 'Operador' },
|
|
95
|
+
locale: 'es-MX',
|
|
96
|
+
installedAddons: [],
|
|
97
|
+
}
|
|
98
|
+
const location = { pathname: opts.pathname ?? basePath, search: opts.search ?? '' }
|
|
99
|
+
const navigate = (to: string, o?: AddonNavigateOptions) => {
|
|
100
|
+
navCalls.push([to, o])
|
|
101
|
+
}
|
|
102
|
+
const result = render(
|
|
103
|
+
<AddonPageHost host={host} api={api} basePath={basePath} location={location} navigate={navigate} chrome={chrome}>
|
|
104
|
+
{ui}
|
|
105
|
+
</AddonPageHost>,
|
|
106
|
+
)
|
|
107
|
+
return Object.assign(result, { api, chrome, navigate: { calls: navCalls } })
|
|
108
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { OptionFilter } from './option-filter'
|
|
2
|
+
import type { ModelDetail, NavView } from '@asteby/metacore-sdk'
|
|
2
3
|
// Shared metadata shape consumed by every host. Some hosts add a `link`
|
|
3
4
|
// action type with a `linkUrl` template — represented here as part of the
|
|
4
5
|
// `type` union so the SDK can render it uniformly.
|
|
@@ -287,6 +288,18 @@ export interface TableMetadata {
|
|
|
287
288
|
* Absent → any move is allowed (the kernel still validates server-side).
|
|
288
289
|
*/
|
|
289
290
|
transitions?: StageTransition[]
|
|
291
|
+
/**
|
|
292
|
+
* Configuration of a declarative `view_type` (map, timeline, calendar,
|
|
293
|
+
* chart, split): the nav entry's `view` block (kernel `NavView`), served on
|
|
294
|
+
* demand with the table metadata, never in the lite manifest. Rendered by
|
|
295
|
+
* `<DeclarativeView>`; absent on hosts that do not serve it.
|
|
296
|
+
*/
|
|
297
|
+
view?: NavView
|
|
298
|
+
/**
|
|
299
|
+
* The model's record detail panels (kernel `ModelDetail`), served with
|
|
300
|
+
* the table metadata. Rendered by `<DetailPanels>` and the split view.
|
|
301
|
+
*/
|
|
302
|
+
detail?: ModelDetail
|
|
290
303
|
}
|
|
291
304
|
|
|
292
305
|
/**
|
|
@@ -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'
|