about summary refs log tree commit diff
path: root/src/lib/hooks/useWebBodyScrollLock.ts
blob: c63c23b29c99897e82dcf693a2d1008038398379 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import {useEffect} from 'react'

import {isWeb} from '#/platform/detection'

let refCount = 0

function incrementRefCount() {
  if (refCount === 0) {
    document.body.style.overflow = 'hidden'
    document.documentElement.style.scrollbarGutter = 'auto'
  }
  refCount++
}

function decrementRefCount() {
  refCount--
  if (refCount === 0) {
    document.body.style.overflow = ''
    document.documentElement.style.scrollbarGutter = ''
  }
}

export function useWebBodyScrollLock(isLockActive: boolean) {
  useEffect(() => {
    if (!isWeb || !isLockActive) {
      return
    }
    incrementRefCount()
    return () => decrementRefCount()
  })
}