-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathradio-group.ts
317 lines (275 loc) · 8.89 KB
/
radio-group.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import {
computed,
defineComponent,
inject,
onMounted,
onUnmounted,
provide,
ref,
toRaw,
// Types
InjectionKey,
Ref,
UnwrapRef,
} from 'vue'
import { dom } from '../../utils/dom'
import { Keys } from '../../keyboard'
import { focusIn, Focus, FocusResult } from '../../utils/focus-management'
import { useId } from '../../hooks/use-id'
import { render } from '../../utils/render'
import { Label, useLabels } from '../label/label'
import { Description, useDescriptions } from '../description/description'
import { useTreeWalker } from '../../hooks/use-tree-walker'
interface Option {
id: string
element: Ref<HTMLElement | null>
propsRef: Ref<{ value: unknown; disabled: boolean }>
}
interface StateDefinition {
// State
options: Ref<Option[]>
value: Ref<unknown>
disabled: Ref<boolean>
firstOption: Ref<Option | undefined>
containsCheckedOption: Ref<boolean>
// State mutators
change(nextValue: unknown): boolean
registerOption(action: Option): void
unregisterOption(id: Option['id']): void
}
let RadioGroupContext = Symbol('RadioGroupContext') as InjectionKey<StateDefinition>
function useRadioGroupContext(component: string) {
let context = inject(RadioGroupContext, null)
if (context === null) {
let err = new Error(`<${component} /> is missing a parent <RadioGroup /> component.`)
if (Error.captureStackTrace) Error.captureStackTrace(err, useRadioGroupContext)
throw err
}
return context
}
// ---
export let RadioGroup = defineComponent({
name: 'RadioGroup',
emits: { 'update:modelValue': (_value: any) => true },
props: {
as: { type: [Object, String], default: 'div' },
disabled: { type: [Boolean], default: false },
modelValue: { type: [Object, String, Number, Boolean] },
},
render() {
let { modelValue, disabled, ...passThroughProps } = this.$props
let propsWeControl = {
ref: 'el',
id: this.id,
role: 'radiogroup',
'aria-labelledby': this.labelledby,
'aria-describedby': this.describedby,
onKeydown: this.handleKeyDown,
}
return render({
props: { ...passThroughProps, ...propsWeControl },
slot: {},
attrs: this.$attrs,
slots: this.$slots,
name: 'RadioGroup',
})
},
setup(props, { emit }) {
let radioGroupRef = ref<HTMLElement | null>(null)
let options = ref<StateDefinition['options']['value']>([])
let labelledby = useLabels({ name: 'RadioGroupLabel' })
let describedby = useDescriptions({ name: 'RadioGroupDescription' })
let value = computed(() => props.modelValue)
let api = {
options,
value,
disabled: computed(() => props.disabled),
firstOption: computed(() =>
options.value.find(option => {
if (option.propsRef.disabled) return false
return true
})
),
containsCheckedOption: computed(() =>
options.value.some(option => toRaw(option.propsRef.value) === toRaw(props.modelValue))
),
change(nextValue: unknown) {
if (props.disabled) return false
if (value.value === nextValue) return false
let nextOption = options.value.find(
option => toRaw(option.propsRef.value) === toRaw(nextValue)
)?.propsRef
if (nextOption?.disabled) return false
emit('update:modelValue', nextValue)
return true
},
registerOption(action: UnwrapRef<Option>) {
let orderMap = Array.from(
radioGroupRef.value?.querySelectorAll('[id^="headlessui-radiogroup-option-"]')!
).reduce(
(lookup, element, index) => Object.assign(lookup, { [element.id]: index }),
{}
) as Record<string, number>
options.value.push(action)
options.value.sort((a, z) => orderMap[a.id] - orderMap[z.id])
},
unregisterOption(id: Option['id']) {
let idx = options.value.findIndex(radio => radio.id === id)
if (idx === -1) return
options.value.splice(idx, 1)
},
}
// @ts-expect-error ...
provide(RadioGroupContext, api)
useTreeWalker({
container: computed(() => dom(radioGroupRef)),
accept(node) {
if (node.getAttribute('role') === 'radio') return NodeFilter.FILTER_REJECT
if (node.hasAttribute('role')) return NodeFilter.FILTER_SKIP
return NodeFilter.FILTER_ACCEPT
},
walk(node) {
node.setAttribute('role', 'none')
},
})
function handleKeyDown(event: KeyboardEvent) {
if (!radioGroupRef.value) return
if (!radioGroupRef.value.contains(event.target as HTMLElement)) return
let all = options.value
.filter(option => option.propsRef.disabled === false)
.map(radio => radio.element) as HTMLElement[]
switch (event.key) {
case Keys.ArrowLeft:
case Keys.ArrowUp:
{
event.preventDefault()
event.stopPropagation()
let result = focusIn(all, Focus.Previous | Focus.WrapAround)
if (result === FocusResult.Success) {
let activeOption = options.value.find(
option => option.element === document.activeElement
)
if (activeOption) api.change(activeOption.propsRef.value)
}
}
break
case Keys.ArrowRight:
case Keys.ArrowDown:
{
event.preventDefault()
event.stopPropagation()
let result = focusIn(all, Focus.Next | Focus.WrapAround)
if (result === FocusResult.Success) {
let activeOption = options.value.find(
option => option.element === document.activeElement
)
if (activeOption) api.change(activeOption.propsRef.value)
}
}
break
case Keys.Space:
{
event.preventDefault()
event.stopPropagation()
let activeOption = options.value.find(
option => option.element === document.activeElement
)
if (activeOption) api.change(activeOption.propsRef.value)
}
break
}
}
let id = `headlessui-radiogroup-${useId()}`
return {
id,
labelledby,
describedby,
el: radioGroupRef,
handleKeyDown,
}
},
})
// ---
enum OptionState {
Empty = 1 << 0,
Active = 1 << 1,
}
export let RadioGroupOption = defineComponent({
name: 'RadioGroupOption',
props: {
as: { type: [Object, String], default: 'div' },
value: { type: [Object, String, Number, Boolean] },
disabled: { type: Boolean, default: false },
},
render() {
let { value, disabled, ...passThroughProps } = this.$props
let slot = {
checked: this.checked,
disabled: this.disabled,
active: Boolean(this.state & OptionState.Active),
}
let propsWeControl = {
id: this.id,
ref: 'el',
role: 'radio',
'aria-checked': this.checked ? 'true' : 'false',
'aria-labelledby': this.labelledby,
'aria-describedby': this.describedby,
'aria-disabled': this.disabled ? true : undefined,
tabIndex: this.tabIndex,
onClick: this.disabled ? undefined : this.handleClick,
onFocus: this.disabled ? undefined : this.handleFocus,
onBlur: this.disabled ? undefined : this.handleBlur,
}
return render({
props: { ...passThroughProps, ...propsWeControl },
slot,
attrs: this.$attrs,
slots: this.$slots,
name: 'RadioGroupOption',
})
},
setup(props) {
let api = useRadioGroupContext('RadioGroupOption')
let id = `headlessui-radiogroup-option-${useId()}`
let labelledby = useLabels({ name: 'RadioGroupLabel' })
let describedby = useDescriptions({ name: 'RadioGroupDescription' })
let optionRef = ref<HTMLElement | null>(null)
let propsRef = computed(() => ({ value: props.value, disabled: props.disabled }))
let state = ref(OptionState.Empty)
onMounted(() => api.registerOption({ id, element: optionRef, propsRef }))
onUnmounted(() => api.unregisterOption(id))
let isFirstOption = computed(() => api.firstOption.value?.id === id)
let disabled = computed(() => api.disabled.value || props.disabled)
let checked = computed(() => toRaw(api.value.value) === toRaw(props.value))
return {
id,
el: optionRef,
labelledby,
describedby,
state,
disabled,
checked,
tabIndex: computed(() => {
if (disabled.value) return -1
if (checked.value) return 0
if (!api.containsCheckedOption.value && isFirstOption.value) return 0
return -1
}),
handleClick() {
if (!api.change(props.value)) return
state.value |= OptionState.Active
optionRef.value?.focus()
},
handleFocus() {
state.value |= OptionState.Active
},
handleBlur() {
state.value &= ~OptionState.Active
},
}
},
})
// ---
export let RadioGroupLabel = Label
export let RadioGroupDescription = Description