1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- import { computed, unref, shallowRef, ref, watch, onBeforeUnmount } from 'vue';
- import { createPopper } from '@popperjs/core';
- import { fromPairs } from 'lodash-unified';
- const usePopper = (referenceElementRef, popperElementRef, opts = {}) => {
- const stateUpdater = {
- name: "updateState",
- enabled: true,
- phase: "write",
- fn: ({ state }) => {
- const derivedState = deriveState(state);
- Object.assign(states.value, derivedState);
- },
- requires: ["computeStyles"]
- };
- const options = computed(() => {
- const { onFirstUpdate, placement, strategy, modifiers } = unref(opts);
- return {
- onFirstUpdate,
- placement: placement || "bottom",
- strategy: strategy || "absolute",
- modifiers: [
- ...modifiers || [],
- stateUpdater,
- { name: "applyStyles", enabled: false }
- ]
- };
- });
- const instanceRef = shallowRef();
- const states = ref({
- styles: {
- popper: {
- position: unref(options).strategy,
- left: "0",
- top: "0"
- },
- arrow: {
- position: "absolute"
- }
- },
- attributes: {}
- });
- const destroy = () => {
- if (!instanceRef.value)
- return;
- instanceRef.value.destroy();
- instanceRef.value = void 0;
- };
- watch(options, (newOptions) => {
- const instance = unref(instanceRef);
- if (instance) {
- instance.setOptions(newOptions);
- }
- }, {
- deep: true
- });
- watch([referenceElementRef, popperElementRef], ([referenceElement, popperElement]) => {
- destroy();
- if (!referenceElement || !popperElement)
- return;
- instanceRef.value = createPopper(referenceElement, popperElement, unref(options));
- });
- onBeforeUnmount(() => {
- destroy();
- });
- return {
- state: computed(() => {
- var _a;
- return { ...((_a = unref(instanceRef)) == null ? void 0 : _a.state) || {} };
- }),
- styles: computed(() => unref(states).styles),
- attributes: computed(() => unref(states).attributes),
- update: () => {
- var _a;
- return (_a = unref(instanceRef)) == null ? void 0 : _a.update();
- },
- forceUpdate: () => {
- var _a;
- return (_a = unref(instanceRef)) == null ? void 0 : _a.forceUpdate();
- },
- instanceRef: computed(() => unref(instanceRef))
- };
- };
- function deriveState(state) {
- const elements = Object.keys(state.elements);
- const styles = fromPairs(elements.map((element) => [element, state.styles[element] || {}]));
- const attributes = fromPairs(elements.map((element) => [element, state.attributes[element]]));
- return {
- styles,
- attributes
- };
- }
- export { usePopper };
- //# sourceMappingURL=index.mjs.map
|