@cognitap/radiant 0.0.7 → 0.0.8
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 +4 -0
- package/README.md +2 -2
- package/dist/library/Select.d.ts +87 -0
- package/dist/library/Select.d.ts.map +1 -0
- package/dist/library/Select.js +454 -0
- package/dist/library/Select.js.map +1 -0
- package/dist/library/cn.d.ts.map +1 -1
- package/dist/library/cn.js +20 -3
- package/dist/library/cn.js.map +1 -1
- package/dist/library/examples/glass.d.ts.map +1 -1
- package/dist/library/examples/glass.js +5 -0
- package/dist/library/examples/glass.js.map +1 -1
- package/dist/library/index.d.ts +2 -0
- package/dist/library/index.d.ts.map +1 -1
- package/dist/library/index.js +1 -0
- package/dist/library/index.js.map +1 -1
- package/dist/library/internal/select.d.ts +37 -0
- package/dist/library/internal/select.d.ts.map +1 -0
- package/dist/library/internal/select.js +42 -0
- package/dist/library/internal/select.js.map +1 -0
- package/dist/library/motion/host.d.ts +2 -1
- package/dist/library/motion/host.d.ts.map +1 -1
- package/dist/library/motion/host.js.map +1 -1
- package/dist/library/motion/popup.d.ts +5 -0
- package/dist/library/motion/popup.d.ts.map +1 -0
- package/dist/library/motion/popup.js +60 -0
- package/dist/library/motion/popup.js.map +1 -0
- package/dist/library/motion/react.d.ts.map +1 -1
- package/dist/library/motion/react.js +3 -1
- package/dist/library/motion/react.js.map +1 -1
- package/dist/library/react/useControllableState.d.ts +1 -0
- package/dist/library/react/useControllableState.d.ts.map +1 -1
- package/dist/library/react/useControllableState.js +8 -1
- package/dist/library/react/useControllableState.js.map +1 -1
- package/dist/library/selectStyles.d.ts +4 -0
- package/dist/library/selectStyles.d.ts.map +1 -0
- package/dist/library/selectStyles.js +32 -0
- package/dist/library/selectStyles.js.map +1 -0
- package/dist/library/styles.css +1 -1
- package/dist/library/themes/components.d.ts +24 -0
- package/dist/library/themes/components.d.ts.map +1 -1
- package/dist/library/themes/components.js +24 -0
- package/dist/library/themes/components.js.map +1 -1
- package/docs/architecture.md +14 -3
- package/docs/motion.md +4 -4
- package/package.json +1 -1
- package/src/Select.tsx +781 -0
- package/src/cn.ts +20 -3
- package/src/examples/glass.ts +5 -0
- package/src/index.ts +27 -0
- package/src/internal/select.ts +80 -0
- package/src/motion/host.ts +2 -1
- package/src/motion/popup.ts +55 -0
- package/src/motion/react.ts +3 -1
- package/src/react/useControllableState.ts +7 -1
- package/src/selectStyles.ts +34 -0
- package/src/themes/components.ts +24 -0
package/src/Select.tsx
ADDED
|
@@ -0,0 +1,781 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
/* oxlint-disable jsx-a11y/prefer-tag-over-role -- A custom select needs ARIA on its trigger/listbox/options; the native select is a separate form bridge. */
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
createContext,
|
|
7
|
+
useContext,
|
|
8
|
+
useEffect,
|
|
9
|
+
useId,
|
|
10
|
+
useLayoutEffect,
|
|
11
|
+
useRef,
|
|
12
|
+
useState
|
|
13
|
+
} from 'react'
|
|
14
|
+
import type { ComponentProps, ReactNode, RefObject } from 'react'
|
|
15
|
+
import { createPortal } from 'react-dom'
|
|
16
|
+
import { Button, type ButtonProps } from './Button.js'
|
|
17
|
+
import { useField, useFieldControl } from './Field.js'
|
|
18
|
+
import { cn } from './cn.js'
|
|
19
|
+
import { controlMetrics } from './controlStyles.js'
|
|
20
|
+
import { matchSelectText, moveSelectFocus, positionSelect } from './internal/select.js'
|
|
21
|
+
import { useComposedRefs } from './react/useComposedRefs.js'
|
|
22
|
+
import { useControllableState } from './react/useControllableState.js'
|
|
23
|
+
import { useTransitionHost } from './motion/host.js'
|
|
24
|
+
import type { ValueOwner } from './react/useNativeOwner.js'
|
|
25
|
+
import type { ControlSize } from './presentation.js'
|
|
26
|
+
import type { ThemeStyle } from './themes/defineTheme.js'
|
|
27
|
+
import { selectContentClass, selectItemClass, selectTriggerClass } from './selectStyles.js'
|
|
28
|
+
|
|
29
|
+
export type SelectOption = { value: string; disabled?: boolean } & (
|
|
30
|
+
| { label: string; textValue?: string }
|
|
31
|
+
| { label: ReactNode; textValue: string }
|
|
32
|
+
)
|
|
33
|
+
export type SelectProps = ValueOwner<string | null> &
|
|
34
|
+
({ open: boolean; defaultOpen?: never } | { open?: undefined; defaultOpen?: boolean }) & {
|
|
35
|
+
/** One registry for native options, SSR value text and keyboard matching. Values must be unique. */
|
|
36
|
+
items: readonly SelectOption[]
|
|
37
|
+
onValueChange?: (value: string | null) => void
|
|
38
|
+
onOpenChange?: (open: boolean) => void
|
|
39
|
+
name?: string
|
|
40
|
+
form?: string
|
|
41
|
+
autoComplete?: string
|
|
42
|
+
disabled?: boolean
|
|
43
|
+
required?: boolean
|
|
44
|
+
controlSize?: ControlSize
|
|
45
|
+
children?: ReactNode
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type SelectState = {
|
|
49
|
+
value: string | null
|
|
50
|
+
open: boolean
|
|
51
|
+
disabled: boolean
|
|
52
|
+
setValue(value: string | null): void
|
|
53
|
+
setOpen(open: boolean): void
|
|
54
|
+
}
|
|
55
|
+
type Context = SelectState & {
|
|
56
|
+
items: readonly SelectOption[]
|
|
57
|
+
entries: { value: string; textValue: string; disabled?: boolean }[]
|
|
58
|
+
controlSize: ControlSize
|
|
59
|
+
required: boolean
|
|
60
|
+
triggerId: string
|
|
61
|
+
contentId: string
|
|
62
|
+
labelId?: string
|
|
63
|
+
trigger: HTMLButtonElement | null
|
|
64
|
+
setTrigger(node: HTMLButtonElement | null): void
|
|
65
|
+
content: RefObject<HTMLDivElement | null>
|
|
66
|
+
focus(value?: string): void
|
|
67
|
+
commit(value: string): void
|
|
68
|
+
close(restore?: boolean): void
|
|
69
|
+
search(key: string, current: string | null): string | undefined
|
|
70
|
+
restoreFocus: RefObject<boolean>
|
|
71
|
+
}
|
|
72
|
+
const SelectContext = createContext<Context | null>(null)
|
|
73
|
+
const SelectItemContext = createContext<SelectOption | null>(null)
|
|
74
|
+
export function useSelect(): SelectState | null {
|
|
75
|
+
return useContext(SelectContext)
|
|
76
|
+
}
|
|
77
|
+
function useSelectContext() {
|
|
78
|
+
const select = useContext(SelectContext)
|
|
79
|
+
if (!select) throw new Error('Select parts must render inside Select.')
|
|
80
|
+
return select
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Custom selection presentation with a real native form control. */
|
|
84
|
+
export function Select({
|
|
85
|
+
items,
|
|
86
|
+
value,
|
|
87
|
+
defaultValue,
|
|
88
|
+
onValueChange,
|
|
89
|
+
open,
|
|
90
|
+
defaultOpen,
|
|
91
|
+
onOpenChange,
|
|
92
|
+
name,
|
|
93
|
+
form,
|
|
94
|
+
autoComplete,
|
|
95
|
+
disabled: disabledProp,
|
|
96
|
+
required: requiredProp,
|
|
97
|
+
controlSize = 'medium',
|
|
98
|
+
children
|
|
99
|
+
}: SelectProps) {
|
|
100
|
+
const ids = useId()
|
|
101
|
+
const field = useField()
|
|
102
|
+
const disabled = !!(disabledProp || field?.disabled)
|
|
103
|
+
const required = !!(requiredProp || field?.required)
|
|
104
|
+
const entries = items.map(item => ({
|
|
105
|
+
value: item.value,
|
|
106
|
+
disabled: item.disabled,
|
|
107
|
+
textValue: item.textValue ?? (typeof item.label === 'string' ? item.label : '')
|
|
108
|
+
}))
|
|
109
|
+
if (new Set(entries.map(item => item.value)).size !== items.length)
|
|
110
|
+
throw new TypeError('Select item values must be distinct.')
|
|
111
|
+
if (entries.some(item => typeof item.value !== 'string' || !item.textValue.trim()))
|
|
112
|
+
throw new TypeError('Select items need a string value and readable textValue.')
|
|
113
|
+
const selection = useControllableState({
|
|
114
|
+
name: 'Select',
|
|
115
|
+
value,
|
|
116
|
+
defaultValue,
|
|
117
|
+
initialValue: null,
|
|
118
|
+
onChange: onValueChange
|
|
119
|
+
})
|
|
120
|
+
const expansion = useControllableState({
|
|
121
|
+
name: 'Select open',
|
|
122
|
+
value: open,
|
|
123
|
+
defaultValue: defaultOpen,
|
|
124
|
+
initialValue: false,
|
|
125
|
+
onChange: onOpenChange
|
|
126
|
+
})
|
|
127
|
+
const [trigger, setTrigger] = useState<HTMLButtonElement | null>(null)
|
|
128
|
+
const bridge = useRef<HTMLSelectElement>(null)
|
|
129
|
+
const content = useRef<HTMLDivElement>(null)
|
|
130
|
+
const restoreFocus = useRef(true)
|
|
131
|
+
const pendingUser = useRef<string | null>(null)
|
|
132
|
+
const dispatching = useRef(false)
|
|
133
|
+
const searchBuffer = useRef({ text: '', at: 0 })
|
|
134
|
+
const selected = items.find(item => item.value === selection.value)
|
|
135
|
+
const nativeValue = selected?.value ?? ''
|
|
136
|
+
const [initialNativeValue] = useState(nativeValue)
|
|
137
|
+
const isOpen = expansion.value && !disabled
|
|
138
|
+
const unavailable = () => disabled || !!trigger?.matches(':disabled')
|
|
139
|
+
const setOpen = (next: boolean) => {
|
|
140
|
+
if (next && unavailable()) return
|
|
141
|
+
searchBuffer.current = { text: '', at: 0 }
|
|
142
|
+
restoreFocus.current = true
|
|
143
|
+
expansion.request(next)
|
|
144
|
+
}
|
|
145
|
+
const close = (restore = true) => {
|
|
146
|
+
restoreFocus.current = restore
|
|
147
|
+
expansion.request(false)
|
|
148
|
+
}
|
|
149
|
+
const focus = (itemValue?: string) => {
|
|
150
|
+
const nodes = content.current?.querySelectorAll<HTMLElement>('[data-slot~="select-item"]')
|
|
151
|
+
const option = Array.from(nodes ?? []).find(
|
|
152
|
+
node => node.dataset.value === itemValue && node.getAttribute('aria-disabled') !== 'true'
|
|
153
|
+
)
|
|
154
|
+
option?.focus({ preventScroll: true })
|
|
155
|
+
option?.scrollIntoView({ block: 'nearest' })
|
|
156
|
+
}
|
|
157
|
+
const commit = (next: string) => {
|
|
158
|
+
if (unavailable() || !items.some(item => item.value === next && !item.disabled)) return
|
|
159
|
+
if (next !== selection.value) pendingUser.current = next
|
|
160
|
+
selection.request(next)
|
|
161
|
+
close()
|
|
162
|
+
// A declined controlled request must not become a later programmatic change event.
|
|
163
|
+
queueMicrotask(() => {
|
|
164
|
+
pendingUser.current = null
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
const latest = useRef({ selection, close, nativeValue })
|
|
168
|
+
useLayoutEffect(() => {
|
|
169
|
+
latest.current = { selection, close, nativeValue }
|
|
170
|
+
})
|
|
171
|
+
useLayoutEffect(() => {
|
|
172
|
+
const node = bridge.current
|
|
173
|
+
if (!node) return
|
|
174
|
+
node.value = nativeValue
|
|
175
|
+
if (selection.controlled)
|
|
176
|
+
for (const option of node.options) option.defaultSelected = option.value === nativeValue
|
|
177
|
+
if (pendingUser.current !== null && pendingUser.current === nativeValue) {
|
|
178
|
+
pendingUser.current = null
|
|
179
|
+
dispatching.current = true
|
|
180
|
+
try {
|
|
181
|
+
node.dispatchEvent(new Event('change', { bubbles: true }))
|
|
182
|
+
} finally {
|
|
183
|
+
dispatching.current = false
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
})
|
|
187
|
+
useEffect(() => {
|
|
188
|
+
const node = bridge.current
|
|
189
|
+
const owner = node?.form
|
|
190
|
+
if (!owner) return
|
|
191
|
+
const win = node.ownerDocument.defaultView!
|
|
192
|
+
let resetTimer: number | undefined
|
|
193
|
+
const reset = (event: Event) => {
|
|
194
|
+
win.clearTimeout(resetTimer)
|
|
195
|
+
resetTimer = win.setTimeout(() => {
|
|
196
|
+
if (event.defaultPrevented || !node.isConnected) return
|
|
197
|
+
latest.current.selection.reset()
|
|
198
|
+
if (latest.current.selection.controlled) node.value = latest.current.nativeValue
|
|
199
|
+
latest.current.close(false)
|
|
200
|
+
}, 0)
|
|
201
|
+
}
|
|
202
|
+
owner.addEventListener('reset', reset)
|
|
203
|
+
return () => {
|
|
204
|
+
owner.removeEventListener('reset', reset)
|
|
205
|
+
win.clearTimeout(resetTimer)
|
|
206
|
+
}
|
|
207
|
+
}, [form, trigger])
|
|
208
|
+
useEffect(() => {
|
|
209
|
+
if (
|
|
210
|
+
!isOpen &&
|
|
211
|
+
restoreFocus.current &&
|
|
212
|
+
content.current?.contains(content.current.ownerDocument.activeElement)
|
|
213
|
+
)
|
|
214
|
+
trigger?.focus({ preventScroll: true })
|
|
215
|
+
}, [isOpen, trigger])
|
|
216
|
+
const context: Context = {
|
|
217
|
+
value: selection.value,
|
|
218
|
+
setValue: selection.request,
|
|
219
|
+
open: isOpen,
|
|
220
|
+
setOpen,
|
|
221
|
+
disabled,
|
|
222
|
+
items,
|
|
223
|
+
entries,
|
|
224
|
+
controlSize,
|
|
225
|
+
required,
|
|
226
|
+
triggerId: field?.controlProps?.id ?? `${ids}-trigger`,
|
|
227
|
+
contentId: `${ids}-content`,
|
|
228
|
+
labelId: field?.layout === 'control' ? field.labelId : undefined,
|
|
229
|
+
trigger,
|
|
230
|
+
setTrigger,
|
|
231
|
+
content,
|
|
232
|
+
focus,
|
|
233
|
+
commit,
|
|
234
|
+
close,
|
|
235
|
+
restoreFocus,
|
|
236
|
+
search(key, current) {
|
|
237
|
+
const now = Date.now()
|
|
238
|
+
const text = (now - searchBuffer.current.at < 1000 ? searchBuffer.current.text : '') + key
|
|
239
|
+
searchBuffer.current = { text, at: now }
|
|
240
|
+
return matchSelectText(entries, text, current)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return (
|
|
244
|
+
<SelectContext.Provider value={context}>
|
|
245
|
+
{children ?? (
|
|
246
|
+
<>
|
|
247
|
+
<SelectTrigger>
|
|
248
|
+
<SelectValue />
|
|
249
|
+
<SelectIcon />
|
|
250
|
+
</SelectTrigger>
|
|
251
|
+
<SelectPortal>
|
|
252
|
+
<SelectContent />
|
|
253
|
+
</SelectPortal>
|
|
254
|
+
</>
|
|
255
|
+
)}
|
|
256
|
+
<select
|
|
257
|
+
ref={bridge}
|
|
258
|
+
name={name}
|
|
259
|
+
form={form}
|
|
260
|
+
autoComplete={autoComplete}
|
|
261
|
+
required={required}
|
|
262
|
+
disabled={disabled}
|
|
263
|
+
aria-hidden="true"
|
|
264
|
+
tabIndex={-1}
|
|
265
|
+
className="sr-only"
|
|
266
|
+
data-slot="select-native"
|
|
267
|
+
defaultValue={initialNativeValue}
|
|
268
|
+
onFocus={() => trigger?.focus()}
|
|
269
|
+
onInvalid={event => {
|
|
270
|
+
event.preventDefault()
|
|
271
|
+
trigger?.focus()
|
|
272
|
+
}}
|
|
273
|
+
onChange={event => {
|
|
274
|
+
if (dispatching.current) return
|
|
275
|
+
const next = event.currentTarget.value
|
|
276
|
+
if (unavailable()) {
|
|
277
|
+
event.currentTarget.value = latest.current.nativeValue
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
if (items.some(item => item.value === next && !item.disabled)) selection.request(next)
|
|
281
|
+
if (selection.controlled) event.currentTarget.value = nativeValue
|
|
282
|
+
}}
|
|
283
|
+
>
|
|
284
|
+
{!items.some(item => item.value === '') && <option value="">No selection</option>}
|
|
285
|
+
{items.map(item => (
|
|
286
|
+
<option
|
|
287
|
+
key={item.value}
|
|
288
|
+
value={item.value}
|
|
289
|
+
disabled={item.disabled}
|
|
290
|
+
>
|
|
291
|
+
{item.textValue ?? item.label}
|
|
292
|
+
</option>
|
|
293
|
+
))}
|
|
294
|
+
</select>
|
|
295
|
+
</SelectContext.Provider>
|
|
296
|
+
)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export type SelectTriggerProps = Omit<
|
|
300
|
+
ButtonProps,
|
|
301
|
+
'variant' | 'tone' | 'type' | 'pending' | 'controlSize' | 'disabled'
|
|
302
|
+
>
|
|
303
|
+
export function SelectTrigger({
|
|
304
|
+
className,
|
|
305
|
+
onClick,
|
|
306
|
+
onKeyDown,
|
|
307
|
+
ref,
|
|
308
|
+
children,
|
|
309
|
+
...props
|
|
310
|
+
}: SelectTriggerProps) {
|
|
311
|
+
const select = useSelectContext()
|
|
312
|
+
const control = useFieldControl({
|
|
313
|
+
id: props.id ?? select.triggerId,
|
|
314
|
+
disabled: select.disabled,
|
|
315
|
+
required: select.required,
|
|
316
|
+
'aria-describedby': props['aria-describedby'],
|
|
317
|
+
'aria-invalid': props['aria-invalid']
|
|
318
|
+
})
|
|
319
|
+
const hostRef = useComposedRefs(select.setTrigger, ref)
|
|
320
|
+
return (
|
|
321
|
+
<Button
|
|
322
|
+
{...props}
|
|
323
|
+
{...control}
|
|
324
|
+
ref={hostRef}
|
|
325
|
+
variant="outline"
|
|
326
|
+
tone="neutral"
|
|
327
|
+
type="button"
|
|
328
|
+
controlSize={select.controlSize}
|
|
329
|
+
className={cn(
|
|
330
|
+
selectTriggerClass,
|
|
331
|
+
controlMetrics({ controlSize: select.controlSize }),
|
|
332
|
+
className
|
|
333
|
+
)}
|
|
334
|
+
role="combobox"
|
|
335
|
+
aria-haspopup="listbox"
|
|
336
|
+
aria-controls={select.contentId}
|
|
337
|
+
aria-expanded={select.open}
|
|
338
|
+
aria-required={select.required || undefined}
|
|
339
|
+
data-slot="button select-trigger"
|
|
340
|
+
data-state={select.open ? 'open' : 'closed'}
|
|
341
|
+
data-placeholder={select.value === null ? '' : undefined}
|
|
342
|
+
onClick={event => {
|
|
343
|
+
onClick?.(event)
|
|
344
|
+
if (!event.defaultPrevented) select.setOpen(!select.open)
|
|
345
|
+
}}
|
|
346
|
+
onKeyDown={event => {
|
|
347
|
+
onKeyDown?.(event)
|
|
348
|
+
if (event.defaultPrevented || event.ctrlKey || event.altKey || event.metaKey) return
|
|
349
|
+
if (['Enter', ' ', 'ArrowDown', 'ArrowUp'].includes(event.key)) {
|
|
350
|
+
event.preventDefault()
|
|
351
|
+
select.setOpen(true)
|
|
352
|
+
} else if (event.key.length === 1) {
|
|
353
|
+
const next = select.search(event.key, select.value)
|
|
354
|
+
if (next !== undefined) {
|
|
355
|
+
event.preventDefault()
|
|
356
|
+
select.commit(next)
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}}
|
|
360
|
+
>
|
|
361
|
+
{children ?? (
|
|
362
|
+
<>
|
|
363
|
+
<SelectValue />
|
|
364
|
+
<SelectIcon />
|
|
365
|
+
</>
|
|
366
|
+
)}
|
|
367
|
+
</Button>
|
|
368
|
+
)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export type SelectValueProps = Omit<ComponentProps<'span'>, 'style'> & {
|
|
372
|
+
placeholder?: ReactNode
|
|
373
|
+
style?: ThemeStyle
|
|
374
|
+
}
|
|
375
|
+
export function SelectValue({
|
|
376
|
+
placeholder = 'Select an option',
|
|
377
|
+
children,
|
|
378
|
+
className,
|
|
379
|
+
...props
|
|
380
|
+
}: SelectValueProps) {
|
|
381
|
+
const select = useSelectContext()
|
|
382
|
+
return (
|
|
383
|
+
<span
|
|
384
|
+
{...props}
|
|
385
|
+
className={cn('min-w-0 truncate', className)}
|
|
386
|
+
data-slot="select-value"
|
|
387
|
+
>
|
|
388
|
+
{children ?? select.items.find(item => item.value === select.value)?.label ?? placeholder}
|
|
389
|
+
</span>
|
|
390
|
+
)
|
|
391
|
+
}
|
|
392
|
+
export type SelectIconProps = Omit<ComponentProps<'span'>, 'style'> & { style?: ThemeStyle }
|
|
393
|
+
export function SelectIcon({ children, className, ...props }: SelectIconProps) {
|
|
394
|
+
return (
|
|
395
|
+
<span
|
|
396
|
+
{...props}
|
|
397
|
+
aria-hidden="true"
|
|
398
|
+
data-slot="select-icon"
|
|
399
|
+
className={cn('shrink-0', className)}
|
|
400
|
+
>
|
|
401
|
+
{children ?? (
|
|
402
|
+
<svg
|
|
403
|
+
width="16"
|
|
404
|
+
height="16"
|
|
405
|
+
viewBox="0 0 16 16"
|
|
406
|
+
fill="none"
|
|
407
|
+
>
|
|
408
|
+
<path
|
|
409
|
+
d="m4 6 4 4 4-4"
|
|
410
|
+
stroke="currentColor"
|
|
411
|
+
strokeWidth="1.5"
|
|
412
|
+
/>
|
|
413
|
+
</svg>
|
|
414
|
+
)}
|
|
415
|
+
</span>
|
|
416
|
+
)
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Portal into the trigger's local scope; the top layer escapes clipping and modal bounds. */
|
|
420
|
+
export function SelectPortal({ children }: { children?: ReactNode }) {
|
|
421
|
+
const select = useSelectContext()
|
|
422
|
+
return select.trigger?.parentElement ? createPortal(children, select.trigger.parentElement) : null
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
export type SelectContentProps = Omit<ComponentProps<'div'>, 'style' | 'popover'> & {
|
|
426
|
+
style?: ThemeStyle
|
|
427
|
+
position?: 'item-aligned' | 'popper'
|
|
428
|
+
sideOffset?: number
|
|
429
|
+
collisionPadding?: number
|
|
430
|
+
motion?: 'inherit' | 'off'
|
|
431
|
+
}
|
|
432
|
+
export function SelectContent({
|
|
433
|
+
children,
|
|
434
|
+
position = 'item-aligned',
|
|
435
|
+
sideOffset = 4,
|
|
436
|
+
collisionPadding = 8,
|
|
437
|
+
motion = 'inherit',
|
|
438
|
+
className,
|
|
439
|
+
onKeyDown,
|
|
440
|
+
ref,
|
|
441
|
+
...props
|
|
442
|
+
}: SelectContentProps) {
|
|
443
|
+
const select = useSelectContext()
|
|
444
|
+
const mergedRef = useComposedRefs(select.content, ref)
|
|
445
|
+
const {
|
|
446
|
+
ref: transitionRef,
|
|
447
|
+
active: motionActive,
|
|
448
|
+
off: motionOff
|
|
449
|
+
} = useTransitionHost('popup', mergedRef, motion === 'off')
|
|
450
|
+
const latest = useRef(select)
|
|
451
|
+
useLayoutEffect(() => {
|
|
452
|
+
latest.current = select
|
|
453
|
+
})
|
|
454
|
+
const wasOpen = useRef(false)
|
|
455
|
+
useLayoutEffect(() => {
|
|
456
|
+
const state = latest.current
|
|
457
|
+
const node = state.content.current
|
|
458
|
+
const trigger = state.trigger
|
|
459
|
+
if (!node || !trigger) return
|
|
460
|
+
const doc = trigger.ownerDocument
|
|
461
|
+
const win = doc.defaultView!
|
|
462
|
+
if (!state.open) {
|
|
463
|
+
if (
|
|
464
|
+
wasOpen.current &&
|
|
465
|
+
latest.current.restoreFocus.current &&
|
|
466
|
+
node.contains(doc.activeElement)
|
|
467
|
+
)
|
|
468
|
+
trigger.focus({ preventScroll: true })
|
|
469
|
+
if (node.matches(':popover-open')) node.hidePopover()
|
|
470
|
+
wasOpen.current = false
|
|
471
|
+
return
|
|
472
|
+
}
|
|
473
|
+
const seedWidth = () => {
|
|
474
|
+
const available =
|
|
475
|
+
(win.visualViewport?.width ?? win.innerWidth) - 2 * Math.max(0, collisionPadding)
|
|
476
|
+
const width = `${Math.min(trigger.getBoundingClientRect().width, Math.max(0, available))}px`
|
|
477
|
+
if (node.style.getPropertyValue('--_rad-select-width') !== width)
|
|
478
|
+
node.style.setProperty('--_rad-select-width', width)
|
|
479
|
+
}
|
|
480
|
+
// Top-layer auto layout is viewport-sized. Establish the anchor width before it can paint.
|
|
481
|
+
seedWidth()
|
|
482
|
+
node.showPopover()
|
|
483
|
+
const place = () => {
|
|
484
|
+
if (!node.isConnected || !node.matches(':popover-open')) return
|
|
485
|
+
seedWidth()
|
|
486
|
+
const viewport = win.visualViewport
|
|
487
|
+
const selected = Array.from(
|
|
488
|
+
node.querySelectorAll<HTMLElement>('[data-slot~="select-item"]')
|
|
489
|
+
).find(item => item.dataset.value === latest.current.value)
|
|
490
|
+
const rect = trigger.getBoundingClientRect()
|
|
491
|
+
const computed = win.getComputedStyle(node)
|
|
492
|
+
const viewportNode = node.querySelector<HTMLElement>('[data-slot="select-viewport"]')
|
|
493
|
+
const naturalHeight = viewportNode
|
|
494
|
+
? viewportNode.scrollHeight +
|
|
495
|
+
parseFloat(computed.paddingTop) +
|
|
496
|
+
parseFloat(computed.paddingBottom)
|
|
497
|
+
: node.scrollHeight
|
|
498
|
+
const next = positionSelect({
|
|
499
|
+
trigger: rect,
|
|
500
|
+
width: node.getBoundingClientRect().width,
|
|
501
|
+
height:
|
|
502
|
+
naturalHeight +
|
|
503
|
+
parseFloat(computed.borderTopWidth) +
|
|
504
|
+
parseFloat(computed.borderBottomWidth),
|
|
505
|
+
selectedOffset: selected ? selected.offsetTop + selected.offsetHeight / 2 : 24,
|
|
506
|
+
viewport: {
|
|
507
|
+
top: viewport?.offsetTop ?? 0,
|
|
508
|
+
left: viewport?.offsetLeft ?? 0,
|
|
509
|
+
width: viewport?.width ?? win.innerWidth,
|
|
510
|
+
height: viewport?.height ?? win.innerHeight
|
|
511
|
+
},
|
|
512
|
+
padding: Math.max(0, collisionPadding),
|
|
513
|
+
offset: sideOffset,
|
|
514
|
+
aligned: position === 'item-aligned',
|
|
515
|
+
rtl: win.getComputedStyle(trigger).direction === 'rtl'
|
|
516
|
+
})
|
|
517
|
+
for (const [key, value] of Object.entries({
|
|
518
|
+
top: next.top,
|
|
519
|
+
left: next.left,
|
|
520
|
+
width: next.width,
|
|
521
|
+
'max-height': next.maxHeight
|
|
522
|
+
}))
|
|
523
|
+
if (node.style.getPropertyValue(`--_rad-select-${key}`) !== `${value}px`)
|
|
524
|
+
node.style.setProperty(`--_rad-select-${key}`, `${value}px`)
|
|
525
|
+
}
|
|
526
|
+
place()
|
|
527
|
+
const active = doc.activeElement as HTMLElement | null
|
|
528
|
+
if (
|
|
529
|
+
!wasOpen.current ||
|
|
530
|
+
active === doc.body ||
|
|
531
|
+
active?.getAttribute('aria-disabled') === 'true'
|
|
532
|
+
) {
|
|
533
|
+
const first =
|
|
534
|
+
state.items.find(item => item.value === state.value && !item.disabled) ??
|
|
535
|
+
state.items.find(item => !item.disabled)
|
|
536
|
+
if (first) state.focus(first.value)
|
|
537
|
+
else node.focus()
|
|
538
|
+
}
|
|
539
|
+
wasOpen.current = true
|
|
540
|
+
const outside = (event: PointerEvent) => {
|
|
541
|
+
const target = event.target
|
|
542
|
+
if (!(target instanceof win.Node) || node.contains(target) || trigger.contains(target)) return
|
|
543
|
+
latest.current.close(false)
|
|
544
|
+
}
|
|
545
|
+
const focusOut = (event: FocusEvent) => {
|
|
546
|
+
const target = event.target
|
|
547
|
+
if (target === doc.body || target === doc.documentElement) return
|
|
548
|
+
if (target instanceof win.Node && !node.contains(target) && !trigger.contains(target))
|
|
549
|
+
latest.current.close(false)
|
|
550
|
+
}
|
|
551
|
+
const scroll = (event: Event) => {
|
|
552
|
+
if (!(event.target instanceof win.Node) || !node.contains(event.target)) place()
|
|
553
|
+
}
|
|
554
|
+
let frame = 0
|
|
555
|
+
const schedule = () => {
|
|
556
|
+
if (!frame)
|
|
557
|
+
frame = win.requestAnimationFrame(() => {
|
|
558
|
+
frame = 0
|
|
559
|
+
place()
|
|
560
|
+
})
|
|
561
|
+
}
|
|
562
|
+
const observer = new win.ResizeObserver(schedule)
|
|
563
|
+
const mutations = new win.MutationObserver(schedule)
|
|
564
|
+
mutations.observe(node, { childList: true, subtree: true, characterData: true })
|
|
565
|
+
observer.observe(trigger)
|
|
566
|
+
observer.observe(node)
|
|
567
|
+
doc.addEventListener('pointerdown', outside, true)
|
|
568
|
+
doc.addEventListener('focusin', focusOut)
|
|
569
|
+
doc.addEventListener('scroll', scroll, true)
|
|
570
|
+
win.addEventListener('resize', place)
|
|
571
|
+
win.visualViewport?.addEventListener('resize', place)
|
|
572
|
+
win.visualViewport?.addEventListener('scroll', place)
|
|
573
|
+
return () => {
|
|
574
|
+
observer.disconnect()
|
|
575
|
+
mutations.disconnect()
|
|
576
|
+
win.cancelAnimationFrame(frame)
|
|
577
|
+
doc.removeEventListener('pointerdown', outside, true)
|
|
578
|
+
doc.removeEventListener('focusin', focusOut)
|
|
579
|
+
doc.removeEventListener('scroll', scroll, true)
|
|
580
|
+
win.removeEventListener('resize', place)
|
|
581
|
+
win.visualViewport?.removeEventListener('resize', place)
|
|
582
|
+
win.visualViewport?.removeEventListener('scroll', place)
|
|
583
|
+
}
|
|
584
|
+
}, [select.open, select.trigger, select.items, position, sideOffset, collisionPadding])
|
|
585
|
+
useLayoutEffect(() => {
|
|
586
|
+
const node = select.content.current
|
|
587
|
+
const trigger = select.trigger
|
|
588
|
+
return () => {
|
|
589
|
+
if (node?.contains(node.ownerDocument.activeElement) && trigger?.isConnected)
|
|
590
|
+
trigger.focus({ preventScroll: true })
|
|
591
|
+
}
|
|
592
|
+
}, [select.content, select.trigger])
|
|
593
|
+
return (
|
|
594
|
+
<div
|
|
595
|
+
{...props}
|
|
596
|
+
ref={transitionRef}
|
|
597
|
+
id={select.contentId}
|
|
598
|
+
popover="manual"
|
|
599
|
+
role="listbox"
|
|
600
|
+
tabIndex={-1}
|
|
601
|
+
aria-labelledby={
|
|
602
|
+
props['aria-label'] ? undefined : (select.labelId ?? select.trigger?.id ?? select.triggerId)
|
|
603
|
+
}
|
|
604
|
+
className={cn(
|
|
605
|
+
selectContentClass,
|
|
606
|
+
controlMetrics({ controlSize: select.controlSize }),
|
|
607
|
+
motionActive &&
|
|
608
|
+
!motionOff &&
|
|
609
|
+
'opacity-[var(--_rad-select-enter,0)] motion-reduce:opacity-100',
|
|
610
|
+
className
|
|
611
|
+
)}
|
|
612
|
+
data-slot="select-content"
|
|
613
|
+
data-state={select.open ? 'open' : 'closed'}
|
|
614
|
+
data-motion={motion}
|
|
615
|
+
data-position={position}
|
|
616
|
+
onKeyDown={event => {
|
|
617
|
+
onKeyDown?.(event)
|
|
618
|
+
if (event.defaultPrevented) return
|
|
619
|
+
if (event.key === 'Escape') {
|
|
620
|
+
event.preventDefault()
|
|
621
|
+
event.stopPropagation()
|
|
622
|
+
select.close()
|
|
623
|
+
return
|
|
624
|
+
}
|
|
625
|
+
if (event.key === 'Tab') {
|
|
626
|
+
event.preventDefault()
|
|
627
|
+
return
|
|
628
|
+
}
|
|
629
|
+
if (event.ctrlKey || event.altKey || event.metaKey) return
|
|
630
|
+
const target = event.target as HTMLElement
|
|
631
|
+
const current =
|
|
632
|
+
target.closest<HTMLElement>('[data-slot~="select-item"]')?.dataset.value ?? null
|
|
633
|
+
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
|
|
634
|
+
event.preventDefault()
|
|
635
|
+
select.focus(moveSelectFocus(select.entries, current, event.key))
|
|
636
|
+
} else if (event.key.length === 1 && event.key !== ' ') {
|
|
637
|
+
event.preventDefault()
|
|
638
|
+
select.focus(select.search(event.key, current))
|
|
639
|
+
}
|
|
640
|
+
}}
|
|
641
|
+
>
|
|
642
|
+
{children ?? (
|
|
643
|
+
<SelectViewport>
|
|
644
|
+
{select.items.map(item => (
|
|
645
|
+
<SelectItem
|
|
646
|
+
key={item.value}
|
|
647
|
+
value={item.value}
|
|
648
|
+
>
|
|
649
|
+
<SelectItemText />
|
|
650
|
+
<SelectItemIndicator />
|
|
651
|
+
</SelectItem>
|
|
652
|
+
))}
|
|
653
|
+
</SelectViewport>
|
|
654
|
+
)}
|
|
655
|
+
</div>
|
|
656
|
+
)
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
export type SelectViewportProps = Omit<ComponentProps<'div'>, 'style'> & { style?: ThemeStyle }
|
|
660
|
+
export function SelectViewport({ className, ...props }: SelectViewportProps) {
|
|
661
|
+
return (
|
|
662
|
+
<div
|
|
663
|
+
{...props}
|
|
664
|
+
data-slot="select-viewport"
|
|
665
|
+
className={cn(
|
|
666
|
+
'max-h-[calc(var(--_rad-select-max-height,100dvh)-0.5rem)] overflow-y-auto overscroll-contain',
|
|
667
|
+
className
|
|
668
|
+
)}
|
|
669
|
+
/>
|
|
670
|
+
)
|
|
671
|
+
}
|
|
672
|
+
export type SelectItemProps = Omit<ComponentProps<'div'>, 'style'> & {
|
|
673
|
+
value: string
|
|
674
|
+
style?: ThemeStyle
|
|
675
|
+
}
|
|
676
|
+
export function SelectItem({
|
|
677
|
+
value,
|
|
678
|
+
children,
|
|
679
|
+
className,
|
|
680
|
+
onKeyDown,
|
|
681
|
+
onClick,
|
|
682
|
+
onPointerMove,
|
|
683
|
+
...props
|
|
684
|
+
}: SelectItemProps) {
|
|
685
|
+
const select = useSelectContext()
|
|
686
|
+
const item = select.items.find(item => item.value === value)
|
|
687
|
+
if (!item) throw new Error('SelectItem value must exist in Select items.')
|
|
688
|
+
return (
|
|
689
|
+
<SelectItemContext.Provider value={item}>
|
|
690
|
+
<div
|
|
691
|
+
{...props}
|
|
692
|
+
role="option"
|
|
693
|
+
tabIndex={-1}
|
|
694
|
+
aria-selected={select.value === value}
|
|
695
|
+
aria-disabled={item.disabled || undefined}
|
|
696
|
+
data-slot="select-item"
|
|
697
|
+
data-value={value}
|
|
698
|
+
data-disabled={item.disabled ? '' : undefined}
|
|
699
|
+
data-state={select.value === value ? 'checked' : 'unchecked'}
|
|
700
|
+
className={cn(selectItemClass, className)}
|
|
701
|
+
onClick={event => {
|
|
702
|
+
onClick?.(event)
|
|
703
|
+
if (!event.defaultPrevented && !item.disabled) select.commit(value)
|
|
704
|
+
}}
|
|
705
|
+
onPointerMove={event => {
|
|
706
|
+
onPointerMove?.(event)
|
|
707
|
+
if (!event.defaultPrevented && event.pointerType === 'mouse' && !item.disabled)
|
|
708
|
+
event.currentTarget.focus({ preventScroll: true })
|
|
709
|
+
}}
|
|
710
|
+
onKeyDown={event => {
|
|
711
|
+
onKeyDown?.(event)
|
|
712
|
+
if (!event.defaultPrevented && ['Enter', ' '].includes(event.key)) {
|
|
713
|
+
event.preventDefault()
|
|
714
|
+
if (!item.disabled) select.commit(value)
|
|
715
|
+
}
|
|
716
|
+
}}
|
|
717
|
+
>
|
|
718
|
+
{children ?? (
|
|
719
|
+
<>
|
|
720
|
+
<SelectItemText />
|
|
721
|
+
<SelectItemIndicator />
|
|
722
|
+
</>
|
|
723
|
+
)}
|
|
724
|
+
</div>
|
|
725
|
+
</SelectItemContext.Provider>
|
|
726
|
+
)
|
|
727
|
+
}
|
|
728
|
+
export type SelectItemTextProps = Omit<ComponentProps<'span'>, 'style'> & { style?: ThemeStyle }
|
|
729
|
+
export function SelectItemText({ children, className, ...props }: SelectItemTextProps) {
|
|
730
|
+
const item = useContext(SelectItemContext)
|
|
731
|
+
if (!item) throw new Error('SelectItemText must render inside SelectItem.')
|
|
732
|
+
return (
|
|
733
|
+
<span
|
|
734
|
+
{...props}
|
|
735
|
+
data-slot="select-item-text"
|
|
736
|
+
className={cn('min-w-0 flex-1', className)}
|
|
737
|
+
>
|
|
738
|
+
{children ?? item.label}
|
|
739
|
+
</span>
|
|
740
|
+
)
|
|
741
|
+
}
|
|
742
|
+
export function SelectItemIndicator({ children, className, ...props }: SelectIconProps) {
|
|
743
|
+
const select = useSelectContext()
|
|
744
|
+
const item = useContext(SelectItemContext)
|
|
745
|
+
if (!item) throw new Error('SelectItemIndicator must render inside SelectItem.')
|
|
746
|
+
return (
|
|
747
|
+
<span
|
|
748
|
+
{...props}
|
|
749
|
+
data-slot="select-item-indicator"
|
|
750
|
+
aria-hidden="true"
|
|
751
|
+
className={cn('shrink-0', select.value !== item.value && 'invisible', className)}
|
|
752
|
+
>
|
|
753
|
+
{children ?? '✓'}
|
|
754
|
+
</span>
|
|
755
|
+
)
|
|
756
|
+
}
|
|
757
|
+
export type SelectGroupProps = Omit<ComponentProps<'div'>, 'style'> & {
|
|
758
|
+
label: ReactNode
|
|
759
|
+
style?: ThemeStyle
|
|
760
|
+
}
|
|
761
|
+
export function SelectGroup({ label, children, className, ...props }: SelectGroupProps) {
|
|
762
|
+
const id = useId()
|
|
763
|
+
return (
|
|
764
|
+
<div
|
|
765
|
+
{...props}
|
|
766
|
+
role="group"
|
|
767
|
+
aria-labelledby={id}
|
|
768
|
+
data-slot="select-group"
|
|
769
|
+
className={className}
|
|
770
|
+
>
|
|
771
|
+
<div
|
|
772
|
+
id={id}
|
|
773
|
+
data-slot="select-label"
|
|
774
|
+
className="px-3 py-2 text-sm font-semibold"
|
|
775
|
+
>
|
|
776
|
+
{label}
|
|
777
|
+
</div>
|
|
778
|
+
{children}
|
|
779
|
+
</div>
|
|
780
|
+
)
|
|
781
|
+
}
|