index.mjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { throwError } from "../../utils/error.mjs";
  2. import { addClass, getStyle, hasClass, removeClass } from "../../utils/dom/style.mjs";
  3. import { getScrollBarWidth } from "../../utils/dom/scroll.mjs";
  4. import { useNamespace } from "../use-namespace/index.mjs";
  5. import { computed, isRef, onScopeDispose, watch } from "vue";
  6. //#region ../../packages/hooks/use-lockscreen/index.ts
  7. /**
  8. * Hook that monitoring the ref value to lock or unlock the screen.
  9. * When the trigger became true, it assumes modal is now opened and vice versa.
  10. * @param trigger {Ref<boolean>}
  11. */
  12. const useLockscreen = (trigger, options = {}) => {
  13. if (!isRef(trigger)) throwError("[useLockscreen]", "You need to pass a ref param to this function");
  14. const ns = options.ns || useNamespace("popup");
  15. const hiddenCls = computed(() => ns.bm("parent", "hidden"));
  16. let scrollBarWidth = 0;
  17. let withoutHiddenClass = false;
  18. let bodyWidth = "0";
  19. let cleaned = false;
  20. const cleanup = () => {
  21. if (cleaned) return;
  22. cleaned = true;
  23. setTimeout(() => {
  24. if (typeof document === "undefined") return;
  25. if (withoutHiddenClass && document) {
  26. document.body.style.width = bodyWidth;
  27. removeClass(document.body, hiddenCls.value);
  28. }
  29. }, 200);
  30. };
  31. watch(trigger, (val) => {
  32. if (!val) {
  33. cleanup();
  34. return;
  35. }
  36. cleaned = false;
  37. withoutHiddenClass = !hasClass(document.body, hiddenCls.value);
  38. if (withoutHiddenClass) {
  39. bodyWidth = document.body.style.width;
  40. addClass(document.body, hiddenCls.value);
  41. }
  42. scrollBarWidth = getScrollBarWidth(ns.namespace.value);
  43. const bodyHasOverflow = document.documentElement.clientHeight < document.body.scrollHeight;
  44. const bodyOverflowY = getStyle(document.body, "overflowY");
  45. if (scrollBarWidth > 0 && (bodyHasOverflow || bodyOverflowY === "scroll") && withoutHiddenClass) document.body.style.width = `calc(100% - ${scrollBarWidth}px)`;
  46. });
  47. onScopeDispose(() => cleanup());
  48. };
  49. //#endregion
  50. export { useLockscreen };
  51. //# sourceMappingURL=index.mjs.map