@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,121 @@
|
|
|
1
|
+
// FederatedErrorBoundary — isolates a federated remote (page, panel, widget,
|
|
2
|
+
// register() fiber children) from the host shell. A render error inside the
|
|
3
|
+
// remote paints a contained error card with "Reintentar"; the sidebar, header
|
|
4
|
+
// and every other addon keep working. The host reports the incident through
|
|
5
|
+
// `onError` (ops: reportFrontendIncident) — the boundary itself never logs to
|
|
6
|
+
// the network.
|
|
7
|
+
import { Component, type ErrorInfo, type ReactNode } from 'react'
|
|
8
|
+
import { AlertTriangle, RotateCcw } from 'lucide-react'
|
|
9
|
+
import { Button } from '@asteby/metacore-ui/primitives'
|
|
10
|
+
|
|
11
|
+
export interface FederatedErrorInfo {
|
|
12
|
+
/** Addon key (or remote scope) that failed. */
|
|
13
|
+
addonKey?: string
|
|
14
|
+
/** Exposed module that failed (`./pages/control-tower`). */
|
|
15
|
+
expose?: string
|
|
16
|
+
componentStack?: string | null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface FederatedErrorFallbackProps {
|
|
20
|
+
error: Error
|
|
21
|
+
reset: () => void
|
|
22
|
+
addonKey?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface FederatedErrorBoundaryProps {
|
|
26
|
+
addonKey?: string
|
|
27
|
+
expose?: string
|
|
28
|
+
/** Report the failure (telemetry / incident). Called once per error. */
|
|
29
|
+
onError?: (error: Error, info: FederatedErrorInfo) => void
|
|
30
|
+
/** Custom fallback. Default: contained card with the message and a retry button. */
|
|
31
|
+
fallback?: (props: FederatedErrorFallbackProps) => ReactNode
|
|
32
|
+
/** Changing any of these clears the error (e.g. a new `?v=` remote URL). */
|
|
33
|
+
resetKeys?: readonly unknown[]
|
|
34
|
+
/** Called after the user (or a resetKeys change) clears the error. */
|
|
35
|
+
onReset?: () => void
|
|
36
|
+
/** Copy for the default fallback. */
|
|
37
|
+
strings?: Partial<FederatedErrorStrings>
|
|
38
|
+
children?: ReactNode
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface FederatedErrorStrings {
|
|
42
|
+
title: string
|
|
43
|
+
description: string
|
|
44
|
+
retry: string
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const DEFAULT_STRINGS: FederatedErrorStrings = {
|
|
48
|
+
title: 'Esta sección no se pudo mostrar',
|
|
49
|
+
description: 'El resto de la aplicación sigue funcionando. Puedes reintentar.',
|
|
50
|
+
retry: 'Reintentar',
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface State {
|
|
54
|
+
error: Error | null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function changed(a: readonly unknown[] = [], b: readonly unknown[] = []): boolean {
|
|
58
|
+
return a.length !== b.length || a.some((v, i) => !Object.is(v, b[i]))
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class FederatedErrorBoundary extends Component<FederatedErrorBoundaryProps, State> {
|
|
62
|
+
state: State = { error: null }
|
|
63
|
+
|
|
64
|
+
static getDerivedStateFromError(error: unknown): State {
|
|
65
|
+
return { error: error instanceof Error ? error : new Error(String(error)) }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
componentDidCatch(error: unknown, info: ErrorInfo): void {
|
|
69
|
+
const err = error instanceof Error ? error : new Error(String(error))
|
|
70
|
+
try {
|
|
71
|
+
this.props.onError?.(err, {
|
|
72
|
+
addonKey: this.props.addonKey,
|
|
73
|
+
expose: this.props.expose,
|
|
74
|
+
componentStack: info.componentStack,
|
|
75
|
+
})
|
|
76
|
+
} catch {
|
|
77
|
+
/* a failing reporter must not take the shell down */
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
componentDidUpdate(prev: FederatedErrorBoundaryProps): void {
|
|
82
|
+
if (this.state.error && changed(prev.resetKeys, this.props.resetKeys)) this.reset()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
reset = (): void => {
|
|
86
|
+
this.setState({ error: null })
|
|
87
|
+
this.props.onReset?.()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
render(): ReactNode {
|
|
91
|
+
const { error } = this.state
|
|
92
|
+
if (!error) return this.props.children
|
|
93
|
+
if (this.props.fallback) {
|
|
94
|
+
return this.props.fallback({ error, reset: this.reset, addonKey: this.props.addonKey })
|
|
95
|
+
}
|
|
96
|
+
const s = { ...DEFAULT_STRINGS, ...this.props.strings }
|
|
97
|
+
return (
|
|
98
|
+
<div
|
|
99
|
+
role="alert"
|
|
100
|
+
data-testid="federated-error"
|
|
101
|
+
data-addon={this.props.addonKey}
|
|
102
|
+
className="flex min-h-[12rem] flex-col items-center justify-center gap-3 rounded-lg border border-destructive/30 bg-destructive/5 p-6 text-center"
|
|
103
|
+
>
|
|
104
|
+
<AlertTriangle aria-hidden className="h-6 w-6 text-destructive" />
|
|
105
|
+
<div className="space-y-1">
|
|
106
|
+
<p className="text-sm font-medium text-foreground">{s.title}</p>
|
|
107
|
+
<p className="text-xs text-muted-foreground">{s.description}</p>
|
|
108
|
+
{error.message ? (
|
|
109
|
+
<p className="max-w-md break-words font-mono text-[11px] text-muted-foreground/80">
|
|
110
|
+
{error.message}
|
|
111
|
+
</p>
|
|
112
|
+
) : null}
|
|
113
|
+
</div>
|
|
114
|
+
<Button size="sm" variant="outline" onClick={this.reset}>
|
|
115
|
+
<RotateCcw aria-hidden className="mr-1.5 h-3.5 w-3.5" />
|
|
116
|
+
{s.retry}
|
|
117
|
+
</Button>
|
|
118
|
+
</div>
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
}
|
package/src/host-api.ts
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// createHostApi — the HostApi a host hands to federated pages and panels.
|
|
2
|
+
//
|
|
3
|
+
// Built on the host's own authenticated ApiClient (axios-like). The wrapper is
|
|
4
|
+
// the security boundary between the host transport and remote code:
|
|
5
|
+
// - every method resolves to the response BODY only — never the axios
|
|
6
|
+
// response, whose `config.headers` carries the bearer token;
|
|
7
|
+
// - every failure is re-thrown as a HostApiError with status, server message
|
|
8
|
+
// and server body only — never the axios error, whose `config` and
|
|
9
|
+
// `request` carry the same headers;
|
|
10
|
+
// - the remote can address any API path the operator could (the kernel
|
|
11
|
+
// enforces permissions server-side), but it cannot read or replace the
|
|
12
|
+
// credentials the host attaches.
|
|
13
|
+
import { HostApiError } from '@asteby/metacore-sdk'
|
|
14
|
+
import type {
|
|
15
|
+
HostApi,
|
|
16
|
+
HostApiRequestOptions,
|
|
17
|
+
HostQueryPart,
|
|
18
|
+
} from '@asteby/metacore-sdk'
|
|
19
|
+
import type { ApiClient } from './api-context'
|
|
20
|
+
import { batchGet } from './query-batch'
|
|
21
|
+
|
|
22
|
+
export interface CreateHostApiOptions {
|
|
23
|
+
/**
|
|
24
|
+
* Endpoint the host serves capability queries on (`POST`, body
|
|
25
|
+
* `{ capability, input }`, response = the contract's output). The host runs
|
|
26
|
+
* the query with the viewer's permissions. Default `/capabilities/query`.
|
|
27
|
+
*/
|
|
28
|
+
capabilityPath?: string
|
|
29
|
+
/**
|
|
30
|
+
* Group `get()` reads into `POST /q` like runtime-react's own reads.
|
|
31
|
+
* Default `false`: remote reads go straight to their GET; `q()` always
|
|
32
|
+
* batches.
|
|
33
|
+
*/
|
|
34
|
+
batchGets?: boolean
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type AxiosLikeError = {
|
|
38
|
+
message?: string
|
|
39
|
+
response?: { status?: number; data?: unknown }
|
|
40
|
+
status?: number
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function errorMessage(data: unknown, fallback: string): string {
|
|
44
|
+
if (data && typeof data === 'object') {
|
|
45
|
+
const d = data as Record<string, unknown>
|
|
46
|
+
for (const k of ['message', 'error', 'detail']) {
|
|
47
|
+
if (typeof d[k] === 'string' && d[k]) return d[k] as string
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return fallback
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Strip transport details from any error before it reaches remote code. */
|
|
54
|
+
export function toHostApiError(e: unknown): HostApiError {
|
|
55
|
+
if (e instanceof HostApiError) return e
|
|
56
|
+
const err = (e ?? {}) as AxiosLikeError
|
|
57
|
+
const status = err.response?.status ?? err.status ?? 0
|
|
58
|
+
const data = err.response?.data
|
|
59
|
+
const message = errorMessage(data, status ? `Request failed with status ${status}` : 'Network error')
|
|
60
|
+
const code =
|
|
61
|
+
data && typeof data === 'object' && typeof (data as { code?: unknown }).code === 'string'
|
|
62
|
+
? ((data as { code: string }).code)
|
|
63
|
+
: undefined
|
|
64
|
+
return new HostApiError(message, status, { code, data: safeData(data) })
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Server bodies are JSON the operator could already see; anything else
|
|
68
|
+
// (functions, DOM nodes, a Request) is dropped.
|
|
69
|
+
function safeData(data: unknown): unknown {
|
|
70
|
+
if (data === null || data === undefined) return undefined
|
|
71
|
+
if (typeof data !== 'object') return data
|
|
72
|
+
try {
|
|
73
|
+
return JSON.parse(JSON.stringify(data))
|
|
74
|
+
} catch {
|
|
75
|
+
return undefined
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function toConfig(opts?: HostApiRequestOptions): Record<string, unknown> | undefined {
|
|
80
|
+
if (!opts) return undefined
|
|
81
|
+
const config: Record<string, unknown> = {}
|
|
82
|
+
if (opts.params) config.params = opts.params
|
|
83
|
+
if (opts.signal) config.signal = opts.signal
|
|
84
|
+
return config
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function bodyOf<T>(p: Promise<{ data: unknown }>): Promise<T> {
|
|
88
|
+
try {
|
|
89
|
+
const res = await p
|
|
90
|
+
return res.data as T
|
|
91
|
+
} catch (e) {
|
|
92
|
+
throw toHostApiError(e)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Build the remote-facing {@link HostApi} over the host's ApiClient. */
|
|
97
|
+
export function createHostApi(client: ApiClient, options: CreateHostApiOptions = {}): HostApi {
|
|
98
|
+
const capabilityPath = options.capabilityPath ?? '/capabilities/query'
|
|
99
|
+
const withConfig = <A extends unknown[]>(args: A, opts?: HostApiRequestOptions) => {
|
|
100
|
+
const config = toConfig(opts)
|
|
101
|
+
return config ? ([...args, config] as unknown[]) : (args as unknown[])
|
|
102
|
+
}
|
|
103
|
+
const patch = (client as ApiClient & {
|
|
104
|
+
patch?: (url: string, body?: unknown, config?: unknown) => Promise<{ data: unknown }>
|
|
105
|
+
}).patch
|
|
106
|
+
return Object.freeze({
|
|
107
|
+
get: <T,>(path: string, opts?: HostApiRequestOptions) => {
|
|
108
|
+
const args = withConfig([path], opts) as [string, { params?: Record<string, unknown> }?]
|
|
109
|
+
return bodyOf<T>(options.batchGets ? batchGet(client, ...args) : client.get(...args))
|
|
110
|
+
},
|
|
111
|
+
post: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) =>
|
|
112
|
+
bodyOf<T>(client.post(...(withConfig([path, body], opts) as [string, unknown, unknown?]))),
|
|
113
|
+
put: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) =>
|
|
114
|
+
bodyOf<T>(client.put(...(withConfig([path, body], opts) as [string, unknown, unknown?]))),
|
|
115
|
+
patch: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) => {
|
|
116
|
+
if (typeof patch !== 'function') {
|
|
117
|
+
return Promise.reject(new HostApiError('PATCH is not supported by this host', 0))
|
|
118
|
+
}
|
|
119
|
+
return bodyOf<T>(patch.call(client, ...(withConfig([path, body], opts) as [string, unknown, unknown?])))
|
|
120
|
+
},
|
|
121
|
+
delete: <T,>(path: string, opts?: HostApiRequestOptions) =>
|
|
122
|
+
bodyOf<T>(client.delete(...(withConfig([path], opts) as [string, unknown?]))),
|
|
123
|
+
q: async <T,>(path: string, opts?: Pick<HostApiRequestOptions, 'params'>): Promise<HostQueryPart<T>> => {
|
|
124
|
+
try {
|
|
125
|
+
const url = path.startsWith('/') ? path : `/${path}`
|
|
126
|
+
const res = await (opts?.params
|
|
127
|
+
? batchGet(client, url, { params: opts.params as Record<string, unknown> })
|
|
128
|
+
: batchGet(client, url))
|
|
129
|
+
const body = res.data as { success?: boolean; data?: T; meta?: unknown; message?: string }
|
|
130
|
+
return {
|
|
131
|
+
success: body?.success !== false,
|
|
132
|
+
data: body?.data as T,
|
|
133
|
+
meta: body?.meta,
|
|
134
|
+
message: body?.message,
|
|
135
|
+
}
|
|
136
|
+
} catch (e) {
|
|
137
|
+
throw toHostApiError(e)
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
capability: <T,>(key: string, input: Record<string, unknown>) =>
|
|
141
|
+
bodyOf<T>(client.post(capabilityPath, { capability: key, input })),
|
|
142
|
+
}) as HostApi
|
|
143
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -129,6 +129,7 @@ export {
|
|
|
129
129
|
export {
|
|
130
130
|
DynamicView,
|
|
131
131
|
resolveViewRenderer,
|
|
132
|
+
resolveViewKind,
|
|
132
133
|
readViewFromSearch,
|
|
133
134
|
resolveActiveView,
|
|
134
135
|
type DynamicViewProps,
|
|
@@ -234,6 +235,43 @@ export {
|
|
|
234
235
|
} from './cfdi-stamp-panel'
|
|
235
236
|
export { useRecordMutationTick } from './use-record-mutation-tick'
|
|
236
237
|
export * from './addon-loader'
|
|
238
|
+
// Federated pages (frontend.pages[]): host-side loader + remote-facing hooks.
|
|
239
|
+
export {
|
|
240
|
+
AddonPageLoader,
|
|
241
|
+
AddonPageSkeleton,
|
|
242
|
+
type AddonPageLoaderProps,
|
|
243
|
+
} from './addon-page-loader'
|
|
244
|
+
export {
|
|
245
|
+
AddonPageHost,
|
|
246
|
+
createPageChromeStore,
|
|
247
|
+
usePageChromeState,
|
|
248
|
+
useHostContext,
|
|
249
|
+
useHostApi,
|
|
250
|
+
useAddonNavigate,
|
|
251
|
+
useAddonLocation,
|
|
252
|
+
useAddonSearchParams,
|
|
253
|
+
useBreadcrumbs,
|
|
254
|
+
usePageChrome,
|
|
255
|
+
useIsInAddonPage,
|
|
256
|
+
resolveAddonPath,
|
|
257
|
+
addonSubpath,
|
|
258
|
+
type AddonPageHostProps,
|
|
259
|
+
type AddonPageHostValue,
|
|
260
|
+
type AddonPageLocation,
|
|
261
|
+
type AddonNavigateOptions,
|
|
262
|
+
type PageChromeState,
|
|
263
|
+
type PageChromeStore,
|
|
264
|
+
} from './addon-page-host'
|
|
265
|
+
export { createHostApi, toHostApiError, type CreateHostApiOptions } from './host-api'
|
|
266
|
+
export {
|
|
267
|
+
FederatedErrorBoundary,
|
|
268
|
+
type FederatedErrorBoundaryProps,
|
|
269
|
+
type FederatedErrorFallbackProps,
|
|
270
|
+
type FederatedErrorInfo,
|
|
271
|
+
type FederatedErrorStrings,
|
|
272
|
+
} from './federated-error-boundary'
|
|
273
|
+
// Declarative views & detail panels: registry + lazy renderers by type.
|
|
274
|
+
export * from './views'
|
|
237
275
|
export {
|
|
238
276
|
PURGE_ADDON_MESSAGE,
|
|
239
277
|
isAddonFrontendCacheUrl,
|
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
|
+
}
|