| 1 | "use client"; |
| 2 | |
| 3 | import { useTocElement, useTocElementState } from "@platejs/toc/react"; |
| 4 | import { cva } from "class-variance-authority"; |
| 5 | import { PlateElement, type PlateElementProps } from "platejs/react"; |
| 6 | |
| 7 | import { Button } from "@/components/plate/ui/button"; |
| 8 | |
| 9 | const headingItemVariants = cva( |
| 10 | "block h-auto w-full cursor-pointer truncate rounded-none px-0.5 py-1.5 text-left font-medium text-muted-foreground underline decoration-[0.5px] underline-offset-4 hover:bg-accent hover:text-muted-foreground", |
| 11 | { |
| 12 | variants: { |
| 13 | depth: { |
| 14 | 1: "pl-0.5", |
| 15 | 2: "pl-6.5", |
| 16 | 3: "pl-12.5", |
| 17 | }, |
| 18 | }, |
| 19 | }, |
| 20 | ); |
| 21 | |
| 22 | export function TocElement(props: PlateElementProps) { |
| 23 | const state = useTocElementState(); |
| 24 | const { props: btnProps } = useTocElement(state); |
| 25 | const { headingList } = state; |
| 26 | |
| 27 | return ( |
| 28 | <PlateElement {...props} className="mb-1 p-0"> |
| 29 | <div contentEditable={false}> |
| 30 | {headingList.length > 0 ? ( |
| 31 | headingList.map((item) => ( |
| 32 | <Button |
| 33 | key={item.id} |
| 34 | variant="ghost" |
| 35 | className={headingItemVariants({ |
| 36 | depth: item.depth as 1 | 2 | 3, |
| 37 | })} |
| 38 | onClick={(e) => btnProps.onClick(e, item, "smooth")} |
| 39 | aria-current |
| 40 | > |
| 41 | {item.title} |
| 42 | </Button> |
| 43 | )) |
| 44 | ) : ( |
| 45 | <div className="text-sm text-gray-500"> |
| 46 | Create a heading to display the table of contents. |
| 47 | </div> |
| 48 | )} |
| 49 | </div> |
| 50 | {props.children} |
| 51 | </PlateElement> |
| 52 | ); |
| 53 | } |
| 54 |