Skip to content

Commit c21588a

Browse files
authored
feat(core): Select and Link components for json-render (#508)
1 parent a2d20bf commit c21588a

10 files changed

Lines changed: 543 additions & 12 deletions

File tree

‎docs/kit/json-render.md‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,22 @@ Clickable button that triggers an action via the `press` event.
414414
{ type: 'Button', props: { icon: 'ph:plus', variant: 'ghost' }, on: { press: { action: 'my-plugin:add' } } }
415415
```
416416

417+
#### Link
418+
419+
Links to `http`, `https` and `mailto` targets — anything else falls back to rendering `label` as plain text.
420+
421+
| Prop | Type | Default | Description |
422+
|------|------|---------|-------------|
423+
| `href` | `string` | — | Link target |
424+
| `label` | `string` | — | Link text (defaults to `href`) |
425+
| `icon` | `string` | — | Iconify icon name |
426+
| `external` | `boolean` | `true` for `http(s)` | Open in a new tab |
427+
428+
<!-- eslint-skip -->
429+
```ts
430+
{ type: 'Link', props: { href: 'https://vite.dev', label: 'Vite docs', icon: 'ph:arrow-square-out' } }
431+
```
432+
417433
#### TextInput
418434

419435
Text input field with optional two-way state binding.
@@ -438,6 +454,38 @@ Text input field with optional two-way state binding.
438454
}
439455
```
440456

457+
#### Select
458+
459+
Dropdown choosing one value from a fixed set of options, with optional two-way state binding.
460+
461+
| Prop | Type | Default | Description |
462+
|------|------|---------|-------------|
463+
| `value` | `string` | — | Current value (use `$bindState` for two-way binding) |
464+
| `options` | `(string \| { value, label?, icon?, description? })[]` | — | Available choices |
465+
| `placeholder` | `string` | — | Shown while `value` is unset |
466+
| `label` | `string` | — | Label shown above the select |
467+
| `disabled` | `boolean` | `false` | Disable interaction |
468+
| `searchable` | `boolean` | `false` | Add a substring filter box to the panel |
469+
470+
**Event**: `change` — fires when the selected value changes.
471+
472+
<!-- eslint-skip -->
473+
```ts
474+
{
475+
type: 'Select',
476+
props: {
477+
label: 'Environment',
478+
value: { $bindState: '/env' },
479+
options: [
480+
{ value: 'dev', label: 'Development' },
481+
{ value: 'staging', label: 'Staging' },
482+
{ value: 'prod', label: 'Production', description: 'Live traffic' },
483+
],
484+
},
485+
on: { change: { action: 'my-plugin:switch-env' } },
486+
}
487+
```
488+
441489
See [State and Two-Way Binding](#state-and-two-way-binding) for a full example.
442490

443491
### Data display

‎packages/core/src/client/webcomponents/components/floating/FloatingPopover.stories.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { Meta, StoryObj } from '@storybook/vue3-vite'
2-
import { defineComponent, h, onMounted, ref, shallowRef } from 'vue'
2+
import { computed, defineComponent, h, onMounted, ref, shallowRef } from 'vue'
33
import FloatingPopover from './FloatingPopover'
44

55
// @unocss-include
@@ -58,6 +58,41 @@ export const MenuContent: Story = {
5858
]), 'Reveal menu'),
5959
}
6060

