Line data Source code
1 : import { computed, toValue } from 'vue'
2 : import type { MaybeRefOrGetter } from 'vue'
3 :
4 : interface ComboSteppingOptions<T> {
5 : options: MaybeRefOrGetter<readonly T[]>
6 : selectedOption: MaybeRefOrGetter<T | undefined>
7 : disabled: MaybeRefOrGetter<boolean>
8 : dynamicOptions: MaybeRefOrGetter<boolean>
9 : refreshOptions: () => void
10 : onSelect: (option: T) => void
11 : }
12 :
13 3598 : export function useComboStepping<T>(config: ComboSteppingOptions<T>) {
14 3598 : const adjacentOptions = computed(() => {
15 5395 : const options = toValue(config.options)
16 5395 : const selected = toValue(config.selectedOption)
17 5395 : const index = selected === undefined ? -1 : options.indexOf(selected)
18 5395 : return {
19 : [-1]: options[(index < 0 ? options.length : index) - 1],
20 : [1]: options[index + 1]
21 : }
22 : })
23 :
24 14539 : function isStepDisabled(direction: -1 | 1) {
25 14539 : return (
26 : toValue(config.disabled) ||
27 : (!toValue(config.dynamicOptions) &&
28 : adjacentOptions.value[direction] === undefined)
29 : )
30 : }
31 :
32 0 : function stepOption(direction: -1 | 1) {
33 0 : config.refreshOptions()
34 0 : const option = adjacentOptions.value[direction]
35 0 : if (option !== undefined) config.onSelect(option)
36 : }
37 :
38 3598 : return { isStepDisabled, stepOption }
39 : }
|