Skip to content

Commit

Permalink
use a "cancellable" microTask
Browse files Browse the repository at this point in the history
  • Loading branch information
RobinMalfait committed Sep 6, 2022
1 parent 0954ec5 commit 14c196f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ import {
} from '../../utils/render'
import { OpenClosedProvider, State, useOpenClosed } from '../../internal/open-closed'
import { match } from '../../utils/match'
import { microTask } from '../../utils/micro-task'
import { useIsMounted } from '../../hooks/use-is-mounted'
import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect'
import { useLatestValue } from '../../hooks/use-latest-value'
import { useServerHandoffComplete } from '../../hooks/use-server-handoff-complete'
import { useSyncRefs } from '../../hooks/use-sync-refs'
import { useTransition } from '../../hooks/use-transition'
import { useEvent } from '../../hooks/use-event'
import { useDisposables } from '../../hooks/use-disposables'

type ContainerElement = MutableRefObject<HTMLElement | null>

Expand Down Expand Up @@ -128,6 +128,7 @@ function useNesting(done?: () => void, parent?: NestingContextValues) {
let doneRef = useLatestValue(done)
let transitionableChildren = useRef<NestingContextValues['children']['current']>([])
let mounted = useIsMounted()
let d = useDisposables()

let unregister = useEvent((container: ContainerElement, strategy = RenderStrategy.Hidden) => {
let idx = transitionableChildren.current.findIndex(({ el }) => el === container)
Expand All @@ -142,7 +143,7 @@ function useNesting(done?: () => void, parent?: NestingContextValues) {
},
})

microTask(() => {
d.microTask(() => {
if (!hasChildren(transitionableChildren) && mounted.current) {
doneRef.current?.()
}
Expand Down
14 changes: 14 additions & 0 deletions packages/@headlessui-react/src/utils/disposables.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { microTask } from './micro-task'

export function disposables() {
let disposables: Function[] = []
let queue: Function[] = []
Expand Down Expand Up @@ -33,6 +35,18 @@ export function disposables() {
return api.add(() => clearTimeout(timer))
},

microTask(...args: Parameters<typeof microTask>) {
let task = { current: true }
microTask(() => {
if (task.current) {
args[0]()
}
})
return api.add(() => {
task.current = false
})
},

add(cb: () => void) {
disposables.push(cb)
return () => {
Expand Down

0 comments on commit 14c196f

Please sign in to comment.