feat: siderbar operation support portal (#1061)

This commit is contained in:
Joel
2023-08-31 17:46:51 +08:00
committed by GitHub
parent d75e8aeafa
commit 9458b8978f
13 changed files with 1964 additions and 1580 deletions

View File

@@ -34,7 +34,7 @@ export default function Confirm({
const cancelTxt = cancelText || `${t('common.operation.cancel')}`
return (
<Transition appear show={isShow} as={Fragment}>
<Dialog as="div" className="relative z-10" onClose={onClose} onClick={e => e.preventDefault()}>
<Dialog as="div" className="relative z-[100]" onClose={onClose} onClick={e => e.preventDefault()}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"

View File

@@ -1,84 +1,167 @@
'use client'
import { useBoolean } from 'ahooks'
import React, { useEffect, useRef, useState } from 'react'
import type { FC } from 'react'
import { createRoot } from 'react-dom/client'
import React from 'react'
import {
FloatingPortal,
autoUpdate,
flip,
offset,
shift,
useDismiss,
useFloating,
useFocus,
useHover,
useInteractions,
useMergeRefs,
useRole,
} from '@floating-ui/react'
type IPortalToFollowElementProps = {
portalElem: React.ReactNode
children: React.ReactNode
controlShow?: number
controlHide?: number
import type { Placement } from '@floating-ui/react'
type PortalToFollowElemOptions = {
/*
* top, bottom, left, right
* start, end. Default is middle
* combine: top-start, top-end
*/
placement?: Placement
open?: boolean
offset?: number
onOpenChange?: (open: boolean) => void
}
const PortalToFollowElement: FC<IPortalToFollowElementProps> = ({
portalElem,
children,
controlShow,
controlHide,
}) => {
const [isShowContent, { setTrue: showContent, setFalse: hideContent, toggle: toggleContent }] = useBoolean(false)
const [wrapElem, setWrapElem] = useState<HTMLDivElement | null>(null)
export function usePortalToFollowElem({
placement = 'bottom',
open,
offset: offsetValue = 0,
onOpenChange: setControlledOpen,
}: PortalToFollowElemOptions = {}) {
const setOpen = setControlledOpen
useEffect(() => {
if (controlShow)
showContent()
}, [controlShow])
const data = useFloating({
placement,
open,
onOpenChange: setOpen,
whileElementsMounted: autoUpdate,
middleware: [
offset(offsetValue),
flip({
crossAxis: placement.includes('-'),
fallbackAxisSideDirection: 'start',
padding: 5,
}),
shift({ padding: 5 }),
],
})
useEffect(() => {
if (controlHide)
hideContent()
}, [controlHide])
const context = data.context
// todo use click outside hidden
const triggerElemRef = useRef<HTMLDivElement>(null)
const hover = useHover(context, {
move: false,
enabled: open == null,
})
const focus = useFocus(context, {
enabled: open == null,
})
const dismiss = useDismiss(context)
const role = useRole(context, { role: 'tooltip' })
const calLoc = () => {
const triggerElem = triggerElemRef.current
if (!triggerElem) {
return {
display: 'none',
}
}
const {
left: triggerLeft,
top: triggerTop,
height,
} = triggerElem.getBoundingClientRect()
const interactions = useInteractions([hover, focus, dismiss, role])
return {
position: 'fixed',
left: triggerLeft,
top: triggerTop + height,
zIndex: 999,
}
}
useEffect(() => {
if (isShowContent) {
const holder = document.createElement('div')
const root = createRoot(holder)
const style = calLoc()
root.render(
<div style={style as React.CSSProperties}>
{portalElem}
</div>,
)
document.body.appendChild(holder)
setWrapElem(holder)
console.log(holder)
}
else {
wrapElem?.remove?.()
setWrapElem(null)
}
}, [isShowContent])
return (
<div ref={triggerElemRef as React.RefObject<HTMLDivElement>} onClick={toggleContent}>
{children}
</div>
return React.useMemo(
() => ({
open,
setOpen,
...interactions,
...data,
}),
[open, setOpen, interactions, data],
)
}
export default React.memo(PortalToFollowElement)
type ContextType = ReturnType<typeof usePortalToFollowElem> | null
const PortalToFollowElemContext = React.createContext<ContextType>(null)
export function usePortalToFollowElemContext() {
const context = React.useContext(PortalToFollowElemContext)
if (context == null)
throw new Error('PortalToFollowElem components must be wrapped in <PortalToFollowElem />')
return context
}
export function PortalToFollowElem({
children,
...options
}: { children: React.ReactNode } & PortalToFollowElemOptions) {
// This can accept any props as options, e.g. `placement`,
// or other positioning options.
const tooltip = usePortalToFollowElem(options)
return (
<PortalToFollowElemContext.Provider value={tooltip}>
{children}
</PortalToFollowElemContext.Provider>
)
}
export const PortalToFollowElemTrigger = React.forwardRef<
HTMLElement,
React.HTMLProps<HTMLElement> & { asChild?: boolean }
>(({ children, asChild = false, ...props }, propRef) => {
const context = usePortalToFollowElemContext()
const childrenRef = (children as any).ref
const ref = useMergeRefs([context.refs.setReference, propRef, childrenRef])
// `asChild` allows the user to pass any element as the anchor
if (asChild && React.isValidElement(children)) {
return React.cloneElement(
children,
context.getReferenceProps({
ref,
...props,
...children.props,
'data-state': context.open ? 'open' : 'closed',
}),
)
}
return (
<div
ref={ref}
className='inline-block'
// The user can style the trigger based on the state
data-state={context.open ? 'open' : 'closed'}
{...context.getReferenceProps(props)}
>
{children}
</div>
)
})
PortalToFollowElemTrigger.displayName = 'PortalToFollowElemTrigger'
export const PortalToFollowElemContent = React.forwardRef<
HTMLDivElement,
React.HTMLProps<HTMLDivElement>
>(({ style, ...props }, propRef) => {
const context = usePortalToFollowElemContext()
const ref = useMergeRefs([context.refs.setFloating, propRef])
if (!context.open)
return null
return (
<FloatingPortal>
<div
ref={ref}
style={{
...context.floatingStyles,
...style,
}}
{...context.getFloatingProps(props)}
/>
</FloatingPortal>
)
})
PortalToFollowElemContent.displayName = 'PortalToFollowElemContent'

View File

@@ -1,73 +0,0 @@
'use client'
import React, { FC, useState } from 'react'
import PortalToFollowElem from '../portal-to-follow-elem'
import { ChevronDownIcon, CheckIcon } from '@heroicons/react/24/outline'
import cn from 'classnames'
export interface ISelectProps<T> {
value: T
items: { value: T, name: string }[]
onChange: (value: T) => void
}
const Select: FC<ISelectProps<string | number>> = ({
value,
items,
onChange
}) => {
const [controlHide, setControlHide] = useState(0)
const itemsElement = items.map(item => {
const isSelected = item.value === value
return (
<div
key={item.value}
className={cn('relative h-9 leading-9 px-10 rounded-lg text-sm text-gray-700 hover:bg-gray-100')}
onClick={() => {
onChange(item.value)
setControlHide(Date.now())
}}
>
{isSelected && (
<div className='absolute left-4 top-1/2 translate-y-[-50%] flex items-center justify-center w-4 h-4 text-primary-600'>
<CheckIcon width={16} height={16}></CheckIcon>
</div>
)}
{item.name}
</div>
)
})
return (
<div>
<PortalToFollowElem
portalElem={(
<div
className='p-1 rounded-lg bg-white cursor-pointer'
style={{
boxShadow: '0px 10px 15px -3px rgba(0, 0, 0, 0.1), 0px 4px 6px rgba(0, 0, 0, 0.05)'
}}
>
{itemsElement}
</div>
)}
controlHide={controlHide}
>
<div className='relative '>
<div className='flex items-center h-9 px-3 gap-1 cursor-pointer hover:bg-gray-50'>
<div className='text-sm text-gray-700'>{items.find(i => i.value === value)?.name}</div>
<ChevronDownIcon width={16} height={16} />
</div>
{/* <div
className='absolute z-50 left-0 top-9 p-1 w-[112px] rounded-lg bg-white'
style={{
boxShadow: '0px 10px 15px -3px rgba(0, 0, 0, 0.1), 0px 4px 6px rgba(0, 0, 0, 0.05)'
}}
>
{itemsElement}
</div> */}
</div>
</PortalToFollowElem>
</div>
)
}
export default React.memo(Select)