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

33 lines
886 B
TypeScript
Raw Normal View History

2021-06-26 01:35:40 +00:00
import type { Ref } from 'vue';
import { onBeforeUnmount, onMounted } from 'vue';
2020-10-07 14:49:01 +00:00
export default function useSelectTriggerControl(
2020-10-10 05:57:37 +00:00
refs: Ref[],
2020-10-07 14:49:01 +00:00
open: Ref<boolean>,
triggerOpen: (open: boolean) => void,
) {
function onGlobalMouseDown(event: MouseEvent) {
2021-06-22 02:47:33 +00:00
let target = event.target as HTMLElement;
if (target.shadowRoot && event.composed) {
target = (event.composedPath()[0] || target) as HTMLElement;
}
2020-10-10 05:57:37 +00:00
const elements = [refs[0]?.value, refs[1]?.value?.getPopupElement()];
2020-10-07 14:49:01 +00: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);
});
}