Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useScrollLock): support using window or document #3319

Merged
merged 1 commit into from
Aug 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 18 additions & 4 deletions packages/core/useScrollLock/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ function preventDefault(rawEvent: TouchEvent): boolean {
return false
}

function getTargetElement(
element: MaybeRefOrGetter<HTMLElement | SVGElement | Window | Document | null | undefined>,
): HTMLElement | SVGElement | null | undefined {
const el = toValue(element)
if (el instanceof Window)
return window.document.documentElement

if (el instanceof Document)
return document.documentElement

return el
}

/**
* Lock scrolling of the element.
*
Expand All @@ -58,8 +71,9 @@ export function useScrollLock(
let initialOverflow: CSSStyleDeclaration['overflow']

watch(toRef(element), (el) => {
if (el) {
const ele = el as HTMLElement
const target = getTargetElement(el)
if (target) {
const ele = target as HTMLElement
initialOverflow = ele.style.overflow
if (isLocked.value)
ele.style.overflow = 'hidden'
Expand All @@ -69,7 +83,7 @@ export function useScrollLock(
})

const lock = () => {
const ele = (toValue(element) as HTMLElement)
const ele = getTargetElement(element)
if (!ele || isLocked.value)
return
if (isIOS) {
Expand All @@ -85,7 +99,7 @@ export function useScrollLock(
}

const unlock = () => {
const ele = (toValue(element) as HTMLElement)
const ele = getTargetElement(element)
if (!ele || !isLocked.value)
return
isIOS && stopTouchMoveListener?.()
Expand Down