Skip to content

Commit

Permalink
Fix outside click in nested portalled Popover components (#3362)
Browse files Browse the repository at this point in the history
* use `span` as default element for `Hidden` component

This improves the HTML DOM tree if this happens to be used in let's say
a `p` tag where `div` elements are not allowed. The `Hidden` element is
hidden so it doesn't really matter what the underlying element is.

Fixes: #3319

* refactor `useRootContainers` and introduce `MainTreeProvider`

As a general recap, when an outside click happens, we need to react to
it and typically use the `useOutsideClick` hook.

We also require the context of "allowed root containers", this means
that clicking on a 3rd party toast when a dialog is open, that we allow
this even though we are technically clicking outside of the dialog. This
is simply because we don't have control over these elements.

We also need a reference to know what the "main tree" container is,
because this is the container where your application lives and we _know_
that we are not allowed to click on anything in this container. The
complex part is getting a reference to this element.

```html
<html>
<head>
   <title></title>
</head>
<body>
   <div id="app"> <-- main root container -->
      <div></div>
      <div>
         <Popover></Popover> <!-- Current component -->
      </div>
      <div></div>
   </div>

   <!-- Allowed container #1 -->
   <3rd-party-toast-container></3rd-party-toast-container>
</body>

<!-- Allowed container #2 -->
<grammarly-extension></grammarly-extension>
</html>
```

Some examples:

- In case of a `Dialog`, the `Dialog` is rendered in a `Portal` which
  means that a DOM ref to the `Dialog` or anything inside will not point
  to the "main tree" node.

- In case of a `Popover` we can use the `PopoverButton` as an element
  that lives in the main tree. However, if you work with nested
  `Popover` components, and the outer `PopoverPanel` uses the `anchor`
  or `portal` props, then the inner `PortalButton` will not be in the
  main tree either because it will live in the portalled `PopoverPanel`
  of the parent.

This is where the `MainTreeProvider` comes in handy. This component will
use the passed in `node` as the main tree node reference and pass this
via the context through the React tree. This means that a nested
`Popover` will still use a reference from the parent `Popover`.

In case of the `Dialog`, we wrap the `Dialog` itself with this provider
which means that the provider will be in the main tree and can be used
inside the portalled `Dialog`.

Another part of the `MainTreeProvider` is that if no node exists in the
parent (reading from context), and no node is provided via props, then
we will briefly render a hidden element, find the root node of the main
tree (aka, the parent element that is a direct child of the body, `body
> *`). Once we found it, we remove the hidden element again. This way we
don't keep unnecessary DOM nodes around.

* update changelog

* Update packages/@headlessui-react/src/hooks/use-root-containers.tsx

Co-authored-by: Jordan Pittman <[email protected]>

* Update packages/@headlessui-react/src/hooks/use-root-containers.tsx

Co-authored-by: Jordan Pittman <[email protected]>

* Update packages/@headlessui-react/src/hooks/use-root-containers.tsx

Co-authored-by: Jordan Pittman <[email protected]>

* Update packages/@headlessui-react/src/hooks/use-root-containers.tsx

Co-authored-by: Jordan Pittman <[email protected]>

* Update packages/@headlessui-react/src/hooks/use-root-containers.tsx

Co-authored-by: Jordan Pittman <[email protected]>

* use early return

---------

Co-authored-by: Jordan Pittman <[email protected]>
  • Loading branch information
RobinMalfait and thecrypticace authored Jul 5, 2024
1 parent d8f44e0 commit da466ec
Show file tree
Hide file tree
Showing 6 changed files with 160 additions and 91 deletions.
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 containers, but not in the parent of the "main
* tree".
*
* 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).
*
* However, we can't use the `PopoverButton` when it's nested inside of another
* `Popover`'s `PopoverPanel` component if the parent `PopoverPanel` is
* rendered in a `Portal`.
*
* 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` will use this button as well.
*/
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) return

// We will only render this when no `mainTreeNode` is found. This
// means that if we render this element and use it as the
// `mainTreeNode` that we will be unmounting it later.
//
// 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

0 comments on commit da466ec

Please sign in to comment.