vuestic-ui
Version:
Vue 3 UI Framework
74 lines (73 loc) • 2.04 kB
JavaScript
import { ref, provide, computed, inject, onBeforeUnmount, nextTick } from "vue";
import { w as warn } from "../../../utils/console.mjs";
const AccordionServiceKey = Symbol("AccordionService");
const useAccordion = (props, state) => {
const items = ref([]);
const makeState = () => {
const correctItemsCount = Math.max(items.value.length, state.value.length);
return Array.from({ length: correctItemsCount }, (_, index) => {
return state.value[index] ?? false;
});
};
const getItemValue = (item) => {
return state.value[items.value.indexOf(item)] ?? false;
};
const onItemsChanged = () => {
state.value = makeState();
};
const registerItem = (item) => {
items.value.push(item);
onItemsChanged();
};
const unregisterItem = (item) => {
items.value = items.value.filter((i) => i !== item);
nextTick(onItemsChanged);
};
const setItemValue = (item, value) => {
const index = items.value.indexOf(item);
if (index === -1) {
warn("Accordion item is not registered yet");
return;
}
if (!props.multiple) {
state.value = makeState().map((el, i) => {
if (i === index) {
return value;
}
return false;
});
} else {
state.value[index] = value;
}
};
provide(AccordionServiceKey, {
registerItem,
unregisterItem,
getItemValue,
setItemValue,
props: computed(() => props)
});
return { items };
};
const useAccordionItem = () => {
const accordion = inject(AccordionServiceKey, void 0);
if (!accordion) {
return { accordionProps: ref({}) };
}
const item = {};
accordion.registerItem(item);
onBeforeUnmount(() => accordion.unregisterItem(item));
const accordionItemValue = computed({
get: () => accordion.getItemValue(item),
set: (value) => accordion.setItemValue(item, value)
});
return {
accordionItemValue,
accordionProps: accordion.props
};
};
export {
useAccordionItem as a,
useAccordion as u
};
//# sourceMappingURL=useAccordion.mjs.map