Skip to content

Commit

Permalink
🐛 Improve handling eventlistener
Browse files Browse the repository at this point in the history
  • Loading branch information
oddvernes committed Feb 9, 2022
1 parent 23c262f commit 21950b9
Showing 1 changed file with 31 additions and 11 deletions.
42 changes: 31 additions & 11 deletions packages/eds-core-react/src/components/Tabs/Tabs.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { forwardRef, useState, HTMLAttributes } from 'react'
import { forwardRef, useState, HTMLAttributes, useEffect, useRef } from 'react'
import { TabsProvider } from './Tabs.context'
import { Variants } from './Tabs.types'
import { token as tabsToken } from './Tabs.tokens'
import { useId, useToken } from '@equinor/eds-utils'
import { useId, useToken, useCombinedRefs } from '@equinor/eds-utils'
import { ThemeProvider } from 'styled-components'
import { useEds } from '../EdsProvider'

Expand All @@ -28,8 +28,10 @@ const Tabs = forwardRef<HTMLDivElement, TabsProps>(function Tabs(
ref,
) {
const tabsId = useId(id, 'tabs')

const tabsRef = useRef<HTMLDivElement>(null)
const combinedTabsRef = useCombinedRefs<HTMLDivElement>(tabsRef, ref)
const [tabsFocused, setTabsFocused] = useState(false)
const [listenerAttached, setListenerAttached] = useState(false)

let blurTimer

Expand All @@ -48,17 +50,30 @@ const Tabs = forwardRef<HTMLDivElement, TabsProps>(function Tabs(
}
clearTimeout(blurTimer)

//Only force focus on active Tab if Tabs was navigated to with keyboard
const checkIfTabWasPressed = (event: KeyboardEvent) => {
document.removeEventListener('keyup', checkIfTabWasPressed, true)
if (event.key === 'Tab') setTabsFocused(true)
if (tabsFocused) return
if (!listenerAttached) {
setListenerAttached(true)
tabsRef.current.addEventListener('keyup', checkIfTabWasPressed, {
once: true,
})
}
if (!tabsFocused)
document.addEventListener('keyup', checkIfTabWasPressed, true)

onFocus && onFocus(e)
}

//Only force focus on active Tab if Tabs was navigated to with keyboard
const checkIfTabWasPressed = (event: KeyboardEvent) => {
setListenerAttached(false)
if (event.key === 'Tab') setTabsFocused(true)
}

useEffect(() => {
const tabs = tabsRef.current
return () => {
if (tabs) tabs.removeEventListener('keyup', checkIfTabWasPressed)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

const { density } = useEds()
const token = useToken({ density }, tabsToken)

Expand All @@ -73,7 +88,12 @@ const Tabs = forwardRef<HTMLDivElement, TabsProps>(function Tabs(
tabsFocused,
}}
>
<div ref={ref} {...props} onBlur={handleBlur} onFocus={handleFocus} />
<div
ref={combinedTabsRef}
{...props}
onBlur={handleBlur}
onFocus={handleFocus}
/>
</TabsProvider>
</ThemeProvider>
)
Expand Down

0 comments on commit 21950b9

Please sign in to comment.