@stacksjs/components 0.2.991 → 0.2.997
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/dist/ApiOperation-369y1zgt.stx +114 -0
- package/dist/ApiReference-ww45jj32.stx +92 -0
- package/dist/ApiSchema-dsx4tsv4.stx +47 -0
- package/dist/AreaChart-8fy34adp.stx +77 -0
- package/dist/BarChart-4xdrjhhn.stx +77 -0
- package/dist/{Combobox-9n04ec5w.stx → Combobox-fgbpxbty.stx} +174 -5
- package/dist/ComboboxOptions-sfkc98a9.stx +36 -0
- package/dist/{CommandPalette-cj6pe5ph.stx → CommandPalette-sf03s7b2.stx} +3 -1
- package/dist/LineChart-ctebkkm8.stx +77 -0
- package/dist/{Notification-ke5vw4k8.stx → Notification-1pvt347q.stx} +11 -3
- package/dist/{Popover-jjt7p7sn.stx → Popover-gntg33xd.stx} +1 -1
- package/dist/PricingPlan-h7jt2696.stx +67 -0
- package/dist/PricingTable-v3vdn6av.stx +149 -0
- package/dist/SecretField-q2xgth94.stx +219 -0
- package/dist/{Select-36s22z6d.stx → Select-yhmtvqcx.stx} +7 -4
- package/dist/Sparkline-gp859n4h.stx +29 -0
- package/dist/StatCard-gff0yx6b.stx +93 -0
- package/dist/StatGroup-e0d5dmt7.stx +17 -0
- package/dist/components/CodeBlock.d.ts +4 -1
- package/dist/components/CodeGroup.d.ts +34 -0
- package/dist/components/code-group.d.ts +19 -0
- package/dist/components/index.d.ts +2 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +25 -22
- package/dist/ui/api-reference/ApiOperation.d.ts +17 -0
- package/dist/ui/api-reference/ApiReference.d.ts +28 -0
- package/dist/ui/api-reference/ApiSchema.d.ts +17 -0
- package/dist/ui/api-reference/index.d.ts +30 -0
- package/dist/ui/api-reference/openapi.d.ts +137 -0
- package/dist/ui/chart/AreaChart.d.ts +33 -0
- package/dist/ui/chart/BarChart.d.ts +33 -0
- package/dist/ui/chart/LineChart.d.ts +33 -0
- package/dist/ui/chart/Sparkline.d.ts +19 -0
- package/dist/ui/chart/core.d.ts +111 -0
- package/dist/ui/chart/index.d.ts +51 -0
- package/dist/ui/chart/interaction.d.ts +11 -0
- package/dist/ui/combobox/Combobox.d.ts +10 -1
- package/dist/ui/combobox/ComboboxOptions.d.ts +6 -0
- package/dist/ui/combobox/index.d.ts +7 -0
- package/dist/ui/command-palette/CommandPalette.d.ts +2 -0
- package/dist/ui/input/SecretField.d.ts +56 -0
- package/dist/ui/input/index.d.ts +21 -0
- package/dist/ui/notification/Notification.d.ts +2 -0
- package/dist/ui/pricing/PricingPlan.d.ts +21 -0
- package/dist/ui/pricing/PricingTable.d.ts +50 -0
- package/dist/ui/pricing/index.d.ts +38 -0
- package/dist/ui/pricing/pricing.d.ts +64 -0
- package/dist/ui/select/Select.d.ts +2 -0
- package/dist/ui/stat/StatCard.d.ts +42 -0
- package/dist/ui/stat/StatGroup.d.ts +12 -0
- package/dist/ui/stat/format.d.ts +37 -0
- package/dist/ui/stat/index.d.ts +23 -0
- package/package.json +3 -3
- package/src/components/CodeBlock.stx +4 -1
- package/src/components/CodeGroup.stx +217 -0
- package/src/components/code-group.ts +57 -0
- package/src/components/index.ts +2 -0
- package/src/index.ts +18 -0
- package/src/ui/api-reference/ApiOperation.stx +114 -0
- package/src/ui/api-reference/ApiReference.stx +92 -0
- package/src/ui/api-reference/ApiSchema.stx +47 -0
- package/src/ui/api-reference/README.md +44 -0
- package/src/ui/api-reference/index.ts +35 -0
- package/src/ui/api-reference/openapi.ts +825 -0
- package/src/ui/chart/AreaChart.stx +77 -0
- package/src/ui/chart/BarChart.stx +77 -0
- package/src/ui/chart/LineChart.stx +77 -0
- package/src/ui/chart/README.md +97 -0
- package/src/ui/chart/Sparkline.stx +29 -0
- package/src/ui/chart/core.ts +730 -0
- package/src/ui/chart/index.ts +71 -0
- package/src/ui/chart/interaction.ts +175 -0
- package/src/ui/combobox/Combobox.stx +174 -5
- package/src/ui/combobox/ComboboxOptions.stx +20 -0
- package/src/ui/combobox/README.md +41 -0
- package/src/ui/combobox/index.ts +13 -0
- package/src/ui/command-palette/CommandPalette.stx +3 -1
- package/src/ui/input/SecretField.stx +219 -0
- package/src/ui/input/index.ts +32 -0
- package/src/ui/notification/Notification.stx +11 -3
- package/src/ui/popover/Popover.stx +1 -1
- package/src/ui/pricing/PricingPlan.stx +67 -0
- package/src/ui/pricing/PricingTable.stx +149 -0
- package/src/ui/pricing/README.md +74 -0
- package/src/ui/pricing/index.ts +49 -0
- package/src/ui/pricing/pricing.ts +177 -0
- package/src/ui/select/Select.stx +7 -4
- package/src/ui/stat/README.md +60 -0
- package/src/ui/stat/StatCard.stx +93 -0
- package/src/ui/stat/StatGroup.stx +17 -0
- package/src/ui/stat/format.ts +147 -0
- package/src/ui/stat/index.ts +38 -0
- package/dist/ComboboxOptions-zhr9b6rx.stx +0 -16
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Accessor, ChartCurve, ChartSeriesInput, ChartXType, Formatter } from './core'
|
|
2
|
+
|
|
3
|
+
export { default as AreaChart } from './AreaChart.stx'
|
|
4
|
+
export { default as BarChart } from './BarChart.stx'
|
|
5
|
+
export { default as LineChart } from './LineChart.stx'
|
|
6
|
+
export { default as Sparkline } from './Sparkline.stx'
|
|
7
|
+
export {
|
|
8
|
+
buildChartModel,
|
|
9
|
+
type ChartInput,
|
|
10
|
+
type ChartModel,
|
|
11
|
+
type ChartSeries,
|
|
12
|
+
type ChartTick,
|
|
13
|
+
type ChartType,
|
|
14
|
+
renderChartSvg,
|
|
15
|
+
} from './core'
|
|
16
|
+
export type { HoverDetail } from './interaction'
|
|
17
|
+
export type { Accessor, ChartCurve, ChartSeriesInput, ChartXType, Formatter }
|
|
18
|
+
|
|
19
|
+
export interface ChartProps {
|
|
20
|
+
/** The records, or a plain array of numbers. */
|
|
21
|
+
data: unknown[]
|
|
22
|
+
/** Key or function for x. Default `x`; the index for a number array. */
|
|
23
|
+
x?: Accessor
|
|
24
|
+
/** Key or function for y; an array of keys draws a series per key. Default `y`. */
|
|
25
|
+
y?: Accessor | Accessor[]
|
|
26
|
+
/** Series as keys or `{ key, label, color }`. Overrides `y`. */
|
|
27
|
+
series?: Array<Accessor | ChartSeriesInput>
|
|
28
|
+
/** Pixel height. Default 240. */
|
|
29
|
+
height?: number
|
|
30
|
+
/** Inferred: `band` for bars and string x, `time` for dates, else `linear`. */
|
|
31
|
+
xType?: ChartXType
|
|
32
|
+
/** `[min, max]`; a `null` end is taken from the data. */
|
|
33
|
+
yDomain?: [number | null, number | null]
|
|
34
|
+
/** Default `monotone` (`linear` for bars). */
|
|
35
|
+
curve?: ChartCurve
|
|
36
|
+
/** Series colours; defaults to the accent, info, success, warning, danger and secondary roles. */
|
|
37
|
+
colors?: string[]
|
|
38
|
+
/** Tick and tooltip labels: a function, or for y a stat format (`number`, `percent`, `duration`, `bytes`, `currency`). */
|
|
39
|
+
formatX?: Formatter
|
|
40
|
+
formatY?: Formatter
|
|
41
|
+
/** The accessible name. */
|
|
42
|
+
label?: string
|
|
43
|
+
/** Header of the x column in the text alternative. */
|
|
44
|
+
xLabel?: string
|
|
45
|
+
locale?: string
|
|
46
|
+
/** Zone for time labels. Default `UTC`. */
|
|
47
|
+
timeZone?: string
|
|
48
|
+
/** Approximate ticks per axis. Default 5. */
|
|
49
|
+
ticks?: number
|
|
50
|
+
loading?: boolean
|
|
51
|
+
emptyText?: string
|
|
52
|
+
id?: string
|
|
53
|
+
className?: string
|
|
54
|
+
/** The active datum as the pointer or keyboard moves; `null` when it leaves. */
|
|
55
|
+
onHover?: (detail: import('./interaction').HoverDetail | null) => void
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface SparklineProps {
|
|
59
|
+
data: unknown[]
|
|
60
|
+
x?: Accessor
|
|
61
|
+
y?: Accessor
|
|
62
|
+
label?: string
|
|
63
|
+
/** Pixel height. Default 32. */
|
|
64
|
+
height?: number
|
|
65
|
+
/** Fill under the line. */
|
|
66
|
+
area?: boolean
|
|
67
|
+
curve?: ChartCurve
|
|
68
|
+
colors?: string[]
|
|
69
|
+
formatY?: Formatter
|
|
70
|
+
className?: string
|
|
71
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client half of a chart (stacksjs/stx#2318): everything the server
|
|
3
|
+
* cannot do. The SVG is already on the page; this lays it out again at the
|
|
4
|
+
* container's real width, and adds the crosshair, the tooltip and keyboard
|
|
5
|
+
* stepping, reporting the active datum through `onHover`.
|
|
6
|
+
*/
|
|
7
|
+
import type { ChartModel } from './core'
|
|
8
|
+
import { describeDatum, layoutChart, nearestIndex, renderChartSvg } from './core'
|
|
9
|
+
|
|
10
|
+
export interface HoverDetail {
|
|
11
|
+
index: number
|
|
12
|
+
datum: unknown
|
|
13
|
+
x: string
|
|
14
|
+
values: Array<{ series: string, value: number | null, label: string }>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface MountOptions {
|
|
18
|
+
onHover?: (detail: HoverDetail | null) => void
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function mountChart(root: HTMLElement, model: ChartModel, options: MountOptions = {}): () => void {
|
|
22
|
+
const surface = root.querySelector<HTMLElement>('[data-stx-chart-surface]')
|
|
23
|
+
const tooltip = root.querySelector<HTMLElement>('[data-stx-chart-tooltip]')
|
|
24
|
+
const live = root.querySelector<HTMLElement>('[data-stx-chart-live]')
|
|
25
|
+
if (!surface || !model.xs.length)
|
|
26
|
+
return () => {}
|
|
27
|
+
|
|
28
|
+
let width = Number(surface.querySelector('svg')?.getAttribute('data-chart-width')) || 0
|
|
29
|
+
let active = -1
|
|
30
|
+
|
|
31
|
+
function svg(): SVGSVGElement | null {
|
|
32
|
+
return surface!.querySelector('svg')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function render(next: number): void {
|
|
36
|
+
if (!next || Math.abs(next - width) < 1)
|
|
37
|
+
return
|
|
38
|
+
width = next
|
|
39
|
+
// The model's strings are escaped by renderChartSvg; marked inert so the
|
|
40
|
+
// runtime never reads a datum's braces as an expression.
|
|
41
|
+
surface!.innerHTML = renderChartSvg(model, width)
|
|
42
|
+
;(surface as unknown as { __stx_inert_content?: boolean }).__stx_inert_content = true
|
|
43
|
+
if (active >= 0)
|
|
44
|
+
show(active, false)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function show(index: number, announce: boolean): void {
|
|
48
|
+
const el = svg()
|
|
49
|
+
if (!el || index < 0 || index >= model.xs.length)
|
|
50
|
+
return
|
|
51
|
+
active = index
|
|
52
|
+
const layout = layoutChart(model, width || el.viewBox.baseVal.width || 640)
|
|
53
|
+
const x = layout.x(index)
|
|
54
|
+
const focus = el.querySelector('[data-chart-focus]')
|
|
55
|
+
const crosshair = el.querySelector('[data-chart-crosshair]')
|
|
56
|
+
if (crosshair) {
|
|
57
|
+
crosshair.setAttribute('x1', String(x))
|
|
58
|
+
crosshair.setAttribute('x2', String(x))
|
|
59
|
+
}
|
|
60
|
+
model.series.forEach((s, si) => {
|
|
61
|
+
const marker = el.querySelector(`[data-chart-marker="${si}"]`)
|
|
62
|
+
if (!marker)
|
|
63
|
+
return
|
|
64
|
+
const v = s.values[index]
|
|
65
|
+
if (v === null || v === undefined || model.type === 'bar') {
|
|
66
|
+
marker.setAttribute('visibility', 'hidden')
|
|
67
|
+
return
|
|
68
|
+
}
|
|
69
|
+
marker.setAttribute('visibility', 'visible')
|
|
70
|
+
marker.setAttribute('cx', String(x))
|
|
71
|
+
marker.setAttribute('cy', String(layout.y(v)))
|
|
72
|
+
})
|
|
73
|
+
focus?.setAttribute('visibility', 'visible')
|
|
74
|
+
|
|
75
|
+
const text = describeDatum(model, index)
|
|
76
|
+
if (tooltip) {
|
|
77
|
+
tooltip.textContent = ''
|
|
78
|
+
const heading = document.createElement('div')
|
|
79
|
+
heading.className = 'font-medium'
|
|
80
|
+
heading.textContent = model.xLabels[index] ?? ''
|
|
81
|
+
tooltip.appendChild(heading)
|
|
82
|
+
for (const s of model.series) {
|
|
83
|
+
const row = document.createElement('div')
|
|
84
|
+
row.className = 'flex items-center gap-2'
|
|
85
|
+
const swatch = document.createElement('span')
|
|
86
|
+
swatch.setAttribute('aria-hidden', 'true')
|
|
87
|
+
swatch.className = 'inline-block h-2 w-2 rounded-full'
|
|
88
|
+
swatch.style.background = s.color
|
|
89
|
+
row.appendChild(swatch)
|
|
90
|
+
row.appendChild(document.createTextNode(`${s.label}: ${s.labels[index] ?? '—'}`))
|
|
91
|
+
tooltip.appendChild(row)
|
|
92
|
+
}
|
|
93
|
+
;(tooltip as unknown as { __stx_inert_content?: boolean }).__stx_inert_content = true
|
|
94
|
+
tooltip.hidden = false
|
|
95
|
+
// Placed in the surface's own pixels: the svg is drawn 1:1 once laid out.
|
|
96
|
+
const scale = el.getBoundingClientRect().width / (width || 1) || 1
|
|
97
|
+
const left = x * scale
|
|
98
|
+
const flip = left > (surface!.clientWidth || width) * 0.6
|
|
99
|
+
tooltip.style.left = `${Math.round(left)}px`
|
|
100
|
+
tooltip.style.transform = flip ? 'translate(calc(-100% - 12px), 0)' : 'translate(12px, 0)'
|
|
101
|
+
}
|
|
102
|
+
if (announce && live)
|
|
103
|
+
live.textContent = text
|
|
104
|
+
|
|
105
|
+
options.onHover?.({
|
|
106
|
+
index,
|
|
107
|
+
datum: model.data[index],
|
|
108
|
+
x: model.xLabels[index] ?? '',
|
|
109
|
+
values: model.series.map(s => ({ series: s.label, value: s.values[index] ?? null, label: s.labels[index] ?? '—' })),
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function clear(): void {
|
|
114
|
+
if (active < 0)
|
|
115
|
+
return
|
|
116
|
+
active = -1
|
|
117
|
+
svg()?.querySelector('[data-chart-focus]')?.setAttribute('visibility', 'hidden')
|
|
118
|
+
if (tooltip)
|
|
119
|
+
tooltip.hidden = true
|
|
120
|
+
options.onHover?.(null)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function onPointer(event: PointerEvent | MouseEvent): void {
|
|
124
|
+
const el = svg()
|
|
125
|
+
if (!el)
|
|
126
|
+
return
|
|
127
|
+
const rect = el.getBoundingClientRect()
|
|
128
|
+
const scale = rect.width ? (width || rect.width) / rect.width : 1
|
|
129
|
+
const layout = layoutChart(model, width || rect.width || 640)
|
|
130
|
+
const index = nearestIndex(model, layout, (event.clientX - rect.left) * scale)
|
|
131
|
+
if (index !== active)
|
|
132
|
+
show(index, false)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function onKey(event: KeyboardEvent): void {
|
|
136
|
+
const last = model.xs.length - 1
|
|
137
|
+
let next = -1
|
|
138
|
+
if (event.key === 'ArrowRight' || event.key === 'ArrowUp')
|
|
139
|
+
next = active < 0 ? 0 : Math.min(last, active + 1)
|
|
140
|
+
else if (event.key === 'ArrowLeft' || event.key === 'ArrowDown')
|
|
141
|
+
next = active < 0 ? last : Math.max(0, active - 1)
|
|
142
|
+
else if (event.key === 'Home')
|
|
143
|
+
next = 0
|
|
144
|
+
else if (event.key === 'End')
|
|
145
|
+
next = last
|
|
146
|
+
else if (event.key === 'Escape') {
|
|
147
|
+
clear()
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
if (next < 0)
|
|
151
|
+
return
|
|
152
|
+
event.preventDefault()
|
|
153
|
+
show(next, true)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
surface.addEventListener('pointermove', onPointer)
|
|
157
|
+
surface.addEventListener('pointerleave', clear)
|
|
158
|
+
root.addEventListener('keydown', onKey)
|
|
159
|
+
root.addEventListener('blur', clear)
|
|
160
|
+
|
|
161
|
+
let observer: ResizeObserver | null = null
|
|
162
|
+
if (typeof ResizeObserver !== 'undefined') {
|
|
163
|
+
observer = new ResizeObserver(() => render(Math.round(surface.clientWidth)))
|
|
164
|
+
observer.observe(surface)
|
|
165
|
+
}
|
|
166
|
+
render(Math.round(surface.clientWidth))
|
|
167
|
+
|
|
168
|
+
return () => {
|
|
169
|
+
observer?.disconnect()
|
|
170
|
+
surface.removeEventListener('pointermove', onPointer)
|
|
171
|
+
surface.removeEventListener('pointerleave', clear)
|
|
172
|
+
root.removeEventListener('keydown', onKey)
|
|
173
|
+
root.removeEventListener('blur', clear)
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -3,6 +3,15 @@ export const value = $props.value
|
|
|
3
3
|
export const valueJson = JSON.stringify(value === undefined ? null : value)
|
|
4
4
|
export const className = $props.className || ''
|
|
5
5
|
export const as = $props.as || 'div'
|
|
6
|
+
/*
|
|
7
|
+
* Remote suggestions (stacksjs/stx#2319). `source` is a client function,
|
|
8
|
+
* `(query, { signal }) => Promise<Option[]>`, so it can only arrive through a
|
|
9
|
+
* bound attribute (`:source="search"`) and the client reads it live. These are
|
|
10
|
+
* the knobs around it.
|
|
11
|
+
*/
|
|
12
|
+
export const debounce = $num($props.debounce, 150)
|
|
13
|
+
export const minLength = $num($props.minLength, 1)
|
|
14
|
+
export const limit = $num($props.limit, 0)
|
|
6
15
|
|
|
7
16
|
const baseClasses = 'relative'
|
|
8
17
|
export const comboboxClasses = `${baseClasses} ${className}`.trim()
|
|
@@ -25,6 +34,26 @@ const comboboxInstanceId = {{ comboboxInstanceId }}
|
|
|
25
34
|
* (stacksjs/stx#1981).
|
|
26
35
|
*/
|
|
27
36
|
const initialValue = {!! valueJson !!}
|
|
37
|
+
const liveSource = useReactiveProp('source', null, { parse: v => v })
|
|
38
|
+
const isRemote = () => typeof liveSource() === 'function'
|
|
39
|
+
/*
|
|
40
|
+
* The WHEN of remote suggestions (debounce, abort, out-of-order answers) is
|
|
41
|
+
* useSuggestions; this file draws what it answers into the options panel.
|
|
42
|
+
*/
|
|
43
|
+
const remote = useSuggestions({
|
|
44
|
+
source: (q, ctx) => {
|
|
45
|
+
const source = liveSource()
|
|
46
|
+
return typeof source === 'function' ? source(q, ctx) : []
|
|
47
|
+
},
|
|
48
|
+
debounceMs: {{ debounce }},
|
|
49
|
+
minLength: {{ minLength }},
|
|
50
|
+
limit: {{ limit }} > 0 ? {{ limit }} : undefined,
|
|
51
|
+
onSearch: q => emit('search', q),
|
|
52
|
+
onResults: (q, options) => emit('results', q, options),
|
|
53
|
+
onError: (error, q) => emit('error', error, q),
|
|
54
|
+
})
|
|
55
|
+
/* The value each rendered remote option selects, by element. */
|
|
56
|
+
const remoteValues = new WeakMap()
|
|
28
57
|
|
|
29
58
|
const isOpen = state(false)
|
|
30
59
|
const selected = state(initialValue)
|
|
@@ -58,10 +87,13 @@ function syncOptionStates() {
|
|
|
58
87
|
if (!rootEl) return
|
|
59
88
|
const options = rootEl.querySelectorAll('[data-stx-combobox-option]')
|
|
60
89
|
for (const opt of options) {
|
|
61
|
-
const raw = opt.dataset.optionValue
|
|
62
90
|
let v
|
|
63
|
-
|
|
64
|
-
|
|
91
|
+
if (remoteValues.has(opt)) v = remoteValues.get(opt)
|
|
92
|
+
else {
|
|
93
|
+
const raw = opt.dataset.optionValue
|
|
94
|
+
try { v = JSON.parse(raw ?? 'null') }
|
|
95
|
+
catch { v = raw }
|
|
96
|
+
}
|
|
65
97
|
const sel = isSelectedValue(v)
|
|
66
98
|
opt.setAttribute('aria-selected', sel ? 'true' : 'false')
|
|
67
99
|
opt.setAttribute('data-selected', sel ? 'true' : 'false')
|
|
@@ -198,8 +230,126 @@ function onQuery(event) {
|
|
|
198
230
|
syncActiveOption()
|
|
199
231
|
if (!isOpen()) open()
|
|
200
232
|
emit('query', event.detail)
|
|
233
|
+
if (isRemote()) remote.search(event.detail)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/*
|
|
237
|
+
* Remote options are plain strings or `{ value, label, description, disabled }`.
|
|
238
|
+
* An object without `value` selects itself, so a geocoder result keeps its
|
|
239
|
+
* coordinates through the change event.
|
|
240
|
+
*/
|
|
241
|
+
function optionLabel(option) {
|
|
242
|
+
if (option == null) return ''
|
|
243
|
+
if (typeof option !== 'object') return String(option)
|
|
244
|
+
if (option.label != null) return String(option.label)
|
|
245
|
+
if (option.name != null) return String(option.name)
|
|
246
|
+
return option.value != null ? String(option.value) : ''
|
|
247
|
+
}
|
|
248
|
+
function optionValue(option) {
|
|
249
|
+
if (option != null && typeof option === 'object' && 'value' in option) return option.value
|
|
250
|
+
return option
|
|
201
251
|
}
|
|
202
252
|
|
|
253
|
+
/*
|
|
254
|
+
* Draw the remote results into the options panel, after any static options,
|
|
255
|
+
* with text nodes only: a suggestion is data and is never parsed as markup.
|
|
256
|
+
*/
|
|
257
|
+
function renderRemote() {
|
|
258
|
+
if (!rootEl) return
|
|
259
|
+
const list = rootEl.querySelector('[data-stx-combobox-options]')
|
|
260
|
+
if (!list) return
|
|
261
|
+
for (const old of list.querySelectorAll('[data-stx-combobox-remote]')) old.remove()
|
|
262
|
+
const results = remote.results()
|
|
263
|
+
const tag = list.tagName === 'UL' || list.tagName === 'OL' ? 'li' : 'div'
|
|
264
|
+
const anchor = list.querySelector('[data-stx-combobox-status]')
|
|
265
|
+
const doc = rootEl.ownerDocument
|
|
266
|
+
for (const option of results) {
|
|
267
|
+
const el = doc.createElement(tag)
|
|
268
|
+
el.className = 'relative cursor-pointer select-none py-2 pl-10 pr-4 text-fg hover:bg-accent-soft'
|
|
269
|
+
el.setAttribute('data-stx-combobox-option', '')
|
|
270
|
+
el.setAttribute('data-stx-combobox-remote', '')
|
|
271
|
+
el.setAttribute('role', 'option')
|
|
272
|
+
el.setAttribute('aria-selected', 'false')
|
|
273
|
+
const disabled = !!(option && typeof option === 'object' && option.disabled)
|
|
274
|
+
if (disabled) {
|
|
275
|
+
el.setAttribute('aria-disabled', 'true')
|
|
276
|
+
el.className += ' opacity-50 cursor-not-allowed'
|
|
277
|
+
}
|
|
278
|
+
const check = doc.createElement('span')
|
|
279
|
+
check.className = 'absolute inset-y-0 left-0 flex items-center pl-3 text-accent'
|
|
280
|
+
check.setAttribute('data-stx-combobox-check', '')
|
|
281
|
+
check.setAttribute('aria-hidden', 'true')
|
|
282
|
+
const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg')
|
|
283
|
+
svg.setAttribute('class', 'h-5 w-5')
|
|
284
|
+
svg.setAttribute('viewBox', '0 0 20 20')
|
|
285
|
+
svg.setAttribute('fill', 'currentColor')
|
|
286
|
+
const path = doc.createElementNS('http://www.w3.org/2000/svg', 'path')
|
|
287
|
+
path.setAttribute('fill-rule', 'evenodd')
|
|
288
|
+
path.setAttribute('clip-rule', 'evenodd')
|
|
289
|
+
path.setAttribute('d', 'M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z')
|
|
290
|
+
svg.appendChild(path)
|
|
291
|
+
check.appendChild(svg)
|
|
292
|
+
el.appendChild(check)
|
|
293
|
+
const label = doc.createElement('span')
|
|
294
|
+
label.className = 'block truncate'
|
|
295
|
+
label.textContent = optionLabel(option)
|
|
296
|
+
el.appendChild(label)
|
|
297
|
+
if (option && typeof option === 'object' && option.description != null) {
|
|
298
|
+
const description = doc.createElement('span')
|
|
299
|
+
description.className = 'block truncate text-xs text-fg-soft'
|
|
300
|
+
description.textContent = String(option.description)
|
|
301
|
+
el.appendChild(description)
|
|
302
|
+
}
|
|
303
|
+
const value = optionValue(option)
|
|
304
|
+
remoteValues.set(el, value)
|
|
305
|
+
el.addEventListener('click', (event) => {
|
|
306
|
+
if (disabled) return
|
|
307
|
+
const input = rootEl && rootEl.querySelector('[data-stx-combobox-input]')
|
|
308
|
+
if (input) input.value = optionLabel(option)
|
|
309
|
+
event.currentTarget.dispatchEvent(new CustomEvent('stx:combobox-select', { bubbles: true, detail: value }))
|
|
310
|
+
})
|
|
311
|
+
list.insertBefore(el, anchor)
|
|
312
|
+
}
|
|
313
|
+
activeIndex.set(-1)
|
|
314
|
+
syncOptionStates()
|
|
315
|
+
syncActiveOption()
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/*
|
|
319
|
+
* Which of the panel's states is showing: `idle` (no query yet, panel hidden),
|
|
320
|
+
* `loading`, `results`, `empty` or `error`. The slots in <ComboboxOptions>
|
|
321
|
+
* are shown by CSS on this attribute; the live region says the same thing
|
|
322
|
+
* once, politely, since the status rows are hidden from the accessibility
|
|
323
|
+
* tree to keep the listbox to its options.
|
|
324
|
+
*/
|
|
325
|
+
const asyncState = derived(() => {
|
|
326
|
+
if (!isRemote()) return ''
|
|
327
|
+
if (remote.loading()) return remote.results().length ? 'results' : 'loading'
|
|
328
|
+
if (remote.error()) return 'error'
|
|
329
|
+
if (remote.empty()) return 'empty'
|
|
330
|
+
return remote.results().length ? 'results' : 'idle'
|
|
331
|
+
})
|
|
332
|
+
const announcement = derived(() => {
|
|
333
|
+
if (!isRemote() || remote.loading()) return ''
|
|
334
|
+
if (remote.error()) return 'Suggestions could not be loaded.'
|
|
335
|
+
if (remote.empty()) return 'No results.'
|
|
336
|
+
const count = remote.results().length
|
|
337
|
+
if (!count) return ''
|
|
338
|
+
return count === 1 ? '1 result available.' : count + ' results available.'
|
|
339
|
+
})
|
|
340
|
+
|
|
341
|
+
// A subscription, not an effect: only the results decide when to redraw, and
|
|
342
|
+
// an effect would also track the active index the redraw reads and resets.
|
|
343
|
+
// Managed in onMount/onDestroy so `:if` hide/show cycles re-subscribe cleanly.
|
|
344
|
+
let stopRemoteRender = null
|
|
345
|
+
|
|
346
|
+
effect(() => {
|
|
347
|
+
const busy = isRemote() && remote.loading()
|
|
348
|
+
if (!rootEl) return
|
|
349
|
+
const list = rootEl.querySelector('[data-stx-combobox-options]')
|
|
350
|
+
if (list) list.setAttribute('aria-busy', busy ? 'true' : 'false')
|
|
351
|
+
})
|
|
352
|
+
|
|
203
353
|
/*
|
|
204
354
|
* Escape dismisses it, from anywhere rather than only from inside the panel.
|
|
205
355
|
*
|
|
@@ -232,6 +382,9 @@ onMount(() => {
|
|
|
232
382
|
}
|
|
233
383
|
document.addEventListener('click', outsideHandler, true)
|
|
234
384
|
document.addEventListener('keydown', onComboboxKey)
|
|
385
|
+
stopRemoteRender?.()
|
|
386
|
+
stopRemoteRender = remote.results.subscribe(() => renderRemote())
|
|
387
|
+
renderRemote()
|
|
235
388
|
})
|
|
236
389
|
|
|
237
390
|
/*
|
|
@@ -248,6 +401,9 @@ effect(() => {
|
|
|
248
401
|
})
|
|
249
402
|
|
|
250
403
|
onDestroy(() => {
|
|
404
|
+
remote.cancel()
|
|
405
|
+
stopRemoteRender?.()
|
|
406
|
+
stopRemoteRender = null
|
|
251
407
|
window.stx.overlays.close(comboboxInstanceId)
|
|
252
408
|
if (outsideHandler) document.removeEventListener('click', outsideHandler, true)
|
|
253
409
|
document.removeEventListener('keydown', onComboboxKey)
|
|
@@ -255,7 +411,7 @@ onDestroy(() => {
|
|
|
255
411
|
|
|
256
412
|
const dataState = derived(() => isOpen() ? 'open' : 'closed')
|
|
257
413
|
|
|
258
|
-
defineExpose({ isOpen, selected, query, activeIndex, toggle, open, close, selectValue })
|
|
414
|
+
defineExpose({ isOpen, selected, query, activeIndex, toggle, open, close, selectValue, results: remote.results, loading: remote.loading, error: remote.error })
|
|
259
415
|
</script>
|
|
260
416
|
|
|
261
417
|
<component
|
|
@@ -264,15 +420,28 @@ defineExpose({ isOpen, selected, query, activeIndex, toggle, open, close, select
|
|
|
264
420
|
data-stx-combobox
|
|
265
421
|
data-combobox-id="{{ comboboxInstanceId }}"
|
|
266
422
|
:data-state="dataState()"
|
|
423
|
+
:data-async-state="asyncState()"
|
|
267
424
|
@stx:combobox-toggle="onToggle($event)"
|
|
268
425
|
@stx:combobox-select="onSelect($event)"
|
|
269
426
|
@stx:combobox-query="onQuery($event)"
|
|
270
427
|
>
|
|
271
428
|
<slot />
|
|
429
|
+
<span class="sr-only" role="status" aria-live="polite" aria-atomic="true" data-stx-combobox-live x-text="announcement()"></span>
|
|
272
430
|
</component>
|
|
273
431
|
|
|
274
432
|
<style>
|
|
275
|
-
[data-stx-combobox][data-state="closed"] [data-stx-combobox-options]
|
|
433
|
+
[data-stx-combobox][data-state="closed"] [data-stx-combobox-options],
|
|
434
|
+
[data-stx-combobox][data-async-state="idle"] [data-stx-combobox-options]:not(:has([data-stx-combobox-option]:not([data-stx-combobox-remote]))) {
|
|
276
435
|
display: none;
|
|
277
436
|
}
|
|
437
|
+
|
|
438
|
+
/* Remote-suggestion status rows: one shows at a time, per data-async-state. */
|
|
439
|
+
[data-stx-combobox-status] {
|
|
440
|
+
display: none;
|
|
441
|
+
}
|
|
442
|
+
[data-stx-combobox][data-async-state="loading"] [data-stx-combobox-status="loading"],
|
|
443
|
+
[data-stx-combobox][data-async-state="empty"] [data-stx-combobox-status="empty"],
|
|
444
|
+
[data-stx-combobox][data-async-state="error"] [data-stx-combobox-status="error"] {
|
|
445
|
+
display: block;
|
|
446
|
+
}
|
|
278
447
|
</style>
|
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
<script server>
|
|
2
2
|
export const className = $props.className || ''
|
|
3
3
|
export const as = $props.as || 'ul'
|
|
4
|
+
/*
|
|
5
|
+
* The status rows for remote suggestions (stacksjs/stx#2319) are list items in
|
|
6
|
+
* a list and divs otherwise, so a `<ul>` keeps only `<li>` children.
|
|
7
|
+
*/
|
|
8
|
+
export const statusTag = as === 'ul' || as === 'ol' ? 'li' : 'div'
|
|
4
9
|
|
|
5
10
|
const baseClasses = 'absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-panel bg-panel py-1 text-base shadow-lg ring-1 ring-line focus:outline-none'
|
|
6
11
|
export const optionsClasses = `${baseClasses} ${className}`.trim()
|
|
12
|
+
export const statusClasses = 'relative cursor-default select-none py-2 px-4 text-sm text-fg-soft'
|
|
7
13
|
</script>
|
|
8
14
|
|
|
9
15
|
<component
|
|
@@ -13,4 +19,18 @@ export const optionsClasses = `${baseClasses} ${className}`.trim()
|
|
|
13
19
|
role="listbox"
|
|
14
20
|
>
|
|
15
21
|
<slot />
|
|
22
|
+
{{--
|
|
23
|
+
Shown one at a time by the parent <Combobox> through data-async-state, only
|
|
24
|
+
when it has a `source`. Hidden from the accessibility tree so the listbox
|
|
25
|
+
holds only options; the combobox's live region announces the same states.
|
|
26
|
+
--}}
|
|
27
|
+
@if(statusTag === 'li')
|
|
28
|
+
<li class="{{ statusClasses }}" data-stx-combobox-status="loading" aria-hidden="true"><slot name="loading">Searching…</slot></li>
|
|
29
|
+
<li class="{{ statusClasses }}" data-stx-combobox-status="empty" aria-hidden="true"><slot name="empty">No results</slot></li>
|
|
30
|
+
<li class="{{ statusClasses }} text-danger" data-stx-combobox-status="error" aria-hidden="true"><slot name="error">Suggestions could not be loaded. Keep typing to try again.</slot></li>
|
|
31
|
+
@else
|
|
32
|
+
<div class="{{ statusClasses }}" data-stx-combobox-status="loading" aria-hidden="true"><slot name="loading">Searching…</slot></div>
|
|
33
|
+
<div class="{{ statusClasses }}" data-stx-combobox-status="empty" aria-hidden="true"><slot name="empty">No results</slot></div>
|
|
34
|
+
<div class="{{ statusClasses }} text-danger" data-stx-combobox-status="error" aria-hidden="true"><slot name="error">Suggestions could not be loaded. Keep typing to try again.</slot></div>
|
|
35
|
+
@endif
|
|
16
36
|
</component>
|
|
@@ -73,6 +73,12 @@ function handleQueryChange(value) {
|
|
|
73
73
|
| `onChange` | `(value: any) => void` | - | Change handler |
|
|
74
74
|
| `className` | `string` | `''` | Additional CSS classes |
|
|
75
75
|
| `as` | `string` | `'div'` | HTML element to render |
|
|
76
|
+
| `source` | `(query, { signal }) => Promise<Option[]>` | - | Fetch suggestions as the user types (bind a client function) |
|
|
77
|
+
| `debounce` | `number` | `150` | Quiet time in ms after the last keystroke before `source` is asked |
|
|
78
|
+
| `minLength` | `number` | `1` | Fewest characters (trimmed) that ask `source` |
|
|
79
|
+
| `limit` | `number` | - | Keep at most this many suggestions |
|
|
80
|
+
|
|
81
|
+
Events: `change` (value), `query` (text), and with a `source`: `search` (query), `results` (query, options) and `error` (error, query).
|
|
76
82
|
|
|
77
83
|
### ComboboxInput
|
|
78
84
|
| Prop | Type | Default | Description |
|
|
@@ -106,6 +112,41 @@ function handleQueryChange(value) {
|
|
|
106
112
|
| `currentValue` | `any` | - | Current selected value |
|
|
107
113
|
| `onChange` | `(value: any) => void` | - | Change handler |
|
|
108
114
|
|
|
115
|
+
## Remote suggestions
|
|
116
|
+
|
|
117
|
+
Give the combobox a `source` and it asks it as the user types: debounced, with the previous request aborted through `signal`, and a slow answer for an earlier query never overwriting a faster one for a later query. Options are drawn into `<ComboboxOptions>` after any static options.
|
|
118
|
+
|
|
119
|
+
```stx
|
|
120
|
+
<script client>
|
|
121
|
+
async function searchPlaces(query, { signal }) {
|
|
122
|
+
const res = await fetch(`/api/places?q=${encodeURIComponent(query)}`, { signal })
|
|
123
|
+
if (!res.ok) throw new Error(`Search failed (${res.status})`)
|
|
124
|
+
const places = await res.json()
|
|
125
|
+
// Strings, or { label, value, description, disabled }. An object without
|
|
126
|
+
// `value` is selected whole, so a result keeps its coordinates.
|
|
127
|
+
return places.map(p => ({ label: p.name, description: p.region, value: p }))
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function pick(place) { console.log(place.lat, place.lng) }
|
|
131
|
+
function failed(error, query) { console.warn(query, error) }
|
|
132
|
+
</script>
|
|
133
|
+
|
|
134
|
+
<Combobox :source="searchPlaces" :debounce="200" :minLength="2" :limit="8" @change="pick" @error="failed">
|
|
135
|
+
<ComboboxInput placeholder="Search for a place" />
|
|
136
|
+
<ComboboxOptions>
|
|
137
|
+
<p slot="loading">Looking…</p>
|
|
138
|
+
<p slot="empty">No places match</p>
|
|
139
|
+
<p slot="error">Search is unavailable. Keep typing to retry.</p>
|
|
140
|
+
</ComboboxOptions>
|
|
141
|
+
</Combobox>
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
- The `loading`, `empty` and `error` slots have defaults ("Searching…", "No results", and an error line), so they are optional.
|
|
145
|
+
- While a request is pending the listbox has `aria-busy="true"`; when it settles a polite live region announces "3 results available.", "No results." or the failure. The status rows are `aria-hidden` so the listbox holds only options.
|
|
146
|
+
- Arrow keys, Home/End, Enter and Escape behave exactly as with static options. Selecting a remote option fills the input with its label.
|
|
147
|
+
- Suggestions are written as text, never parsed as HTML.
|
|
148
|
+
- The timing rules live in `useSuggestions` (`@stacksjs/stx/composables`), usable on its own for a search box that is not a combobox.
|
|
149
|
+
|
|
109
150
|
## Examples
|
|
110
151
|
|
|
111
152
|
### With Empty State
|
package/src/ui/combobox/index.ts
CHANGED
|
@@ -4,11 +4,24 @@ export { default as ComboboxInput } from './ComboboxInput.stx'
|
|
|
4
4
|
export { default as ComboboxOption } from './ComboboxOption.stx'
|
|
5
5
|
export { default as ComboboxOptions } from './ComboboxOptions.stx'
|
|
6
6
|
|
|
7
|
+
/** A remote suggestion: a string, or an object whose `label` is shown and whose `value` (or the object itself) is selected. */
|
|
8
|
+
export type ComboboxSourceOption = string | { label?: string, value?: any, description?: string, disabled?: boolean, [key: string]: any }
|
|
9
|
+
|
|
10
|
+
export type ComboboxSource = (query: string, context: { signal: AbortSignal }) => Promise<ComboboxSourceOption[] | null | undefined> | ComboboxSourceOption[] | null | undefined
|
|
11
|
+
|
|
7
12
|
export interface ComboboxProps {
|
|
8
13
|
value?: any
|
|
9
14
|
onChange?: (value: any) => void
|
|
10
15
|
className?: string
|
|
11
16
|
as?: string
|
|
17
|
+
/** Fetch suggestions as the user types. Bind a client function: `:source="search"`. */
|
|
18
|
+
source?: ComboboxSource
|
|
19
|
+
/** Quiet time after the last keystroke before `source` is asked, in ms. Default 150. */
|
|
20
|
+
debounce?: number
|
|
21
|
+
/** Fewest characters (trimmed) that ask `source`. Default 1. */
|
|
22
|
+
minLength?: number
|
|
23
|
+
/** Keep at most this many suggestions. Default: all. */
|
|
24
|
+
limit?: number
|
|
12
25
|
}
|
|
13
26
|
|
|
14
27
|
export interface ComboboxInputProps {
|
|
@@ -11,7 +11,9 @@ export const paletteInstanceId = $uid
|
|
|
11
11
|
<script client>
|
|
12
12
|
const emit = defineEmits()
|
|
13
13
|
const paletteInstanceId = {{ paletteInstanceId }}
|
|
14
|
-
|
|
14
|
+
// Live, so a parent's `:open="paletteOpen()"` opens and closes it after mount,
|
|
15
|
+
// as it does a Dialog or Drawer (stacksjs/stx#2327).
|
|
16
|
+
const isOpen = useReactiveProp('open', {{ open }})
|
|
15
17
|
const query = state({{ initialQuery }})
|
|
16
18
|
|
|
17
19
|
function close() {
|