-
Notifications
You must be signed in to change notification settings - Fork 285
Expand file tree
/
Copy pathuse-modal.ts
More file actions
72 lines (64 loc) · 1.94 KB
/
use-modal.ts
File metadata and controls
72 lines (64 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { onUnmounted, watch, ref } from 'vue';
import { ModalProps, EmitEventFn, UseModal } from '../modal-types';
import { lockScroll } from '../../../shared/utils/lock-scroll';
import { useNamespace, focusStack } from '@devui/shared'
import type { FoucusLayer } from '@devui/shared'
import { ZINDEX } from '../const'
export function useModal(props: ModalProps, emit: EmitEventFn): UseModal {
let lockScrollCb: () => void;
const ns = useNamespace('modal')
const overlayZIndex = ref('')
const modalZIndex = ref('')
const paused = ref(false)
const layer: FoucusLayer = {
pause() {
paused.value = true
},
resume() {
paused.value = false
}
}
const removeAdditions = () => {
lockScrollCb?.()
props.escapable && window.removeEventListener('keyup', onKeydown)
setTimeout(() => {
focusStack.remove(layer)
});
}
function close(): void {
emit('update:modelValue', false);
emit('close');
}
function execClose() {
props.beforeClose ? props.beforeClose(close) : close();
}
function onKeydown(event: KeyboardEvent) {
if (event.code === 'Escape' && !paused.value) {
execClose();
}
}
function calculateZIndex() {
const modalDomsLength = document.querySelectorAll(`.${ns.b()}`).length
overlayZIndex.value = `calc(var(--devui-z-index-modal, 1050) + ${(modalDomsLength - 1) * ZINDEX} - 1)`
modalZIndex.value = `calc(var(--devui-z-index-modal, 1050) + ${(modalDomsLength - 1) * ZINDEX})`
}
watch(
() => props.modelValue,
(val, oldVal) => {
if (val) {
calculateZIndex()
props.lockScroll && (lockScrollCb = lockScroll());
props.escapable && window.addEventListener('keyup', onKeydown)
focusStack.push(layer)
} else {
oldVal !== undefined && removeAdditions()
}
},
{
immediate: true,
flush: 'post'
}
);
onUnmounted(removeAdditions);
return { execClose, overlayZIndex, modalZIndex };
}