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 arrow key handling in Tab (after DOM order changes) #2145

Merged
merged 2 commits into from
Jan 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/@headlessui-react/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed

- Fix SSR tab rendering on React 17 ([#2102](https://github.com/tailwindlabs/headlessui/pull/2102))
- Fix arrow key handling in `Tab` (after DOM order changes) ([#2145](https://github.com/tailwindlabs/headlessui/pull/2145))

## [1.7.7] - 2022-12-16

Expand Down
171 changes: 171 additions & 0 deletions packages/@headlessui-react/src/components/tabs/tabs.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,177 @@ describe('Rendering', () => {
})
)

it(
'should guarantee the order of DOM nodes when reversing the tabs and panels themselves, then performing actions (controlled component)',
suppressConsoleLogs(async () => {
function Example() {
let [selectedIndex, setSelectedIndex] = useState(1)
let [tabs, setTabs] = useState([0, 1, 2])

return (
<>
<button
onClick={() => {
setTabs((tabs) => tabs.slice().reverse())
setSelectedIndex((idx) => tabs.length - 1 - idx)
}}
>
reverse
</button>
<Tab.Group selectedIndex={selectedIndex} onChange={setSelectedIndex}>
<Tab.List>
{tabs.map((tab) => (
<Tab key={tab}>Tab {tab}</Tab>
))}
</Tab.List>

<Tab.Panels>
{tabs.map((tab) => (
<Tab.Panel key={tab}>Content {tab}</Tab.Panel>
))}
</Tab.Panels>
</Tab.Group>
<p id="selectedIndex">{selectedIndex}</p>
</>
)
}

render(<Example />)

let selectedIndexElement = document.getElementById('selectedIndex')

assertTabs({ active: 1 })

await click(getByText('Tab 0'))
assertTabs({ active: 0 })
expect(selectedIndexElement).toHaveTextContent('0')

await click(getByText('Tab 1'))
assertTabs({ active: 1 })
expect(selectedIndexElement).toHaveTextContent('1')

await click(getByText('Tab 2'))
assertTabs({ active: 2 })
expect(selectedIndexElement).toHaveTextContent('2')

await click(getByText('reverse'))

// Note: the indices are reversed now
await click(getByText('Tab 0'))
assertTabs({ active: 2 })
expect(selectedIndexElement).toHaveTextContent('2')

await click(getByText('Tab 1'))
assertTabs({ active: 1 })
expect(selectedIndexElement).toHaveTextContent('1')

await click(getByText('Tab 2'))
assertTabs({ active: 0 })
expect(selectedIndexElement).toHaveTextContent('0')

await click(getByText('reverse'))

// Note: the indices are reversed again now (back to normal)
await click(getByText('Tab 0'))
assertTabs({ active: 0 })
expect(selectedIndexElement).toHaveTextContent('0')

await click(getByText('Tab 1'))
assertTabs({ active: 1 })
expect(selectedIndexElement).toHaveTextContent('1')

await click(getByText('Tab 2'))
assertTabs({ active: 2 })
expect(selectedIndexElement).toHaveTextContent('2')
})
)

it(
'should guarantee the order of DOM nodes when reversing the tabs and panels themselves, then performing actions (uncontrolled component)',
suppressConsoleLogs(async () => {
function Example() {
let [tabs, setTabs] = useState([0, 1, 2])

return (
<>
<button
onClick={() => {
setTabs((tabs) => tabs.slice().reverse())
}}
>
reverse
</button>
<Tab.Group>
{({ selectedIndex }) => (
<>
<Tab.List>
{tabs.map((tab) => (
<Tab key={tab}>Tab {tab}</Tab>
))}
</Tab.List>

<Tab.Panels>
{tabs.map((tab) => (
<Tab.Panel key={tab}>Content {tab}</Tab.Panel>
))}
</Tab.Panels>

<p id="selectedIndex">{selectedIndex}</p>
</>
)}
</Tab.Group>
</>
)
}

render(<Example />)

let selectedIndexElement = document.getElementById('selectedIndex')

await click(getByText('Tab 0'))
assertTabs({ active: 0 })
expect(selectedIndexElement).toHaveTextContent('0')

await click(getByText('Tab 1'))
assertTabs({ active: 1 })
expect(selectedIndexElement).toHaveTextContent('1')

await click(getByText('Tab 2'))
assertTabs({ active: 2 })
expect(selectedIndexElement).toHaveTextContent('2')

await click(getByText('reverse'))

// Note: the indices are reversed now
await click(getByText('Tab 0'))
assertTabs({ active: 2 })
expect(selectedIndexElement).toHaveTextContent('2')

await click(getByText('Tab 1'))
assertTabs({ active: 1 })
expect(selectedIndexElement).toHaveTextContent('1')

await click(getByText('Tab 2'))
assertTabs({ active: 0 })
expect(selectedIndexElement).toHaveTextContent('0')

await click(getByText('reverse'))

// Note: the indices are reversed again now (back to normal)
await click(getByText('Tab 0'))
assertTabs({ active: 0 })
expect(selectedIndexElement).toHaveTextContent('0')

await click(getByText('Tab 1'))
assertTabs({ active: 1 })
expect(selectedIndexElement).toHaveTextContent('1')

await click(getByText('Tab 2'))
assertTabs({ active: 2 })
expect(selectedIndexElement).toHaveTextContent('2')
})
)

describe('`renderProps`', () => {
it(
'should be possible to render using as={Fragment}',
Expand Down
40 changes: 31 additions & 9 deletions packages/@headlessui-react/src/components/tabs/tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,29 +61,37 @@ let reducers: {
) => StateDefinition
} = {
[ActionTypes.SetSelectedIndex](state, action) {
let focusableTabs = state.tabs.filter((tab) => !tab.current?.hasAttribute('disabled'))
let tabs = sortByDomNode(state.tabs, (tab) => tab.current)
let panels = sortByDomNode(state.panels, (panel) => panel.current)

let focusableTabs = tabs.filter((tab) => !tab.current?.hasAttribute('disabled'))

let nextState = { ...state, tabs, panels }

// Underflow
if (action.index < 0) {
return { ...state, selectedIndex: state.tabs.indexOf(focusableTabs[0]) }
return { ...nextState, selectedIndex: tabs.indexOf(focusableTabs[0]) }
}

// Overflow
else if (action.index > state.tabs.length) {
else if (action.index > tabs.length) {
return {
...state,
selectedIndex: state.tabs.indexOf(focusableTabs[focusableTabs.length - 1]),
...nextState,
selectedIndex: tabs.indexOf(focusableTabs[focusableTabs.length - 1]),
}
}

// Middle
let before = state.tabs.slice(0, action.index)
let after = state.tabs.slice(action.index)
let before = tabs.slice(0, action.index)
let after = tabs.slice(action.index)

let next = [...after, ...before].find((tab) => focusableTabs.includes(tab))
if (!next) return state
if (!next) return nextState

return { ...state, selectedIndex: state.tabs.indexOf(next) }
let selectedIndex = tabs.indexOf(next) ?? state.selectedIndex
if (selectedIndex === -1) selectedIndex = state.selectedIndex

return { ...nextState, selectedIndex }
},
[ActionTypes.RegisterTab](state, action) {
if (state.tabs.includes(action.tab)) return state
Expand Down Expand Up @@ -237,6 +245,20 @@ let Tabs = forwardRefWithAs(function Tabs<TTag extends ElementType = typeof DEFA
dispatch({ type: ActionTypes.SetSelectedIndex, index: selectedIndex ?? defaultIndex })
}, [selectedIndex /* Deliberately skipping defaultIndex */])

useIsoMorphicEffect(() => {
if (realSelectedIndex.current === undefined) return
if (state.tabs.length <= 0) return

// TODO: Figure out a way to detect this without the slow sort on every render. Might be fine
// unless you have a lot of tabs.
let sorted = sortByDomNode(state.tabs, (tab) => tab.current)
let didOrderChange = sorted.some((tab, i) => state.tabs[i] !== tab)

if (didOrderChange) {
change(sorted.indexOf(state.tabs[realSelectedIndex.current]))
}
})

let SSRCounter = useRef({ tabs: 0, panels: 0 })
let ourProps = { ref: tabsRef }

Expand Down
1 change: 1 addition & 0 deletions packages/@headlessui-vue/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed

- Ensure `disabled="false"` is not incorrectly passed to the underlying DOM Node ([#2138](https://github.com/tailwindlabs/headlessui/pull/2138))
- Fix arrow key handling in `Tab` (after DOM order changes) ([#2145](https://github.com/tailwindlabs/headlessui/pull/2145))

## [1.7.7] - 2022-12-16

Expand Down
Loading