@asteby/metacore-runtime-react 52.1.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 +18 -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 +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- 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/package.json +16 -4
- 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 +18 -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 +38 -0
- 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
|
@@ -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'
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// `view_type: map` and `kind: map` detail panels — CONTRACT + ACCESSIBLE
|
|
2
|
+
// FALLBACK. The interactive renderer (MapLibre, clustering, layers, dark
|
|
3
|
+
// style) belongs to `@asteby/metacore-maps`, which registers itself with
|
|
4
|
+
// `registerViewRenderer('map', …)` / `registerPanelRenderer('map', …)`. Until a
|
|
5
|
+
// host does, this chunk renders what every map must offer anyway: the
|
|
6
|
+
// equivalent keyboard-navigable list of features, each with an "open in map"
|
|
7
|
+
// link. The pure helpers below (features, route) are the shared contract the
|
|
8
|
+
// maps package builds on, so both renderers read the manifest identically.
|
|
9
|
+
import * as React from 'react'
|
|
10
|
+
import { useTranslation } from 'react-i18next'
|
|
11
|
+
import { MapPin } from 'lucide-react'
|
|
12
|
+
import type { MapPoint, MapView } from '@asteby/metacore-sdk'
|
|
13
|
+
import { buildRelationFilterParams } from '../dynamic-relation-helpers'
|
|
14
|
+
import type { PanelRendererProps, ViewRendererProps } from './types'
|
|
15
|
+
import { displayValue } from './data-source'
|
|
16
|
+
import { ViewSkeleton } from './skeleton'
|
|
17
|
+
|
|
18
|
+
const MAX_FEATURES = 500
|
|
19
|
+
|
|
20
|
+
export interface MapFeature {
|
|
21
|
+
key: string
|
|
22
|
+
lat: number
|
|
23
|
+
lng: number
|
|
24
|
+
/** `color_by` value (option key); the renderer maps it to a token. */
|
|
25
|
+
color?: string
|
|
26
|
+
/** Popup fields in `popup[]` order. */
|
|
27
|
+
popup: Array<{ field: string; value: string }>
|
|
28
|
+
row: Record<string, unknown>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function num(v: unknown): number | null {
|
|
32
|
+
const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN
|
|
33
|
+
return Number.isFinite(n) ? n : null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Coordinates of a row: `point {lat,lng}` columns or a GeoJSON Point column. */
|
|
37
|
+
export function rowCoordinates(
|
|
38
|
+
row: Record<string, unknown>,
|
|
39
|
+
point: MapPoint | undefined,
|
|
40
|
+
geometry: string | undefined,
|
|
41
|
+
): { lat: number; lng: number } | null {
|
|
42
|
+
if (point) {
|
|
43
|
+
const lat = num(row[point.lat])
|
|
44
|
+
const lng = num(row[point.lng])
|
|
45
|
+
if (lat === null || lng === null || Math.abs(lat) > 90 || Math.abs(lng) > 180) return null
|
|
46
|
+
return { lat, lng }
|
|
47
|
+
}
|
|
48
|
+
if (geometry) {
|
|
49
|
+
let g = row[geometry] as unknown
|
|
50
|
+
if (typeof g === 'string') {
|
|
51
|
+
try {
|
|
52
|
+
g = JSON.parse(g)
|
|
53
|
+
} catch {
|
|
54
|
+
return null
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const geo = g as { type?: string; coordinates?: unknown[] } | null
|
|
58
|
+
if (geo?.type === 'Point' && Array.isArray(geo.coordinates)) {
|
|
59
|
+
const lng = num(geo.coordinates[0])
|
|
60
|
+
const lat = num(geo.coordinates[1])
|
|
61
|
+
if (lat !== null && lng !== null) return { lat, lng }
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return null
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Pure: rows → map features (rows without valid coordinates are skipped). */
|
|
68
|
+
export function toMapFeatures(rows: Record<string, unknown>[], view: MapView): MapFeature[] {
|
|
69
|
+
const out: MapFeature[] = []
|
|
70
|
+
rows.forEach((row, i) => {
|
|
71
|
+
const c = rowCoordinates(row, view.point, view.geometry)
|
|
72
|
+
if (!c) return
|
|
73
|
+
out.push({
|
|
74
|
+
key: String(row.id ?? i),
|
|
75
|
+
...c,
|
|
76
|
+
color: view.color_by ? displayValue(row[view.color_by]) || undefined : undefined,
|
|
77
|
+
popup: (view.popup ?? []).map((field) => ({ field, value: displayValue(row[field]) })),
|
|
78
|
+
row,
|
|
79
|
+
})
|
|
80
|
+
})
|
|
81
|
+
return out
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Pure: ordered route points of a record's children (`route.order_by` ascending). */
|
|
85
|
+
export function toRoutePoints(
|
|
86
|
+
children: Record<string, unknown>[],
|
|
87
|
+
route: NonNullable<MapView['route']>,
|
|
88
|
+
): Array<{ lat: number; lng: number }> {
|
|
89
|
+
return [...children]
|
|
90
|
+
.sort((a, b) => String(a[route.order_by] ?? '').localeCompare(String(b[route.order_by] ?? '')))
|
|
91
|
+
.map((r) => rowCoordinates(r, route.point, undefined))
|
|
92
|
+
.filter((p): p is { lat: number; lng: number } => p !== null)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** "Open in map" link (OpenStreetMap; no key, no tracking script). */
|
|
96
|
+
export function openInMapHref(lat: number, lng: number): string {
|
|
97
|
+
return `https://www.openstreetmap.org/?mlat=${lat}&mlon=${lng}#map=16/${lat}/${lng}`
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function MapFeatureList({
|
|
101
|
+
features,
|
|
102
|
+
onOpen,
|
|
103
|
+
}: {
|
|
104
|
+
features: MapFeature[]
|
|
105
|
+
onOpen?: (row: Record<string, unknown>) => void
|
|
106
|
+
}) {
|
|
107
|
+
const { t } = useTranslation()
|
|
108
|
+
if (features.length === 0) {
|
|
109
|
+
return (
|
|
110
|
+
<p className="py-8 text-center text-sm text-muted-foreground" data-testid="map-empty">
|
|
111
|
+
{t('metacore.views.map_empty', 'No hay ubicaciones para mostrar.')}
|
|
112
|
+
</p>
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
return (
|
|
116
|
+
<ul className="divide-y rounded-lg border" data-testid="map-feature-list">
|
|
117
|
+
{features.map((f) => {
|
|
118
|
+
const label = f.popup[0]?.value || f.key
|
|
119
|
+
return (
|
|
120
|
+
<li key={f.key} className="flex items-start gap-3 p-3">
|
|
121
|
+
<MapPin aria-hidden className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
|
|
122
|
+
<div className="min-w-0 flex-1">
|
|
123
|
+
{onOpen ? (
|
|
124
|
+
<button
|
|
125
|
+
type="button"
|
|
126
|
+
className="truncate text-left text-sm font-medium text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
|
127
|
+
onClick={() => onOpen(f.row)}
|
|
128
|
+
>
|
|
129
|
+
{label}
|
|
130
|
+
</button>
|
|
131
|
+
) : (
|
|
132
|
+
<span className="truncate text-sm font-medium text-foreground">{label}</span>
|
|
133
|
+
)}
|
|
134
|
+
{f.popup.length > 1 || f.color ? (
|
|
135
|
+
<p className="truncate text-xs text-muted-foreground">
|
|
136
|
+
{[f.color, ...f.popup.slice(1).map((p) => p.value)].filter(Boolean).join(' · ')}
|
|
137
|
+
</p>
|
|
138
|
+
) : null}
|
|
139
|
+
</div>
|
|
140
|
+
<a
|
|
141
|
+
href={openInMapHref(f.lat, f.lng)}
|
|
142
|
+
target="_blank"
|
|
143
|
+
rel="noopener noreferrer"
|
|
144
|
+
className="shrink-0 text-xs text-primary underline-offset-2 hover:underline"
|
|
145
|
+
aria-label={t('metacore.views.open_in_map_of', 'Abrir en mapa: {{label}}', { label })}
|
|
146
|
+
>
|
|
147
|
+
{t('metacore.views.open_in_map', 'Abrir en mapa')}
|
|
148
|
+
</a>
|
|
149
|
+
</li>
|
|
150
|
+
)
|
|
151
|
+
})}
|
|
152
|
+
</ul>
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** `view_type: map` fallback renderer: the accessible list of features. */
|
|
157
|
+
export default function MapViewFallback(props: ViewRendererProps<'map'>) {
|
|
158
|
+
const { model, view, data, onOpenRecord, className } = props
|
|
159
|
+
const { t } = useTranslation()
|
|
160
|
+
const [rows, setRows] = React.useState<Record<string, unknown>[] | null>(null)
|
|
161
|
+
const [error, setError] = React.useState(false)
|
|
162
|
+
React.useEffect(() => {
|
|
163
|
+
let cancelled = false
|
|
164
|
+
data
|
|
165
|
+
.list(model, { per_page: MAX_FEATURES })
|
|
166
|
+
.then((res) => !cancelled && setRows(res.rows))
|
|
167
|
+
.catch(() => !cancelled && setError(true))
|
|
168
|
+
return () => {
|
|
169
|
+
cancelled = true
|
|
170
|
+
}
|
|
171
|
+
}, [data, model])
|
|
172
|
+
if (error) {
|
|
173
|
+
return (
|
|
174
|
+
<p role="alert" className="text-sm text-destructive">
|
|
175
|
+
{t('metacore.views.error', 'No se pudo cargar la información.')}
|
|
176
|
+
</p>
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
if (!rows) return <ViewSkeleton />
|
|
180
|
+
return (
|
|
181
|
+
<div className={className} data-testid="map-view-fallback">
|
|
182
|
+
<MapFeatureList features={toMapFeatures(rows, view)} onOpen={onOpenRecord} />
|
|
183
|
+
</div>
|
|
184
|
+
)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** `kind: map` panel fallback: the record's point and its route stops. */
|
|
188
|
+
export function MapPanel({ panel, record, metadata, data }: PanelRendererProps) {
|
|
189
|
+
const view = panel.map
|
|
190
|
+
const route = view?.route
|
|
191
|
+
const rel = route ? metadata?.relations?.find((r) => r.name === route.relation) : undefined
|
|
192
|
+
const [stops, setStops] = React.useState<Array<{ lat: number; lng: number }>>([])
|
|
193
|
+
const recordId = record.id
|
|
194
|
+
React.useEffect(() => {
|
|
195
|
+
if (!route || !rel || recordId === undefined || recordId === null) return
|
|
196
|
+
let cancelled = false
|
|
197
|
+
data
|
|
198
|
+
.list(rel.through, {
|
|
199
|
+
...buildRelationFilterParams(rel.foreign_key, String(recordId), rel.scope),
|
|
200
|
+
per_page: MAX_FEATURES,
|
|
201
|
+
sortBy: route.order_by,
|
|
202
|
+
order: 'asc',
|
|
203
|
+
})
|
|
204
|
+
.then((res) => !cancelled && setStops(toRoutePoints(res.rows, route)))
|
|
205
|
+
.catch(() => undefined)
|
|
206
|
+
return () => {
|
|
207
|
+
cancelled = true
|
|
208
|
+
}
|
|
209
|
+
}, [data, route, rel, recordId])
|
|
210
|
+
if (!view) return null
|
|
211
|
+
const own = toMapFeatures([record], { ...view, popup: view.popup ?? [] })
|
|
212
|
+
const features: MapFeature[] = [
|
|
213
|
+
...stops.map((s, i) => ({ key: `stop-${i}`, ...s, popup: [{ field: '#', value: `#${i + 1}` }], row: {} })),
|
|
214
|
+
...own,
|
|
215
|
+
]
|
|
216
|
+
return <MapFeatureList features={features} />
|
|
217
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// `kind: relation` and `kind: stats` detail panels. Lazy chunk. Both only
|
|
2
|
+
// display server values: a relation panel lists the record's children (first
|
|
3
|
+
// `limit` rows), a stats panel formats a few of the record's own fields.
|
|
4
|
+
import * as React from 'react'
|
|
5
|
+
import { useTranslation } from 'react-i18next'
|
|
6
|
+
import { buildRelationFilterParams } from '../dynamic-relation-helpers'
|
|
7
|
+
import type { PanelRendererProps } from './types'
|
|
8
|
+
import { displayValue, toDate } from './data-source'
|
|
9
|
+
import { ViewSkeleton } from './skeleton'
|
|
10
|
+
|
|
11
|
+
export type StatFormat =
|
|
12
|
+
| 'number'
|
|
13
|
+
| 'currency'
|
|
14
|
+
| 'percent'
|
|
15
|
+
| 'compact'
|
|
16
|
+
| 'date'
|
|
17
|
+
| 'datetime'
|
|
18
|
+
| 'relative_date'
|
|
19
|
+
|
|
20
|
+
/** Pure: format one stat value for display. `now` is injectable for tests. */
|
|
21
|
+
export function formatStat(
|
|
22
|
+
value: unknown,
|
|
23
|
+
format: string | undefined,
|
|
24
|
+
opts: { locale?: string; currency?: string; timeZone?: string; now?: Date } = {},
|
|
25
|
+
): string {
|
|
26
|
+
if (value === null || value === undefined || value === '') return '—'
|
|
27
|
+
const { locale, currency, timeZone } = opts
|
|
28
|
+
const num = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN
|
|
29
|
+
try {
|
|
30
|
+
switch (format as StatFormat | undefined) {
|
|
31
|
+
case 'currency':
|
|
32
|
+
if (Number.isNaN(num)) break
|
|
33
|
+
return new Intl.NumberFormat(locale, { style: 'currency', currency: currency || 'MXN' }).format(num)
|
|
34
|
+
case 'percent':
|
|
35
|
+
if (Number.isNaN(num)) break
|
|
36
|
+
return new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 }).format(num)
|
|
37
|
+
case 'compact':
|
|
38
|
+
if (Number.isNaN(num)) break
|
|
39
|
+
return new Intl.NumberFormat(locale, { notation: 'compact' }).format(num)
|
|
40
|
+
case 'number':
|
|
41
|
+
if (Number.isNaN(num)) break
|
|
42
|
+
return new Intl.NumberFormat(locale).format(num)
|
|
43
|
+
case 'date':
|
|
44
|
+
case 'datetime': {
|
|
45
|
+
const d = toDate(value)
|
|
46
|
+
if (!d) break
|
|
47
|
+
return new Intl.DateTimeFormat(locale, {
|
|
48
|
+
dateStyle: 'medium',
|
|
49
|
+
...(format === 'datetime' ? { timeStyle: 'short' } : {}),
|
|
50
|
+
timeZone,
|
|
51
|
+
}).format(d)
|
|
52
|
+
}
|
|
53
|
+
case 'relative_date': {
|
|
54
|
+
const d = toDate(value)
|
|
55
|
+
if (!d) break
|
|
56
|
+
const now = opts.now ?? new Date()
|
|
57
|
+
const diffMs = d.getTime() - now.getTime()
|
|
58
|
+
const abs = Math.abs(diffMs)
|
|
59
|
+
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
|
|
60
|
+
if (abs < 3_600_000) return rtf.format(Math.round(diffMs / 60_000), 'minute')
|
|
61
|
+
if (abs < 86_400_000) return rtf.format(Math.round(diffMs / 3_600_000), 'hour')
|
|
62
|
+
return rtf.format(Math.round(diffMs / 86_400_000), 'day')
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
} catch {
|
|
66
|
+
/* invalid locale/currency: fall through to the raw value */
|
|
67
|
+
}
|
|
68
|
+
return displayValue(value)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function StatsPanelView({ panel, record, metadata, locale, currency, timeZone }: PanelRendererProps) {
|
|
72
|
+
const { t } = useTranslation()
|
|
73
|
+
const items = panel.stats?.items ?? []
|
|
74
|
+
const labelOf = (field: string, label?: string) =>
|
|
75
|
+
label ? t(label) : metadata?.columns?.find((c) => c.key === field)?.label ?? field
|
|
76
|
+
return (
|
|
77
|
+
<dl className="grid grid-cols-2 gap-3 sm:grid-cols-4" data-testid="stats-panel">
|
|
78
|
+
{items.map((it) => (
|
|
79
|
+
<div key={it.field} className="rounded-md bg-muted/40 p-3">
|
|
80
|
+
<dt className="text-xs text-muted-foreground">{labelOf(it.field, it.label)}</dt>
|
|
81
|
+
<dd className="mt-1 text-lg font-semibold tabular-nums text-foreground">
|
|
82
|
+
{formatStat(record[it.field], it.format, { locale, currency, timeZone })}
|
|
83
|
+
</dd>
|
|
84
|
+
</div>
|
|
85
|
+
))}
|
|
86
|
+
</dl>
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function RelationPanelView({ panel, record, metadata, data, onOpenRecord }: PanelRendererProps) {
|
|
91
|
+
const { t } = useTranslation()
|
|
92
|
+
const cfg = panel.relation
|
|
93
|
+
const rel = metadata?.relations?.find((r) => r.name === cfg?.name)
|
|
94
|
+
const limit = Math.min(Math.max(cfg?.limit ?? 10, 1), 50)
|
|
95
|
+
const [rows, setRows] = React.useState<Record<string, unknown>[] | null>(null)
|
|
96
|
+
const [total, setTotal] = React.useState<number | undefined>()
|
|
97
|
+
const [error, setError] = React.useState(false)
|
|
98
|
+
const recordId = record.id
|
|
99
|
+
|
|
100
|
+
React.useEffect(() => {
|
|
101
|
+
if (!rel || rel.kind !== 'one_to_many' || recordId === undefined || recordId === null) return
|
|
102
|
+
let cancelled = false
|
|
103
|
+
setRows(null)
|
|
104
|
+
setError(false)
|
|
105
|
+
data
|
|
106
|
+
.list(rel.through, {
|
|
107
|
+
...buildRelationFilterParams(rel.foreign_key, String(recordId), rel.scope),
|
|
108
|
+
per_page: limit,
|
|
109
|
+
})
|
|
110
|
+
.then(
|
|
111
|
+
(res) => {
|
|
112
|
+
if (cancelled) return
|
|
113
|
+
setRows(res.rows)
|
|
114
|
+
setTotal(res.total)
|
|
115
|
+
},
|
|
116
|
+
() => !cancelled && setError(true),
|
|
117
|
+
)
|
|
118
|
+
return () => {
|
|
119
|
+
cancelled = true
|
|
120
|
+
}
|
|
121
|
+
}, [data, rel, recordId, limit])
|
|
122
|
+
|
|
123
|
+
if (!cfg) return null
|
|
124
|
+
if (!rel || rel.kind !== 'one_to_many') {
|
|
125
|
+
return <p className="text-xs text-muted-foreground">{cfg.name}</p>
|
|
126
|
+
}
|
|
127
|
+
if (error) {
|
|
128
|
+
return (
|
|
129
|
+
<p role="alert" className="text-sm text-destructive">
|
|
130
|
+
{t('metacore.views.error', 'No se pudo cargar la información.')}
|
|
131
|
+
</p>
|
|
132
|
+
)
|
|
133
|
+
}
|
|
134
|
+
if (!rows) return <ViewSkeleton height={160} />
|
|
135
|
+
if (rows.length === 0) {
|
|
136
|
+
return <p className="py-4 text-sm text-muted-foreground">{t('metacore.views.empty', 'Sin datos todavía.')}</p>
|
|
137
|
+
}
|
|
138
|
+
const columns =
|
|
139
|
+
cfg.columns && cfg.columns.length > 0
|
|
140
|
+
? cfg.columns
|
|
141
|
+
: Object.keys(rows[0]).filter((k) => k !== 'id' && k !== rel.foreign_key && k !== 'organization_id').slice(0, 4)
|
|
142
|
+
return (
|
|
143
|
+
<div className="overflow-x-auto" data-testid="relation-panel">
|
|
144
|
+
<table className="w-full text-sm">
|
|
145
|
+
<thead>
|
|
146
|
+
<tr className="border-b text-left text-xs text-muted-foreground">
|
|
147
|
+
{columns.map((c) => (
|
|
148
|
+
<th key={c} scope="col" className="px-2 py-1.5 font-medium">
|
|
149
|
+
{c}
|
|
150
|
+
</th>
|
|
151
|
+
))}
|
|
152
|
+
</tr>
|
|
153
|
+
</thead>
|
|
154
|
+
<tbody>
|
|
155
|
+
{rows.map((row, i) => (
|
|
156
|
+
<tr
|
|
157
|
+
key={String(row.id ?? i)}
|
|
158
|
+
className={['border-b last:border-0', onOpenRecord ? 'cursor-pointer hover:bg-muted/40' : ''].join(' ')}
|
|
159
|
+
onClick={onOpenRecord ? () => onOpenRecord(rel.through, row) : undefined}
|
|
160
|
+
>
|
|
161
|
+
{columns.map((c) => (
|
|
162
|
+
<td key={c} className="px-2 py-1.5">
|
|
163
|
+
{displayValue(row[c])}
|
|
164
|
+
</td>
|
|
165
|
+
))}
|
|
166
|
+
</tr>
|
|
167
|
+
))}
|
|
168
|
+
</tbody>
|
|
169
|
+
</table>
|
|
170
|
+
{total !== undefined && total > rows.length ? (
|
|
171
|
+
<p className="mt-2 text-xs text-muted-foreground">
|
|
172
|
+
{t('metacore.views.showing_of', '{{shown}} de {{total}}', { shown: rows.length, total })}
|
|
173
|
+
</p>
|
|
174
|
+
) : null}
|
|
175
|
+
</div>
|
|
176
|
+
)
|
|
177
|
+
}
|