@cognitap/radiant 0.0.83 → 0.0.84

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.
Files changed (102) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/library/color/colorValue.d.ts +8 -0
  3. package/dist/library/color/colorValue.d.ts.map +1 -0
  4. package/dist/library/color/colorValue.js +87 -0
  5. package/dist/library/color/colorValue.js.map +1 -0
  6. package/dist/library/color/oklch.d.ts +2 -0
  7. package/dist/library/color/oklch.d.ts.map +1 -1
  8. package/dist/library/color/oklch.js +27 -11
  9. package/dist/library/color/oklch.js.map +1 -1
  10. package/dist/library/components/Cascader/Cascader.d.ts +25 -0
  11. package/dist/library/components/Cascader/Cascader.d.ts.map +1 -0
  12. package/dist/library/components/Cascader/Cascader.js +154 -0
  13. package/dist/library/components/Cascader/Cascader.js.map +1 -0
  14. package/dist/library/components/Cascader/CascaderColumn.d.ts +25 -0
  15. package/dist/library/components/Cascader/CascaderColumn.d.ts.map +1 -0
  16. package/dist/library/components/Cascader/CascaderColumn.js +80 -0
  17. package/dist/library/components/Cascader/CascaderColumn.js.map +1 -0
  18. package/dist/library/components/ColorInput/ColorInput.d.ts +22 -0
  19. package/dist/library/components/ColorInput/ColorInput.d.ts.map +1 -0
  20. package/dist/library/components/ColorInput/ColorInput.js +63 -0
  21. package/dist/library/components/ColorInput/ColorInput.js.map +1 -0
  22. package/dist/library/components/ColorPicker/ColorArea.d.ts +11 -0
  23. package/dist/library/components/ColorPicker/ColorArea.d.ts.map +1 -0
  24. package/dist/library/components/ColorPicker/ColorArea.js +58 -0
  25. package/dist/library/components/ColorPicker/ColorArea.js.map +1 -0
  26. package/dist/library/components/ColorPicker/ColorPicker.d.ts +37 -0
  27. package/dist/library/components/ColorPicker/ColorPicker.d.ts.map +1 -0
  28. package/dist/library/components/ColorPicker/ColorPicker.js +135 -0
  29. package/dist/library/components/ColorPicker/ColorPicker.js.map +1 -0
  30. package/dist/library/components/DataTable/DataTable.d.ts +47 -0
  31. package/dist/library/components/DataTable/DataTable.d.ts.map +1 -0
  32. package/dist/library/components/DataTable/DataTable.js +146 -0
  33. package/dist/library/components/DataTable/DataTable.js.map +1 -0
  34. package/dist/library/components/Rating/Rating.d.ts +21 -0
  35. package/dist/library/components/Rating/Rating.d.ts.map +1 -0
  36. package/dist/library/components/Rating/Rating.js +81 -0
  37. package/dist/library/components/Rating/Rating.js.map +1 -0
  38. package/dist/library/components/Select/Select.d.ts +3 -9
  39. package/dist/library/components/Select/Select.d.ts.map +1 -1
  40. package/dist/library/components/Select/Select.js +16 -156
  41. package/dist/library/components/Select/Select.js.map +1 -1
  42. package/dist/library/components/Select/SelectPopup.d.ts +29 -0
  43. package/dist/library/components/Select/SelectPopup.d.ts.map +1 -0
  44. package/dist/library/components/Select/SelectPopup.js +179 -0
  45. package/dist/library/components/Select/SelectPopup.js.map +1 -0
  46. package/dist/library/components/Slider/Slider.d.ts +2 -2
  47. package/dist/library/components/Slider/Slider.d.ts.map +1 -1
  48. package/dist/library/components/Slider/Slider.js +44 -3
  49. package/dist/library/components/Slider/Slider.js.map +1 -1
  50. package/dist/library/components/Stepper/Stepper.d.ts +48 -0
  51. package/dist/library/components/Stepper/Stepper.d.ts.map +1 -0
  52. package/dist/library/components/Stepper/Stepper.js +81 -0
  53. package/dist/library/components/Stepper/Stepper.js.map +1 -0
  54. package/dist/library/components/Timeline/Timeline.d.ts +30 -0
  55. package/dist/library/components/Timeline/Timeline.d.ts.map +1 -0
  56. package/dist/library/components/Timeline/Timeline.js +15 -0
  57. package/dist/library/components/Timeline/Timeline.js.map +1 -0
  58. package/dist/library/components/Tree/Tree.d.ts +48 -0
  59. package/dist/library/components/Tree/Tree.d.ts.map +1 -0
  60. package/dist/library/components/Tree/Tree.js +298 -0
  61. package/dist/library/components/Tree/Tree.js.map +1 -0
  62. package/dist/library/components/Tree/treeModel.d.ts +43 -0
  63. package/dist/library/components/Tree/treeModel.d.ts.map +1 -0
  64. package/dist/library/components/Tree/treeModel.js +83 -0
  65. package/dist/library/components/Tree/treeModel.js.map +1 -0
  66. package/dist/library/components/Tree/useTreeLoading.d.ts +6 -0
  67. package/dist/library/components/Tree/useTreeLoading.d.ts.map +1 -0
  68. package/dist/library/components/Tree/useTreeLoading.js +69 -0
  69. package/dist/library/components/Tree/useTreeLoading.js.map +1 -0
  70. package/dist/library/components/TreeSelect/TreeSelect.d.ts +29 -0
  71. package/dist/library/components/TreeSelect/TreeSelect.d.ts.map +1 -0
  72. package/dist/library/components/TreeSelect/TreeSelect.js +163 -0
  73. package/dist/library/components/TreeSelect/TreeSelect.js.map +1 -0
  74. package/dist/library/index.d.ts +10 -0
  75. package/dist/library/index.d.ts.map +1 -1
  76. package/dist/library/index.js +9 -0
  77. package/dist/library/index.js.map +1 -1
  78. package/dist/library/react/useFormReset.d.ts +1 -1
  79. package/dist/library/react/useFormReset.d.ts.map +1 -1
  80. package/dist/library/react/useFormReset.js.map +1 -1
  81. package/dist/library/styles.css +1 -1
  82. package/package.json +1 -1
  83. package/src/color/colorValue.ts +89 -0
  84. package/src/color/oklch.ts +33 -14
  85. package/src/components/Cascader/Cascader.tsx +315 -0
  86. package/src/components/Cascader/CascaderColumn.tsx +203 -0
  87. package/src/components/ColorInput/ColorInput.tsx +191 -0
  88. package/src/components/ColorPicker/ColorArea.tsx +98 -0
  89. package/src/components/ColorPicker/ColorPicker.tsx +283 -0
  90. package/src/components/DataTable/DataTable.tsx +384 -0
  91. package/src/components/Rating/Rating.tsx +202 -0
  92. package/src/components/Select/Select.tsx +20 -192
  93. package/src/components/Select/SelectPopup.tsx +246 -0
  94. package/src/components/Slider/Slider.tsx +51 -2
  95. package/src/components/Stepper/Stepper.tsx +306 -0
  96. package/src/components/Timeline/Timeline.tsx +139 -0
  97. package/src/components/Tree/Tree.tsx +530 -0
  98. package/src/components/Tree/treeModel.ts +110 -0
  99. package/src/components/Tree/useTreeLoading.ts +73 -0
  100. package/src/components/TreeSelect/TreeSelect.tsx +326 -0
  101. package/src/index.ts +35 -0
  102. package/src/react/useFormReset.ts +4 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cognitap/radiant",
