feat: modal resize and draggable to absolute position

Signed-off-by: Innei <i@innei.in>
This commit is contained in:
Innei
2024-08-10 17:50:57 +08:00
parent 71712f464d
commit aad5eba2ed
5 changed files with 423 additions and 340 deletions
@@ -1,6 +1,8 @@
import { getUISettings } from "@renderer/atoms/settings/ui"
import { jotaiStore } from "@renderer/lib/jotai"
import { useCallback, useContext, useId, useRef } from "react"
import { useCallback, useContext, useId, useRef, useState } from "react"
import { flushSync } from "react-dom"
import { useEventCallback } from "usehooks-ts"
import { modalStackAtom } from "./atom"
import { CurrentModalContext } from "./context"
@@ -73,3 +75,42 @@ const actions = {
}
export const useCurrentModal = () => useContext(CurrentModalContext)
export const useResizeableModal = (
modalElementRef: React.RefObject<HTMLDivElement>,
{
enableResizeable,
}: {
enableResizeable: boolean
},
) => {
const [resizeableStyle, setResizeableStyle] = useState(
{} as React.CSSProperties,
)
const [isResizeable, setIsResizeable] = useState(false)
const handlePointDown = useEventCallback(() => {
if (!enableResizeable) return
if (isResizeable) return
const $modalElement = modalElementRef.current
if (!$modalElement) return
const rect = $modalElement.getBoundingClientRect()
const { x, y } = rect
flushSync(() => {
setIsResizeable(true)
setResizeableStyle({
position: "fixed",
top: `${y}px`,
left: `${x}px`,
})
})
})
return {
resizeableStyle,
isResizeable,
handlePointDown,
}
}
@@ -10,7 +10,11 @@ import { useAnimationControls, useDragControls } from "framer-motion"
import { produce } from "immer"
import { useSetAtom } from "jotai"
import { Resizable } from "re-resizable"
import type { PointerEventHandler, SyntheticEvent } from "react"
import type {
PointerEventHandler,
PropsWithChildren,
SyntheticEvent,
} from "react"
import {
createElement,
forwardRef,
@@ -18,6 +22,7 @@ import {
memo,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
@@ -30,297 +35,322 @@ import { modalStackAtom } from "./atom"
import { MODAL_STACK_Z_INDEX, modalMontionConfig } from "./constants"
import type { CurrentModalContentProps, ModalActionsInternal } from "./context"
import { CurrentModalContext } from "./context"
import { useResizeableModal } from "./hooks"
import type { ModalProps } from "./types"
export const ModalInternal: Component<{
item: ModalProps & { id: string }
index: number
export const ModalInternal = memo(
forwardRef<
HTMLDivElement,
{
item: ModalProps & { id: string }
index: number
isTop: boolean
onClose?: (open: boolean) => void
}> = memo(
forwardRef(function Modal(
{ item, index, onClose: onPropsClose, children, isTop },
ref: any,
) {
const {
CustomModalComponent,
modalClassName,
content,
title,
clickOutsideToDismiss,
modalContainerClassName,
wrapper: Wrapper = Fragment,
max,
icon,
canClose = true,
isTop: boolean
onClose?: (open: boolean) => void
} & PropsWithChildren
>(function Modal(
{ item, index, onClose: onPropsClose, children, isTop },
ref,
) {
const {
CustomModalComponent,
modalClassName,
content,
title,
clickOutsideToDismiss,
modalContainerClassName,
wrapper: Wrapper = Fragment,
max,
icon,
canClose = true,
draggable = false,
resizeable = false,
resizeDefaultSize,
} = item
draggable = false,
resizeable = false,
resizeDefaultSize,
} = item
const setStack = useSetAtom(modalStackAtom)
const setStack = useSetAtom(modalStackAtom)
const [currentIsClosing, setCurrentIsClosing] = useState(false)
const [currentIsClosing, setCurrentIsClosing] = useState(false)
const close = useEventCallback((forceClose = false) => {
if (!canClose && !forceClose) return
setCurrentIsClosing(true)
nextFrame(() => {
setStack((p) => p.filter((modal) => modal.id !== item.id))
})
onPropsClose?.(false)
})
const onClose = useCallback(
(open: boolean): void => {
if (!open) {
close()
}
},
[close],
)
const opaque = useUISettingKey("modalOpaque")
const zIndexStyle = useMemo(
() => ({ zIndex: MODAL_STACK_Z_INDEX + index + 1 }),
[index],
)
const dismiss = useCallback(
(e: SyntheticEvent) => {
e.stopPropagation()
close(true)
},
[close],
)
const animateController = useAnimationControls()
useEffect(() => {
requestAnimationFrame(() => {
animateController.start(modalMontionConfig.animate)
})
}, [animateController])
const noticeModal = useCallback(() => {
animateController
.start({
scale: 1.05,
transition: {
duration: 0.06,
},
})
.then(() => {
animateController.start({
scale: 1,
const close = useEventCallback((forceClose = false) => {
if (!canClose && !forceClose) return
setCurrentIsClosing(true)
nextFrame(() => {
setStack((p) => p.filter((modal) => modal.id !== item.id))
})
onPropsClose?.(false)
})
})
}, [animateController])
const dragController = useDragControls()
const handleDrag: PointerEventHandler<HTMLDivElement> = useCallback(
(e) => {
if (draggable) {
dragController.start(e)
}
},
[dragController, draggable],
)
useEffect(() => {
if (isTop) return
animateController.start({
scale: 0.96,
y: 10,
})
return () => {
try {
animateController.stop()
animateController.start({
scale: 1,
y: 0,
})
} catch {
/* empty */
}
}
}, [isTop])
const modalContentRef = useRef<HTMLDivElement>(null)
const ModalProps: ModalActionsInternal = useMemo(
() => ({
dismiss: close,
setClickOutSideToDismiss: (v) => {
setStack((state) =>
produce(state, (draft) => {
const model = draft.find((modal) => modal.id === item.id)
if (!model) return
if (model.clickOutsideToDismiss === v) return
model.clickOutsideToDismiss = v
}),
const onClose = useCallback(
(open: boolean): void => {
if (!open) {
close()
}
},
[close],
)
},
}),
[close, item.id, setStack],
)
const ModalContextProps = useMemo<CurrentModalContentProps>(
() => ({
...ModalProps,
ref: modalContentRef,
}),
[ModalProps],
)
const opaque = useUISettingKey("modalOpaque")
const edgeElementRef = useRef<HTMLDivElement>(null)
const zIndexStyle = useMemo(
() => ({ zIndex: MODAL_STACK_Z_INDEX + index + 1 }),
[index],
)
const dismiss = useCallback(
(e: SyntheticEvent) => {
e.stopPropagation()
const finalChildren = useMemo(
() => (
<CurrentModalContext.Provider value={ModalContextProps}>
<AppErrorBoundary errorType={ErrorComponentType.Modal}>
<RootPortalProvider value={edgeElementRef.current as HTMLElement}>
{children ?? createElement(content, ModalProps)}
</RootPortalProvider>
</AppErrorBoundary>
</CurrentModalContext.Provider>
),
[ModalContextProps, ModalProps, children, content],
)
close(true)
},
[close],
)
useEffect(() => {
if (currentIsClosing) {
// Radix dialog will block pointer events
document.body.style.pointerEvents = "auto"
}
}, [currentIsClosing])
const modalElementRef = useRef<HTMLDivElement>(null)
const switchHotkeyScope = useSwitchHotKeyScope()
useEffect(() => {
switchHotkeyScope("Modal")
return () => {
switchHotkeyScope("Home")
}
}, [switchHotkeyScope])
const {
handlePointDown: handleResizeEnable,
isResizeable,
resizeableStyle,
} = useResizeableModal(modalElementRef, {
enableResizeable: resizeable,
})
const animateController = useAnimationControls()
useEffect(() => {
requestAnimationFrame(() => {
animateController.start(modalMontionConfig.animate)
})
}, [animateController])
const noticeModal = useCallback(() => {
animateController
.start({
scale: 1.05,
transition: {
duration: 0.06,
},
})
.then(() => {
animateController.start({
scale: 1,
})
})
}, [animateController])
if (CustomModalComponent) {
return (
<Wrapper>
<Dialog.Root open onOpenChange={onClose}>
<Dialog.Portal>
<Dialog.DialogTitle className="sr-only">
{title}
</Dialog.DialogTitle>
<Dialog.Content asChild>
<div
ref={edgeElementRef}
className={cn(
"no-drag-region fixed inset-0 z-20 overflow-auto",
currentIsClosing ?
"!pointer-events-none" :
"!pointer-events-auto",
modalContainerClassName,
)}
onClick={
clickOutsideToDismiss && canClose ? dismiss : undefined
}
style={zIndexStyle}
>
<div
className={cn("contents", modalClassName)}
onClick={stopPropagation}
ref={ref}
>
<CustomModalComponent>{finalChildren}</CustomModalComponent>
</div>
</div>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
</Wrapper>
)
}
const dragController = useDragControls()
const handleDrag: PointerEventHandler<HTMLDivElement> = useCallback(
(e) => {
if (draggable) {
dragController.start(e)
}
},
[dragController, draggable],
)
const ResizeSwitch = resizeable ? Resizable : Fragment
useEffect(() => {
if (isTop) return
animateController.start({
scale: 0.96,
y: 10,
})
return () => {
try {
animateController.stop()
animateController.start({
scale: 1,
y: 0,
})
} catch {
/* empty */
}
}
}, [isTop])
return (
<Wrapper>
<Dialog.Root open onOpenChange={onClose}>
<Dialog.Portal>
<Dialog.Content asChild>
<div
ref={edgeElementRef}
style={zIndexStyle}
className={cn(
"center fixed inset-0 z-20 flex",
currentIsClosing && "!pointer-events-none",
modalContainerClassName,
)}
onClick={
clickOutsideToDismiss && canClose ? dismiss : noticeModal
}
>
<m.div
ref={ref}
style={zIndexStyle}
{...modalMontionConfig}
animate={animateController}
className={cn(
"relative flex flex-col overflow-hidden rounded-lg",
opaque ?
"bg-theme-modal-background-opaque" :
"bg-theme-modal-background backdrop-blur-sm",
"shadow-modal p-2",
max ?
"h-[90vh] w-[90vw]" :
"max-h-[70vh] min-w-[300px] max-w-[90vw] lg:max-h-[calc(100vh-20rem)] lg:max-w-[70vw]",
const modalContentRef = useRef<HTMLDivElement>(null)
const ModalProps: ModalActionsInternal = useMemo(
() => ({
dismiss: close,
setClickOutSideToDismiss: (v) => {
setStack((state) =>
produce(state, (draft) => {
const model = draft.find((modal) => modal.id === item.id)
if (!model) return
if (model.clickOutsideToDismiss === v) return
model.clickOutsideToDismiss = v
}),
)
},
}),
[close, item.id, setStack],
)
"border border-slate-200 dark:border-neutral-800",
modalClassName,
)}
onClick={stopPropagation}
drag
dragControls={dragController}
dragElastic={0}
dragListener={false}
dragMomentum={false}
dragConstraints={edgeElementRef}
whileDrag={{
cursor: "grabbing",
}}
>
<ResizeSwitch defaultSize={resizeDefaultSize} className="flex grow flex-col">
<div
className="relative flex items-center"
onPointerDownCapture={handleDrag}
>
<Dialog.Title className="flex shrink-0 grow items-center gap-2 px-4 py-1 text-lg font-semibold">
{icon && <span className="size-4">{icon}</span>}
const ModalContextProps = useMemo<CurrentModalContentProps>(
() => ({
...ModalProps,
ref: modalContentRef,
}),
[ModalProps],
)
<span>{title}</span>
</Dialog.Title>
{canClose && (
<Dialog.DialogClose
className="center p-2"
tabIndex={1}
onClick={close}
const edgeElementRef = useRef<HTMLDivElement>(null)
const finalChildren = useMemo(
() => (
<CurrentModalContext.Provider value={ModalContextProps}>
<AppErrorBoundary errorType={ErrorComponentType.Modal}>
<RootPortalProvider value={edgeElementRef.current as HTMLElement}>
{children ?? createElement(content, ModalProps)}
</RootPortalProvider>
</AppErrorBoundary>
</CurrentModalContext.Provider>
),
[ModalContextProps, ModalProps, children, content],
)
useEffect(() => {
if (currentIsClosing) {
// Radix dialog will block pointer events
document.body.style.pointerEvents = "auto"
}
}, [currentIsClosing])
const switchHotkeyScope = useSwitchHotKeyScope()
useEffect(() => {
switchHotkeyScope("Modal")
return () => {
switchHotkeyScope("Home")
}
}, [switchHotkeyScope])
const modalStyle = useMemo(
() => ({ ...zIndexStyle, ...resizeableStyle }),
[resizeableStyle, zIndexStyle],
)
useImperativeHandle(ref, () => modalElementRef.current!)
if (CustomModalComponent) {
return (
<Wrapper>
<Dialog.Root open onOpenChange={onClose}>
<Dialog.Portal>
<Dialog.DialogTitle className="sr-only">
{title}
</Dialog.DialogTitle>
<Dialog.Content asChild>
<div
ref={edgeElementRef}
className={cn(
"no-drag-region fixed inset-0 z-20 overflow-auto",
currentIsClosing ?
"!pointer-events-none" :
"!pointer-events-auto",
modalContainerClassName,
)}
onClick={
clickOutsideToDismiss && canClose ? dismiss : undefined
}
style={zIndexStyle}
>
<div
className={cn("contents", modalClassName)}
onClick={stopPropagation}
ref={modalElementRef}
>
<i className="i-mgc-close-cute-re" />
</Dialog.DialogClose>
)}
</div>
<Divider className="my-2 shrink-0 border-slate-200 opacity-80 dark:border-neutral-800" />
<CustomModalComponent>{finalChildren}</CustomModalComponent>
</div>
</div>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
</Wrapper>
)
}
<div className="min-h-0 shrink grow overflow-auto px-4 py-2">
{finalChildren}
const ResizeSwitch = resizeable ? Resizable : Fragment
return (
<Wrapper>
<Dialog.Root open onOpenChange={onClose}>
<Dialog.Portal>
<Dialog.Content asChild>
<div
ref={edgeElementRef}
style={zIndexStyle}
className={cn(
"fixed inset-0 z-20 flex",
currentIsClosing && "!pointer-events-none",
modalContainerClassName,
!isResizeable && "center",
)}
onClick={
clickOutsideToDismiss && canClose ? dismiss : noticeModal
}
>
<m.div
ref={modalElementRef}
style={modalStyle}
{...modalMontionConfig}
animate={animateController}
className={cn(
"relative flex flex-col overflow-hidden rounded-lg p-2",
opaque ?
"bg-theme-modal-background-opaque" :
"bg-theme-modal-background backdrop-blur-sm",
"shadow-modal",
max ?
"h-[90vh] w-[90vw]" :
"max-h-[70vh] min-w-[300px] max-w-[90vw] lg:max-h-[calc(100vh-20rem)] lg:max-w-[70vw]",
"border border-slate-200 dark:border-neutral-800",
modalClassName,
)}
onClick={stopPropagation}
drag
dragControls={dragController}
dragElastic={0}
dragListener={false}
dragMomentum={false}
dragConstraints={edgeElementRef}
whileDrag={{
cursor: "grabbing",
}}
>
<ResizeSwitch
onResizeStart={handleResizeEnable}
defaultSize={resizeDefaultSize}
className="flex grow flex-col"
>
<div
className="relative flex items-center"
onPointerDownCapture={handleDrag}
onPointerDown={handleResizeEnable}
>
<Dialog.Title className="flex shrink-0 grow items-center gap-2 px-4 py-1 text-lg font-semibold">
{icon && <span className="size-4">{icon}</span>}
<span>{title}</span>
</Dialog.Title>
{canClose && (
<Dialog.DialogClose
className="center p-2"
tabIndex={1}
onClick={close}
>
<i className="i-mgc-close-cute-re" />
</Dialog.DialogClose>
)}
</div>
<Divider className="my-2 shrink-0 border-slate-200 opacity-80 dark:border-neutral-800" />
<div className="min-h-0 shrink grow overflow-auto px-4 py-2">
{finalChildren}
</div>
</ResizeSwitch>
</m.div>
</div>
</ResizeSwitch>
</m.div>
</div>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
</Wrapper>
)
}),
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
</Wrapper>
)
}),
)
@@ -7,6 +7,7 @@ export interface ModalProps {
icon?: ReactNode
CustomModalComponent?: FC<PropsWithChildren>
content: FC<ModalActionsInternal>
clickOutsideToDismiss?: boolean
modalClassName?: string
@@ -1,4 +1,5 @@
import { useModalStack } from "@renderer/components/ui/modal/stacked/hooks"
import { NoopChildren } from "@renderer/components/ui/modal/stacked/utils"
import { createElement, useCallback } from "react"
import { SettingModalContent } from "./content"
@@ -15,14 +16,7 @@ export const useSettingModal = () => {
createElement(SettingModalContent, {
initialTab,
}),
CustomModalComponent: (props) =>
createElement(
"div",
{
className: "center h-full center",
},
props.children,
),
CustomModalComponent: NoopChildren,
modalContainerClassName: "overflow-hidden",
}),
[present],
@@ -1,12 +1,13 @@
import { useUISettingSelector } from "@renderer/atoms/settings/ui"
import { m } from "@renderer/components/common/Motion"
import { Logo } from "@renderer/components/icons/logo"
import { useResizeableModal } from "@renderer/components/ui/modal"
import { preventDefault } from "@renderer/lib/dom"
import { cn } from "@renderer/lib/utils"
import { useDragControls } from "framer-motion"
import { Resizable } from "re-resizable"
import type { PointerEventHandler, PropsWithChildren } from "react"
import { useCallback, useEffect } from "react"
import { useCallback, useEffect, useRef } from "react"
import { settings } from "../constants"
import { SettingsSidebarTitle } from "../title"
@@ -20,6 +21,13 @@ export function SettingModalLayout(
const { children, initialTab } = props
const setTab = useSetSettingTab()
const tab = useSettingTab()
const elementRef = useRef<HTMLDivElement>(null)
const { handlePointDown, isResizeable, resizeableStyle } = useResizeableModal(
elementRef,
{
enableResizeable: true,
},
)
useEffect(() => {
if (!tab) {
@@ -40,73 +48,82 @@ export function SettingModalLayout(
(e) => {
if (draggable) {
dragController.start(e)
handlePointDown()
}
},
[dragController, draggable],
[dragController, draggable, handlePointDown],
)
return (
<m.div
exit={{
opacity: 0,
scale: 0.96,
}}
className={cn(
"relative flex overflow-hidden rounded-xl border border-border",
!overlay && "shadow-perfect",
)}
onContextMenu={preventDefault}
drag={draggable}
dragControls={dragController}
dragListener={false}
dragMomentum={false}
dragElastic={false}
whileDrag={{
cursor: "grabbing",
}}
>
<Resizable
defaultSize={{
width: 800,
height: 700,
<div className={cn("h-full", !isResizeable && "center")}>
<m.div
exit={{
opacity: 0,
scale: 0.96,
}}
className="flex max-h-[80vh] max-w-[95vw] flex-col"
>
{draggable && (
<div
className="absolute inset-x-0 top-0 z-[1] h-8"
onPointerDown={handleDrag}
/>
className={cn(
"relative flex max-h-[80vh] max-w-[95vw] overflow-hidden rounded-xl border border-border",
!overlay && "shadow-perfect",
)}
<div className="flex h-0 flex-1 bg-theme-modal-background-opaque">
<div className="w-44 border-r px-2 py-6">
<div className="mb-4 flex h-8 items-center gap-2 px-2 font-bold">
<Logo className="mr-1 size-6" />
{APP_NAME}
style={resizeableStyle}
onContextMenu={preventDefault}
drag={draggable}
dragControls={dragController}
dragListener={false}
dragMomentum={false}
dragElastic={false}
whileDrag={{
cursor: "grabbing",
}}
>
<Resizable
onResizeStart={handlePointDown}
style={{ ...resizeableStyle, position: "static" }}
defaultSize={{
width: 800,
height: 700,
}}
className="flex flex-col"
>
{draggable && (
<div
className="absolute inset-x-0 top-0 z-[1] h-8"
onPointerDown={handleDrag}
/>
)}
<div
className="flex h-0 flex-1 bg-theme-modal-background-opaque"
ref={elementRef}
>
<div className="w-44 border-r px-2 py-6">
<div className="mb-4 flex h-8 items-center gap-2 px-2 font-bold">
<Logo className="mr-1 size-6" />
{APP_NAME}
</div>
{settings.map((t) => (
<button
key={t.path}
className={`my-1 flex w-full items-center rounded-lg px-2.5 py-0.5 leading-loose text-theme-foreground/70 transition-colors ${
tab === t.path ?
"bg-theme-item-active text-theme-foreground/90" :
""
}`}
type="button"
onClick={() => setTab(t.path)}
>
<SettingsSidebarTitle
path={t.path}
className="text-[0.94rem] font-medium"
/>
</button>
))}
</div>
<div className="relative flex h-full flex-1 flex-col bg-theme-background pt-1">
{children}
</div>
{settings.map((t) => (
<button
key={t.path}
className={`my-1 flex w-full items-center rounded-lg px-2.5 py-0.5 leading-loose text-theme-foreground/70 transition-colors ${
tab === t.path ?
"bg-theme-item-active text-theme-foreground/90" :
""
}`}
type="button"
onClick={() => setTab(t.path)}
>
<SettingsSidebarTitle
path={t.path}
className="text-[0.94rem] font-medium"
/>
</button>
))}
</div>
<div className="relative flex h-full flex-1 flex-col bg-theme-background pt-1">
{children}
</div>
</div>
</Resizable>
</m.div>
</Resizable>
</m.div>
</div>
)
}