chore: Scroll lock composable to reuse

This commit is contained in:
iamsivin
2025-05-09 16:47:53 +05:30
parent 9c5af11b84
commit 0c5379147d
5 changed files with 182 additions and 29 deletions
@@ -0,0 +1,49 @@
/**
* useGlobalScrollLock composable
*
* Usage:
* const { lockScroll, unlockScroll, isLocked } = useGlobalScrollLock(target);
* target can be a ref, DOM element, or selector string (class, id, etc)
* eg: lockScroll('.conversation-panel'); unlockScroll();
*/
import { ref, unref, shallowRef, onUnmounted } from 'vue';
import { useScrollLock } from '@vueuse/core';
export function useGlobalScrollLock(defaultTarget) {
const scrollLockInstance = shallowRef(null);
const isLocked = ref(false);
function resolveTarget(target) {
if (!target) return null;
if (typeof target === 'string') return document.querySelector(target); // class, id, etc
if (target instanceof HTMLElement) return target; // DOM element
return unref(target); // ref
}
function unlockScroll() {
if (!scrollLockInstance.value) return false;
scrollLockInstance.value.value = false;
isLocked.value = false;
scrollLockInstance.value = null;
return true;
}
function lockScroll(target = defaultTarget) {
unlockScroll(); // Always unlock first
const el = resolveTarget(target);
if (!el) return false;
scrollLockInstance.value = useScrollLock(el, true);
isLocked.value = true;
return true;
}
onUnmounted(() => {
unlockScroll();
});
return { lockScroll, unlockScroll, isLocked };
}