@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
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// createHostApi is the boundary between the host transport (axios with the
|
|
2
|
+
// bearer token in config.headers) and remote code: bodies only, sanitized errors.
|
|
3
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
4
|
+
import { HostApiError } from '@asteby/metacore-sdk'
|
|
5
|
+
import { createHostApi, toHostApiError } from '../host-api'
|
|
6
|
+
import type { ApiClient } from '../api-context'
|
|
7
|
+
|
|
8
|
+
const TOKEN = 'Bearer secret-jwt'
|
|
9
|
+
|
|
10
|
+
function axiosLike(): ApiClient & { patch: ApiClient['put'] } {
|
|
11
|
+
const respond = (url: string, data: unknown) =>
|
|
12
|
+
Promise.resolve({
|
|
13
|
+
data,
|
|
14
|
+
headers: { 'x-thing': '1' },
|
|
15
|
+
config: { url, headers: { Authorization: TOKEN } },
|
|
16
|
+
})
|
|
17
|
+
return {
|
|
18
|
+
get: vi.fn((url: string) => respond(url, { success: true, data: [{ id: 1 }] })),
|
|
19
|
+
post: vi.fn((url: string, body?: unknown) => respond(url, { echo: body })),
|
|
20
|
+
put: vi.fn((url: string) => respond(url, { ok: true })),
|
|
21
|
+
patch: vi.fn((url: string) => respond(url, { patched: true })),
|
|
22
|
+
delete: vi.fn((url: string) => respond(url, { deleted: true })),
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
describe('createHostApi', () => {
|
|
27
|
+
it('resolves to the body only (no headers, no config with the token)', async () => {
|
|
28
|
+
const api = createHostApi(axiosLike())
|
|
29
|
+
const body = await api.get('/data/Shipment')
|
|
30
|
+
expect(body).toEqual({ success: true, data: [{ id: 1 }] })
|
|
31
|
+
expect(JSON.stringify(body)).not.toContain('secret-jwt')
|
|
32
|
+
expect(await api.patch('/data/Shipment/1', { a: 1 })).toEqual({ patched: true })
|
|
33
|
+
expect(await api.delete('/data/Shipment/1')).toEqual({ deleted: true })
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('forwards params and signal, nothing else', async () => {
|
|
37
|
+
const client = axiosLike()
|
|
38
|
+
const api = createHostApi(client)
|
|
39
|
+
const ctrl = new AbortController()
|
|
40
|
+
await api.get('/data/Shipment', { params: { f_status: 'eq:late' }, signal: ctrl.signal })
|
|
41
|
+
expect(client.get).toHaveBeenCalledWith('/data/Shipment', { params: { f_status: 'eq:late' }, signal: ctrl.signal })
|
|
42
|
+
await api.get('/plain')
|
|
43
|
+
expect(client.get).toHaveBeenLastCalledWith('/plain')
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('posts capability queries to the host endpoint', async () => {
|
|
47
|
+
const client = axiosLike()
|
|
48
|
+
const api = createHostApi(client, { capabilityPath: '/caps' })
|
|
49
|
+
const out = await api.capability('commerce.shipping.track', { tracking_number: 'X1' })
|
|
50
|
+
expect(client.post).toHaveBeenCalledWith('/caps', {
|
|
51
|
+
capability: 'commerce.shipping.track',
|
|
52
|
+
input: { tracking_number: 'X1' },
|
|
53
|
+
})
|
|
54
|
+
expect(out).toEqual({ echo: { capability: 'commerce.shipping.track', input: { tracking_number: 'X1' } } })
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('is frozen: a remote cannot swap methods for the next remote', () => {
|
|
58
|
+
const api = createHostApi(axiosLike())
|
|
59
|
+
expect(Object.isFrozen(api)).toBe(true)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('re-throws transport errors without config/request (no token leak)', async () => {
|
|
63
|
+
const client = axiosLike()
|
|
64
|
+
client.post = vi.fn(() =>
|
|
65
|
+
Promise.reject({
|
|
66
|
+
message: 'Request failed with status code 422',
|
|
67
|
+
config: { headers: { Authorization: TOKEN } },
|
|
68
|
+
request: { _header: `Authorization: ${TOKEN}` },
|
|
69
|
+
response: { status: 422, data: { message: 'Paquetería inválida', code: 'invalid_carrier' } },
|
|
70
|
+
}),
|
|
71
|
+
)
|
|
72
|
+
const api = createHostApi(client)
|
|
73
|
+
const err = await api.post('/data/Shipment', {}).catch((e) => e)
|
|
74
|
+
expect(err).toBeInstanceOf(HostApiError)
|
|
75
|
+
expect(err.status).toBe(422)
|
|
76
|
+
expect(err.code).toBe('invalid_carrier')
|
|
77
|
+
expect(err.message).toBe('Paquetería inválida')
|
|
78
|
+
expect(JSON.stringify({ ...err, message: err.message })).not.toContain('secret-jwt')
|
|
79
|
+
expect('config' in err).toBe(false)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it('maps network errors to status 0', () => {
|
|
83
|
+
const e = toHostApiError(new TypeError('Failed to fetch'))
|
|
84
|
+
expect(e.status).toBe(0)
|
|
85
|
+
expect(e.message).toBe('Network error')
|
|
86
|
+
})
|
|
87
|
+
})
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Guards the host's first paint: the package index must not reach recharts (or
|
|
2
|
+
// any other heavy charting/map library) through STATIC imports. Dynamic
|
|
3
|
+
// `import()` is allowed — that is how ./widgets/lazy-charts defers it.
|
|
4
|
+
import { describe, expect, it } from 'vitest'
|
|
5
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
6
|
+
import { dirname, join, resolve } from 'node:path'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
|
|
9
|
+
const SRC = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
10
|
+
const HEAVY = ['recharts', 'maplibre-gl', 'leaflet', 'echarts', 'd3', '@visx']
|
|
11
|
+
|
|
12
|
+
function resolveLocal(from: string, spec: string): string | null {
|
|
13
|
+
const base = resolve(dirname(from), spec)
|
|
14
|
+
for (const c of [base, `${base}.ts`, `${base}.tsx`, join(base, 'index.ts'), join(base, 'index.tsx')]) {
|
|
15
|
+
if (existsSync(c) && statSync(c).isFile()) return c
|
|
16
|
+
}
|
|
17
|
+
return null
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Static specifiers: `import ... from 'x'`, `import 'x'`, `export ... from 'x'`.
|
|
21
|
+
// `import type` / `export type` are erased and skipped.
|
|
22
|
+
function staticSpecifiers(code: string): string[] {
|
|
23
|
+
const out: string[] = []
|
|
24
|
+
const re = /(?:^|\n)\s*(?:import|export)\s+(type\s+)?(?:[^'";]*?\sfrom\s+)?['"]([^'"]+)['"]/g
|
|
25
|
+
for (const m of code.matchAll(re)) if (!m[1]) out.push(m[2])
|
|
26
|
+
return out
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function staticGraph(entry: string) {
|
|
30
|
+
const seen = new Set<string>()
|
|
31
|
+
const external = new Map<string, string>() // pkg -> first importer
|
|
32
|
+
const walk = (file: string) => {
|
|
33
|
+
if (seen.has(file)) return
|
|
34
|
+
seen.add(file)
|
|
35
|
+
for (const spec of staticSpecifiers(readFileSync(file, 'utf8'))) {
|
|
36
|
+
if (spec.startsWith('.')) {
|
|
37
|
+
const next = resolveLocal(file, spec)
|
|
38
|
+
if (next) walk(next)
|
|
39
|
+
} else if (!external.has(spec)) {
|
|
40
|
+
external.set(spec, file.slice(SRC.length + 1))
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
walk(entry)
|
|
45
|
+
return { seen, external }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
describe('runtime-react index static graph', () => {
|
|
49
|
+
const { seen, external } = staticGraph(join(SRC, 'index.ts'))
|
|
50
|
+
|
|
51
|
+
it('walks a non-trivial graph (guards against a broken walker)', () => {
|
|
52
|
+
expect(seen.size).toBeGreaterThan(50)
|
|
53
|
+
expect(external.has('react')).toBe(true)
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it.each(HEAVY)('does not statically reach %s', (lib) => {
|
|
57
|
+
const hit = [...external].find(([spec]) => spec === lib || spec.startsWith(`${lib}/`))
|
|
58
|
+
expect(hit && `${hit[0]} imported from ${hit[1]}`).toBeUndefined()
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it.each([
|
|
62
|
+
'views/chart-view.tsx',
|
|
63
|
+
'views/timeline-view.tsx',
|
|
64
|
+
'views/calendar-view.tsx',
|
|
65
|
+
'views/split-view.tsx',
|
|
66
|
+
'views/map-view.tsx',
|
|
67
|
+
'views/panels.tsx',
|
|
68
|
+
'testing.tsx',
|
|
69
|
+
])('loads %s lazily (declarative renderers by type, test helpers never)', (file) => {
|
|
70
|
+
expect(seen.has(join(SRC, file))).toBe(false)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('reaches the view registry and the federated page host (light modules)', () => {
|
|
74
|
+
expect(seen.has(join(SRC, 'views/registry.tsx'))).toBe(true)
|
|
75
|
+
expect(seen.has(join(SRC, 'addon-page-loader.tsx'))).toBe(true)
|
|
76
|
+
expect(external.has('@testing-library/react')).toBe(false)
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('keeps the recharts-backed module out of the static graph', () => {
|
|
80
|
+
expect(seen.has(join(SRC, 'widgets/charts.tsx'))).toBe(false)
|
|
81
|
+
expect(seen.has(join(SRC, 'widgets/lazy-charts.tsx'))).toBe(true)
|
|
82
|
+
})
|
|
83
|
+
})
|
package/src/addon-loader.tsx
CHANGED
|
@@ -24,7 +24,9 @@ function getMfRuntime(): Promise<MfRuntime> {
|
|
|
24
24
|
return mfRuntime
|
|
25
25
|
}
|
|
26
26
|
import type { AddonAPI, AddonLayout, Registry } from '@asteby/metacore-sdk'
|
|
27
|
+
import { ensureRemoteIntegrity, RemoteIntegrityError } from '@asteby/metacore-sdk'
|
|
27
28
|
import { useDeclareAddonLayout } from './addon-layout-context'
|
|
29
|
+
import { FederatedErrorBoundary, type FederatedErrorInfo } from './federated-error-boundary'
|
|
28
30
|
import {
|
|
29
31
|
composeDisposables,
|
|
30
32
|
disposableFromRegisterResult,
|
|
@@ -80,6 +82,18 @@ export interface AddonLoaderProps {
|
|
|
80
82
|
* — the loader sets the context value via {@link useDeclareAddonLayout}.
|
|
81
83
|
*/
|
|
82
84
|
layout?: AddonLayout
|
|
85
|
+
/**
|
|
86
|
+
* SRI of `remoteEntry.js` (`manifest.frontend.integrity`). When set, the
|
|
87
|
+
* entry is verified before the MF runtime imports it and a mismatch fails
|
|
88
|
+
* the load permanently (no retry). Unset = previous behaviour.
|
|
89
|
+
*/
|
|
90
|
+
integrity?: string
|
|
91
|
+
/**
|
|
92
|
+
* Render errors thrown by `children` (the addon's UI mounted under this
|
|
93
|
+
* fiber) are contained by a {@link FederatedErrorBoundary}; this reports
|
|
94
|
+
* them (ops: reportFrontendIncident).
|
|
95
|
+
*/
|
|
96
|
+
onRenderError?: (error: Error, info: FederatedErrorInfo) => void
|
|
83
97
|
children?: React.ReactNode
|
|
84
98
|
}
|
|
85
99
|
|
|
@@ -108,6 +122,7 @@ function isRuntimeNotReady(e: unknown): boolean {
|
|
|
108
122
|
|
|
109
123
|
/** Transient network / gateway failures while the host API is restarting. */
|
|
110
124
|
function isTransientRemoteLoadError(e: unknown): boolean {
|
|
125
|
+
if (e instanceof RemoteIntegrityError) return false
|
|
111
126
|
if (isRuntimeNotReady(e)) return true
|
|
112
127
|
const msg = e instanceof Error ? e.message : String(e)
|
|
113
128
|
return (
|
|
@@ -134,11 +149,20 @@ async function withRemoteLoadRetry<T>(op: () => T | Promise<T>): Promise<T> {
|
|
|
134
149
|
}
|
|
135
150
|
}
|
|
136
151
|
|
|
137
|
-
|
|
152
|
+
/**
|
|
153
|
+
* Load one exposed module of a federated remote through the MF runtime:
|
|
154
|
+
* verifies `integrity` (SRI) first, (re)registers the remote when its URL
|
|
155
|
+
* changed, then `loadRemote("<scope>/<expose>")`. Transient failures (host
|
|
156
|
+
* boot race, gateway blips) are retried; an integrity mismatch is not.
|
|
157
|
+
* Shared by {@link AddonLoader} (`./register`) and `AddonPageLoader` (pages).
|
|
158
|
+
*/
|
|
159
|
+
export async function loadFederatedModule<T = unknown>(
|
|
138
160
|
scope: string,
|
|
139
161
|
url: string,
|
|
140
162
|
module: string,
|
|
141
|
-
|
|
163
|
+
integrity?: string,
|
|
164
|
+
): Promise<T | null> {
|
|
165
|
+
if (integrity) await withRemoteLoadRetry(() => ensureRemoteIntegrity(url, integrity))
|
|
142
166
|
// Re-register whenever the `?v=` URL changes so a fiber swap actually
|
|
143
167
|
// fetches the new remoteEntry. `force: true` wipes that remote's module
|
|
144
168
|
// cache — without it, loadRemote would keep serving the previous bundle.
|
|
@@ -151,12 +175,19 @@ async function loadAddon(
|
|
|
151
175
|
markRemoteRegistered(scope, url)
|
|
152
176
|
}
|
|
153
177
|
return withRemoteLoadRetry(() =>
|
|
154
|
-
getMfRuntime().then((mf) =>
|
|
155
|
-
mf.loadRemote<AddonRegisterModule>(remoteId(scope, module)),
|
|
156
|
-
),
|
|
178
|
+
getMfRuntime().then((mf) => mf.loadRemote<T>(remoteId(scope, module))),
|
|
157
179
|
)
|
|
158
180
|
}
|
|
159
181
|
|
|
182
|
+
async function loadAddon(
|
|
183
|
+
scope: string,
|
|
184
|
+
url: string,
|
|
185
|
+
module: string,
|
|
186
|
+
integrity?: string,
|
|
187
|
+
): Promise<AddonRegisterModule | null> {
|
|
188
|
+
return loadFederatedModule<AddonRegisterModule>(scope, url, module, integrity)
|
|
189
|
+
}
|
|
190
|
+
|
|
160
191
|
export function AddonLoader({
|
|
161
192
|
scope,
|
|
162
193
|
url,
|
|
@@ -169,6 +200,8 @@ export function AddonLoader({
|
|
|
169
200
|
onReady,
|
|
170
201
|
onError,
|
|
171
202
|
layout,
|
|
203
|
+
integrity,
|
|
204
|
+
onRenderError,
|
|
172
205
|
children,
|
|
173
206
|
}: AddonLoaderProps) {
|
|
174
207
|
const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading')
|
|
@@ -189,7 +222,7 @@ export function AddonLoader({
|
|
|
189
222
|
try {
|
|
190
223
|
setStatus('loading')
|
|
191
224
|
if (key) await purgeAddonFrontendCache(key)
|
|
192
|
-
const mod = await loadAddon(scope, url, module)
|
|
225
|
+
const mod = await loadAddon(scope, url, module, integrity)
|
|
193
226
|
if (cancelled) return
|
|
194
227
|
const plugin = resolvePluginExports(mod)
|
|
195
228
|
if (typeof plugin.register !== 'function') {
|
|
@@ -225,7 +258,7 @@ export function AddonLoader({
|
|
|
225
258
|
// api identity is expected to be stable per addon; including it would
|
|
226
259
|
// re-register on every parent render. Fiber identity is (scope, url, module).
|
|
227
260
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
228
|
-
}, [scope, url, module, addonKey, unbindKey, hostRegistry])
|
|
261
|
+
}, [scope, url, module, addonKey, unbindKey, hostRegistry, integrity])
|
|
229
262
|
|
|
230
263
|
if (status === 'loading') return <>{fallback}</>
|
|
231
264
|
if (status === 'error') {
|
|
@@ -236,5 +269,15 @@ export function AddonLoader({
|
|
|
236
269
|
if (onError) return null
|
|
237
270
|
return <div className="text-sm text-red-500">Addon load error: {error?.message}</div>
|
|
238
271
|
}
|
|
239
|
-
return
|
|
272
|
+
if (children === undefined || children === null) return null
|
|
273
|
+
return (
|
|
274
|
+
<FederatedErrorBoundary
|
|
275
|
+
addonKey={addonKey || api.manifest?.key || scope}
|
|
276
|
+
expose={module}
|
|
277
|
+
onError={onRenderError}
|
|
278
|
+
resetKeys={[url]}
|
|
279
|
+
>
|
|
280
|
+
{children}
|
|
281
|
+
</FederatedErrorBoundary>
|
|
282
|
+
)
|
|
240
283
|
}
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
// AddonPageHost — what the host mounts around a federated page (embedded or
|
|
2
|
+
// full screen) so the remote can use host services without importing host
|
|
3
|
+
// code and without ever touching credentials.
|
|
4
|
+
//
|
|
5
|
+
// Host side (ops FederatedPageHost, starter-core):
|
|
6
|
+
//
|
|
7
|
+
// const chrome = useMemo(createPageChromeStore, [])
|
|
8
|
+
// <AddonPageHost
|
|
9
|
+
// host={hostContext} // org, user, branch, locale…
|
|
10
|
+
// api={hostApi} // createHostApi(axios)
|
|
11
|
+
// basePath="/a/shipping/control-tower"
|
|
12
|
+
// location={{ pathname, search }} // from the host router
|
|
13
|
+
// navigate={(to, o) => router.navigate({ to, replace: o?.replace })}
|
|
14
|
+
// chrome={chrome} // header reads it
|
|
15
|
+
// >
|
|
16
|
+
// <Page … />
|
|
17
|
+
// </AddonPageHost>
|
|
18
|
+
//
|
|
19
|
+
// // header: const { title, actions, focus, breadcrumbs } = usePageChromeState(chrome)
|
|
20
|
+
//
|
|
21
|
+
// Remote side (inside the page):
|
|
22
|
+
//
|
|
23
|
+
// const api = useHostApi()
|
|
24
|
+
// const { org, user, locale } = useHostContext()
|
|
25
|
+
// const navigate = useAddonNavigate() // relative to basePath
|
|
26
|
+
// const [params, setParams] = useAddonSearchParams()
|
|
27
|
+
// useBreadcrumbs([{ title: t('shipping.nav.group'), url: '/m/Shipment' }])
|
|
28
|
+
// usePageChrome({ title: t('shipping.pages.control_tower'), focus: true })
|
|
29
|
+
import {
|
|
30
|
+
createContext,
|
|
31
|
+
useCallback,
|
|
32
|
+
useContext,
|
|
33
|
+
useEffect,
|
|
34
|
+
useMemo,
|
|
35
|
+
useRef,
|
|
36
|
+
useSyncExternalStore,
|
|
37
|
+
type ReactNode,
|
|
38
|
+
} from 'react'
|
|
39
|
+
import type {
|
|
40
|
+
AddonHostContext,
|
|
41
|
+
Breadcrumb,
|
|
42
|
+
HostApi,
|
|
43
|
+
PageChrome,
|
|
44
|
+
} from '@asteby/metacore-sdk'
|
|
45
|
+
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
// Chrome store: page → host header. A tiny external store so the header (above
|
|
48
|
+
// the page in the tree) re-renders without a provider re-render cascade.
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
export interface PageChromeState extends PageChrome {
|
|
52
|
+
breadcrumbs: Breadcrumb[]
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface PageChromeStore {
|
|
56
|
+
get(): PageChromeState
|
|
57
|
+
subscribe(listener: () => void): () => void
|
|
58
|
+
/** Merge a partial update (page side). */
|
|
59
|
+
set(patch: Partial<PageChromeState>): void
|
|
60
|
+
/** Back to empty (page unmounted). */
|
|
61
|
+
reset(): void
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const EMPTY_CHROME: PageChromeState = Object.freeze({ breadcrumbs: [] }) as PageChromeState
|
|
65
|
+
|
|
66
|
+
export function createPageChromeStore(initial?: Partial<PageChromeState>): PageChromeStore {
|
|
67
|
+
let state: PageChromeState = { ...EMPTY_CHROME, ...initial }
|
|
68
|
+
const listeners = new Set<() => void>()
|
|
69
|
+
const emit = () => listeners.forEach((l) => l())
|
|
70
|
+
return {
|
|
71
|
+
get: () => state,
|
|
72
|
+
subscribe(listener) {
|
|
73
|
+
listeners.add(listener)
|
|
74
|
+
return () => listeners.delete(listener)
|
|
75
|
+
},
|
|
76
|
+
set(patch) {
|
|
77
|
+
state = { ...state, ...patch }
|
|
78
|
+
emit()
|
|
79
|
+
},
|
|
80
|
+
reset() {
|
|
81
|
+
state = { ...EMPTY_CHROME, ...initial }
|
|
82
|
+
emit()
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Host side: subscribe the header to what the page declared. */
|
|
88
|
+
export function usePageChromeState(store: PageChromeStore): PageChromeState {
|
|
89
|
+
return useSyncExternalStore(store.subscribe, store.get, store.get)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
// Context
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
export interface AddonNavigateOptions {
|
|
97
|
+
replace?: boolean
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Location of the host router, as plain strings (router-agnostic). */
|
|
101
|
+
export interface AddonPageLocation {
|
|
102
|
+
pathname: string
|
|
103
|
+
search: string
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface AddonPageHostValue {
|
|
107
|
+
host: AddonHostContext
|
|
108
|
+
api: HostApi
|
|
109
|
+
basePath: string
|
|
110
|
+
location: AddonPageLocation
|
|
111
|
+
navigate: (to: string, opts?: AddonNavigateOptions) => void
|
|
112
|
+
chrome?: PageChromeStore
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const AddonPageHostContext = createContext<AddonPageHostValue | null>(null)
|
|
116
|
+
|
|
117
|
+
export interface AddonPageHostProps extends Omit<AddonPageHostValue, 'basePath'> {
|
|
118
|
+
basePath: string
|
|
119
|
+
children: ReactNode
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function AddonPageHost({
|
|
123
|
+
host,
|
|
124
|
+
api,
|
|
125
|
+
basePath,
|
|
126
|
+
location,
|
|
127
|
+
navigate,
|
|
128
|
+
chrome,
|
|
129
|
+
children,
|
|
130
|
+
}: AddonPageHostProps) {
|
|
131
|
+
const base = normalizeBase(basePath)
|
|
132
|
+
const value = useMemo<AddonPageHostValue>(
|
|
133
|
+
() => ({ host, api, basePath: base, location, navigate, chrome }),
|
|
134
|
+
[host, api, base, location, navigate, chrome],
|
|
135
|
+
)
|
|
136
|
+
// The chrome belongs to the page: clear it when the page goes away so the
|
|
137
|
+
// next screen does not inherit a stale title or header buttons.
|
|
138
|
+
useEffect(() => () => chrome?.reset(), [chrome])
|
|
139
|
+
return <AddonPageHostContext.Provider value={value}>{children}</AddonPageHostContext.Provider>
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function usePageHost(hook: string): AddonPageHostValue {
|
|
143
|
+
const ctx = useContext(AddonPageHostContext)
|
|
144
|
+
if (!ctx) {
|
|
145
|
+
throw new Error(
|
|
146
|
+
`${hook}() must run inside <AddonPageHost>. Hosts mount it around every federated page; ` +
|
|
147
|
+
'in tests use renderWithHost() from @asteby/metacore-runtime-react/testing.',
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
return ctx
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** True when rendered inside a host page (lets shared components degrade). */
|
|
154
|
+
export function useIsInAddonPage(): boolean {
|
|
155
|
+
return useContext(AddonPageHostContext) !== null
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ---------------------------------------------------------------------------
|
|
159
|
+
// Remote-facing hooks
|
|
160
|
+
// ---------------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
/** Org, user, branch, locale, installed addons and realtime of the host. */
|
|
163
|
+
export function useHostContext(): AddonHostContext {
|
|
164
|
+
return usePageHost('useHostContext').host
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Authenticated API client provided by the host (never exposes the token). */
|
|
168
|
+
export function useHostApi(): HostApi {
|
|
169
|
+
return usePageHost('useHostApi').api
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function normalizeBase(base: string): string {
|
|
173
|
+
const b = `/${base.replace(/^\/+|\/+$/g, '')}`
|
|
174
|
+
return b === '/' ? '' : b
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Resolve `to` inside the page. Plain paths are base-relative:
|
|
179
|
+
* `"shipments/42"` and `"/shipments/42"` both land on `<base>/shipments/42`.
|
|
180
|
+
* `"./x"` and `"../x"` resolve against the current sub-path (like URLs), and
|
|
181
|
+
* `".."` never climbs above the base. `""` / `"?q=1"` keep the current path.
|
|
182
|
+
* A `?query` / `#hash` is kept.
|
|
183
|
+
*/
|
|
184
|
+
export function resolveAddonPath(basePath: string, currentSubpath: string, to: string): string {
|
|
185
|
+
const base = normalizeBase(basePath)
|
|
186
|
+
const m = /^([^?#]*)(.*)$/.exec(to)
|
|
187
|
+
const pathPart = m ? m[1] : to
|
|
188
|
+
const suffix = m ? m[2] : ''
|
|
189
|
+
const current = currentSubpath.split('/').filter(Boolean)
|
|
190
|
+
let segs: string[]
|
|
191
|
+
if (pathPart === '') {
|
|
192
|
+
segs = current
|
|
193
|
+
} else if (pathPart.startsWith('./') || pathPart.startsWith('../') || pathPart === '.' || pathPart === '..') {
|
|
194
|
+
// Relative to the current "directory" (drop the last segment, like URLs).
|
|
195
|
+
segs = current.slice(0, -1)
|
|
196
|
+
} else {
|
|
197
|
+
segs = []
|
|
198
|
+
}
|
|
199
|
+
for (const seg of pathPart.split('/')) {
|
|
200
|
+
if (!seg || seg === '.') continue
|
|
201
|
+
if (seg === '..') segs.pop()
|
|
202
|
+
else segs.push(seg)
|
|
203
|
+
}
|
|
204
|
+
const rest = segs.join('/')
|
|
205
|
+
return `${base}${rest ? `/${rest}` : ''}${suffix}` || '/'
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Path below the page base (`"shipments/42"`), from the host location. */
|
|
209
|
+
export function addonSubpath(basePath: string, pathname: string): string {
|
|
210
|
+
const base = normalizeBase(basePath)
|
|
211
|
+
if (base && (pathname === base || pathname.startsWith(`${base}/`))) {
|
|
212
|
+
return pathname.slice(base.length).replace(/^\/+/, '')
|
|
213
|
+
}
|
|
214
|
+
return ''
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Navigate inside the page. The host router does the work (no
|
|
219
|
+
* `window.location`), so history, guards and the shell stay intact.
|
|
220
|
+
* `navigate(-1)` goes back.
|
|
221
|
+
*/
|
|
222
|
+
export function useAddonNavigate(): (to: string | number, opts?: AddonNavigateOptions) => void {
|
|
223
|
+
const { basePath, location, navigate } = usePageHost('useAddonNavigate')
|
|
224
|
+
const sub = addonSubpath(basePath, location.pathname)
|
|
225
|
+
return useCallback(
|
|
226
|
+
(to: string | number, opts?: AddonNavigateOptions) => {
|
|
227
|
+
if (typeof to === 'number') {
|
|
228
|
+
if (typeof window !== 'undefined') window.history.go(to)
|
|
229
|
+
return
|
|
230
|
+
}
|
|
231
|
+
navigate(resolveAddonPath(basePath, sub, to), opts)
|
|
232
|
+
},
|
|
233
|
+
[basePath, sub, navigate],
|
|
234
|
+
)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Location relative to the page: `{ path: "shipments/42", search: "?x=1" }`. */
|
|
238
|
+
export function useAddonLocation(): { path: string; search: string } {
|
|
239
|
+
const { basePath, location } = usePageHost('useAddonLocation')
|
|
240
|
+
return useMemo(
|
|
241
|
+
() => ({ path: addonSubpath(basePath, location.pathname), search: location.search }),
|
|
242
|
+
[basePath, location.pathname, location.search],
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Search params of the page URL, with a setter that goes through the host router. */
|
|
247
|
+
export function useAddonSearchParams(): [
|
|
248
|
+
URLSearchParams,
|
|
249
|
+
(next: URLSearchParams | Record<string, string>, opts?: AddonNavigateOptions) => void,
|
|
250
|
+
] {
|
|
251
|
+
const { basePath, location, navigate } = usePageHost('useAddonSearchParams')
|
|
252
|
+
const params = useMemo(() => new URLSearchParams(location.search), [location.search])
|
|
253
|
+
const set = useCallback(
|
|
254
|
+
(next: URLSearchParams | Record<string, string>, opts?: AddonNavigateOptions) => {
|
|
255
|
+
const qs = (next instanceof URLSearchParams ? next : new URLSearchParams(next)).toString()
|
|
256
|
+
const sub = addonSubpath(basePath, location.pathname)
|
|
257
|
+
navigate(`${normalizeBase(basePath)}${sub ? `/${sub}` : ''}${qs ? `?${qs}` : ''}`, {
|
|
258
|
+
replace: opts?.replace ?? true,
|
|
259
|
+
})
|
|
260
|
+
},
|
|
261
|
+
[basePath, location.pathname, navigate],
|
|
262
|
+
)
|
|
263
|
+
return [params, set]
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function sameCrumbs(a: Breadcrumb[], b: Breadcrumb[]): boolean {
|
|
267
|
+
return a.length === b.length && a.every((c, i) => c.title === b[i].title && c.url === b[i].url)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Declare the page's breadcrumbs (shown by the host header before the page
|
|
272
|
+
* title). Cleared on unmount. No-op on hosts without a chrome store.
|
|
273
|
+
*/
|
|
274
|
+
export function useBreadcrumbs(crumbs: Breadcrumb[]): void {
|
|
275
|
+
const { chrome } = usePageHost('useBreadcrumbs')
|
|
276
|
+
const last = useRef<Breadcrumb[] | null>(null)
|
|
277
|
+
useEffect(() => {
|
|
278
|
+
if (!chrome) return
|
|
279
|
+
if (last.current && sameCrumbs(last.current, crumbs)) return
|
|
280
|
+
last.current = crumbs
|
|
281
|
+
chrome.set({ breadcrumbs: crumbs })
|
|
282
|
+
})
|
|
283
|
+
useEffect(
|
|
284
|
+
() => () => {
|
|
285
|
+
last.current = null
|
|
286
|
+
chrome?.set({ breadcrumbs: [] })
|
|
287
|
+
},
|
|
288
|
+
[chrome],
|
|
289
|
+
)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Declare title, subtitle, header actions and focus mode. Values update on
|
|
294
|
+
* every render that changes them; everything is cleared on unmount.
|
|
295
|
+
*/
|
|
296
|
+
export function usePageChrome(chrome: PageChrome): void {
|
|
297
|
+
const { chrome: store } = usePageHost('usePageChrome')
|
|
298
|
+
const { title, subtitle, actions, focus } = chrome
|
|
299
|
+
// Action handlers are usually inline closures: keep the latest in a ref so
|
|
300
|
+
// the store only changes when what the header SHOWS changes.
|
|
301
|
+
const handlers = useRef(new Map<string, () => void>())
|
|
302
|
+
handlers.current = new Map((actions ?? []).map((a) => [a.key, a.onSelect]))
|
|
303
|
+
const actionsSig = JSON.stringify(
|
|
304
|
+
(actions ?? []).map(({ onSelect: _onSelect, ...rest }) => rest),
|
|
305
|
+
)
|
|
306
|
+
useEffect(() => {
|
|
307
|
+
if (!store) return
|
|
308
|
+
const stable = (actions ?? []).map((a) => ({
|
|
309
|
+
...a,
|
|
310
|
+
onSelect: () => handlers.current.get(a.key)?.(),
|
|
311
|
+
}))
|
|
312
|
+
store.set({ title, subtitle, actions: stable, focus })
|
|
313
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
314
|
+
}, [store, title, subtitle, actionsSig, focus])
|
|
315
|
+
useEffect(
|
|
316
|
+
() => () => store?.set({ title: undefined, subtitle: undefined, actions: undefined, focus: undefined }),
|
|
317
|
+
[store],
|
|
318
|
+
)
|
|
319
|
+
}
|