components#useBodyScroll TypeScript Examples

The following examples show how to use components#useBodyScroll. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: body-scroll.test.tsx    From geist-ui with MIT License 4 votes vote down vote up
describe('UseBodyScroll', () => {
  it('should work correctly', () => {
    const ref = React.createRef<HTMLDivElement>()
    ;(ref as any).current = document.createElement('div')
    const { result } = renderHook(() => useBodyScroll(ref))
    const [hidden, setHidden] = result.current
    expect(hidden).toBe(false)

    act(() => setHidden(true))
    expect(result.current[0]).toBe(true)
  })

  it('should set overflow', async () => {
    const ref = React.createRef<HTMLDivElement>()
    ;(ref as any).current = document.createElement('div')
    const el = ref.current as HTMLDivElement
    const { result } = renderHook(() => useBodyScroll(ref))

    act(() => result.current[1](true))
    expect(el.style.overflow).toEqual('hidden')

    act(() => result.current[1](false))
    await sleep(10)
    expect(el.style.overflow).not.toEqual('hidden')
  })

  it('the last value of overflow should be recovered after setHidden', async () => {
    const ref = React.createRef<HTMLDivElement>()
    const div = document.createElement('div')
    div.style.overflow = 'scroll'
    ;(ref as any).current = div
    const el = ref.current as HTMLDivElement
    const { result } = renderHook(() => useBodyScroll(ref))
    expect(el.style.overflow).toEqual('scroll')

    act(() => result.current[1](true))
    expect(el.style.overflow).toEqual('hidden')

    act(() => result.current[1](false))
    await sleep(10)
    expect(el.style.overflow).toEqual('scroll')
  })

  it('should work correctly with multiple element', async () => {
    const ref = React.createRef<HTMLDivElement>()
    ;(ref as any).current = document.createElement('div')
    const el = ref.current as HTMLDivElement
    const { result } = renderHook(() => useBodyScroll(ref))

    const ref2 = React.createRef<HTMLDivElement>()
    ;(ref2 as any).current = document.createElement('div')
    const el2 = ref2.current as HTMLDivElement
    const { result: result2 } = renderHook(() => useBodyScroll(ref2))

    act(() => result.current[1](true))
    act(() => result2.current[1](true))
    expect(el.style.overflow).toEqual('hidden')
    expect(el2.style.overflow).toEqual('hidden')

    act(() => result.current[1](false))
    act(() => result2.current[1](false))
    await sleep(10)
    expect(el.style.overflow).toEqual('')
    expect(el2.style.overflow).toEqual('')
  })

  it('should work correctly with options', async () => {
    const ref = React.createRef<HTMLDivElement>()
    ;(ref as any).current = document.createElement('div')
    const el = ref.current as HTMLDivElement
    const { result } = renderHook(() => useBodyScroll(ref, { delayReset: 300 }))

    act(() => result.current[1](true))
    expect(el.style.overflow).toEqual('hidden')

    act(() => result.current[1](false))
    await sleep(10)
    expect(el.style.overflow).toEqual('hidden')
    await sleep(100)
    expect(el.style.overflow).toEqual('hidden')
    await sleep(250)
    expect(el.style.overflow).not.toEqual('hidden')
  })

  it('should work correctly when set element repeatedly', () => {
    let _ref: RefObject<HTMLDivElement> | null = null
    const ref = React.createRef<HTMLDivElement>()
    ;(ref as any).current = document.createElement('div')
    _ref = ref
    const el = ref.current as HTMLDivElement
    const { result, rerender } = renderHook(() => useBodyScroll(_ref))

    act(() => result.current[1](true))
    expect(el.style.overflow).toEqual('hidden')

    // Force tigger rerender at the same value
    _ref = React.createRef<HTMLDivElement>()
    rerender()

    _ref = ref
    rerender()
    act(() => result.current[1](true))
    expect(el.style.overflow).toEqual('hidden')
  })

  it('should set body when missing all params', () => {
    const { result } = renderHook(() => useBodyScroll())

    act(() => result.current[1](true))
    expect(document.body.style.overflow).toEqual('hidden')
  })
})
Example #2
Source File: menu.tsx    From geist-ui with MIT License 4 votes vote down vote up
Menu: React.FC<unknown> = () => {
  const router = useRouter()
  const theme = useTheme()
  const { isChinese } = useConfigs()
  const { tabbar: currentUrlTabValue, locale } = useLocale()
  const [expanded, setExpanded] = useState<boolean>(false)
  const [, setBodyHidden] = useBodyScroll(null, { delayReset: 300 })
  const isMobile = useMediaQuery('xs', { match: 'down' })
  const allSides = useMemo(() => Metadata[locale], [locale])

  useEffect(() => {
    const prefetch = async () => {
      const urls = isChinese
        ? ['/zh-cn/guide/introduction', '/zh-cn/components/text', '/zh-cn/customization']
        : ['/en-us/guide/introduction', '/en-us/components/text', '/en-us/customization']
      await Promise.all(
        urls.map(async url => {
          await router.prefetch(url)
        }),
      )
    }
    prefetch()
      .then()
      .catch(err => console.log(err))
  }, [isChinese])

  useEffect(() => {
    setBodyHidden(expanded)
  }, [expanded])

  useEffect(() => {
    if (!isMobile) {
      setExpanded(false)
    }
  }, [isMobile])

  useEffect(() => {
    const handleRouteChange = () => {
      setExpanded(false)
    }

    router.events.on('routeChangeComplete', handleRouteChange)
    return () => router.events.off('routeChangeComplete', handleRouteChange)
  }, [router.events])

  const handleTabChange = useCallback(
    (tab: string) => {
      const shouldRedirectDefaultPage = currentUrlTabValue !== tab
      if (!shouldRedirectDefaultPage) return
      const defaultPath = `/${locale}/${tab}`
      router.push(defaultPath)
    },
    [currentUrlTabValue, locale],
  )
  const [isLocked, setIsLocked] = useState<boolean>(false)

  useEffect(() => {
    const handler = () => {
      const isLocked = document.body.style.overflow === 'hidden'
      setIsLocked(last => (last !== isLocked ? isLocked : last))
    }
    const observer = new MutationObserver(mutations => {
      mutations.forEach(function (mutation) {
        if (mutation.type !== 'attributes') return
        handler()
      })
    })

    observer.observe(document.body, {
      attributes: true,
    })
    return () => {
      observer.disconnect()
    }
  }, [])

  return (
    <>
      <div className="menu-wrapper">
        <nav className="menu">
          <div className="content">
            <div className="logo">
              <NextLink href={`/${locale}`}>
                <a aria-label="Go Home">
                  <Image
                    src="/images/logo.png"
                    width="20px"
                    height="20px"
                    mr={0.5}
                    draggable={false}
                    title="Logo"
                  />
                  Geist
                </a>
              </NextLink>
            </div>

            <div className="tabs">
              <Tabs
                value={currentUrlTabValue}
                leftSpace={0}
                activeClassName="current"
                align="center"
                hideDivider
                hideBorder
                onChange={handleTabChange}>
                <Tabs.Item font="14px" label={isChinese ? '主页' : 'Home'} value="" />
                {allSides.map((tab, index) => (
                  <Tabs.Item
                    font="14px"
                    label={tab.localeName || tab.name}
                    value={tab.name}
                    key={`${tab.localeName || tab.name}-${index}`}
                  />
                ))}
              </Tabs>
            </div>

            <div className="controls">
              {isMobile ? (
                <Button
                  className="menu-toggle"
                  auto
                  type="abort"
                  onClick={() => setExpanded(!expanded)}>
                  <MenuIcon size="1.125rem" />
                </Button>
              ) : (
                <Controls />
              )}
            </div>
          </div>
        </nav>
      </div>
      <MenuMobile expanded={expanded} />

      <style jsx>{`
        .menu-wrapper {
          height: var(--geist-page-nav-height);
        }
        .menu {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          padding-right: ${isLocked ? 'var(--geist-page-scrollbar-width)' : 0};
          height: var(--geist-page-nav-height);
          //width: 100%;
          backdrop-filter: saturate(180%) blur(5px);
          background-color: ${addColorAlpha(theme.palette.background, 0.8)};
          box-shadow: ${theme.type === 'dark'
            ? '0 0 0 1px #333'
            : '0 0 15px 0 rgba(0, 0, 0, 0.1)'};
          z-index: 999;
        }
        nav .content {
          display: flex;
          align-items: center;
          justify-content: space-between;
          max-width: 1000px;
          height: 100%;
          margin: 0 auto;
          user-select: none;
          padding: 0 ${theme.layout.gap};
        }
        .logo {
          flex: 1 1;
          display: flex;
          align-items: center;
          justify-content: flex-start;
        }
        .logo a {
          display: inline-flex;
          flex-direction: row;
          align-items: center;
          font-size: 1.125rem;
          font-weight: 500;
          color: inherit;
          height: 28px;
        }
        .logo :global(.image) {
          border: 1px solid ${theme.palette.border};
          border-radius: 2rem;
        }
        .tabs {
          flex: 1 1;
          padding: 0 ${theme.layout.gap};
        }
        .tabs :global(.content) {
          display: none;
        }
        @media only screen and (max-width: ${theme.breakpoints.xs.max}) {
          .tabs {
            display: none;
          }
        }
        .controls {
          flex: 1 1;
          display: flex;
          align-items: center;
          justify-content: flex-end;
        }
        .controls :global(.menu-toggle) {
          display: flex;
          align-items: center;
          min-width: 40px;
          height: 40px;
          padding: 0;
        }
      `}</style>
    </>
  )
}