61+
/**
62+
* A real toggle button drives the popover (rather than the mount-time
63+
* harness the other stories use), to exercise `ignore` — clicking the
64+
* trigger again while open must close it once, not close-then-reopen — and
65+
* `panelClass`, which replaces the default tooltip padding.
66+
*/
67+
export const ToggleTrigger: Story = {
68+
render: () => defineComponent({
69+
setup() {
70+
const triggerEl = ref<HTMLElement | null>(null)
71+
const open = ref(false)
72+
const item = computed(() => (open.value && triggerEl.value)
73+
? { el: triggerEl.value, content: () => h('div', { class: 'flex flex-col gap-0.5 min-w-40' }, [
74+
h('div', { class: 'px2 pt1 pb1.5 op60 text-2.75 uppercase tracking-wide font-medium' }, 'Menu'),
75+
...['Overview', 'Pages', 'Components'].map(label =>
76+
h('button', { class: 'px2 py1.5 rounded text-sm text-left op80 hover:op100 hover:bg-active transition' }, label)),
77+
]) }
78+
: null)
79+
return () => h('div', { class: 'flex items-center justify-center p20 min-h-80 font-sans' }, [
80+
h('button', {
81+
ref: (el: any) => (triggerEl.value = el),
82+
class: 'px3 py1.5 rounded border border-base bg-glass color-base shadow',
83+
onClick: () => (open.value = !open.value),
84+
}, 'Toggle menu'),
85+
h(FloatingPopover, {
86+
item: item.value,
87+
panelClass: '!p0',
88+
ignore: [triggerEl],
89+
onDismiss: () => (open.value = false),
90+
}),
91+
])
92+
},
93+
}),
94+
}
95+
6196
export const CornerAnchors: Story = {
6297
render: () => defineComponent({
6398
setup() {

‎packages/core/src/client/webcomponents/components/floating/FloatingPopover.ts‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
import type { MaybeElementRef } from '@vueuse/core'
12
import type { PropType, VNode } from 'vue'
23
import type { FloatingPopoverProps } from '../../state/floating-tooltip'
34
import { onClickOutside, useDebounceFn, useEventListener } from '@vueuse/core'
4-
import { defineComponent, h, onMounted, onUpdated, reactive, ref, useTemplateRef, watch } from 'vue'
5+
import { defineComponent, h, nextTick, onMounted, onUpdated, reactive, ref, useTemplateRef, watch } from 'vue'
56
import { resolveFloatingPosition } from './floating-position'
67

78
// @unocss-include
@@ -17,6 +18,16 @@ const FloatingPopoverComponent = defineComponent({
1718
type: Boolean,
1819
default: true,
1920
},
21+
/** Appended to the panel's class list — lets a consumer replace the default tooltip padding (e.g. a listbox). */
22+
panelClass: {
23+
type: [String, Array] as PropType<string | string[]>,
24+
required: false,
25+
},
26+
/** Elements `dismissOnClickOutside` should not treat as "outside" — typically the trigger that toggles this popover. */
27+
ignore: {
28+
type: Array as PropType<MaybeElementRef[]>,
29+
required: false,
30+
},
2031
},
2132
emits: ['dismiss'],
2233
setup(props, { emit }) {
@@ -25,6 +36,15 @@ const FloatingPopoverComponent = defineComponent({
2536
const renderCounter = ref(0)
2637

2738
const panelSize = reactive({ width: 0, height: 0 })
39+
// Before the first measurement, `resolveFloatingPosition` centers the panel
40+
// under the anchor via `transform: translateX(-50%)` (it doesn't know the
41+
// panel's real width yet); once measured, it switches to an absolute `left`
42+
// with no transform. Both resolve to the same visual position, but
43+
// transitioning `left` and `transform` independently between them produces
44+
// a visible sideways wobble — so `measured` only flips (re-enabling the
45+
// transition) a tick after `panelSize` updates, letting that one
46+
// size-correcting render apply instantly rather than animate.
47+
const measured = ref(false)
2848

2949
function measurePanel() {
3050
if (!props.item || !panel.value)
@@ -34,6 +54,9 @@ const FloatingPopoverComponent = defineComponent({
3454
panelSize.width = width
3555
panelSize.height = height
3656
}
57+
nextTick(() => {
58+
measured.value = true
59+
})
3760
}
3861

3962
onMounted(measurePanel)
@@ -44,18 +67,26 @@ const FloatingPopoverComponent = defineComponent({
4467
renderCounter.value++
4568
})
4669

70+
// The panel is `position: fixed` against a rect measured at render time, so
71+
// scrolling any ancestor (not just the window) needs to trigger a re-measure.
72+
useEventListener(window, 'scroll', () => {
73+
if (el.value)
74+
renderCounter.value++
75+
}, { capture: true, passive: true })
76+
4777
const clearThrottled = useDebounceFn(() => {
4878
if (props.item?.el == null) {
4979
el.value = undefined
5080
panelSize.width = 0
5181
panelSize.height = 0
82+
measured.value = false
5283
}
5384
}, 800)
5485

5586
if (props.dismissOnClickOutside) {
5687
onClickOutside(panel, () => {
5788
emit('dismiss')
58-
})
89+
}, { ignore: props.ignore })
5990
}
6091

6192
watch(
@@ -84,6 +115,8 @@ const FloatingPopoverComponent = defineComponent({
84115
if (!el.value)
85116
return null
86117

118+
const transitionClass = measured.value ? 'transition-all duration-300' : 'transition-opacity duration-300'
119+
87120
// When dismissing (item is null), keep the last known position
88121
// so the popover fades out in place instead of jumping
89122
if (!props.item) {
@@ -92,8 +125,9 @@ const FloatingPopoverComponent = defineComponent({
92125
{
93126
ref: 'panel',
94127
class: [
95-
'fixed z-floating-tooltip text-xs transition-all duration-300 w-max bg-glass color-base border border-base rounded px2 p1',
128+
`fixed z-floating-tooltip text-xs ${transitionClass} w-max bg-glass color-base border border-base rounded px2 p1`,
96129
'op0 pointer-events-none',
130+
props.panelClass,
97131
],
98132
style: previousStyle,
99133
},
@@ -128,8 +162,9 @@ const FloatingPopoverComponent = defineComponent({
128162
{
129163
ref: 'panel',
130164
class: [
131-
'fixed z-floating-tooltip text-xs transition-all duration-300 w-max bg-glass color-base border border-base rounded px2 p1',
165+
`fixed z-floating-tooltip text-xs ${transitionClass} w-max bg-glass color-base border border-base rounded px2 p1`,
132166
props.item ? 'op100' : 'op0 pointer-events-none',
167+
props.panelClass,
133168
],
134169
style,
135170
},

‎packages/core/src/client/webcomponents/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ export type {
1616
IconProps,
1717
JsonRenderElement,
1818
KeyValueTableProps,
19+
LinkProps,
1920
ProgressProps,
21+
SelectOption,
22+
SelectProps,
2023
StackProps,
2124
SwitchProps,
2225
TabDescriptor,

‎packages/core/src/client/webcomponents/json-render/JsonRender.stories.ts‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ const meta = {
3333
parameters: {
3434
docs: {
3535
description: {
36-
component: 'The json-render primitive registry (`Stack`, `Card`, `Tabs`, `Text`, `Badge`, `Button`, `Icon`, `Divider`, `Switch`, `KeyValueTable`, `DataTable`, `CodeBlock`, `Progress`) rendered from a declarative spec — the same renderer plugins use to build panels without shipping Vue.',
36+
component: 'The json-render primitive registry (`Stack`, `Card`, `Tabs`, `Text`, `Badge`, `Button`, `Link`, `Icon`, `Divider`, `TextInput`, `Select`, `Switch`, `KeyValueTable`, `DataTable`, `CodeBlock`, `Progress`, `Tree`) rendered from a declarative spec — the same renderer plugins use to build panels without shipping Vue.',
3737
},
3838
},
3939
},
@@ -48,7 +48,7 @@ export const Gallery: Story = {
4848
root: 'root',
4949
state: { notifications: true },
5050
elements: {
51-
root: { type: 'Stack', props: { direction: 'column', gap: 16, padding: 4 }, children: ['heading', 'badges', 'buttons', 'progress', 'toggle', 'divider', 'kv', 'table', 'code'] },
51+
root: { type: 'Stack', props: { direction: 'column', gap: 16, padding: 4 }, children: ['heading', 'badges', 'buttons', 'progress', 'toggle', 'select', 'links', 'inputs', 'divider', 'kv', 'table', 'code'] },
5252
heading: { type: 'Text', props: { text: 'Build summary', variant: 'heading' } },
5353
badges: { type: 'Stack', props: { direction: 'row', gap: 8, align: 'center' }, children: ['b1', 'b2', 'b3', 'b4'] },
5454
b1: { type: 'Badge', props: { text: 'passing', variant: 'success' } },
@@ -63,6 +63,23 @@ export const Gallery: Story = {
6363
btn4: { type: 'Button', props: { label: 'Deploying…', variant: 'primary', icon: 'ph:rocket-launch', loading: true } },
6464
progress: { type: 'Progress', props: { value: 68, max: 100, label: 'Bundling' } },
6565
toggle: { type: 'Switch', props: { label: 'Notifications', value: '{{notifications}}' } },
66+
select: { type: 'Select', props: {
67+
label: 'Environment',
68+
placeholder: 'Choose one…',
69+
value: 'staging',
70+
options: [
71+
{ value: 'dev', label: 'Development' },
72+
{ value: 'staging', label: 'Staging' },
73+
{ value: 'prod', label: 'Production', description: 'Live traffic', icon: 'ph:warning' },
74+
],
75+
} },
76+
links: { type: 'Stack', props: { direction: 'row', gap: 16 }, children: ['link', 'rejectedLink'] },
77+
link: { type: 'Link', props: { href: 'https://vite.dev', label: 'Vite docs', icon: 'ph:arrow-square-out' } },
78+
/* `javascript:` is not in the allowed scheme list — this must render as plain text, never as an `<a>`. */
79+
rejectedLink: { type: 'Link', props: { href: 'javascript:alert(1)', label: 'Rejected href (renders as text)' } },
80+
inputs: { type: 'Stack', props: { direction: 'row', gap: 16 }, children: ['search', 'loadingInput'] },
81+
search: { type: 'TextInput', props: { type: 'search', placeholder: 'Filter modules…' } },
82+
loadingInput: { type: 'TextInput', props: { placeholder: 'Saving…', loading: true } },
6683
divider: { type: 'Divider', props: { label: 'Details' } },
6784
kv: { type: 'KeyValueTable', props: { data: {
6885
Vite: '8.1.2',
@@ -184,6 +201,47 @@ export const Tabs: StoryObj<Meta<TabsArgs>> = {
184201
} as unknown as Spec)),
185202
}
186203

204+
/**
205+
* A popover listbox (built on the shared `FloatingPopover` primitive) bound
206+
* to `/region` — open it with a click or ArrowDown, move the highlight with
207+
* Arrow/Home/End, commit with Enter, and Escape to close without changing
208+
* the value. Toggle `searchable` to add a substring filter box to the panel.
209+
*/
210+
interface SelectArgs {
211+
placeholder: string
212+
disabled: boolean
213+
searchable: boolean
214+
}
215+
216+
export const Select: StoryObj<Meta<SelectArgs>> = {
217+
argTypes: {
218+
placeholder: { control: 'text' },
219+
disabled: { control: 'boolean' },
220+
searchable: { control: 'boolean' },
221+
},
222+
args: { placeholder: 'Choose a region…', disabled: false, searchable: true },
223+
render: args => renderSpec(() => ({
224+
root: 'root',
225+
state: { region: undefined },
226+
elements: {
227+
root: { type: 'Select', props: {
228+
label: 'Region',
229+
placeholder: args.placeholder,
230+
disabled: args.disabled,
231+
searchable: args.searchable,
232+
value: { $bindState: '/region' },
233+
options: [
234+
{ value: 'us-east-1', label: 'US East (N. Virginia)' },
235+
{ value: 'us-west-2', label: 'US West (Oregon)' },
236+
{ value: 'eu-west-1', label: 'Europe (Ireland)' },
237+
{ value: 'eu-west-3', label: 'Europe (Paris)', description: 'Lowest latency from CDG' },
238+
{ value: 'ap-southeast-1', label: 'Asia Pacific (Singapore)' },
239+
],
240+
} },
241+
},
242+
} as unknown as Spec)),
243+
}
244+
187245
/**
188246
* An element whose `type` has no entry in the registry — e.g. authored
189247
* against a newer base-catalog version than this client implements, or a
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { defineComponent, h } from 'vue'
2+
import DockIcon from '../../components/dock/DockIcon.vue'
3+
import { primary } from './tokens'
4+
import { registryProps } from './types'
5+
6+
const ALLOWED_SCHEMES = new Set(['http:', 'https:', 'mailto:'])
7+
8+
export interface LinkProps {
9+
href?: string
10+
label?: string
11+
/** Iconify name, rendered before the label. */
12+
icon?: string
13+
/** Open in a new tab. Defaults to `true` for `http(s)` URLs. */
14+
external?: boolean
15+
}
16+
17+
/**
18+
* Specs can come from a streamed/model-generated source (`@json-render/core`'s
19+
* `compileSpecStream`), and the client can run embedded in a host page — so a
20+
* `javascript:` href here would execute in that page. Only resolve to an
21+
* anchor for schemes that can't run script.
22+
*/
23+
function resolveHref(href: string | undefined): string | undefined {
24+
if (!href)
25+
return undefined
26+
try {
27+
const url = new URL(href, location.href)
28+
return ALLOWED_SCHEMES.has(url.protocol) ? href : undefined
29+
}
30+
catch {
31+
return undefined
32+
}
33+
}
34+
35+
export const Link = defineComponent({
36+
name: 'JrLink',
37+
props: registryProps<'Link', LinkProps>(),
38+
setup(ctx) {
39+
return () => {
40+
const { label, icon, external } = ctx.element.props
41+
const href = resolveHref(ctx.element.props.href)
42+
const content = [
43+
icon ? h(DockIcon, { icon, class: 'w-3.5 h-3.5' }) : null,
44+
h('span', label ?? href),
45+
]
46+
47+
if (!href) {
48+
return h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: '6px' } }, content)
49+
}
50+
51+
const openInNewTab = external ?? href.startsWith('http')
52+
53+
return h('a', {
54+
href,
55+
target: openInNewTab ? '_blank' : undefined,
56+
rel: openInNewTab ? 'noopener noreferrer' : undefined,
57+
style: {
58+
display: 'inline-flex',
59+
alignItems: 'center',
60+
gap: '6px',
61+
color: primary,
62+
textDecoration: 'none',
63+
},
64+
onMouseenter: (e: MouseEvent) => { (e.currentTarget as HTMLElement).style.textDecoration = 'underline' },
65+
onMouseleave: (e: MouseEvent) => { (e.currentTarget as HTMLElement).style.textDecoration = 'none' },
66+
}, content)
67+
}
68+
},
69+
})

0 commit comments

Comments
 (0)