Skip to content

Commit 9dfaf6a

Browse files
committed
refactor(json-render-ui): wrap @antfu/design components
Build the reference frontend on @antfu/design's Vue components directly instead of hand-rolled markup, so it tracks the shared design system and stops drifting. - Icon wraps DisplayIconifyRemoteIcon, which fetches with color=currentColor — fixing the reported bug where a button/text icon didn't inherit its color. - Button→ActionButton, Badge→DisplayBadge, Card→LayoutCard, Divider→ LayoutSeparator, TextInput→FormTextInput, Switch→FormSwitch, Progress→DisplayProgressBar, KeyValueTable→DisplayKeyValue. - Stack, Text, CodeBlock, the value-tree Tree, and the row-clickable/loadable DataTable stay bespoke where @antfu/design has no matching primitive. - @antfu/design becomes a peer dependency, kept external in the tsdown build (its .vue is compiled by the consumer's Vite); a *.vue shim resolves types. Consumers exclude it from optimizeDeps and safelist the runtime badge colors. Docs and the minimal-json-render example updated for the consumer setup. Created with the help of an agent.
1 parent abc7854 commit 9dfaf6a

16 files changed

Lines changed: 178 additions & 167 deletions

File tree

‎docs/guide/json-render.md‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,24 @@ there is no live RPC, so the action bridge reports actions as unavailable and
120120
`interactive: false` renders a static-output notice. Local state and bindings
121121
still work.
122122

123-
The reference components author their class strings in `.ts`, so a consuming
124-
app must opt `.ts` into UnoCSS extraction (`content.pipeline.include` for Vite),
125-
and add the lib to the scanned sources when it lives in `node_modules`.
123+
### Consuming the reference frontend
124+
125+
`@devframes/json-render-ui` wraps `@antfu/design`'s Vue components directly
126+
(`ActionButton`, `DisplayBadge`, `LayoutCard`, `FormTextInput`, `FormSwitch`,
127+
`DisplayProgressBar`, `DisplayKeyValue`, and `DisplayIconifyRemoteIcon` for
128+
fully dynamic, `currentColor`-inheriting icons), so it looks and behaves like
129+
the rest of the devframe surfaces. A few catalog components stay bespoke where
130+
`@antfu/design` has no matching primitive — `Stack`, `Text`, `CodeBlock`, the
131+
value-tree `Tree`, and the row-clickable/loadable `DataTable`.
132+
133+
A consuming Vite app therefore:
134+
135+
- installs `@antfu/design` (a peer dependency) and imports `@antfu/design/styles.css`;
136+
- excludes it from dep pre-bundling so `@vitejs/plugin-vue` compiles its SFCs —
137+
`optimizeDeps: { exclude: ['@antfu/design'] }`;
138+
- composes the shared UnoCSS preset (`presetAnthonyDesign`) and safelists the
139+
runtime-selected badge colors the base catalog can emit —
140+
`safelist: ['badge-color-green', 'badge-color-amber', 'badge-color-red', 'badge-color-blue']`.
126141

127142
## Rendering inside a hub
128143

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
11
// Side-effect style imports used by the SPA entry.
22
declare module '*.css' {}
33
declare module 'virtual:uno.css' {}
4+
5+
// @devframes/json-render-ui resolves to source in the workspace, and wraps
6+
// `@antfu/design` `.vue` components — declare the module so `tsc` resolves them.
7+
declare module '*.vue' {
8+
import type { DefineComponent } from 'vue'
9+
10+
const component: DefineComponent<any, any, any>
11+
export default component
12+
}

‎examples/minimal-json-render/src/client/vite.config.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ export default defineConfig({
99
root: fileURLToPath(new URL('.', import.meta.url)),
1010
resolve: { alias },
1111
plugins: [UnoCSS(), vue()],
12+
// `@antfu/design` (pulled in by @devframes/json-render-ui) ships raw `.vue`;
13+
// let @vitejs/plugin-vue compile its SFCs instead of esbuild pre-bundling.
14+
optimizeDeps: { exclude: ['@antfu/design', '@devframes/json-render-ui'] },
1215
build: {
1316
outDir: fileURLToPath(new URL('../../dist/client', import.meta.url)),
1417
emptyOutDir: true,

‎examples/minimal-json-render/uno.config.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ export default defineConfig({
2121
],
2222
transformers: [transformerDirectives(), transformerVariantGroup()],
2323
preflights: [{ getCSS: () => '*,::before,::after{border-color:#8882}' }],
24+
// `Badge` in @devframes/json-render-ui picks a `badge-color-<name>` at runtime
25+
// from a fixed set, so those classes need safelisting.
26+
safelist: ['badge-color-green', 'badge-color-amber', 'badge-color-red', 'badge-color-blue'],
2427
shortcuts: {
2528
'z-nav': 'z-[30]',
2629
'z-dropdown': 'z-[40]',

‎packages/json-render-ui/.storybook/main.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ const config: StorybookConfig = {
1616
return mergeConfig(config, {
1717
resolve: { alias },
1818
plugins: [vue(), UnoCSS()],
19+
// `@antfu/design` ships raw `.vue`; let plugin-vue compile its SFCs.
20+
optimizeDeps: { exclude: ['@antfu/design'] },
1921
server: { allowedHosts: true },
2022
})
2123
},

‎packages/json-render-ui/package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,12 @@
3838
"prepack": "pnpm run build"
3939
},
4040
"peerDependencies": {
41+
"@antfu/design": "^0.3.0",
4142
"@devframes/json-render": "workspace:*",
4243
"vue": "^3.5.0"
4344
},
4445
"dependencies": {
45-
"@json-render/vue": "catalog:frontend",
46-
"dompurify": "catalog:frontend"
46+
"@json-render/vue": "catalog:frontend"
4747
},
4848
"devDependencies": {
4949
"@antfu/design": "catalog:frontend",
Lines changed: 37 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
import type { JrComponent } from './_shared'
2+
import ActionButton from '@antfu/design/components/Action/ActionButton.vue'
3+
import FormSwitch from '@antfu/design/components/Form/FormSwitch.vue'
4+
import FormTextInput from '@antfu/design/components/Form/FormTextInput.vue'
25
import { useBoundProp } from '@json-render/vue'
36
import { h } from 'vue'
47
import { Icon } from './icon'
@@ -12,36 +15,32 @@ interface ButtonProps {
1215
loading?: boolean
1316
}
1417

15-
const buttonBase
16-
= 'inline-flex items-center gap-1.5 rounded px2.5 py1 text-sm font-medium transition disabled:op-50 disabled:cursor-not-allowed'
18+
// Catalog variant → `@antfu/design` ActionButton variant. `danger` has no
19+
// upstream variant, so it renders as `primary` with a red override.
1720
const buttonVariant: Record<string, string> = {
18-
primary: 'bg-primary color-white hover:bg-primary/90',
19-
secondary: 'bg-secondary color-base border border-base hover:bg-active',
20-
ghost: 'color-base hover:bg-secondary',
21-
danger: 'bg-red color-white hover:bg-red/90',
21+
primary: 'primary',
22+
secondary: 'action',
23+
ghost: 'text',
24+
danger: 'primary',
2225
}
2326

2427
export const Button: JrComponent<ButtonProps> = ({ props, on }) => {
25-
const busy = !!props.loading
28+
const variant = props.variant ?? 'secondary'
2629
return h(
27-
'button',
30+
ActionButton,
2831
{
29-
type: 'button',
30-
class: `${buttonBase} ${buttonVariant[props.variant ?? 'secondary'] ?? buttonVariant.secondary}`,
31-
disabled: props.disabled || busy,
32-
onClick: () => {
33-
const handle = on('press')
34-
handle.emit()
35-
},
32+
variant: buttonVariant[variant] ?? 'action',
33+
disabled: props.disabled,
34+
loading: props.loading,
35+
// `danger` isn't an ActionButton variant — override the primary tint.
36+
class: variant === 'danger' ? 'bg-red! color-white! border-red! hover:bg-red/90!' : undefined,
37+
onClick: () => on('press').emit(),
3638
},
37-
[
38-
// Dependency-free CSS spinner (no icon font needed); the dynamic Icon
39-
// resolves the button's icon at runtime, like the standalone Icon.
40-
busy
41-
? h('span', { class: 'inline-block h-3.5 w-3.5 rounded-full border-2 border-current border-t-transparent animate-spin' })
42-
: props.icon
43-
? Icon({ props: { name: props.icon, size: 16 } } as Parameters<typeof Icon>[0])
44-
: null,
39+
// Render the dynamic Icon in the slot (ActionButton's own `icon` prop is a
40+
// static UnoCSS class, unsuited to spec-supplied names). Skip it while
41+
// loading — ActionButton already shows its spinner.
42+
() => [
43+
props.icon && !props.loading ? Icon({ props: { name: props.icon, size: 16 } } as Parameters<typeof Icon>[0]) : null,
4544
props.label ? h('span', props.label) : null,
4645
],
4746
)
@@ -56,23 +55,18 @@ interface TextInputProps {
5655
loading?: boolean
5756
}
5857

59-
const fieldBase
60-
= 'w-full rounded border border-base bg-base color-base px2 py1 text-sm outline-none focus:border-primary disabled:op-50'
61-
6258
export const TextInput: JrComponent<TextInputProps> = ({ props, on, bindings }) => {
6359
const [value, setValue] = useBoundProp(props.value, bindings?.value)
64-
const input = h('input', {
65-
class: fieldBase,
66-
type: props.type ?? 'text',
67-
value: value ?? '',
68-
placeholder: props.placeholder,
69-
disabled: props.disabled || props.loading,
70-
onInput: (e: Event) => {
71-
// Carry the new value into bound state, then fire the `change` action —
72-
// an improvement over the Vite bridge's payload-free `change`.
73-
setValue((e.target as HTMLInputElement).value)
60+
const input = h(FormTextInput, {
61+
'modelValue': value ?? '',
62+
'onUpdate:modelValue': (next: string) => {
63+
// Carry the new value into bound state, then fire the `change` action.
64+
setValue(next)
7465
on('change').emit()
7566
},
67+
'placeholder': props.placeholder,
68+
'type': props.type ?? 'text',
69+
'disabled': props.disabled || props.loading,
7670
})
7771
if (props.label) {
7872
return h('label', { class: 'flex flex-col gap-1 text-sm color-muted' }, [
@@ -91,25 +85,13 @@ interface SwitchProps {
9185

9286
export const Switch: JrComponent<SwitchProps> = ({ props, on, bindings }) => {
9387
const [value, setValue] = useBoundProp(props.value, bindings?.value)
94-
const checked = !!value
95-
const toggle = h('button', {
96-
'type': 'button',
97-
'role': 'switch',
98-
'aria-checked': checked ? 'true' : 'false',
99-
'disabled': props.disabled,
100-
'class': `relative inline-flex h-5 w-9 items-center rounded-full transition disabled:op-50 ${checked ? 'bg-primary' : 'bg-active'}`,
101-
'onClick': () => {
102-
setValue(!checked)
88+
return h(FormSwitch, {
89+
'modelValue': !!value,
90+
'onUpdate:modelValue': (next: boolean) => {
91+
setValue(next)
10392
on('change').emit()
10493
},
105-
}, [
106-
h('span', { class: `inline-block h-4 w-4 transform rounded-full bg-base shadow transition ${checked ? 'translate-x-4.5' : 'translate-x-0.5'}` }),
107-
])
108-
if (props.label) {
109-
return h('label', { class: 'inline-flex items-center gap-2 text-sm color-base cursor-pointer' }, [
110-
toggle,
111-
h('span', props.label),
112-
])
113-
}
114-
return toggle
94+
'label': props.label,
95+
'disabled': props.disabled,
96+
})
11597
}

‎packages/json-render-ui/src/components/data.ts‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import type { VNodeChild } from 'vue'
22
import type { JrComponent } from './_shared'
3+
import DisplayKeyValue from '@antfu/design/components/Display/DisplayKeyValue.vue'
4+
import DisplayProgressBar from '@antfu/design/components/Display/DisplayProgressBar.vue'
35
import { useBoundProp } from '@json-render/vue'
46
import { h } from 'vue'
57
import { toNumber } from './_shared'
@@ -17,17 +19,13 @@ function formatValue(value: unknown): string {
1719
return String(value)
1820
}
1921

22+
// Renders each entry as an `@antfu/design` DisplayKeyValue row.
2023
export const KeyValueTable: JrComponent<KeyValueTableProps> = ({ props, loading }) => {
2124
if (loading || props.loading)
2225
return h('div', { class: 'color-faint text-sm' }, 'Loading…')
2326
const entries = Object.entries(props.data ?? {})
24-
return h('table', { class: 'w-full text-sm border-collapse' }, [
25-
h('tbody', entries.map(([key, value]) =>
26-
h('tr', { class: 'border-b border-base' }, [
27-
h('td', { class: 'py1 pr3 color-muted font-medium align-top' }, key),
28-
h('td', { class: 'py1 color-base font-mono break-all' }, formatValue(value)),
29-
]))),
30-
])
27+
return h('div', { class: 'flex flex-col gap-1' }, entries.map(([key, value]) =>
28+
h(DisplayKeyValue, { key, label: key, value: formatValue(value) })))
3129
}
3230

3331
interface DataTableColumn { key: string, label?: string }
@@ -45,6 +43,9 @@ function normalizeColumns(columns: DataTableProps['columns'], rows: DataTablePro
4543
return first ? Object.keys(first).map(key => ({ key })) : []
4644
}
4745

46+
// `@antfu/design` LayoutDataTable has no per-row click or loading state, both of
47+
// which the catalog requires (`rowClick`, `loading`), so this stays custom on
48+
// the shared tokens. (A candidate to contribute back upstream.)
4849
export const DataTable: JrComponent<DataTableProps> = ({ props, on, bindings, loading }) => {
4950
if (loading || props.loading)
5051
return h('div', { class: 'color-faint text-sm' }, 'Loading…')
@@ -63,8 +64,7 @@ export const DataTable: JrComponent<DataTableProps> = ({ props, on, bindings, lo
6364
h('tr', {
6465
class: 'border-b border-base hover:bg-secondary cursor-pointer',
6566
onClick: () => {
66-
// Deliver row + index into bound state (Vite's rowClick dropped
67-
// them), then fire the action.
67+
// Deliver row + index into bound state, then fire the action.
6868
setSelected({ row, index })
6969
on('rowClick').emit()
7070
},
@@ -80,15 +80,17 @@ interface ProgressProps {
8080
label?: string
8181
}
8282

83+
// Wraps `@antfu/design` DisplayProgressBar (which takes a 0–1 ratio), adding the
84+
// catalog's visible label + percentage row.
8385
export const Progress: JrComponent<ProgressProps> = ({ props }) => {
8486
const max = toNumber(props.max, 100)
8587
const value = toNumber(props.value, 0)
86-
const pct = max > 0 ? Math.min(100, Math.max(0, (value / max) * 100)) : 0
88+
const ratio = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0
8789
return h('div', { class: 'flex flex-col gap-1' }, [
88-
props.label ? h('div', { class: 'flex justify-between text-xs color-muted' }, [h('span', props.label), h('span', `${Math.round(pct)}%`)]) : null,
89-
h('div', { class: 'h-2 w-full rounded-full bg-active overflow-hidden' }, [
90-
h('div', { class: 'h-full rounded-full bg-primary transition-all', style: { width: `${pct}%` } }),
91-
]),
90+
props.label
91+
? h('div', { class: 'flex justify-between text-xs color-muted' }, [h('span', props.label), h('span', `${Math.round(ratio * 100)}%`)])
92+
: null,
93+
h(DisplayProgressBar, { value: ratio, label: props.label }),
9294
])
9395
}
9496

@@ -120,5 +122,7 @@ function renderNode(value: unknown, keyLabel: string | null, expanded: boolean):
120122
])
121123
}
122124

125+
// `@antfu/design` DisplayTree nests a flat path list (file/folder style), not an
126+
// arbitrary JSON value, so the catalog's value-tree viewer stays custom.
123127
export const Tree: JrComponent<TreeProps> = ({ props }) =>
124128
h('div', { class: 'color-base' }, [renderNode(props.data, null, props.defaultExpanded !== false)])
Lines changed: 23 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,29 @@
11
import type { JrComponent } from './_shared'
2-
import DOMPurify from 'dompurify'
3-
import { defineComponent, h, ref, watchEffect } from 'vue'
2+
import DisplayIconifyRemoteIcon from '@antfu/design/components/Display/DisplayIconifyRemoteIcon.vue'
3+
import { h } from 'vue'
44

5-
const ICONIFY_API = 'https://api.iconify.design'
6-
// Sanitize the spec-supplied name before it reaches a URL: Iconify names are
7-
// `prefix:icon`, lowercase alphanumerics plus `-`/`:`.
8-
const SAFE_NAME = /^[a-z0-9]+:[a-z0-9-]+$/
9-
10-
const cache = new Map<string, Promise<string | null>>()
11-
12-
async function fetchIcon(name: string): Promise<string | null> {
13-
if (!SAFE_NAME.test(name))
14-
return null
15-
let promise = cache.get(name)
16-
if (!promise) {
17-
const [prefix, icon] = name.split(':')
18-
promise = fetch(`${ICONIFY_API}/${prefix}/${icon}.svg`)
19-
.then(r => (r.ok ? r.text() : null))
20-
.then(svg => (svg ? DOMPurify.sanitize(svg, { USE_PROFILES: { svg: true, svgFilters: true } }) : null))
21-
.catch(() => null)
22-
cache.set(name, promise)
23-
}
24-
return promise
5+
interface IconProps {
6+
/** Icon name resolved at runtime, e.g. `ph:rocket-launch`. */
7+
name?: string
8+
size?: number
259
}
2610

2711
/**
28-
* Fully dynamic icon: resolves whatever (sanitized) icon name a spec supplies
29-
* at runtime from the Iconify API, with no bundled/preferred set. A deliberate,
30-
* documented deviation from the repo's Phosphor-first convention — that applies
31-
* to a surface's own chrome, not to spec-driven content icons.
12+
* Fully dynamic icon: wraps `@antfu/design`'s `DisplayIconifyRemoteIcon`, which
13+
* fetches the (sanitized) SVG from the Iconify API with `color=currentColor` —
14+
* so the icon inherits the surrounding text color (e.g. white inside a primary
15+
* button). A deliberate, documented deviation from the repo's Phosphor-first
16+
* convention, which governs a surface's own chrome, not spec-driven content
17+
* icons.
3218
*/
33-
const IconImpl = defineComponent({
34-
name: 'JsonRenderIcon',
35-
props: {
36-
name: { type: String, default: '' },
37-
size: { type: Number, default: 16 },
38-
},
39-
setup(props) {
40-
const svg = ref<string | null>(null)
41-
watchEffect(async () => {
42-
svg.value = props.name ? await fetchIcon(props.name) : null
43-
})
44-
return () => h('span', {
45-
'class': 'inline-flex items-center justify-center color-base',
46-
'style': { width: `${props.size}px`, height: `${props.size}px` },
47-
'role': 'img',
48-
'aria-label': props.name,
49-
'innerHTML': svg.value ?? '',
50-
})
51-
},
52-
})
53-
54-
interface IconProps { name?: string, size?: number }
55-
56-
export const Icon: JrComponent<IconProps> = ({ props }) =>
57-
h(IconImpl, { name: props.name ?? '', size: props.size ?? 16 })
19+
export const Icon: JrComponent<IconProps> = ({ props }) => {
20+
const size = props.size ?? 16
21+
return h(
22+
'span',
23+
{
24+
class: 'inline-flex shrink-0 items-center justify-center',
25+
style: { fontSize: `${size}px`, width: `${size}px`, height: `${size}px` },
26+
},
27+
props.name ? [h(DisplayIconifyRemoteIcon, { icon: props.name })] : [],
28+
)
29+
}

0 commit comments

Comments
 (0)