import { Editor, useEditorState } from "@tiptap/react"; import { AlignCenter, AlignLeft, AlignRight, Bold, Heading1, Heading2, Heading3, Highlighter, Italic, List, ListOrdered, } from "lucide-react"; import { Toggle } from "../ui/toggle"; interface MenubarProps { editor: Editor | null; } // 1. The main exported component remains safe and handles the null state cleanly export default function Menubar({ editor }: MenubarProps) { if (!editor) { return null; } // Only render the inner menu once the editor is explicitly available return ; } // 2. The inner component runs safely because 'editor' is guaranteed to be an Editor instance function MenubarInner({ editor }: { editor: Editor }) { const editorState = useEditorState({ editor, // Now safely guaranteed never to be null or undefined selector: (ctx) => { return { isBold: ctx.editor.isActive("bold"), isItalic: ctx.editor.isActive("italic"), isStrike: ctx.editor.isActive("strike"), isHighlight: ctx.editor.isActive("highlight"), isAlignLeft: ctx.editor.isActive({ textAlign: "left" }), isAlignCenter: ctx.editor.isActive({ textAlign: "center" }), isAlignRight: ctx.editor.isActive({ textAlign: "right" }), isAlignJustify: ctx.editor.isActive({ textAlign: "justify" }), isParagraph: ctx.editor.isActive("paragraph"), isHeading1: ctx.editor.isActive("heading", { level: 1 }), isHeading2: ctx.editor.isActive("heading", { level: 2 }), isHeading3: ctx.editor.isActive("heading", { level: 3 }), }; }, }); const options = [ { icon: , onClick: () => editor.chain().focus().toggleHeading({ level: 1 }).run(), pressed: editorState.isHeading1, }, { icon: , onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), pressed: editorState.isHeading2, }, { icon: , onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), pressed: editorState.isHeading3, }, { icon: , onClick: () => editor.chain().focus().toggleBold().run(), pressed: editorState.isBold, }, { icon: , onClick: () => editor.chain().focus().toggleItalic().run(), pressed: editorState.isItalic, }, { icon: , onClick: () => editor.chain().focus().toggleTextAlign("left").run(), pressed: editorState.isAlignLeft, }, { icon: , onClick: () => editor.chain().focus().toggleTextAlign("center").run(), pressed: editorState.isAlignCenter, }, { icon: , onClick: () => editor.chain().focus().toggleTextAlign("right").run(), pressed: editorState.isAlignRight, }, { icon: , onClick: () => editor.chain().focus().toggleBulletList().run(), pressed: editor.isActive("bulletList"), }, { icon: , onClick: () => editor.chain().focus().toggleOrderedList().run(), pressed: editor.isActive("orderedList"), }, { icon: , onClick: () => editor.chain().focus().toggleHighlight().run(), pressed: editorState.isHighlight, }, ]; return (
{options.map((option, index) => ( {option.icon} ))}
); }