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 outside click in nested portalled Popover components #3362

Merged
merged 9 commits into from
Jul 5, 2024
1 change: 1 addition & 0 deletions packages/@headlessui-react/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
- Fix crash in `Combobox` component when in `virtual` mode when options are empty ([#3356](https://github.com/tailwindlabs/headlessui/pull/3356))
- Fix hanging tests when using `anchor` prop ([#3357](https://github.com/tailwindlabs/headlessui/pull/3357))
- Fix `transition` and `focus` prop combination for `PopoverPanel` component ([#3361](https://github.com/tailwindlabs/headlessui/pull/3361))
- Fix outside click in nested portalled `Popover` components ([#3362](https://github.com/tailwindlabs/headlessui/pull/3362))

## [2.1.1] - 2024-06-26

Expand Down
35 changes: 19 additions & 16 deletions packages/@headlessui-react/src/components/dialog/dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@ import { useIsTouchDevice } from '../../hooks/use-is-touch-device'
import { useOnDisappear } from '../../hooks/use-on-disappear'
import { useOutsideClick } from '../../hooks/use-outside-click'
import { useOwnerDocument } from '../../hooks/use-owner'
import { useRootContainers } from '../../hooks/use-root-containers'
import {
MainTreeProvider,
useMainTreeNode,
useRootContainers,
} from '../../hooks/use-root-containers'
import { useScrollLock } from '../../hooks/use-scroll-lock'
import { useServerHandoffComplete } from '../../hooks/use-server-handoff-complete'
import { useSyncRefs } from '../../hooks/use-sync-refs'
import { CloseProvider } from '../../internal/close-provider'
import { HoistFormFields } from '../../internal/form-fields'
import { ResetOpenClosedProvider, State, useOpenClosed } from '../../internal/open-closed'
import { ForcePortalRoot } from '../../internal/portal-force-root'
import type { Props } from '../../types'
Expand Down Expand Up @@ -180,11 +183,9 @@ let InternalDialog = forwardRefWithAs(function InternalDialog<
},
}

let {
resolveContainers: resolveRootContainers,
mainTreeNodeRef,
MainTreeNode,
} = useRootContainers({
let mainTreeNode = useMainTreeNode()
let { resolveContainers: resolveRootContainers } = useRootContainers({
mainTreeNode,
portals,
defaultContainers: [defaultContainer],
})
Expand All @@ -207,8 +208,7 @@ let InternalDialog = forwardRefWithAs(function InternalDialog<
]),
disallowed: useEvent(() => [
// Disallow the "main" tree root node
mainTreeNodeRef.current?.closest<HTMLElement>('body > *:not(#headlessui-portal-root)') ??
null,
mainTreeNode?.closest<HTMLElement>('body > *:not(#headlessui-portal-root)') ?? null,
]),
})

Expand Down Expand Up @@ -320,9 +320,6 @@ let InternalDialog = forwardRefWithAs(function InternalDialog<
</DialogContext.Provider>
</Portal>
</ForcePortalRoot>
<HoistFormFields>
<MainTreeNode />
</HoistFormFields>
</ResetOpenClosedProvider>
)
})
Expand Down Expand Up @@ -395,13 +392,19 @@ function DialogFn<TTag extends ElementType = typeof DEFAULT_DIALOG_TAG>(

if ((open !== undefined || transition) && !rest.static) {
return (
<Transition show={open} transition={transition} unmount={rest.unmount}>
<InternalDialog ref={ref} {...rest} />
</Transition>
<MainTreeProvider>
<Transition show={open} transition={transition} unmount={rest.unmount}>
<InternalDialog ref={ref} {...rest} />
</Transition>
</MainTreeProvider>
)
}

return <InternalDialog ref={ref} open={open} {...rest} />
return (
<MainTreeProvider>
<InternalDialog ref={ref} open={open} {...rest} />
</MainTreeProvider>
)
}

// ---
Expand Down
94 changes: 46 additions & 48 deletions packages/@headlessui-react/src/components/popover/popover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ import { useOnDisappear } from '../../hooks/use-on-disappear'
import { useOutsideClick } from '../../hooks/use-outside-click'
import { useOwnerDocument } from '../../hooks/use-owner'
import { useResolveButtonType } from '../../hooks/use-resolve-button-type'
import { useMainTreeNode, useRootContainers } from '../../hooks/use-root-containers'
import {
MainTreeProvider,
useMainTreeNode,
useRootContainers,
} from '../../hooks/use-root-containers'
import { useScrollLock } from '../../hooks/use-scroll-lock'
import { optionalRef, useSyncRefs } from '../../hooks/use-sync-refs'
import { Direction as TabDirection, useTabDirection } from '../../hooks/use-tab-direction'
Expand Down Expand Up @@ -195,7 +199,6 @@ let PopoverGroupContext = createContext<{
unregisterPopover(registerBag: PopoverRegisterBag): void
isFocusWithinPopoverGroup(): boolean
closeOthers(buttonId: string): void
mainTreeNodeRef: MutableRefObject<HTMLElement | null>
} | null>(null)
PopoverGroupContext.displayName = 'PopoverGroupContext'

Expand Down Expand Up @@ -343,8 +346,9 @@ function PopoverFn<TTag extends ElementType = typeof DEFAULT_POPOVER_TAG>(
useEffect(() => registerPopover?.(registerBag), [registerPopover, registerBag])

let [portals, PortalWrapper] = useNestedPortals()
let mainTreeNode = useMainTreeNode(button)
let root = useRootContainers({
mainTreeNodeRef: groupContext?.mainTreeNodeRef,
mainTreeNode,
portals,
defaultContainers: [button, panel],
})
Expand Down Expand Up @@ -416,33 +420,34 @@ function PopoverFn<TTag extends ElementType = typeof DEFAULT_POPOVER_TAG>(
let ourProps = { ref: popoverRef }

return (
<FloatingProvider>
<PopoverPanelContext.Provider value={null}>
<PopoverContext.Provider value={reducerBag}>
<PopoverAPIContext.Provider value={api}>
<CloseProvider value={close}>
<OpenClosedProvider
value={match(popoverState, {
[PopoverStates.Open]: State.Open,
[PopoverStates.Closed]: State.Closed,
})}
>
<PortalWrapper>
{render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_POPOVER_TAG,
name: 'Popover',
<MainTreeProvider node={mainTreeNode}>
<FloatingProvider>
<PopoverPanelContext.Provider value={null}>
<PopoverContext.Provider value={reducerBag}>
<PopoverAPIContext.Provider value={api}>
<CloseProvider value={close}>
<OpenClosedProvider
value={match(popoverState, {
[PopoverStates.Open]: State.Open,
[PopoverStates.Closed]: State.Closed,
})}
<root.MainTreeNode />
</PortalWrapper>
</OpenClosedProvider>
</CloseProvider>
</PopoverAPIContext.Provider>
</PopoverContext.Provider>
</PopoverPanelContext.Provider>
</FloatingProvider>
>
<PortalWrapper>
{render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_POPOVER_TAG,
name: 'Popover',
})}
</PortalWrapper>
</OpenClosedProvider>
</CloseProvider>
</PopoverAPIContext.Provider>
</PopoverContext.Provider>
</PopoverPanelContext.Provider>
</FloatingProvider>
</MainTreeProvider>
)
}

Expand Down Expand Up @@ -1110,7 +1115,6 @@ function GroupFn<TTag extends ElementType = typeof DEFAULT_GROUP_TAG>(
let internalGroupRef = useRef<HTMLElement | null>(null)
let groupRef = useSyncRefs(internalGroupRef, ref)
let [popovers, setPopovers] = useState<PopoverRegisterBag[]>([])
let root = useMainTreeNode()

let unregisterPopover = useEvent((registerBag: PopoverRegisterBag) => {
setPopovers((existing) => {
Expand Down Expand Up @@ -1157,15 +1161,8 @@ function GroupFn<TTag extends ElementType = typeof DEFAULT_GROUP_TAG>(
unregisterPopover: unregisterPopover,
isFocusWithinPopoverGroup,
closeOthers,
mainTreeNodeRef: root.mainTreeNodeRef,
}),
[
registerPopover,
unregisterPopover,
isFocusWithinPopoverGroup,
closeOthers,
root.mainTreeNodeRef,
]
[registerPopover, unregisterPopover, isFocusWithinPopoverGroup, closeOthers]
)

let slot = useMemo(() => ({}) satisfies GroupRenderPropArg, [])
Expand All @@ -1174,16 +1171,17 @@ function GroupFn<TTag extends ElementType = typeof DEFAULT_GROUP_TAG>(
let ourProps = { ref: groupRef }

return (
<PopoverGroupContext.Provider value={contextBag}>
{render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_GROUP_TAG,
name: 'Popover.Group',
})}
<root.MainTreeNode />
</PopoverGroupContext.Provider>
<MainTreeProvider>
<PopoverGroupContext.Provider value={contextBag}>
{render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_GROUP_TAG,
name: 'Popover.Group',
})}
</PopoverGroupContext.Provider>
</MainTreeProvider>
)
}

Expand Down
2 changes: 1 addition & 1 deletion packages/@headlessui-react/src/components/tabs/tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ function PanelFn<TTag extends ElementType = typeof DEFAULT_PANEL_TAG>(
)

if (!selected && (theirProps.unmount ?? true) && !(theirProps.static ?? false)) {
return <Hidden as="span" aria-hidden="true" {...ourProps} />
return <Hidden aria-hidden="true" {...ourProps} />
}

return render({
Expand Down
117 changes: 92 additions & 25 deletions packages/@headlessui-react/src/hooks/use-root-containers.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import React, { useMemo, useRef, type MutableRefObject } from 'react'
import React, { createContext, useContext, useState, type MutableRefObject } from 'react'
import { Hidden, HiddenFeatures } from '../internal/hidden'
import { getOwnerDocument } from '../utils/owner'
import { useEvent } from './use-event'
import { useOwnerDocument } from './use-owner'

export function useRootContainers({
defaultContainers = [],
portals,
mainTreeNodeRef: _mainTreeNodeRef,

// Reference to a node in the "main" tree, not in the portalled Dialog tree.
mainTreeNode,
}: {
defaultContainers?: (HTMLElement | null | MutableRefObject<HTMLElement | null>)[]
portals?: MutableRefObject<HTMLElement[]>
mainTreeNodeRef?: MutableRefObject<HTMLElement | null>
mainTreeNode?: HTMLElement | null
} = {}) {
// Reference to a node in the "main" tree, not in the portalled Dialog tree.
let mainTreeNodeRef = useRef<HTMLElement | null>(_mainTreeNodeRef?.current ?? null)
let ownerDocument = useOwnerDocument(mainTreeNodeRef)
let ownerDocument = useOwnerDocument(mainTreeNode)

let resolveContainers = useEvent(() => {
let containers: HTMLElement[] = []
Expand Down Expand Up @@ -42,8 +43,10 @@ export function useRootContainers({
if (container === document.head) continue // Skip `<head>`
if (!(container instanceof HTMLElement)) continue // Skip non-HTMLElements
if (container.id === 'headlessui-portal-root') continue // Skip the Headless UI portal root
if (container.contains(mainTreeNodeRef.current)) continue // Skip if it is the main app
if (container.contains((mainTreeNodeRef.current?.getRootNode() as ShadowRoot)?.host)) continue // Skip if it is the main app (and the component is inside a shadow root)
if (mainTreeNode) {
if (container.contains(mainTreeNode)) continue // Skip if it is the main app
if (container.contains((mainTreeNode?.getRootNode() as ShadowRoot)?.host)) continue // Skip if it is the main app (and the component is inside a shadow root)
}
if (containers.some((defaultContainer) => container.contains(defaultContainer))) continue // Skip if the current container is part of a container we've already seen (e.g.: default container / portal)

containers.push(container)
Expand All @@ -57,25 +60,89 @@ export function useRootContainers({
contains: useEvent((element: HTMLElement) =>
resolveContainers().some((container) => container.contains(element))
),
mainTreeNodeRef,
MainTreeNode: useMemo(() => {
return function MainTreeNode() {
if (_mainTreeNodeRef != null) return null
return <Hidden features={HiddenFeatures.Hidden} ref={mainTreeNodeRef} />
}
}, [mainTreeNodeRef, _mainTreeNodeRef]),
}
}

export function useMainTreeNode() {
let mainTreeNodeRef = useRef<HTMLElement | null>(null)
let MainTreeContext = createContext<HTMLElement | null>(null)

return {
mainTreeNodeRef,
MainTreeNode: useMemo(() => {
return function MainTreeNode() {
return <Hidden features={HiddenFeatures.Hidden} ref={mainTreeNodeRef} />
}
}, [mainTreeNodeRef]),
}
/**
* A provider for the main tree node.
*
* When a component is rendered in a `Portal`, it is no longer part of the main
* tree. This provider helps to find the main tree node and pass it along to the
* components that need it.
*
* The main tree node is used for features such as outside click behavior, where
* we allow clicks in 3rd party contains, but not in the parent of the "main
* tree".
RobinMalfait marked this conversation as resolved.
Show resolved Hide resolved
*
* In case of a `Popover`, we can use the `PopoverButton` as a marker in the
* "main tree", the `PopoverPanel` can't be used because it could be rendered in
* a `Portal` (e.g.: when using the `anchor` props).
*
RobinMalfait marked this conversation as resolved.
Show resolved Hide resolved
* However, we can't use the `PopoverButton` when it's nested inside of another
* `Popover`'s `PopoverPanel` component (if that parent `PopoverPanel` is
* rendered in a `Portal`).
*
RobinMalfait marked this conversation as resolved.
Show resolved Hide resolved
* This is where the `MainTreeProvider` comes in. It will find the "main tree"
* node and pass it on. The top-level `PopoverButton` will be used as a marker
* in the "main tree" and nested `Popover` use this button as well.
*/
RobinMalfait marked this conversation as resolved.
Show resolved Hide resolved
export function MainTreeProvider({
children,
node,
}: {
children: React.ReactNode
node?: HTMLElement | null
}) {
let [mainTreeNode, setMainTreeNode] = useState<HTMLElement | null>(null)

// 1. Prefer the main tree node from context
// 2. Prefer the provided node
// 3. Create a new node at this point, and find the main tree node
let resolvedMainTreeNode = useMainTreeNode(node ?? mainTreeNode)

return (
<MainTreeContext.Provider value={resolvedMainTreeNode}>
{children}

{/**
* If no main tree node is found at this point, then we briefly render an
* element to find the main tree node and pass it along.
*/}
{resolvedMainTreeNode === null && (
<Hidden
features={HiddenFeatures.Hidden}
ref={(el) => {
if (el) {
// We will only render this when no `mainTreeNode` is found. This
RobinMalfait marked this conversation as resolved.
Show resolved Hide resolved
// means that if we render this element and use it as the
// `mainTreeNode` that we will be unmounting it later again.
//
RobinMalfait marked this conversation as resolved.
Show resolved Hide resolved
// However, we can resolve the actual root container of the main
// tree node and use that instead.
for (let container of getOwnerDocument(el)?.querySelectorAll('html > *, body > *') ??
[]) {
if (container === document.body) continue // Skip `<body>`
if (container === document.head) continue // Skip `<head>`
if (!(container instanceof HTMLElement)) continue // Skip non-HTMLElements
if (container?.contains(el)) {
setMainTreeNode(container)
break
}
}
}
}}
/>
)}
</MainTreeContext.Provider>
)
}

/**
* Get the main tree node from context or fallback to the optionally provided node.
*/
export function useMainTreeNode(fallbackMainTreeNode: HTMLElement | null = null) {
// Prefer the main tree node from context, but fallback to the provided node.
return useContext(MainTreeContext) ?? fallbackMainTreeNode
}
2 changes: 1 addition & 1 deletion packages/@headlessui-react/src/internal/hidden.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ElementType, Ref } from 'react'
import type { Props } from '../types'
import { forwardRefWithAs, render, type HasDisplayName, type RefProp } from '../utils/render'

let DEFAULT_VISUALLY_HIDDEN_TAG = 'div' as const
let DEFAULT_VISUALLY_HIDDEN_TAG = 'span' as const

export enum HiddenFeatures {
// The default, no features.
Expand Down
Loading