Skip to content
Open
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
4 changes: 3 additions & 1 deletion packages/@headlessui-react/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- Nothing yet!
### Fixed

- Ensure interrupted transitions complete after changing direction ([#3892](https://github.com/tailwindlabs/headlessui/issues/3892))

## [2.2.10] - 2026-04-07

Expand Down
86 changes: 86 additions & 0 deletions packages/@headlessui-react/src/hooks/use-transition.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { render, waitFor } from '@testing-library/react'
import React, { act, useState } from 'react'
import { transitionDataAttributes, useTransition } from './use-transition'

class TestCSSTransition {
playState: AnimationPlayState = 'running'
finished: Promise<Animation>

private resolve!: (animation: Animation) => void
private reject!: (reason: Error) => void

constructor() {
this.finished = new Promise<Animation>((resolve, reject) => {
this.resolve = resolve
this.reject = reject
})
}

finish() {
this.playState = 'finished'
this.resolve(this as unknown as Animation)
}

cancel() {
this.playState = 'idle'
this.reject(new DOMException('The transition was cancelled', 'AbortError'))
}
}

it('waits for a replacement transition when an enter transition is interrupted', async () => {
let end = jest.fn()
let originalCSSTransition = Object.getOwnPropertyDescriptor(globalThis, 'CSSTransition')
Object.defineProperty(globalThis, 'CSSTransition', {
configurable: true,
writable: true,
value: TestCSSTransition,
})

let enter = new TestCSSTransition()
let leave = new TestCSSTransition()
let animations: Animation[] = [enter as unknown as Animation]
let getAnimations = jest
.spyOn(Element.prototype, 'getAnimations')
.mockImplementation(() => animations)

function Example({ show }: { show: boolean }) {
let [element, setElement] = useState<HTMLElement | null>(null)
let [visible, transitionData] = useTransition(true, element, show, { end })

return visible ? (
<div ref={setElement} data-testid="content" {...transitionDataAttributes(transitionData)} />
) : null
}

try {
let { queryByTestId, rerender } = render(<Example show={true} />)

await waitFor(() => expect(getAnimations).toHaveBeenCalledTimes(1))

rerender(<Example show={false} />)
await waitFor(() => expect(getAnimations).toHaveBeenCalledTimes(2))

// The browser cancels the captured enter transition and replaces it with
// the transition back to the closed state.
animations = [leave as unknown as Animation]
await act(async () => enter.cancel())

await waitFor(() => expect(getAnimations).toHaveBeenCalledTimes(3))
expect(queryByTestId('content')).toHaveAttribute('data-enter')
expect(queryByTestId('content')).toHaveAttribute('data-closed')
expect(end).not.toHaveBeenCalled()

await act(async () => leave.finish())

await waitFor(() => expect(queryByTestId('content')).toBeNull())
expect(end).toHaveBeenCalledTimes(1)
expect(end).toHaveBeenCalledWith(false)
} finally {
getAnimations.mockRestore()
if (originalCSSTransition) {
Object.defineProperty(globalThis, 'CSSTransition', originalCSSTransition)
} else {
Reflect.deleteProperty(globalThis, 'CSSTransition')
}
}
})
37 changes: 18 additions & 19 deletions packages/@headlessui-react/src/hooks/use-transition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,6 @@ export function useTransition(
}
},
done() {
if (cancelledRef.current) {
if (hasPendingTransitions(element)) {
return
}
}

inFlight.current = false

removeFlag(TransitionState.Enter | TransitionState.Leave | TransitionState.Closed)
Expand Down Expand Up @@ -256,26 +250,31 @@ function transition(
function waitForTransition(node: HTMLElement | null, done: () => void) {
let d = disposables()
if (!node) return d.dispose
let element = node

let cancelled = false
d.add(() => {
cancelled = true
})

let transitions =
node.getAnimations?.().filter((animation) => animation instanceof CSSTransition) ?? []
// If there are no transitions, we can stop early.
if (transitions.length === 0) {
done()
return d.dispose
}
function waitForTransitions() {
if (cancelled) return

// Wait for all the transitions to complete.
Promise.allSettled(transitions.map((transition) => transition.finished)).then(() => {
if (!cancelled) {
let transitions = getPendingTransitions(element)
// If there are no transitions, we can stop early.
if (transitions.length === 0) {
done()
return
}
})

// A transition can be replaced when its direction changes, so check the
// current transitions again after this batch has settled.
Promise.allSettled(transitions.map((transition) => transition.finished)).then(() =>
waitForTransitions()
)
}

waitForTransitions()

return d.dispose
}
Expand Down Expand Up @@ -305,10 +304,10 @@ function prepareTransition(
node.style.transition = previous
}

function hasPendingTransitions(node: HTMLElement) {
function getPendingTransitions(node: HTMLElement) {
let animations = node.getAnimations?.() ?? []

return animations.some((animation) => {
return animations.filter((animation) => {
return animation instanceof CSSTransition && animation.playState !== 'finished'
})
}