ant-design-vue/components/vc-select/hooks/useSelectTriggerControl.ts

33 lines
886 B
TypeScript
Raw Normal View History

2021-06-26 09:35:40 +08:00
import type { Ref } from 'vue';
import { onBeforeUnmount, onMounted } from 'vue';
2020-10-07 22:49:01 +08:00
export default function useSelectTriggerControl(
2020-10-10 13:57:37 +08:00
refs: Ref[],
2020-10-07 22:49:01 +08:00
open: Ref<boolean>,
triggerOpen: (open: boolean) => void,
) {
function onGlobalMouseDown(event: MouseEvent) {
2021-06-22 10:47:33 +08:00
let target = event.target as HTMLElement;
if (target.shadowRoot && event.composed) {
target = (event.composedPath()[0] || target) as HTMLElement;
}
2020-10-10 13:57:37 +08:00
const elements = [refs[0]?.value, refs[1]?.value?.getPopupElement()];
2020-10-07 22:49:01 +08:00
if (
open.value &&
elements.every(element => element && !element.contains(target) && element !== target)
) {
// Should trigger close
triggerOpen(false);
}
}
onMounted(() => {
window.addEventListener('mousedown', onGlobalMouseDown);
});
onBeforeUnmount(() => {
window.removeEventListener('mousedown', onGlobalMouseDown);
});
}