@varlet/ui
Version:
A Vue3 component library based on Material Design 2 and 3, supporting mobile and desktop.
73 lines (72 loc) • 2.26 kB
JavaScript
import { ref, watch } from "vue";
import { isEmpty } from "@varlet/shared";
function useSelectController(options) {
const {
multiple: multipleGetter,
modelValue: modelValueGetter,
optionProviders: optionProvidersGetter,
optionProvidersLength: optionProvidersLengthGetter,
optionIsIndeterminate
} = options;
const label = ref("");
const labels = ref([]);
watch(modelValueGetter, syncOptions, { deep: true });
watch(optionProvidersLengthGetter, syncOptions);
function computeLabel() {
const multiple = multipleGetter();
const modelValue = modelValueGetter();
if (multiple) {
labels.value = modelValue.map(findLabel);
}
if (!multiple && !isEmpty(modelValue)) {
label.value = findLabel(modelValue);
}
if (!multiple && isEmpty(modelValue)) {
label.value = "";
}
}
function findLabel(targetValue) {
var _a;
const options2 = optionProvidersGetter();
let option = options2.find(({ value }) => value.value === targetValue);
if (!option) {
option = options2.find(({ label: label2 }) => label2.value === targetValue);
}
return (_a = option == null ? void 0 : option.label.value) != null ? _a : "";
}
function getOptionProviderKey({ value, label: label2 }) {
var _a;
return (_a = value.value) != null ? _a : label2.value;
}
function getSelectedValue(option) {
const multiple = multipleGetter();
const options2 = optionProvidersGetter();
return multiple ? options2.filter(({ selected }) => selected.value).map(getOptionProviderKey) : getOptionProviderKey(option);
}
function syncOptions() {
const multiple = multipleGetter();
const modelValue = modelValueGetter();
const options2 = optionProvidersGetter();
if (multiple) {
options2.forEach(
(option) => option.sync(
modelValue.includes(getOptionProviderKey(option)),
optionIsIndeterminate ? optionIsIndeterminate(option) : void 0
)
);
} else {
options2.forEach((option) => option.sync(modelValue === getOptionProviderKey(option)));
}
computeLabel();
}
return {
label,
labels,
getOptionProviderKey,
computeLabel,
getSelectedValue
};
}
export {
useSelectController
};