import { onMounted, onBeforeUnmount, watch, type Ref } from 'vue' import { useNuxtApp } from '#app' import type Lenis from 'lenis' import { useAppStore } from '~/stores/app' export const usePageScrollLock = (isLocked: Ref | boolean) => { const { $lenis } = useNuxtApp() as ReturnType & { $lenis?: Lenis } const lockScroll = () => { if (import.meta.client) { document.documentElement.classList.add('is-home-intro-active') $lenis?.scrollTo(0, { immediate: true }) $lenis?.stop() } } const unlockScroll = () => { if (import.meta.client) { document.documentElement.classList.remove('is-home-intro-active') $lenis?.start() } } // If passed a boolean, lock immediately and unlock on unmount if (typeof isLocked === 'boolean') { if (isLocked) { onMounted(() => { lockScroll() }) onBeforeUnmount(() => { unlockScroll() }) } } else { // If passed a ref, watch its value watch(isLocked, (locked) => { if (locked) { lockScroll() } else { unlockScroll() } }, { immediate: true }) onBeforeUnmount(() => { unlockScroll() }) } return { lockScroll, unlockScroll } }