refactor: make SidePeek more reusable and composable
This commit is contained in:
committed by
Chuma McPhoy
parent
301de3a110
commit
b1698a8a2e
@@ -1,67 +1,37 @@
|
||||
"use client"
|
||||
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation"
|
||||
import { ReactNode, useEffect, useState } from "react"
|
||||
import { Button, Dialog, DialogTrigger, Modal } from "react-aria-components"
|
||||
import { X } from "react-feather"
|
||||
import { Children, cloneElement, PropsWithChildren } from "react"
|
||||
import { Dialog, DialogTrigger, Modal } from "react-aria-components"
|
||||
|
||||
import Title from "@/components/TempDesignSystem/Text/Title"
|
||||
|
||||
import styles from "./sidePeek.module.css"
|
||||
|
||||
type SidePeekProps = {
|
||||
content: Record<string, { title: string; content: ReactNode }>
|
||||
activeContent: string | null
|
||||
onClose: (isOpen: boolean) => void
|
||||
}
|
||||
export default function SidePeek({ content }: SidePeekProps) {
|
||||
const [sidePeekContent, setSidePeekContent] = useState<string | null>(null)
|
||||
|
||||
const searchParams = useSearchParams()
|
||||
const activeSidePeek = searchParams.get("sidepeek")
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
|
||||
useEffect(() => {
|
||||
if (activeSidePeek) {
|
||||
setSidePeekContent(activeSidePeek)
|
||||
}
|
||||
}, [activeSidePeek])
|
||||
|
||||
const activeContent = sidePeekContent && content[sidePeekContent]
|
||||
|
||||
function handleClose(isOpen: boolean) {
|
||||
if (!isOpen) {
|
||||
console.log("closing the modal now")
|
||||
setSidePeekContent(null)
|
||||
|
||||
const nextSearchParams = new URLSearchParams(searchParams.toString())
|
||||
nextSearchParams.delete("sidepeek")
|
||||
|
||||
router.push(`${pathname}?${nextSearchParams}`, { scroll: false })
|
||||
}
|
||||
}
|
||||
|
||||
export default function SidePeek({
|
||||
children,
|
||||
onClose,
|
||||
activeContent,
|
||||
}: PropsWithChildren<SidePeekProps>) {
|
||||
return (
|
||||
<DialogTrigger>
|
||||
<Modal
|
||||
className={styles.sidePeek}
|
||||
isOpen={!!activeContent}
|
||||
onOpenChange={handleClose}
|
||||
onOpenChange={onClose}
|
||||
>
|
||||
<Dialog className={styles.dialog}>
|
||||
{({ close }) => (
|
||||
<aside className={styles.content}>
|
||||
<header className={styles.header}>
|
||||
{activeContent && (
|
||||
<Title level={"h2"} as={"h3"}>
|
||||
{activeContent.title}
|
||||
</Title>
|
||||
)}
|
||||
<Button onPress={close} className={styles.closeBtn}>
|
||||
<X height={32} width={32} className={styles.closeIcon} />
|
||||
</Button>
|
||||
</header>
|
||||
{activeContent && activeContent.content}
|
||||
</aside>
|
||||
<>
|
||||
{Children.map(children, (child) => {
|
||||
return cloneElement(child as React.ReactElement, {
|
||||
onClose: close,
|
||||
})
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</Dialog>
|
||||
</Modal>
|
||||
|
||||
Reference in New Issue
Block a user