fix: popover behaviour when clicking outside of popover (#1355)

This commit is contained in:
Aman Harwara
2022-07-27 20:52:08 +05:30
committed by GitHub
parent 8c364f6d58
commit 58e751f986
4 changed files with 69 additions and 7 deletions

View File

@@ -1,6 +1,29 @@
import { UuidGenerator } from '@standardnotes/snjs'
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import PositionedPopoverContent from './PositionedPopoverContent'
import { PopoverProps } from './Types'
type PopoverContextData = {
registerChildPopover: (id: string) => void
unregisterChildPopover: (id: string) => void
}
const PopoverContext = createContext<PopoverContextData | null>(null)
const useRegisterPopoverToParent = (popoverId: string) => {
const parentPopoverContext = useContext(PopoverContext)
useEffect(() => {
const currentId = popoverId
parentPopoverContext?.registerChildPopover(currentId)
return () => {
parentPopoverContext?.unregisterChildPopover(currentId)
}
}, [parentPopoverContext, popoverId])
}
type Props = PopoverProps & {
open: boolean
}
@@ -16,20 +39,47 @@ const Popover = ({
side,
togglePopover,
}: Props) => {
const popoverId = useRef(UuidGenerator.GenerateUuid())
useRegisterPopoverToParent(popoverId.current)
const [childPopovers, setChildPopovers] = useState<Set<string>>(new Set())
const registerChildPopover = useCallback((id: string) => {
setChildPopovers((childPopovers) => new Set(childPopovers.add(id)))
}, [])
const unregisterChildPopover = useCallback((id: string) => {
setChildPopovers((childPopovers) => {
childPopovers.delete(id)
return new Set(childPopovers)
})
}, [])
const contextValue = useMemo(
() => ({
registerChildPopover,
unregisterChildPopover,
}),
[registerChildPopover, unregisterChildPopover],
)
return open ? (
<>
<PopoverContext.Provider value={contextValue}>
<PositionedPopoverContent
align={align}
anchorElement={anchorElement}
anchorPoint={anchorPoint}
childPopovers={childPopovers}
className={className}
id={popoverId.current}
overrideZIndex={overrideZIndex}
side={side}
togglePopover={togglePopover}
>
{children}
</PositionedPopoverContent>
</>
</PopoverContext.Provider>
) : null
}