import {onMounted, toValue, watch, type WritableComputedRef} from 'vue'; import {toArray} from '@myparcel/ts-utils'; import {type ArrayItem, type SelectInputEmits, type SelectInputModelValue, type SelectInputProps} from '../../types'; import {type ElementOptionsContext, useElementOptions} from './useElementOptions'; import {type ElementContext, useElementContext} from './useElementContext'; type ModelValue = Multiple extends true ? T : ArrayItem; export interface InputWithOptionsContext extends ElementOptionsContext { id: string; model: WritableComputedRef>; } export const useInputWithOptionsContext = < T extends SelectInputModelValue = SelectInputModelValue, Props extends SelectInputProps = SelectInputProps, Multiple extends boolean = boolean, >( props: Props, emit: SelectInputEmits, multiple?: Multiple, ): InputWithOptionsContext => { const {id, model} = useElementContext(props, emit) as ElementContext>; const {options} = useElementOptions(props); onMounted(() => { watch( options, (newOptions) => { const values = toArray(toValue(model)); const hasExistingValue = values.length && newOptions.some((option) => values.includes(option.value as ModelValue)); if (hasExistingValue || newOptions.length === 0) { return; } model.value = (multiple ? [newOptions[0].value] : newOptions[0].value) as ModelValue; }, {immediate: Number(toValue(options)?.length) > 0}, ); }); return {id, options, model}; };