2021-11-29 15:58:44 +08:00
|
|
|
import { watch, isRef, onScopeDispose } from 'vue'
|
2020-09-09 21:18:08 +08:00
|
|
|
|
2021-12-12 23:28:03 +08:00
|
|
|
import { isClient } from '@vueuse/core'
|
2020-09-09 21:18:08 +08:00
|
|
|
import {
|
2022-02-11 11:03:15 +08:00
|
|
|
throwError,
|
2020-09-09 21:18:08 +08:00
|
|
|
addClass,
|
|
|
|
removeClass,
|
|
|
|
hasClass,
|
|
|
|
getStyle,
|
2022-02-11 11:03:15 +08:00
|
|
|
getScrollBarWidth,
|
|
|
|
} from '@element-plus/utils'
|
2020-09-09 21:18:08 +08:00
|
|
|
|
|
|
|
import type { Ref } from 'vue'
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Hook that monitoring the ref value to lock or unlock the screen.
|
|
|
|
* When the trigger became true, it assumes modal is now opened and vice versa.
|
|
|
|
* @param trigger {Ref<boolean>}
|
|
|
|
*/
|
2021-11-29 15:58:44 +08:00
|
|
|
export const useLockscreen = (trigger: Ref<boolean>) => {
|
2020-09-09 21:18:08 +08:00
|
|
|
if (!isRef(trigger)) {
|
|
|
|
throwError(
|
2021-11-29 15:58:44 +08:00
|
|
|
'[useLockscreen]',
|
2021-09-04 19:29:28 +08:00
|
|
|
'You need to pass a ref param to this function'
|
2020-09-09 21:18:08 +08:00
|
|
|
)
|
|
|
|
}
|
2021-12-12 23:28:03 +08:00
|
|
|
if (!isClient || hasClass(document.body, 'el-popup-parent--hidden')) {
|
2021-12-07 17:25:50 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-09-09 21:18:08 +08:00
|
|
|
let scrollBarWidth = 0
|
|
|
|
let withoutHiddenClass = false
|
|
|
|
let bodyPaddingRight = '0'
|
|
|
|
let computedBodyPaddingRight = 0
|
2021-03-16 21:40:45 +08:00
|
|
|
|
|
|
|
const cleanup = () => {
|
|
|
|
removeClass(document.body, 'el-popup-parent--hidden')
|
|
|
|
if (withoutHiddenClass) {
|
|
|
|
document.body.style.paddingRight = bodyPaddingRight
|
|
|
|
}
|
|
|
|
}
|
2021-09-04 19:29:28 +08:00
|
|
|
watch(trigger, (val) => {
|
2021-11-29 15:58:44 +08:00
|
|
|
if (!val) {
|
2021-03-16 21:40:45 +08:00
|
|
|
cleanup()
|
2021-11-29 15:58:44 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
withoutHiddenClass = !hasClass(document.body, 'el-popup-parent--hidden')
|
|
|
|
if (withoutHiddenClass) {
|
|
|
|
bodyPaddingRight = document.body.style.paddingRight
|
|
|
|
computedBodyPaddingRight = parseInt(
|
|
|
|
getStyle(document.body, 'paddingRight'),
|
|
|
|
10
|
|
|
|
)
|
|
|
|
}
|
|
|
|
scrollBarWidth = getScrollBarWidth()
|
|
|
|
const bodyHasOverflow =
|
|
|
|
document.documentElement.clientHeight < document.body.scrollHeight
|
|
|
|
const bodyOverflowY = getStyle(document.body, 'overflowY')
|
|
|
|
if (
|
|
|
|
scrollBarWidth > 0 &&
|
|
|
|
(bodyHasOverflow || bodyOverflowY === 'scroll') &&
|
|
|
|
withoutHiddenClass
|
|
|
|
) {
|
|
|
|
document.body.style.paddingRight = `${
|
|
|
|
computedBodyPaddingRight + scrollBarWidth
|
|
|
|
}px`
|
2020-09-09 21:18:08 +08:00
|
|
|
}
|
2021-11-29 15:58:44 +08:00
|
|
|
addClass(document.body, 'el-popup-parent--hidden')
|
2020-09-09 21:18:08 +08:00
|
|
|
})
|
2021-11-29 15:58:44 +08:00
|
|
|
onScopeDispose(() => cleanup())
|
2020-09-09 21:18:08 +08:00
|
|
|
}
|