-
Notifications
You must be signed in to change notification settings - Fork 1k
/
tabs.ts
409 lines (344 loc) · 10.8 KB
/
tabs.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import {
Fragment,
computed,
defineComponent,
h,
inject,
onMounted,
onUnmounted,
provide,
ref,
watchEffect,
// Types
InjectionKey,
Ref,
} from 'vue'
import { Features, render, omit } from '../../utils/render'
import { useId } from '../../hooks/use-id'
import { Keys } from '../../keyboard'
import { dom } from '../../utils/dom'
import { match } from '../../utils/match'
import { focusIn, Focus } from '../../utils/focus-management'
import { useResolveButtonType } from '../../hooks/use-resolve-button-type'
import { FocusSentinel } from '../../internal/focus-sentinel'
import { microTask } from '../../utils/micro-task'
type StateDefinition = {
// State
selectedIndex: Ref<number | null>
orientation: Ref<'vertical' | 'horizontal'>
activation: Ref<'auto' | 'manual'>
tabs: Ref<Ref<HTMLElement | null>[]>
panels: Ref<Ref<HTMLElement | null>[]>
// State mutators
setSelectedIndex(index: number): void
registerTab(tab: Ref<HTMLElement | null>): void
unregisterTab(tab: Ref<HTMLElement | null>): void
registerPanel(panel: Ref<HTMLElement | null>): void
unregisterPanel(panel: Ref<HTMLElement | null>): void
}
let TabsContext = Symbol('TabsContext') as InjectionKey<StateDefinition>
function useTabsContext(component: string) {
let context = inject(TabsContext, null)
if (context === null) {
let err = new Error(`<${component} /> is missing a parent <TabGroup /> component.`)
if (Error.captureStackTrace) Error.captureStackTrace(err, useTabsContext)
throw err
}
return context
}
// ---
export let TabGroup = defineComponent({
name: 'TabGroup',
emits: {
change: (_index: number) => true,
},
props: {
as: { type: [Object, String], default: 'template' },
selectedIndex: { type: [Number], default: null },
defaultIndex: { type: [Number], default: 0 },
vertical: { type: [Boolean], default: false },
manual: { type: [Boolean], default: false },
},
inheritAttrs: false,
setup(props, { slots, attrs, emit }) {
let selectedIndex = ref<StateDefinition['selectedIndex']['value']>(null)
let tabs = ref<StateDefinition['tabs']['value']>([])
let panels = ref<StateDefinition['panels']['value']>([])
let isControlled = computed(() => props.selectedIndex !== null)
let realSelectedIndex = computed(() =>
isControlled.value ? props.selectedIndex : selectedIndex.value
)
let api = {
selectedIndex,
orientation: computed(() => (props.vertical ? 'vertical' : 'horizontal')),
activation: computed(() => (props.manual ? 'manual' : 'auto')),
tabs,
panels,
setSelectedIndex(index: number) {
if (realSelectedIndex.value !== index) {
emit('change', index)
}
if (!isControlled.value) {
selectedIndex.value = index
}
},
registerTab(tab: typeof tabs['value'][number]) {
if (!tabs.value.includes(tab)) tabs.value.push(tab)
},
unregisterTab(tab: typeof tabs['value'][number]) {
let idx = tabs.value.indexOf(tab)
if (idx !== -1) tabs.value.splice(idx, 1)
},
registerPanel(panel: typeof panels['value'][number]) {
if (!panels.value.includes(panel)) panels.value.push(panel)
},
unregisterPanel(panel: typeof panels['value'][number]) {
let idx = panels.value.indexOf(panel)
if (idx !== -1) panels.value.splice(idx, 1)
},
}
provide(TabsContext, api)
watchEffect(() => {
if (api.tabs.value.length <= 0) return
if (props.selectedIndex === null && selectedIndex.value !== null) return
let tabs = api.tabs.value.map((tab) => dom(tab)).filter(Boolean) as HTMLElement[]
let focusableTabs = tabs.filter((tab) => !tab.hasAttribute('disabled'))
let indexToSet = props.selectedIndex ?? props.defaultIndex
// Underflow
if (indexToSet < 0) {
selectedIndex.value = tabs.indexOf(focusableTabs[0])
}
// Overflow
else if (indexToSet > api.tabs.value.length) {
selectedIndex.value = tabs.indexOf(focusableTabs[focusableTabs.length - 1])
}
// Middle
else {
let before = tabs.slice(0, indexToSet)
let after = tabs.slice(indexToSet)
let next = [...after, ...before].find((tab) => focusableTabs.includes(tab))
if (!next) return
selectedIndex.value = tabs.indexOf(next)
}
})
return () => {
let slot = { selectedIndex: selectedIndex.value }
return h(Fragment, [
tabs.value.length <= 0 &&
h(FocusSentinel, {
onFocus: () => {
for (let tab of tabs.value) {
let el = dom(tab)
if (el?.tabIndex === 0) {
el.focus()
return true
}
}
return false
},
}),
render({
theirProps: {
...attrs,
...omit(props, ['selectedIndex', 'defaultIndex', 'manual', 'vertical', 'onChange']),
},
ourProps: {},
slot,
slots,
attrs,
name: 'TabGroup',
}),
])
}
},
})
// ---
export let TabList = defineComponent({
name: 'TabList',
props: {
as: { type: [Object, String], default: 'div' },
},
setup(props, { attrs, slots }) {
let api = useTabsContext('TabList')
return () => {
let slot = { selectedIndex: api.selectedIndex.value }
let ourProps = {
role: 'tablist',
'aria-orientation': api.orientation.value,
}
let theirProps = props
return render({
ourProps,
theirProps,
slot,
attrs,
slots,
name: 'TabList',
})
}
},
})
// ---
export let Tab = defineComponent({
name: 'Tab',
props: {
as: { type: [Object, String], default: 'button' },
disabled: { type: [Boolean], default: false },
},
setup(props, { attrs, slots, expose }) {
let api = useTabsContext('Tab')
let id = `headlessui-tabs-tab-${useId()}`
let internalTabRef = ref<HTMLElement | null>(null)
expose({ el: internalTabRef, $el: internalTabRef })
onMounted(() => api.registerTab(internalTabRef))
onUnmounted(() => api.unregisterTab(internalTabRef))
let myIndex = computed(() => api.tabs.value.indexOf(internalTabRef))
let selected = computed(() => myIndex.value === api.selectedIndex.value)
function handleKeyDown(event: KeyboardEvent) {
let list = api.tabs.value.map((tab) => dom(tab)).filter(Boolean) as HTMLElement[]
if (event.key === Keys.Space || event.key === Keys.Enter) {
event.preventDefault()
event.stopPropagation()
api.setSelectedIndex(myIndex.value)
return
}
switch (event.key) {
case Keys.Home:
case Keys.PageUp:
event.preventDefault()
event.stopPropagation()
return focusIn(list, Focus.First)
case Keys.End:
case Keys.PageDown:
event.preventDefault()
event.stopPropagation()
return focusIn(list, Focus.Last)
}
if (
match(api.orientation.value, {
vertical() {
if (event.key === Keys.ArrowUp) return focusIn(list, Focus.Previous | Focus.WrapAround)
if (event.key === Keys.ArrowDown) return focusIn(list, Focus.Next | Focus.WrapAround)
return
},
horizontal() {
if (event.key === Keys.ArrowLeft)
return focusIn(list, Focus.Previous | Focus.WrapAround)
if (event.key === Keys.ArrowRight) return focusIn(list, Focus.Next | Focus.WrapAround)
return
},
})
) {
return event.preventDefault()
}
}
function handleFocus() {
dom(internalTabRef)?.focus()
}
let ready = ref(false)
function handleSelection() {
if (ready.value) return
ready.value = true
if (props.disabled) return
dom(internalTabRef)?.focus()
api.setSelectedIndex(myIndex.value)
microTask(() => {
ready.value = false
})
}
// This is important because we want to only focus the tab when it gets focus
// OR it finished the click event (mouseup). However, if you perform a `click`,
// then you will first get the `focus` and then get the `click` event.
function handleMouseDown(event: MouseEvent) {
event.preventDefault()
}
let type = useResolveButtonType(
computed(() => ({ as: props.as, type: attrs.type })),
internalTabRef
)
return () => {
let slot = { selected: selected.value }
let ourProps = {
ref: internalTabRef,
onKeydown: handleKeyDown,
onFocus: api.activation.value === 'manual' ? handleFocus : handleSelection,
onMousedown: handleMouseDown,
onClick: handleSelection,
id,
role: 'tab',
type: type.value,
'aria-controls': api.panels.value[myIndex.value]?.value?.id,
'aria-selected': selected.value,
tabIndex: selected.value ? 0 : -1,
disabled: props.disabled ? true : undefined,
}
return render({
ourProps,
theirProps: props,
slot,
attrs,
slots,
name: 'Tab',
})
}
},
})
// ---
export let TabPanels = defineComponent({
name: 'TabPanels',
props: {
as: { type: [Object, String], default: 'div' },
},
setup(props, { slots, attrs }) {
let api = useTabsContext('TabPanels')
return () => {
let slot = { selectedIndex: api.selectedIndex.value }
return render({
theirProps: props,
ourProps: {},
slot,
attrs,
slots,
name: 'TabPanels',
})
}
},
})
export let TabPanel = defineComponent({
name: 'TabPanel',
props: {
as: { type: [Object, String], default: 'div' },
static: { type: Boolean, default: false },
unmount: { type: Boolean, default: true },
},
setup(props, { attrs, slots, expose }) {
let api = useTabsContext('TabPanel')
let id = `headlessui-tabs-panel-${useId()}`
let internalPanelRef = ref<HTMLElement | null>(null)
expose({ el: internalPanelRef, $el: internalPanelRef })
onMounted(() => api.registerPanel(internalPanelRef))
onUnmounted(() => api.unregisterPanel(internalPanelRef))
let myIndex = computed(() => api.panels.value.indexOf(internalPanelRef))
let selected = computed(() => myIndex.value === api.selectedIndex.value)
return () => {
let slot = { selected: selected.value }
let ourProps = {
ref: internalPanelRef,
id,
role: 'tabpanel',
'aria-labelledby': api.tabs.value[myIndex.value]?.value?.id,
tabIndex: selected.value ? 0 : -1,
}
return render({
ourProps,
theirProps: props,
slot,
attrs,
slots,
features: Features.Static | Features.RenderStrategy,
visible: selected.value,
name: 'TabPanel',
})
}
},
})