@oruga-ui/oruga-next
Version:
UI components for Vue.js and CSS framework agnostic
85 lines (84 loc) • 2.78 kB
JavaScript
/*! Oruga v0.11.4 | MIT License | github.com/oruga-ui/oruga */
import { getCurrentInstance, ref, watch, provide, inject, onUnmounted } from "vue";
import { u as unrefElement } from "./unrefElement-D7RSwowH.mjs";
import { u as useDebounce } from "./useDebounce-CkJIjBla.mjs";
import { u as useSequentialId } from "./useSequentialId-f2w0V9tB.mjs";
function useProviderParent(options) {
const vm = getCurrentInstance();
if (!vm)
throw new Error(
"useProviderChild must be called within a component setup function."
);
const configField = vm.proxy?.$options.configField;
const key = options?.key || configField;
const childItems = ref([]);
if (options?.rootRef) {
const sortHandler = useDebounce((items) => {
const parent = unrefElement(options.rootRef);
if (!parent) return;
const ids = items.map((item) => `[data-id="${key}-${item.identifier}"]`).join(",");
if (!ids) return;
const children = parent.querySelectorAll(ids);
const sortedIds = Array.from(children).map(
(el) => el.getAttribute("data-id")?.replace(`${key}-`, "")
);
items.forEach(
(item) => item.index = sortedIds.indexOf(`${item.identifier}`)
);
items.sort((a, b) => a.index - b.index);
}, 500);
watch(childItems, sortHandler);
}
const { nextSequence } = useSequentialId(1);
function registerItem(data) {
const index = childItems.value.length;
const identifier = nextSequence();
const item = { index, data, identifier };
childItems.value = [
...childItems.value,
item
];
return item;
}
function unregisterItem(item) {
childItems.value = childItems.value.filter((i) => i !== item);
}
provide("$o-" + key, {
registerItem,
unregisterItem,
data: options?.data
});
return {
childItems
};
}
function useProviderChild(options) {
options = Object.assign({ needParent: true, register: true }, options);
const vm = getCurrentInstance();
if (!vm)
throw new Error(
"useProviderChild must be called within a component setup function."
);
const configField = vm.proxy?.$options.configField;
const key = options?.key || configField;
const parent = inject("$o-" + key, void 0);
if (options.needParent && !parent)
throw new Error(
`You should wrap ${vm.proxy?.$options.name} in a ${key} component`
);
const item = ref();
if (parent && options.register)
item.value = parent.registerItem(
options?.data
);
onUnmounted(() => {
if (parent && item.value) parent.unregisterItem(item.value);
});
const data = parent?.data || ref();
return { parent: data, item };
}
export {
useProviderChild as a,
useProviderParent as u
};
//# sourceMappingURL=useParentProvider-C2ZghYdt.mjs.map