index.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { isRef, onScopeDispose, watch } from 'vue'
  2. import { computed } from '@vue/reactivity'
  3. import { isClient } from '@vueuse/core'
  4. import {
  5. addClass,
  6. getScrollBarWidth,
  7. getStyle,
  8. hasClass,
  9. removeClass,
  10. throwError,
  11. } from '@element-plus/utils'
  12. import { useNamespace } from '../use-namespace'
  13. import type { Ref } from 'vue'
  14. import type { UseNamespaceReturn } from '../use-namespace'
  15. export type UseLockScreenOptions = {
  16. ns?: UseNamespaceReturn
  17. // shouldLock?: MaybeRef<boolean>
  18. }
  19. /**
  20. * Hook that monitoring the ref value to lock or unlock the screen.
  21. * When the trigger became true, it assumes modal is now opened and vice versa.
  22. * @param trigger {Ref<boolean>}
  23. */
  24. export const useLockscreen = (
  25. trigger: Ref<boolean>,
  26. options: UseLockScreenOptions = {}
  27. ) => {
  28. if (!isRef(trigger)) {
  29. throwError(
  30. '[useLockscreen]',
  31. 'You need to pass a ref param to this function'
  32. )
  33. }
  34. const ns = options.ns || useNamespace('popup')
  35. const hiddenCls = computed(() => ns.bm('parent', 'hidden'))
  36. if (!isClient || hasClass(document.body, hiddenCls.value)) {
  37. return
  38. }
  39. let scrollBarWidth = 0
  40. let withoutHiddenClass = false
  41. let bodyWidth = '0'
  42. const cleanup = () => {
  43. setTimeout(() => {
  44. removeClass(document?.body, hiddenCls.value)
  45. if (withoutHiddenClass && document) {
  46. document.body.style.width = bodyWidth
  47. }
  48. }, 200)
  49. }
  50. watch(trigger, (val) => {
  51. if (!val) {
  52. cleanup()
  53. return
  54. }
  55. withoutHiddenClass = !hasClass(document.body, hiddenCls.value)
  56. if (withoutHiddenClass) {
  57. bodyWidth = document.body.style.width
  58. }
  59. scrollBarWidth = getScrollBarWidth(ns.namespace.value)
  60. const bodyHasOverflow =
  61. document.documentElement.clientHeight < document.body.scrollHeight
  62. const bodyOverflowY = getStyle(document.body, 'overflowY')
  63. if (
  64. scrollBarWidth > 0 &&
  65. (bodyHasOverflow || bodyOverflowY === 'scroll') &&
  66. withoutHiddenClass
  67. ) {
  68. document.body.style.width = `calc(100% - ${scrollBarWidth}px)`
  69. }
  70. addClass(document.body, hiddenCls.value)
  71. })
  72. onScopeDispose(() => cleanup())
  73. }