3
- "version": "0.0.83",
3
+ "version": "0.0.84",
4
4
  "description": "React interaction components and presentation primitives",
5
5
  "homepage": "https://radiant-docs.pages.dev",
6
6
  "bugs": {
@@ -0,0 +1,89 @@
1
+ import { clamp, rgbToOklch, srgbMapper, wrapHue, type OklchColor } from './oklch.js'
2
+
3
+ export type ColorFormat = 'oklch' | 'hex' | 'rgb'
4
+ export type ColorChannels = Omit<OklchColor, 'value'> & { alpha: number }
5
+
6
+ const number = '[+-]?(?:[0-9]+(?:\\.[0-9]+)?|\\.[0-9]+)(?:e[+-]?[0-9]+)?'
7
+ const numeric = new RegExp('^(' + number + ')(%)?$', 'i')
8
+ const angle = new RegExp('^(' + number + ')(deg|grad|rad|turn)?$', 'i')
9
+ const angleScale = { deg: 1, grad: 0.9, rad: 180 / Math.PI, turn: 360 }
10
+
11
+ function scalar(token: string, fullScale: number): number {
12
+ const parts = numeric.exec(token)
13
+ if (!parts) return NaN
14
+ const value = Number(parts[1])
15
+ return parts[2] ? (value / 100) * fullScale : value
16
+ }
17
+
18
+ function hexColor(value: string): ColorChannels | null {
19
+ if (!/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.test(value)) return null
20
+ const hex =
21
+ value.length <= 5
22
+ ? value
23
+ .slice(1)
24
+ .split('')
25
+ .map(digit => digit.repeat(2))
26
+ .join('')
27
+ : value.slice(1)
28
+ const [r, g, b] = [0, 2, 4].map(index => parseInt(hex.slice(index, index + 2), 16) / 255)
29
+ return { ...rgbToOklch(r, g, b), alpha: hex.length === 8 ? parseInt(hex.slice(6), 16) / 255 : 1 }
30
+ }
31
+
32
+ export function parseColor(value: string): ColorChannels | null {
33
+ const text = value.trim().toLowerCase()
34
+ if (text.startsWith('#')) return hexColor(text)
35
+ const match = /^(oklch|rgb|rgba)\(\s*(.*?)\s*\)$/.exec(text)
36
+ if (!match) return null
37
+ const rgb = match[1] !== 'oklch'
38
+ const [body, opacity, extra] = match[2].split('/')
39
+ if (extra !== undefined) return null
40
+ const commaSeparated = body.includes(',')
41
+ if (commaSeparated && (!rgb || opacity !== undefined)) return null
42
+ const values = commaSeparated
43
+ ? body.split(',').map(token => token.trim())
44
+ : body.trim().split(/\s+/)
45
+ const alphaToken = commaSeparated ? values.splice(3, 1)[0] : opacity?.trim()
46
+ if (values.length !== 3) return null
47
+ const alpha = alphaToken === undefined ? 1 : scalar(alphaToken, 1)
48
+ if (!Number.isFinite(alpha)) return null
49
+
50
+ if (rgb) {
51
+ const channels = values.map(token => scalar(token, 255))
52
+ if (!channels.every(Number.isFinite)) return null
53
+ const [r, g, b] = channels.map(channel => clamp(channel / 255))
54
+ return { ...rgbToOklch(r, g, b), alpha: clamp(alpha) }
55
+ }
56
+
57
+ const L = scalar(values[0], 1)
58
+ const C = scalar(values[1], 0.4)
59
+ const degrees = angle.exec(values[2])
60
+ const unit = (degrees?.[2] ?? 'deg') as keyof typeof angleScale
61
+ const hue = degrees ? Number(degrees[1]) * angleScale[unit] : NaN
62
+ if (![L, C, hue].every(Number.isFinite)) return null
63
+ return { L: clamp(L), C: Math.max(0, C), h: wrapHue(hue), alpha: clamp(alpha) }
64
+ }
65
+
66
+ function formatNumber(value: number, places: number) {
67
+ return Number(value.toFixed(places)).toString()
68
+ }
69
+
70
+ export function formatColor(color: ColorChannels, format: ColorFormat): string {
71
+ if (format === 'oklch') {
72
+ const tail = color.alpha === 1 ? '' : ' / ' + formatNumber(color.alpha, 4)
73
+ return `oklch(${formatNumber(color.L * 100, 4)}% ${formatNumber(color.C, 5)} ${formatNumber(wrapHue(color.h), 3)}${tail})`
74
+ }
75
+ const hex = srgbMapper().toHex(color.L, color.C, color.h)
76
+ if (format === 'hex') {
77
+ const suffix =
78
+ color.alpha === 1
79
+ ? ''
80
+ : Math.round(color.alpha * 255)
81
+ .toString(16)
82
+ .padStart(2, '0')
83
+ .toUpperCase()
84
+ return hex + suffix
85
+ }
86
+ const rgb = [1, 3, 5].map(index => parseInt(hex.slice(index, index + 2), 16)).join(' ')
87
+ const tail = color.alpha === 1 ? '' : ' / ' + formatNumber(color.alpha, 4)
88
+ return `rgb(${rgb}${tail})`
89
+ }
@@ -16,7 +16,14 @@ const encoded = (n: number) =>
16
16
  n <= 0.0031308 ? 12.92 * n : 1.055 * Math.max(0, n) ** (1 / 2.4) - 0.055
17
17
 
18
18
  export function measureHex(hex: string): OklchColor {
19
- const [r, g, b] = [1, 3, 5].map(i => linear(parseInt(hex.slice(i, i + 2), 16) / 255))
19
+ const [r, g, b] = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255)
20
+ return { value: hex, ...rgbToOklch(r, g, b) }
21
+ }
22
+
23
+ export function rgbToOklch(red: number, green: number, blue: number): Omit<OklchColor, 'value'> {
24
+ const r = linear(red)
25
+ const g = linear(green)
26
+ const b = linear(blue)
20
27
  const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
21
28
  const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
22
29
  const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
@@ -24,7 +31,7 @@ export function measureHex(hex: string): OklchColor {
24
31
  const a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s
25
32
  const bAxis = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s
26
33
  const C = Math.hypot(a, bAxis)
27
- return { value: hex, L, C, h: C < 1e-6 ? 0 : wrapHue((Math.atan2(bAxis, a) * 180) / Math.PI) }
34
+ return { L, C, h: C < 1e-6 ? 0 : wrapHue((Math.atan2(bAxis, a) * 180) / Math.PI) }
28
35
  }
29
36
 
30
37
  function linearRgb(L: number, C: number, h: number): Triple {
@@ -41,6 +48,20 @@ function linearRgb(L: number, C: number, h: number): Triple {
41
48
  ]
42
49
  }
43
50
 
51
+ function encodeLinearRgb(rgb: Triple): string {
52
+ return (
53
+ '#' +
54
+ rgb
55
+ .map(channel =>
56
+ Math.round(clamp(encoded(channel)) * 255)
57
+ .toString(16)
58
+ .padStart(2, '0')
59
+ )
60
+ .join('')
61
+ .toUpperCase()
62
+ )
63
+ }
64
+
44
65
  /** Per-generation caches: bounded by this wall, without history-dependent global state. */
45
66
  export function srgbMapper() {
46
67
  const chromas = new Map<string, number>(),
@@ -79,17 +100,15 @@ export function srgbMapper() {
79
100
  }
80
101
  function map(L: number, C: number, h: number): OklchColor {
81
102
  const rgb = linearRgb(clamp(L), Math.min(C, maxChroma(L, h)), h)
82
- const value =
83
- '#' +
84
- rgb
85
- .map(n =>
86
- Math.round(clamp(encoded(n)) * 255)
87
- .toString(16)
88
- .padStart(2, '0')
89
- )
90
- .join('')
91
- .toUpperCase()
92
- return measureHex(value)
103
+ return measureHex(encodeLinearRgb(rgb))
104
+ }
105
+ function toHex(L: number, C: number, h: number): string {
106
+ const rgb = linearRgb(clamp(L), C, h)
107
+ // Preserve existing sRGB colors, including the blue corner outside the first chroma boundary.
108
+ // The tolerance is below half of one encoded channel step and absorbs OKLCH rounding.
109
+ return rgb.every(channel => channel >= -0.0001 && channel <= 1.0001)
110
+ ? encodeLinearRgb(rgb)
111
+ : map(L, C, h).value
93
112
  }
94
- return { maxChroma, cuspLightness, map }
113
+ return { maxChroma, cuspLightness, map, toHex }
95
114
  }
@@ -0,0 +1,315 @@
1
+ 'use client'
2
+
3
+ import { useId, useLayoutEffect, useRef, useState, type ComponentProps } from 'react'
4
+ import { cn } from 'cn'
5
+ import { requireAccessibleName } from '../../internal/accessibleName.js'
6
+ import { joinIds } from '../../internal/ids.js'
7
+ import type { ControlSize, PartStyle } from '../../presentation.js'
8
+ import { useComposedRefs } from '../../react/useComposedRefs.js'
9
+ import { useControllableState } from '../../react/useControllableState.js'
10
+ import { useFormReset } from '../../react/useFormReset.js'
11
+ import type { ValueOwner } from '../../react/useNativeOwner.js'
12
+ import type { ThemeStyle } from '../../themes/defineTheme.js'
13
+ import { Button } from '../Button/Button.js'
14
+ import { useField, useFieldControl } from '../Field/Field.js'
15
+ import { SelectIcon, SelectViewport } from '../Select/Select.js'
16
+ import { SelectPopup } from '../Select/SelectPopup.js'
17
+ import { selectTriggerClass } from '../Select/selectStyles.js'
18
+ import { controlMetrics } from '../shared/controlStyles.js'
19
+ import { useTreeCollection } from '../Tree/Tree.js'
20
+ import { treePath, type TreeItem, type TreeNode } from '../Tree/treeModel.js'
21
+ import { CascaderColumn, isCascaderBranch } from './CascaderColumn.js'
22
+
23
+ export type CascaderProps = Pick<
24
+ ComponentProps<'button'>,
25
+ | 'id'
26
+ | 'ref'
27
+ | 'name'
28
+ | 'form'
29
+ | 'disabled'
30
+ | 'aria-label'
31
+ | 'aria-labelledby'
32
+ | 'aria-describedby'
33
+ | 'aria-invalid'
34
+ | 'onClick'
35
+ | 'onKeyDown'
36
+ | 'className'
37
+ > &
38
+ ValueOwner<string | null> & {
39
+ items: readonly TreeItem[]
40
+ /** The committed leaf key. */
41
+ onValueChange?: (value: string | null) => void
42
+ /** Optional listbox headings in root-to-leaf order. */
43
+ columnLabels?: readonly string[]
44
+ placeholder?: string
45
+ required?: boolean
46
+ controlSize?: ControlSize
47
+ loadingText?: string
48
+ errorText?: string
49
+ emptyText?: string
50
+ style?: ThemeStyle
51
+ parts?: { content?: PartStyle; column?: PartStyle }
52
+ }
53
+
54
+ type Cursor = { column: number; value?: string }
55
+
56
+ export function Cascader({
57
+ items,
58
+ value,
59
+ defaultValue,
60
+ onValueChange,
61
+ columnLabels,
62
+ placeholder = 'Select an item',
63
+ loadingText = 'Loading…',
64
+ errorText = 'Could not load. Retry',
65
+ emptyText = 'No options',
66
+ controlSize = 'medium',
67
+ parts,
68
+ className,
69
+ onClick,
70
+ onKeyDown,
71
+ ref,
72
+ name,
73
+ form,
74
+ ...attributes
75
+ }: CascaderProps) {
76
+ const { model, load } = useTreeCollection(items)
77
+ const selection = useControllableState({
78
+ name: 'Cascader value',
79
+ value,
80
+ defaultValue,
81
+ initialValue: null,
82
+ onChange: onValueChange
83
+ })
84
+ const committed = selection.value === null ? undefined : model.byValue.get(selection.value)
85
+ const pathText = treePath(committed)
86
+ .map(node => node.textValue)
87
+ .join(' / ')
88
+ const submitted =
89
+ committed && (committed.disabled || isCascaderBranch(committed)) ? '' : (selection.value ?? '')
90
+ const [branch, setBranch] = useState<string | null>(null)
91
+ const [cursor, setCursor] = useState<Cursor>({ column: 0 })
92
+ const trail = treePath(branch === null ? undefined : model.byValue.get(branch)).filter(
93
+ node => !node.disabled && isCascaderBranch(node)
94
+ )
95
+ const depth = Math.min(cursor.column, trail.length)
96
+
97
+ const control = useFieldControl(attributes)
98
+ const field = useField()
99
+ const labelId =
100
+ attributes['aria-labelledby'] ?? (field?.layout === 'control' ? field.labelId : undefined)
101
+ requireAccessibleName('Cascader', {
102
+ 'aria-label': attributes['aria-label'],
103
+ 'aria-labelledby': labelId
104
+ })
105
+ const id = useId()
106
+ const pickerLabel = labelId ?? id + '-label'
107
+ const contentId = id + '-content'
108
+ const valueId = id + '-value'
109
+ const [trigger, setTrigger] = useState<HTMLButtonElement | null>(null)
110
+ const triggerRef = useComposedRefs(ref, setTrigger)
111
+ const content = useRef<HTMLDivElement>(null)
112
+ const bridge = useRef<HTMLSelectElement>(null)
113
+ const restoreFocus = useRef(true)
114
+ const [open, setOpen] = useState(false)
115
+ const [reportedInvalid, setReportedInvalid] = useState(false)
116
+ if (open && control.disabled) setOpen(false)
117
+ const shown = open && !control.disabled
118
+ const invalid = control['aria-invalid'] || (reportedInvalid && !submitted) || undefined
119
+
120
+ function close(restore = true) {
121
+ restoreFocus.current = restore
122
+ setOpen(false)
123
+ }
124
+
125
+ function show() {
126
+ if (control.disabled || trigger?.matches(':disabled')) return
127
+ const parent = committed?.disabled ? null : committed?.parent
128
+ setBranch(parent?.value ?? null)
129
+ setCursor({ column: parent?.level ?? 0, value: committed?.value })
130
+ restoreFocus.current = true
131
+ setOpen(true)
132
+ }
133
+
134
+ function navigateInto(node: TreeNode, column: number) {
135
+ if (isCascaderBranch(node)) {
136
+ setBranch(node.value)
137
+ setCursor({ column: column + 1 })
138
+ if (!node.load) load(node)
139
+ } else {
140
+ selection.request(node.value)
141
+ close()
142
+ }
143
+ }
144
+
145
+ useLayoutEffect(() => {
146
+ if (!shown) return
147
+ const column = content.current?.querySelector<HTMLElement>(
148
+ '[data-slot="cascader-column"][tabindex="0"]'
149
+ )
150
+ if (!column?.matches(':focus')) column?.focus({ preventScroll: true })
151
+ const target = column?.querySelector('[data-active]') ?? column
152
+ target?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
153
+ }, [shown, depth, cursor.value, model])
154
+
155
+ useLayoutEffect(() => {
156
+ for (const option of bridge.current?.options ?? []) option.defaultSelected = option.selected
157
+ }, [submitted])
158
+ useFormReset(bridge, () => {
159
+ selection.reset()
160
+ setReportedInvalid(false)
161
+ close(false)
162
+ })
163
+
164
+ return (
165
+ <>
166
+ {!labelId && (
167
+ <span
168
+ id={pickerLabel}
169
+ className="sr-only"
170
+ >
171
+ {attributes['aria-label']}
172
+ </span>
173
+ )}
174
+ <Button
175
+ ref={triggerRef}
176
+ id={control.id ?? id + '-trigger'}
177
+ type="button"
178
+ variant="outline"
179
+ tone="neutral"
180
+ controlSize={controlSize}
181
+ disabled={control.disabled}
182
+ motion="off"
183
+ aria-labelledby={joinIds(pickerLabel, valueId)}
184
+ aria-describedby={control['aria-describedby']}
185
+ aria-invalid={invalid}
186
+ aria-controls={trigger ? contentId : undefined}
187
+ aria-haspopup="dialog"
188
+ aria-expanded={shown}
189
+ data-invalid={invalid && invalid !== 'false' ? '' : undefined}
190
+ data-slot="cascader-trigger"
191
+ data-state={shown ? 'open' : 'closed'}
192
+ data-placeholder={selection.value === null ? '' : undefined}
193
+ style={attributes.style}
194
+ render={resolved => (
195
+ <button
196
+ {...resolved}
197
+ className={cn(selectTriggerClass, controlMetrics({ controlSize }), className)}
198
+ />
199
+ )}
200
+ onClick={event => {
201
+ onClick?.(event)
202
+ if (event.defaultPrevented) return
203
+ if (shown) close()
204
+ else show()
205
+ }}
206
+ onKeyDown={event => {
207
+ onKeyDown?.(event)
208
+ if (event.defaultPrevented || event.ctrlKey || event.altKey || event.metaKey) return
209
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
210
+ event.preventDefault()
211
+ show()
212
+ }
213
+ }}
214
+ >
215
+ <span
216
+ id={valueId}
217
+ data-slot="cascader-value"
218
+ className="min-w-0 truncate"
219
+ >
220
+ {pathText || selection.value || placeholder}
221
+ </span>
222
+ <SelectIcon data-slot="cascader-icon" />
223
+ </Button>
224
+ {trigger && (
225
+ <SelectPopup
226
+ state={{
227
+ open: shown,
228
+ trigger,
229
+ restoreFocus,
230
+ content,
231
+ close,
232
+ focusInitial: node =>
233
+ node
234
+ .querySelector<HTMLElement>('[data-slot="cascader-column"][tabindex="0"]')
235
+ ?.focus({ preventScroll: true })
236
+ }}
237
+ id={contentId}
238
+ // oxlint-disable-next-line jsx-a11y/prefer-tag-over-role -- The Select popup uses the popover top layer.
239
+ role="dialog"
240
+ aria-labelledby={pickerLabel}
241
+ controlSize={controlSize}
242
+ position="popper"
243
+ width="content"
244
+ data-slot="cascader-content"
245
+ className={parts?.content?.className}
246
+ style={parts?.content?.style}
247
+ onKeyDown={event => {
248
+ if (event.defaultPrevented) return
249
+ if (event.key === 'Escape' || (event.key === 'Tab' && event.shiftKey)) {
250
+ event.preventDefault()
251
+ event.stopPropagation()
252
+ close()
253
+ }
254
+ }}
255
+ >
256
+ <SelectViewport className="flex items-stretch overflow-x-auto">
257
+ {[undefined, ...trail].map((parent, column) => {
258
+ const entries = parent?.children ?? model.roots
259
+ const chosen =
260
+ trail[column]?.value ??
261
+ (committed?.parent === (parent ?? null) ? committed?.value : undefined)
262
+ return (
263
+ <CascaderColumn
264
+ key={parent ? 'branch-' + parent.value : 'root'}
265
+ id={id + '-column-' + column}
266
+ items={entries}
267
+ label={parent?.textValue}
268
+ labelledBy={parent ? undefined : pickerLabel}
269
+ heading={columnLabels?.[column]}
270
+ parent={parent}
271
+ selected={chosen}
272
+ current={depth === column ? cursor.value : undefined}
273
+ focused={depth === column}
274
+ loadingText={loadingText}
275
+ errorText={errorText}
276
+ emptyText={emptyText}
277
+ part={parts?.column}
278
+ onMove={value => setCursor({ column, value })}
279
+ onBack={() => {
280
+ if (column > 0) setCursor({ column: column - 1, value: parent?.value })
281
+ }}
282
+ onActivate={node => navigateInto(node, column)}
283
+ onRetry={() => {
284
+ if (parent) load(parent)
285
+ }}
286
+ />
287
+ )
288
+ })}
289
+ </SelectViewport>
290
+ </SelectPopup>
291
+ )}
292
+ <select
293
+ ref={bridge}
294
+ name={name}
295
+ form={form}
296
+ required={control.required}
297
+ disabled={control.disabled}
298
+ value={submitted}
299
+ onChange={() => {}}
300
+ onInvalid={event => {
301
+ event.preventDefault()
302
+ setReportedInvalid(true)
303
+ trigger?.focus()
304
+ }}
305
+ aria-hidden="true"
306
+ tabIndex={-1}
307
+ className="sr-only"
308
+ data-slot="cascader-native"
309
+ >
310
+ <option value="">{placeholder || 'No selection'}</option>
311
+ {submitted && <option value={submitted}>{pathText || submitted}</option>}
312
+ </select>
313
+ </>
314
+ )
315
+ }
@@ -0,0 +1,203 @@
1
+ 'use client'
2
+
3
+ /* oxlint-disable jsx-a11y/prefer-tag-over-role -- Cascading listboxes own active descendants and branch indicators. */
4
+
5
+ import { useRef, type KeyboardEvent } from 'react'
6
+ import { cn } from 'cn'
7
+ import { matchSelectText, moveSelectFocus } from '../../internal/select.js'
8
+ import { useLocaleMatcher } from '../../react/useLocale.js'
9
+ import type { PartStyle } from '../../presentation.js'
10
+ import { selectItemClass } from '../Select/selectStyles.js'
11
+ import { scrollbarClass } from '../shared/scrollbarStyles.js'
12
+ import type { TreeNode } from '../Tree/treeModel.js'
13
+
14
+ export function isCascaderBranch(node: TreeNode) {
15
+ return node.branch || !!node.item.loadChildren
16
+ }
17
+
18
+ type CascaderColumnProps = {
19
+ id: string
20
+ items: TreeNode[]
21
+ label?: string
22
+ labelledBy?: string
23
+ heading?: string
24
+ parent?: TreeNode
25
+ selected?: string
26
+ current?: string
27
+ focused: boolean
28
+ loadingText: string
29
+ errorText: string
30
+ emptyText: string
31
+ part?: PartStyle
32
+ onMove(value: string): void
33
+ onBack(): void
34
+ onActivate(node: TreeNode): void
35
+ onRetry(): void
36
+ }
37
+
38
+ export function CascaderColumn({
39
+ id,
40
+ items,
41
+ label,
42
+ labelledBy,
43
+ heading,
44
+ parent,
45
+ selected,
46
+ current,
47
+ focused,
48
+ loadingText,
49
+ errorText,
50
+ emptyText,
51
+ part,
52
+ onMove,
53
+ onBack,
54
+ onActivate,
55
+ onRetry
56
+ }: CascaderColumnProps) {
57
+ const matcher = useLocaleMatcher()
58
+ const search = useRef({ text: '', time: 0 })
59
+ const active =
60
+ items.find(item => !item.disabled && item.value === (current ?? selected)) ??
61
+ items.find(item => !item.disabled)
62
+ const pending = !!parent?.item.loadChildren && (!parent.load || parent.load.status === 'loading')
63
+ const failed = parent?.load?.status === 'error'
64
+ const status = pending ? loadingText : failed ? errorText : emptyText
65
+ const statusId = id + '-status'
66
+ const activeId = active ? id + '-' + active.position : failed ? statusId : undefined
67
+
68
+ function navigate(event: KeyboardEvent<HTMLDivElement>) {
69
+ if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return
70
+ const element = event.currentTarget
71
+ const view = element.ownerDocument.defaultView!
72
+ const back = view.getComputedStyle(element).direction === 'rtl' ? 'ArrowRight' : 'ArrowLeft'
73
+ const forward = back === 'ArrowLeft' ? 'ArrowRight' : 'ArrowLeft'
74
+ const { key } = event
75
+ if (key === back) {
76
+ event.preventDefault()
77
+ onBack()
78
+ return
79
+ }
80
+ if (key === forward || key === 'Enter' || key === ' ') {
81
+ event.preventDefault()
82
+ if (active && (key !== forward || isCascaderBranch(active))) onActivate(active)
83
+ else if (failed && key !== forward) onRetry()
84
+ return
85
+ }
86
+ let next: string | undefined
87
+ if (key === 'ArrowUp' || key === 'ArrowDown' || key === 'Home' || key === 'End') {
88
+ next = moveSelectFocus(items, active?.value ?? null, key)
89
+ } else if (matcher.isSingleKey(key)) {
90
+ const time = view.performance.now()
91
+ search.current = {
92
+ time,
93
+ text: (time - search.current.time > 700 ? '' : search.current.text) + key
94
+ }
95
+ next = matchSelectText(items, search.current.text, active?.value ?? null, matcher)
96
+ } else {
97
+ return
98
+ }
99
+ event.preventDefault()
100
+ if (next !== undefined) onMove(next)
101
+ }
102
+
103
+ return (
104
+ <div className="w-48 min-w-28 flex-1 border-e border-[var(--rad-color-border)] last:border-e-0 sm:min-w-44">
105
+ {heading && (
106
+ <div
107
+ id={id + '-heading'}
108
+ className="px-2 py-1.5 text-xs font-semibold [color:var(--rad-color-muted-foreground)] sm:px-3"
109
+ >
110
+ {heading}
111
+ </div>
112
+ )}
113
+ <div
114
+ role="listbox"
115
+ tabIndex={focused ? 0 : -1}
116
+ aria-label={heading ? undefined : label}
117
+ aria-labelledby={heading ? id + '-heading' : labelledBy}
118
+ aria-activedescendant={activeId}
119
+ aria-busy={pending || undefined}
120
+ data-slot="cascader-column"
121
+ className={cn(
122
+ 'group/cascader max-h-[min(18rem,calc(100dvh-4rem))] overflow-y-auto overscroll-contain px-1 focus:outline-none',
123
+ scrollbarClass,
124
+ part?.className
125
+ )}
126
+ style={part?.style}
127
+ onKeyDown={navigate}
128
+ onBlur={() => {
129
+ search.current = { time: 0, text: '' }
130
+ }}
131
+ onClick={event => {
132
+ const option = (event.target as Element).closest<HTMLElement>('[role="option"]')
133
+ if (!option || option.getAttribute('aria-disabled') === 'true') return
134
+ event.currentTarget.focus({ preventScroll: true })
135
+ const item = items.find(node => node.value === option.dataset.value)
136
+ if (item) onActivate(item)
137
+ else if (failed) onRetry()
138
+ }}
139
+ >
140
+ {items.length ? (
141
+ items.map(item => {
142
+ const branch = isCascaderBranch(item)
143
+ return (
144
+ <div
145
+ key={item.value}
146
+ id={id + '-' + item.position}
147
+ role="option"
148
+ aria-selected={!item.disabled && item.value === selected}
149
+ aria-disabled={item.disabled || undefined}
150
+ data-slot="cascader-option"
151
+ data-value={item.value}
152
+ data-selected={!item.disabled && item.value === selected ? '' : undefined}
153
+ data-disabled={item.disabled ? '' : undefined}
154
+ data-active={item.value === active?.value ? '' : undefined}
155
+ className={cn(
156
+ selectItemClass,
157
+ 'max-sm:gap-1 max-sm:px-2 not-data-disabled:cursor-pointer not-data-disabled:hover:bg-[var(--rad-color-neutral)] group-focus-visible/cascader:data-active:[outline:2px_solid_var(--rad-color-focus)] group-focus-visible/cascader:data-active:outline-offset-[-2px] group-focus-visible/cascader:forced-colors:data-active:outline-[Highlight]'
158
+ )}
159
+ >
160
+ {item.item.icon && (
161
+ <span
162
+ aria-hidden="true"
163
+ className="shrink-0"
164
+ >
165
+ {item.item.icon}
166
+ </span>
167
+ )}
168
+ <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{item.textValue}</span>
169
+ {branch && (
170
+ <span
171
+ aria-hidden="true"
172
+ className="shrink-0 rtl:rotate-180"
173
+ >
174
+ ›
175
+ </span>
176
+ )}
177
+ </div>
178
+ )
179
+ })
180
+ ) : (
181
+ <div
182
+ id={statusId}
183
+ role="option"
184
+ aria-selected={false}
185
+ aria-disabled={!failed || undefined}
186
+ data-slot="cascader-status"
187
+ data-active=""
188
+ className={cn(
189
+ selectItemClass,
190
+ failed ? 'cursor-pointer underline' : '[color:var(--rad-color-muted-foreground)]',
191
+ 'max-sm:px-2 group-focus-visible/cascader:[outline:2px_solid_var(--rad-color-focus)] group-focus-visible/cascader:outline-offset-[-2px]'
192
+ )}
193
+ >
194
+ {status}
195
+ </div>
196
+ )}
197
+ </div>
198
+ {parent?.item.loadChildren && (
199
+ <output className="sr-only">{items.length ? '' : status}</output>
200
+ )}
201
+ </div>
202
+ )
203
+ }