@asteby/metacore-runtime-react 53.23.1 → 53.24.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 +22 -0
- package/dist/addon-page-host.d.ts +6 -1
- package/dist/addon-page-host.d.ts.map +1 -1
- package/dist/addon-page-host.js +16 -2
- package/dist/dynamic-columns.d.ts +8 -0
- package/dist/dynamic-columns.d.ts.map +1 -1
- package/dist/dynamic-columns.js +30 -1
- package/dist/host-api-client.d.ts +55 -0
- package/dist/host-api-client.d.ts.map +1 -0
- package/dist/host-api-client.js +85 -0
- package/dist/host-api-context.d.ts +10 -0
- package/dist/host-api-context.d.ts.map +1 -0
- package/dist/host-api-context.js +10 -0
- package/dist/host-api.d.ts.map +1 -1
- package/dist/host-api.js +4 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/types.d.ts +20 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/use-host-api-client.d.ts +8 -0
- package/dist/use-host-api-client.d.ts.map +1 -0
- package/dist/use-host-api-client.js +12 -0
- package/dist/view-system/card-spec.d.ts +3 -2
- package/dist/view-system/card-spec.d.ts.map +1 -1
- package/dist/view-system/card-spec.js +7 -6
- package/dist/views/panels.d.ts.map +1 -1
- package/dist/views/panels.js +2 -1
- package/package.json +5 -5
- package/src/__tests__/host-api-client.test.tsx +119 -0
- package/src/__tests__/resolve-row-actions.test.ts +44 -0
- package/src/addon-page-host.tsx +18 -2
- package/src/dynamic-columns.tsx +28 -1
- package/src/host-api-client.ts +137 -0
- package/src/host-api-context.tsx +18 -0
- package/src/host-api.ts +3 -0
- package/src/index.ts +8 -0
- package/src/types.ts +25 -3
- package/src/use-host-api-client.ts +13 -0
- package/src/view-system/card-spec.tsx +7 -6
- package/src/views/panels.tsx +2 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { BADGE_TONE_CLASS } from '@asteby/metacore-ui/layout';
|
|
3
3
|
import { cn } from '@asteby/metacore-ui/lib';
|
|
4
|
-
|
|
4
|
+
import { formatAmount } from '@asteby/metacore-lib';
|
|
5
|
+
function fmt(v, f = 'text', locale, currency) {
|
|
5
6
|
if (v == null || v === '')
|
|
6
7
|
return '';
|
|
7
8
|
try {
|
|
@@ -10,7 +11,7 @@ function fmt(v, f = 'text', locale) {
|
|
|
10
11
|
if (f === 'percent')
|
|
11
12
|
return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(Number(v))}%`;
|
|
12
13
|
if (f === 'currency')
|
|
13
|
-
return
|
|
14
|
+
return formatAmount(v, { currency, locale });
|
|
14
15
|
if (f === 'date')
|
|
15
16
|
return new Date(String(v)).toLocaleDateString(locale);
|
|
16
17
|
if (f === 'datetime')
|
|
@@ -22,7 +23,7 @@ function fmt(v, f = 'text', locale) {
|
|
|
22
23
|
return String(v);
|
|
23
24
|
}
|
|
24
25
|
/** Pure: row + manifest CardSpec -> display model. Missing fields are skipped, never throw. */
|
|
25
|
-
export function resolveCard(spec, row, locale) {
|
|
26
|
+
export function resolveCard(spec, row, locale, currency) {
|
|
26
27
|
const bv = spec.badge ? row[spec.badge.field] : undefined;
|
|
27
28
|
const key = bv == null ? '' : String(bv);
|
|
28
29
|
return {
|
|
@@ -30,11 +31,11 @@ export function resolveCard(spec, row, locale) {
|
|
|
30
31
|
subtitle: spec.subtitle ? fmt(row[spec.subtitle]) || undefined : undefined,
|
|
31
32
|
badge: spec.badge && key ? { text: spec.badge.labels?.[key] ?? key, tone: spec.badge.tones?.[key] ?? 'info' } : undefined,
|
|
32
33
|
chips: (spec.chips ?? []).map((f) => fmt(row[f])).filter(Boolean),
|
|
33
|
-
meta: (spec.meta ?? []).map((m) => ({ label: m.label, value: fmt(row[m.field], m.format, locale) })).filter((m) => m.value),
|
|
34
|
+
meta: (spec.meta ?? []).map((m) => ({ label: m.label, value: fmt(row[m.field], m.format, locale, currency) })).filter((m) => m.value),
|
|
34
35
|
};
|
|
35
36
|
}
|
|
36
|
-
export function ConfigurableCard({ spec, row, onClick, locale }) {
|
|
37
|
-
const c = resolveCard(spec, row, locale);
|
|
37
|
+
export function ConfigurableCard({ spec, row, onClick, locale, currency }) {
|
|
38
|
+
const c = resolveCard(spec, row, locale, currency);
|
|
38
39
|
const Tag = onClick ? 'button' : 'div';
|
|
39
40
|
return (_jsxs(Tag, { ...(onClick ? { type: 'button', onClick } : {}), className: cn('flex w-full flex-col gap-2 rounded-xl border bg-card p-4 text-start', onClick && 'transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'), children: [_jsxs("div", { className: 'flex items-start justify-between gap-2', children: [_jsx("span", { className: 'line-clamp-2 font-medium', children: c.title }), c.badge && (_jsx("span", { "data-tone": c.badge.tone, className: cn('shrink-0 rounded-full px-2 text-xs font-semibold leading-5 ring-1 ring-inset', BADGE_TONE_CLASS[c.badge.tone].replace(/motion-safe:animate-pulse/, '')), children: c.badge.text }))] }), c.subtitle && _jsx("span", { className: 'line-clamp-2 text-sm text-muted-foreground', children: c.subtitle }), c.chips.length > 0 && (_jsx("div", { className: 'flex flex-wrap gap-1', children: c.chips.map((x, i) => (_jsx("span", { className: 'rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground', children: x }, i))) })), c.meta.length > 0 && (_jsx("dl", { className: 'mt-auto grid grid-cols-2 gap-x-3 gap-y-1 text-xs text-muted-foreground', children: c.meta.map((m, i) => (_jsxs("div", { className: 'min-w-0', children: [m.label && _jsx("dt", { className: 'sr-only', children: m.label }), _jsx("dd", { className: 'truncate', children: m.value })] }, i))) }))] }));
|
|
40
41
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"panels.d.ts","sourceRoot":"","sources":["../../src/views/panels.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAG9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"panels.d.ts","sourceRoot":"","sources":["../../src/views/panels.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAG9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AAKjD,MAAM,MAAM,UAAU,GAChB,QAAQ,GACR,UAAU,GACV,SAAS,GACT,SAAS,GACT,MAAM,GACN,UAAU,GACV,eAAe,CAAA;AAErB,8EAA8E;AAC9E,wBAAgB,UAAU,CACtB,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,IAAI,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,IAAI,CAAA;CAAO,GACjF,MAAM,CA4CR;AAED,wBAAgB,cAAc,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,kBAAkB,qBAiBzG;AAED,wBAAgB,iBAAiB,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,EAAE,kBAAkB,4BAuFpG"}
|
package/dist/views/panels.js
CHANGED
|
@@ -6,6 +6,7 @@ import * as React from 'react';
|
|
|
6
6
|
import { useTranslation } from 'react-i18next';
|
|
7
7
|
import { buildRelationFilterParams } from '../dynamic-relation-helpers';
|
|
8
8
|
import { displayValue, toDate } from './data-source';
|
|
9
|
+
import { formatAmount } from '@asteby/metacore-lib';
|
|
9
10
|
import { ViewSkeleton } from './skeleton';
|
|
10
11
|
/** Pure: format one stat value for display. `now` is injectable for tests. */
|
|
11
12
|
export function formatStat(value, format, opts = {}) {
|
|
@@ -18,7 +19,7 @@ export function formatStat(value, format, opts = {}) {
|
|
|
18
19
|
case 'currency':
|
|
19
20
|
if (Number.isNaN(num))
|
|
20
21
|
break;
|
|
21
|
-
return
|
|
22
|
+
return formatAmount(num, { currency, locale });
|
|
22
23
|
case 'percent':
|
|
23
24
|
if (Number.isNaN(num))
|
|
24
25
|
break;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@asteby/metacore-runtime-react",
|
|
3
|
-
"version": "53.
|
|
3
|
+
"version": "53.24.0",
|
|
4
4
|
"description": "React runtime for metacore hosts — renders addon contributions dynamically",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -37,8 +37,8 @@
|
|
|
37
37
|
}
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@asteby/metacore-charts": "^0.1.
|
|
41
|
-
"@asteby/metacore-lib": "^0.
|
|
40
|
+
"@asteby/metacore-charts": "^0.1.1",
|
|
41
|
+
"@asteby/metacore-lib": "^0.11.0",
|
|
42
42
|
"@dnd-kit/core": "^6.3.0",
|
|
43
43
|
"@dnd-kit/sortable": "^10.0.0",
|
|
44
44
|
"@dnd-kit/utilities": "^3.2.2",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"zustand": ">=5",
|
|
64
64
|
"@module-federation/runtime": ">=2.5",
|
|
65
65
|
"@testing-library/react": ">=14",
|
|
66
|
-
"@asteby/metacore-genui": "^2.9.
|
|
66
|
+
"@asteby/metacore-genui": "^2.9.1"
|
|
67
67
|
},
|
|
68
68
|
"peerDependenciesMeta": {
|
|
69
69
|
"@tanstack/react-router": {
|
|
@@ -105,7 +105,7 @@
|
|
|
105
105
|
"vitest": "^4.0.0",
|
|
106
106
|
"zustand": "^5.0.0",
|
|
107
107
|
"@module-federation/runtime": "^2.5.0",
|
|
108
|
-
"@asteby/metacore-genui": "2.9.
|
|
108
|
+
"@asteby/metacore-genui": "2.9.1"
|
|
109
109
|
},
|
|
110
110
|
"scripts": {
|
|
111
111
|
"build": "tsc -p tsconfig.json",
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
3
|
+
import { cleanup, render, screen } from '@testing-library/react'
|
|
4
|
+
import { HostApiError } from '@asteby/metacore-sdk'
|
|
5
|
+
import type { HostApi } from '@asteby/metacore-sdk'
|
|
6
|
+
import { ApiError, isAbortError } from '@asteby/metacore-lib/envelope'
|
|
7
|
+
import { createHostApiClient } from '../host-api-client'
|
|
8
|
+
import { HostApiProvider } from '../host-api-context'
|
|
9
|
+
import { useHostApiClient } from '../use-host-api-client'
|
|
10
|
+
import { createMockHostApi } from '../testing'
|
|
11
|
+
|
|
12
|
+
const stub = (over: Partial<HostApi>): HostApi => ({ ...createMockHostApi(), ...over }) as HostApi
|
|
13
|
+
|
|
14
|
+
describe('createHostApiClient', () => {
|
|
15
|
+
it('unwraps the envelope and keeps bare bodies', async () => {
|
|
16
|
+
const c = createHostApiClient(
|
|
17
|
+
stub({
|
|
18
|
+
get: (async (p: string) =>
|
|
19
|
+
p === '/a' ? { success: true, data: { id: 1 }, meta: { total: 9 } } : { x: 1 }) as never,
|
|
20
|
+
}),
|
|
21
|
+
)
|
|
22
|
+
expect(await c.get('/a')).toEqual({ id: 1 })
|
|
23
|
+
expect(await c.get('/b')).toEqual({ x: 1 })
|
|
24
|
+
const l = await c.list('/a')
|
|
25
|
+
expect(l.items).toEqual([])
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('list returns items and meta.total', async () => {
|
|
29
|
+
const c = createHostApiClient(
|
|
30
|
+
stub({ get: (async () => ({ success: true, data: [1, 2], meta: { total: 9 } })) as never }),
|
|
31
|
+
)
|
|
32
|
+
const l = await c.list<number>('/x')
|
|
33
|
+
expect(l.items).toEqual([1, 2])
|
|
34
|
+
expect(l.total).toBe(9)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('throws ApiError on success:false envelope', async () => {
|
|
38
|
+
const c = createHostApiClient(stub({ post: (async () => ({ success: false, message: 'nope' })) as never }))
|
|
39
|
+
await expect(c.post('/x', {})).rejects.toMatchObject({ name: 'ApiError', message: 'nope' })
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('maps HostApiError (401) to ApiError with status and code', async () => {
|
|
43
|
+
const c = createHostApiClient(
|
|
44
|
+
stub({ get: (async () => { throw new HostApiError('Unauthorized', 401, { code: 'token_expired' }) }) as never }),
|
|
45
|
+
)
|
|
46
|
+
const e = await c.get('/x').catch((x) => x)
|
|
47
|
+
expect(e).toBeInstanceOf(ApiError)
|
|
48
|
+
expect(e.status).toBe(401)
|
|
49
|
+
expect(e.code).toBe('token_expired')
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('forwards params and signal, and keeps abort as AbortError', async () => {
|
|
53
|
+
const ctrl = new AbortController()
|
|
54
|
+
const get = vi.fn(async (_p: string, o?: { signal?: AbortSignal }) => {
|
|
55
|
+
ctrl.abort()
|
|
56
|
+
throw new HostApiError('Network error', 0)
|
|
57
|
+
void o
|
|
58
|
+
})
|
|
59
|
+
const c = createHostApiClient(stub({ get: get as never }))
|
|
60
|
+
const e = await c.get('/x', { params: { q: 'a' }, signal: ctrl.signal }).catch((x) => x)
|
|
61
|
+
expect(get).toHaveBeenCalledWith('/x', { params: { q: 'a' }, signal: ctrl.signal })
|
|
62
|
+
expect(isAbortError(e)).toBe(true)
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('passes through a native abort error from the transport', async () => {
|
|
66
|
+
const abort = Object.assign(new Error('x'), { name: 'AbortError' })
|
|
67
|
+
const c = createHostApiClient(stub({ get: (async () => { throw abort }) as never }))
|
|
68
|
+
expect(await c.get('/x').catch((x) => x)).toBe(abort)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('upload sends multipart FormData with file and fields', async () => {
|
|
72
|
+
const post = vi.fn(async () => ({ success: true, data: { url: '/storage/a.png' } }))
|
|
73
|
+
const c = createHostApiClient(stub({ post: post as never }))
|
|
74
|
+
const out = await c.upload<{ url: string }>('/upload', new File(['x'], 'a.png'), { folder: 'f' })
|
|
75
|
+
expect(out.url).toBe('/storage/a.png')
|
|
76
|
+
const form = (post.mock.calls[0] as unknown[])[1] as FormData
|
|
77
|
+
expect(form).toBeInstanceOf(FormData)
|
|
78
|
+
expect((form.get('file') as File).name).toBe('a.png')
|
|
79
|
+
expect(form.get('folder')).toBe('f')
|
|
80
|
+
const own = new FormData()
|
|
81
|
+
await c.upload('/upload', own)
|
|
82
|
+
expect((post.mock.calls[1] as unknown[])[1]).toBe(own)
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it('blob requests responseType blob', async () => {
|
|
86
|
+
const get = vi.fn(async () => new Blob(['pdf']))
|
|
87
|
+
const c = createHostApiClient(stub({ get: get as never }))
|
|
88
|
+
expect(await c.blob('/d.pdf')).toBeInstanceOf(Blob)
|
|
89
|
+
expect(get).toHaveBeenCalledWith('/d.pdf', { responseType: 'blob' })
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it('axiosLike keeps the envelope in data', async () => {
|
|
93
|
+
const env = { success: true, data: [1] }
|
|
94
|
+
const c = createHostApiClient(stub({ get: (async () => env) as never }))
|
|
95
|
+
expect(await c.axiosLike().get('/x')).toEqual({ data: env })
|
|
96
|
+
})
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
import { afterEach } from 'vitest'
|
|
100
|
+
afterEach(cleanup)
|
|
101
|
+
describe('useHostApiClient', () => {
|
|
102
|
+
function Probe() {
|
|
103
|
+
const c = useHostApiClient()
|
|
104
|
+
return <span>{typeof c.get}</span>
|
|
105
|
+
}
|
|
106
|
+
it('resolves from HostApiProvider', () => {
|
|
107
|
+
render(
|
|
108
|
+
<HostApiProvider api={createMockHostApi()}>
|
|
109
|
+
<Probe />
|
|
110
|
+
</HostApiProvider>,
|
|
111
|
+
)
|
|
112
|
+
expect(screen.getByText('function')).toBeTruthy()
|
|
113
|
+
})
|
|
114
|
+
it('throws a clear error without a host (no localStorage fallback)', () => {
|
|
115
|
+
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
116
|
+
expect(() => render(<Probe />)).toThrow(/HostApiProvider/)
|
|
117
|
+
spy.mockRestore()
|
|
118
|
+
})
|
|
119
|
+
})
|
|
@@ -106,4 +106,48 @@ describe('isRowActionVisible', () => {
|
|
|
106
106
|
// Flat lookup must NOT match nested conditions (regression of row[field]).
|
|
107
107
|
expect(isActionConditionMet(approve, { 'user.verified': false } as any)).toBe(false)
|
|
108
108
|
})
|
|
109
|
+
|
|
110
|
+
it('isActionConditionMet compares numerically (gt/gte/lt/lte) and composes with all/any', () => {
|
|
111
|
+
const gt0 = { condition: { field: 'debt', operator: 'gt', value: '0' } }
|
|
112
|
+
expect(isActionConditionMet(gt0, { debt: '12.50' })).toBe(true)
|
|
113
|
+
expect(isActionConditionMet(gt0, { debt: 0 })).toBe(false)
|
|
114
|
+
expect(isActionConditionMet(gt0, { debt: null })).toBe(false)
|
|
115
|
+
expect(isActionConditionMet(gt0, { debt: 'abc' })).toBe(false)
|
|
116
|
+
expect(isActionConditionMet({ condition: { field: 's', operator: 'lt', value: '5' } }, { s: 4 })).toBe(true)
|
|
117
|
+
expect(isActionConditionMet({ condition: { field: 's', operator: 'lte', value: '5' } }, { s: 5 })).toBe(true)
|
|
118
|
+
expect(isActionConditionMet({ condition: { field: 's', operator: 'gte', value: '5' } }, { s: 4 })).toBe(false)
|
|
119
|
+
const both = {
|
|
120
|
+
condition: {
|
|
121
|
+
operator: 'all',
|
|
122
|
+
field: '',
|
|
123
|
+
value: '',
|
|
124
|
+
conditions: [
|
|
125
|
+
{ field: 'amount', operator: 'gt', value: '0' },
|
|
126
|
+
{ field: 'cat', operator: 'neq', value: '4' },
|
|
127
|
+
],
|
|
128
|
+
},
|
|
129
|
+
}
|
|
130
|
+
expect(isActionConditionMet(both, { amount: 10, cat: 1 })).toBe(true)
|
|
131
|
+
expect(isActionConditionMet(both, { amount: 10, cat: 4 })).toBe(false)
|
|
132
|
+
const either = { condition: { operator: 'any', field: '', value: '', conditions: [{ field: 'a', operator: 'truthy', value: '' }, { field: 'b', operator: 'truthy', value: '' }] } }
|
|
133
|
+
expect(isActionConditionMet(either, { a: null, b: 1 })).toBe(true)
|
|
134
|
+
expect(isActionConditionMet(either, { a: null, b: 0 })).toBe(false)
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
it('supports nested groups and legacy aliases stay intact', () => {
|
|
138
|
+
const nested = {
|
|
139
|
+
condition: {
|
|
140
|
+
operator: 'any',
|
|
141
|
+
conditions: [
|
|
142
|
+
{ operator: 'all', conditions: [{ field: 'a', operator: 'gt', value: 1 }, { field: 'b', operator: 'falsy' }] },
|
|
143
|
+
{ field: 'c', operator: 'in', value: [1, 2] },
|
|
144
|
+
],
|
|
145
|
+
},
|
|
146
|
+
}
|
|
147
|
+
expect(isActionConditionMet(nested, { a: 2, b: 0, c: 9 })).toBe(true)
|
|
148
|
+
expect(isActionConditionMet(nested, { a: 2, b: 1, c: 2 })).toBe(true)
|
|
149
|
+
expect(isActionConditionMet(nested, { a: 2, b: 1, c: 9 })).toBe(false)
|
|
150
|
+
expect(isActionConditionMet({ condition: { field: 'x', operator: 'notEquals', value: 'y' } }, { x: 'z' })).toBe(true)
|
|
151
|
+
expect(isActionConditionMet({ condition: { field: 'x', operator: 'weird' } }, { x: 'z' })).toBe(true)
|
|
152
|
+
})
|
|
109
153
|
})
|
package/src/addon-page-host.tsx
CHANGED
|
@@ -36,6 +36,7 @@ import {
|
|
|
36
36
|
useSyncExternalStore,
|
|
37
37
|
type ReactNode,
|
|
38
38
|
} from 'react'
|
|
39
|
+
import { HostApiContext } from './host-api-context'
|
|
39
40
|
import type {
|
|
40
41
|
AddonHostContext,
|
|
41
42
|
Breadcrumb,
|
|
@@ -164,9 +165,24 @@ export function useHostContext(): AddonHostContext {
|
|
|
164
165
|
return usePageHost('useHostContext').host
|
|
165
166
|
}
|
|
166
167
|
|
|
167
|
-
/**
|
|
168
|
+
/**
|
|
169
|
+
* Authenticated API client provided by the host (never exposes the token).
|
|
170
|
+
* Resolves from <AddonPageHost> or, for surfaces mounted outside a page
|
|
171
|
+
* (modals, pickers), from <HostApiProvider>. Throws when neither exists: a
|
|
172
|
+
* remote never falls back to reading credentials itself.
|
|
173
|
+
*/
|
|
168
174
|
export function useHostApi(): HostApi {
|
|
169
|
-
|
|
175
|
+
const page = useContext(AddonPageHostContext)
|
|
176
|
+
const provided = useContext(HostApiContext)
|
|
177
|
+
const api = page?.api ?? provided
|
|
178
|
+
if (!api) {
|
|
179
|
+
throw new Error(
|
|
180
|
+
'useHostApi() must run inside <AddonPageHost> (pages) or <HostApiProvider api={createHostApi(client)}> (modals, pickers); ' +
|
|
181
|
+
'the host mounts one around every federated surface; addons must not read the token from localStorage. ' +
|
|
182
|
+
'In tests use renderWithHost() from @asteby/metacore-runtime-react/testing.',
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
return api
|
|
170
186
|
}
|
|
171
187
|
|
|
172
188
|
function normalizeBase(base: string): string {
|
package/src/dynamic-columns.tsx
CHANGED
|
@@ -287,7 +287,24 @@ export const isActionAllowedForRowState = (action: any, row: any, stageField?: s
|
|
|
287
287
|
*/
|
|
288
288
|
export const isActionConditionMet = (action: any, row: any): boolean => {
|
|
289
289
|
if (!action?.condition) return true
|
|
290
|
-
|
|
290
|
+
return evalActionCondition(action.condition, row)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Evaluates one ActionCondition (or an `all`/`any` composition of them) against a row.
|
|
295
|
+
* Besides the equality/membership/truthy family it supports numeric comparisons
|
|
296
|
+
* (`gt` | `gte` | `lt` | `lte`: both sides coerced with Number(); a non-numeric side never matches)
|
|
297
|
+
* and `all` / `any` groups (`{ operator: 'all', conditions: [...] }`), so a host can ship
|
|
298
|
+
* `amount > 0 && status != 4` as data instead of an unexpressible legacy string.
|
|
299
|
+
*/
|
|
300
|
+
export const evalActionCondition = (cond: any, row: any): boolean => {
|
|
301
|
+
const { field, operator, value } = cond ?? {}
|
|
302
|
+
const group = String(operator ?? '').toLowerCase()
|
|
303
|
+
if (group === 'all' || group === 'any') {
|
|
304
|
+
const list: any[] = Array.isArray(cond.conditions) ? cond.conditions : []
|
|
305
|
+
if (list.length === 0) return true
|
|
306
|
+
return group === 'all' ? list.every((c) => evalActionCondition(c, row)) : list.some((c) => evalActionCondition(c, row))
|
|
307
|
+
}
|
|
291
308
|
if (!field) return true
|
|
292
309
|
|
|
293
310
|
const coerce = (v: unknown): string => {
|
|
@@ -324,6 +341,16 @@ export const isActionConditionMet = (action: any, row: any): boolean => {
|
|
|
324
341
|
case 'blank':
|
|
325
342
|
case 'empty':
|
|
326
343
|
return rowValue === '' || rowValue === 'false' || rowValue === '0'
|
|
344
|
+
case 'gt':
|
|
345
|
+
case 'gte':
|
|
346
|
+
case 'lt':
|
|
347
|
+
case 'lte': {
|
|
348
|
+
if (rowValue === '' || values[0] === '' || values[0] === undefined) return false
|
|
349
|
+
const l = Number(rowValue)
|
|
350
|
+
const r = Number(values[0])
|
|
351
|
+
if (Number.isNaN(l) || Number.isNaN(r)) return false
|
|
352
|
+
return op === 'gt' ? l > r : op === 'gte' ? l >= r : op === 'lt' ? l < r : l <= r
|
|
353
|
+
}
|
|
327
354
|
default:
|
|
328
355
|
return true
|
|
329
356
|
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// createHostApiClient — the ONE HTTP client for federated addons (modals,
|
|
2
|
+
// pickers, pages). It wraps the host-injected HostApi (see createHostApi), so:
|
|
3
|
+
// - baseURL, bearer token, org/branch/language headers, 401 handling and
|
|
4
|
+
// refresh live in the HOST transport; the addon never reads localStorage;
|
|
5
|
+
// - the kernel envelope `{success,data,meta}` is unwrapped here with
|
|
6
|
+
// @asteby/metacore-lib/envelope (success:false throws ApiError);
|
|
7
|
+
// - every failure is the single `ApiError` (status, code, details);
|
|
8
|
+
// - a cancelled request rethrows an AbortError (use isAbortError()).
|
|
9
|
+
import { HostApiError } from '@asteby/metacore-sdk'
|
|
10
|
+
import type { HostApi, HostApiParams } from '@asteby/metacore-sdk'
|
|
11
|
+
import {
|
|
12
|
+
ApiError,
|
|
13
|
+
isAbortError,
|
|
14
|
+
isEnvelope,
|
|
15
|
+
unwrapEnvelope,
|
|
16
|
+
unwrapList,
|
|
17
|
+
type UnwrappedList,
|
|
18
|
+
} from '@asteby/metacore-lib/envelope'
|
|
19
|
+
|
|
20
|
+
export { ApiError, isAbortError }
|
|
21
|
+
|
|
22
|
+
export interface HostRequestConfig {
|
|
23
|
+
params?: HostApiParams
|
|
24
|
+
signal?: AbortSignal
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Minimal axios-like surface (what DynamicSelectField & co. call). */
|
|
28
|
+
export interface AxiosLikeClient {
|
|
29
|
+
get(url: string, config?: HostRequestConfig): Promise<{ data: unknown }>
|
|
30
|
+
post(url: string, body?: unknown, config?: HostRequestConfig): Promise<{ data: unknown }>
|
|
31
|
+
put(url: string, body?: unknown, config?: HostRequestConfig): Promise<{ data: unknown }>
|
|
32
|
+
patch(url: string, body?: unknown, config?: HostRequestConfig): Promise<{ data: unknown }>
|
|
33
|
+
delete(url: string, config?: HostRequestConfig): Promise<{ data: unknown }>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface HostApiClient {
|
|
37
|
+
/** Unwrapped `data` of the envelope (bare bodies pass through). */
|
|
38
|
+
get<T = unknown>(path: string, config?: HostRequestConfig): Promise<T>
|
|
39
|
+
post<T = unknown>(path: string, body?: unknown, config?: HostRequestConfig): Promise<T>
|
|
40
|
+
put<T = unknown>(path: string, body?: unknown, config?: HostRequestConfig): Promise<T>
|
|
41
|
+
patch<T = unknown>(path: string, body?: unknown, config?: HostRequestConfig): Promise<T>
|
|
42
|
+
delete<T = unknown>(path: string, config?: HostRequestConfig): Promise<T>
|
|
43
|
+
/** List read: `items` + `total` (meta.total) + `meta`. Never null. */
|
|
44
|
+
list<T = unknown>(path: string, config?: HostRequestConfig): Promise<UnwrappedList<T>>
|
|
45
|
+
/** Binary read (PDF, image, CSV) as a Blob. */
|
|
46
|
+
blob(path: string, config?: HostRequestConfig): Promise<Blob>
|
|
47
|
+
/**
|
|
48
|
+
* Multipart upload. Pass a ready FormData, or a File plus extra fields
|
|
49
|
+
* (`{ folder }`); the file goes under `fileField` (default `"file"`).
|
|
50
|
+
* The transport sets the multipart boundary; do not set Content-Type.
|
|
51
|
+
*/
|
|
52
|
+
upload<T = unknown>(
|
|
53
|
+
path: string,
|
|
54
|
+
file: File | Blob | FormData,
|
|
55
|
+
fields?: Record<string, string>,
|
|
56
|
+
opts?: { fileField?: string; signal?: AbortSignal },
|
|
57
|
+
): Promise<T>
|
|
58
|
+
/**
|
|
59
|
+
* Axios-like adapter for runtime-react fields that expect `{ data }` with
|
|
60
|
+
* the envelope still in place (`<ApiProvider client={client.axiosLike()}>`
|
|
61
|
+
* for a federated remote mounted outside the host provider).
|
|
62
|
+
*/
|
|
63
|
+
axiosLike(): AxiosLikeClient
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function abortError(signal: AbortSignal): Error {
|
|
67
|
+
const reason = signal.reason
|
|
68
|
+
if (reason instanceof Error && isAbortError(reason)) return reason
|
|
69
|
+
const e = new Error('The operation was aborted')
|
|
70
|
+
e.name = 'AbortError'
|
|
71
|
+
return e
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function toApiError(e: unknown, signal?: AbortSignal): Error {
|
|
75
|
+
if (isAbortError(e)) return e as Error
|
|
76
|
+
if (signal?.aborted) return abortError(signal)
|
|
77
|
+
if (e instanceof ApiError) return e
|
|
78
|
+
if (e instanceof HostApiError) {
|
|
79
|
+
return new ApiError(e.message, { status: e.status || undefined, code: e.code, details: e.data, cause: e })
|
|
80
|
+
}
|
|
81
|
+
if (e instanceof Error) return new ApiError(e.message, { cause: e })
|
|
82
|
+
return new ApiError('request failed', { cause: e })
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Build the client over the host-injected {@link HostApi}. */
|
|
86
|
+
export function createHostApiClient(api: HostApi): HostApiClient {
|
|
87
|
+
const run = async <R,>(p: () => Promise<R>, signal?: AbortSignal): Promise<R> => {
|
|
88
|
+
try {
|
|
89
|
+
return await p()
|
|
90
|
+
} catch (e) {
|
|
91
|
+
throw toApiError(e, signal)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const body = <T,>(p: () => Promise<unknown>, signal?: AbortSignal) =>
|
|
95
|
+
run(async () => unwrapEnvelope<T>(await p()), signal)
|
|
96
|
+
|
|
97
|
+
const client: HostApiClient = {
|
|
98
|
+
get: (path, c) => body(() => api.get(path, c), c?.signal),
|
|
99
|
+
post: (path, b, c) => body(() => api.post(path, b, c), c?.signal),
|
|
100
|
+
put: (path, b, c) => body(() => api.put(path, b, c), c?.signal),
|
|
101
|
+
patch: (path, b, c) => body(() => api.patch(path, b, c), c?.signal),
|
|
102
|
+
delete: (path, c) => body(() => api.delete(path, c), c?.signal),
|
|
103
|
+
list: (path, c) =>
|
|
104
|
+
run(async () => unwrapList(await api.get(path, c)), c?.signal),
|
|
105
|
+
blob: (path, c) =>
|
|
106
|
+
run(() => api.get<Blob>(path, { ...c, responseType: 'blob' }), c?.signal),
|
|
107
|
+
upload: (path, file, fields, opts) => {
|
|
108
|
+
let form: FormData
|
|
109
|
+
if (typeof FormData !== 'undefined' && file instanceof FormData) {
|
|
110
|
+
form = file
|
|
111
|
+
} else {
|
|
112
|
+
form = new FormData()
|
|
113
|
+
form.append(opts?.fileField ?? 'file', file as Blob)
|
|
114
|
+
for (const [k, v] of Object.entries(fields ?? {})) form.append(k, v)
|
|
115
|
+
}
|
|
116
|
+
return body(() => api.post(path, form, opts?.signal ? { signal: opts.signal } : undefined), opts?.signal)
|
|
117
|
+
},
|
|
118
|
+
axiosLike: () => {
|
|
119
|
+
// Envelope kept (the runtime-react fields unwrap it themselves),
|
|
120
|
+
// but a `success:false` body still fails as ApiError.
|
|
121
|
+
const raw = async (p: () => Promise<unknown>, signal?: AbortSignal) =>
|
|
122
|
+
run(async () => {
|
|
123
|
+
const data = await p()
|
|
124
|
+
if (isEnvelope(data)) unwrapEnvelope(data)
|
|
125
|
+
return { data }
|
|
126
|
+
}, signal)
|
|
127
|
+
return {
|
|
128
|
+
get: (u, c) => raw(() => api.get(u, c), c?.signal),
|
|
129
|
+
post: (u, b, c) => raw(() => api.post(u, b, c), c?.signal),
|
|
130
|
+
put: (u, b, c) => raw(() => api.put(u, b, c), c?.signal),
|
|
131
|
+
patch: (u, b, c) => raw(() => api.patch(u, b, c), c?.signal),
|
|
132
|
+
delete: (u, c) => raw(() => api.delete(u, c), c?.signal),
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
}
|
|
136
|
+
return client
|
|
137
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// HostApiProvider — hands the host-built HostApi to federated surfaces that
|
|
2
|
+
// mount OUTSIDE <AddonPageHost> (action modals, record pickers, widgets).
|
|
3
|
+
// Pages already get it from <AddonPageHost api=…>; both resolve through
|
|
4
|
+
// useHostApi() / useHostApiClient().
|
|
5
|
+
import { createContext, type ReactNode } from 'react'
|
|
6
|
+
import type { HostApi } from '@asteby/metacore-sdk'
|
|
7
|
+
|
|
8
|
+
export const HostApiContext = createContext<HostApi | null>(null)
|
|
9
|
+
|
|
10
|
+
export interface HostApiProviderProps {
|
|
11
|
+
/** `createHostApi(hostAxios)` — the host owns baseURL, credentials and headers. */
|
|
12
|
+
api: HostApi
|
|
13
|
+
children: ReactNode
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function HostApiProvider({ api, children }: HostApiProviderProps) {
|
|
17
|
+
return <HostApiContext.Provider value={api}>{children}</HostApiContext.Provider>
|
|
18
|
+
}
|
package/src/host-api.ts
CHANGED
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
HostQueryPart,
|
|
18
18
|
} from '@asteby/metacore-sdk'
|
|
19
19
|
import type { ApiClient } from './api-context'
|
|
20
|
+
import { isAbortError } from '@asteby/metacore-lib/envelope'
|
|
20
21
|
import { batchGet } from './query-batch'
|
|
21
22
|
|
|
22
23
|
export interface CreateHostApiOptions {
|
|
@@ -111,6 +112,8 @@ async function bodyOf<T>(p: Promise<{ data: unknown }>, opts?: HostApiRequestOpt
|
|
|
111
112
|
}
|
|
112
113
|
return res.data as T
|
|
113
114
|
} catch (e) {
|
|
115
|
+
// A cancelled request stays an abort (callers filter it with isAbortError).
|
|
116
|
+
if (isAbortError(e)) throw e
|
|
114
117
|
throw toHostApiError(opts?.responseType === 'blob' ? await decodeBlobError(e) : e)
|
|
115
118
|
}
|
|
116
119
|
}
|
package/src/index.ts
CHANGED
|
@@ -305,6 +305,14 @@ export {
|
|
|
305
305
|
type PageChromeStore,
|
|
306
306
|
} from './addon-page-host'
|
|
307
307
|
export { createHostApi, toHostApiError, type CreateHostApiOptions } from './host-api'
|
|
308
|
+
export { HostApiProvider, type HostApiProviderProps } from './host-api-context'
|
|
309
|
+
export {
|
|
310
|
+
createHostApiClient,
|
|
311
|
+
type HostApiClient,
|
|
312
|
+
type HostRequestConfig,
|
|
313
|
+
type AxiosLikeClient,
|
|
314
|
+
} from './host-api-client'
|
|
315
|
+
export { useHostApiClient } from './use-host-api-client'
|
|
308
316
|
export {
|
|
309
317
|
FederatedErrorBoundary,
|
|
310
318
|
type FederatedErrorBoundaryProps,
|
package/src/types.ts
CHANGED
|
@@ -612,10 +612,32 @@ export interface ColumnItemField {
|
|
|
612
612
|
ref?: string
|
|
613
613
|
}
|
|
614
614
|
|
|
615
|
+
/**
|
|
616
|
+
* Canonical operator names (same vocabulary as the kernel's declarative
|
|
617
|
+
* conditions): `eq` `neq` `in` `not_in` `gt` `gte` `lt` `lte` `truthy` `falsy`,
|
|
618
|
+
* plus the `all` / `any` groups. Legacy aliases (`equals`, `notEquals`, `notin`,
|
|
619
|
+
* `==`, `!=`, `present`, `set`, `blank`, `empty`) are still evaluated but are not
|
|
620
|
+
* part of the typed contract.
|
|
621
|
+
*/
|
|
622
|
+
export type ActionConditionOperator =
|
|
623
|
+
| 'eq' | 'neq' | 'in' | 'not_in'
|
|
624
|
+
| 'gt' | 'gte' | 'lt' | 'lte'
|
|
625
|
+
| 'truthy' | 'falsy'
|
|
626
|
+
| 'all' | 'any'
|
|
627
|
+
|
|
615
628
|
export interface ActionCondition {
|
|
616
|
-
field
|
|
617
|
-
|
|
618
|
-
|
|
629
|
+
/** Row field (dotted paths allowed). Unused by `all`/`any` groups. */
|
|
630
|
+
field?: string
|
|
631
|
+
/**
|
|
632
|
+
* `gt|gte|lt|lte` compare numerically (a non-numeric side never matches);
|
|
633
|
+
* `truthy|falsy` test presence and take no `value`; `all|any` combine
|
|
634
|
+
* `conditions` (AND / OR, nestable; an empty list passes).
|
|
635
|
+
*/
|
|
636
|
+
operator: ActionConditionOperator
|
|
637
|
+
/** Comparison operand; a list for `in` / `not_in`. Omitted for `truthy|falsy` and groups. */
|
|
638
|
+
value?: string | number | boolean | Array<string | number | boolean>
|
|
639
|
+
/** Members of an `all` / `any` group. */
|
|
640
|
+
conditions?: ActionCondition[]
|
|
619
641
|
}
|
|
620
642
|
|
|
621
643
|
/**
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { useMemo } from 'react'
|
|
2
|
+
import { useHostApi } from './addon-page-host'
|
|
3
|
+
import { createHostApiClient, type HostApiClient } from './host-api-client'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The addon's HTTP client, built over the host-injected HostApi. Works inside
|
|
7
|
+
* <AddonPageHost> (pages) and <HostApiProvider> (modals, pickers). Without a
|
|
8
|
+
* host it throws a clear error: there is no localStorage / fetch fallback.
|
|
9
|
+
*/
|
|
10
|
+
export function useHostApiClient(): HostApiClient {
|
|
11
|
+
const api = useHostApi()
|
|
12
|
+
return useMemo(() => createHostApiClient(api), [api])
|
|
13
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { BADGE_TONE_CLASS, type Severity } from '@asteby/metacore-ui/layout'
|
|
2
2
|
import { cn } from '@asteby/metacore-ui/lib'
|
|
3
|
+
import { formatAmount } from '@asteby/metacore-lib'
|
|
3
4
|
import type { CardFieldSpec, CardSpec } from './types'
|
|
4
5
|
|
|
5
6
|
export interface ResolvedCard {
|
|
@@ -10,12 +11,12 @@ export interface ResolvedCard {
|
|
|
10
11
|
meta: { label?: string; value: string }[]
|
|
11
12
|
}
|
|
12
13
|
|
|
13
|
-
function fmt(v: unknown, f: CardFieldSpec['format'] = 'text', locale?: string): string {
|
|
14
|
+
function fmt(v: unknown, f: CardFieldSpec['format'] = 'text', locale?: string, currency?: string): string {
|
|
14
15
|
if (v == null || v === '') return ''
|
|
15
16
|
try {
|
|
16
17
|
if (f === 'number') return new Intl.NumberFormat(locale).format(Number(v))
|
|
17
18
|
if (f === 'percent') return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(Number(v))}%`
|
|
18
|
-
if (f === 'currency') return
|
|
19
|
+
if (f === 'currency') return formatAmount(v as number | string, { currency, locale })
|
|
19
20
|
if (f === 'date') return new Date(String(v)).toLocaleDateString(locale)
|
|
20
21
|
if (f === 'datetime') return new Date(String(v)).toLocaleString(locale)
|
|
21
22
|
} catch {
|
|
@@ -25,7 +26,7 @@ function fmt(v: unknown, f: CardFieldSpec['format'] = 'text', locale?: string):
|
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
/** Pure: row + manifest CardSpec -> display model. Missing fields are skipped, never throw. */
|
|
28
|
-
export function resolveCard(spec: CardSpec, row: Record<string, unknown>, locale?: string): ResolvedCard {
|
|
29
|
+
export function resolveCard(spec: CardSpec, row: Record<string, unknown>, locale?: string, currency?: string): ResolvedCard {
|
|
29
30
|
const bv = spec.badge ? row[spec.badge.field] : undefined
|
|
30
31
|
const key = bv == null ? '' : String(bv)
|
|
31
32
|
return {
|
|
@@ -33,12 +34,12 @@ export function resolveCard(spec: CardSpec, row: Record<string, unknown>, locale
|
|
|
33
34
|
subtitle: spec.subtitle ? fmt(row[spec.subtitle]) || undefined : undefined,
|
|
34
35
|
badge: spec.badge && key ? { text: spec.badge.labels?.[key] ?? key, tone: spec.badge.tones?.[key] ?? 'info' } : undefined,
|
|
35
36
|
chips: (spec.chips ?? []).map((f) => fmt(row[f])).filter(Boolean),
|
|
36
|
-
meta: (spec.meta ?? []).map((m) => ({ label: m.label, value: fmt(row[m.field], m.format, locale) })).filter((m) => m.value),
|
|
37
|
+
meta: (spec.meta ?? []).map((m) => ({ label: m.label, value: fmt(row[m.field], m.format, locale, currency) })).filter((m) => m.value),
|
|
37
38
|
}
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
export function ConfigurableCard({ spec, row, onClick, locale }: { spec: CardSpec; row: Record<string, unknown>; onClick?: () => void; locale?: string }) {
|
|
41
|
-
const c = resolveCard(spec, row, locale)
|
|
41
|
+
export function ConfigurableCard({ spec, row, onClick, locale, currency }: { spec: CardSpec; row: Record<string, unknown>; onClick?: () => void; locale?: string; currency?: string }) {
|
|
42
|
+
const c = resolveCard(spec, row, locale, currency)
|
|
42
43
|
const Tag = onClick ? 'button' : 'div'
|
|
43
44
|
return (
|
|
44
45
|
<Tag
|