import { useEffect, type ReactNode } from "react" import { EditorContent, useEditor } from "@tiptap/react" import Placeholder from "@tiptap/extension-placeholder" import StarterKit from "@tiptap/starter-kit" import { Bold, Italic, List, ListOrdered, Redo2, Undo2, } from "lucide-react" import { cn } from "@/lib/utils" import { richTextPlainLength } from "../../lib/richText" export interface RichTextEditorProps { value?: string onChange: (html: string) => void placeholder?: string maxLength?: number className?: string editorClassName?: string disabled?: boolean } function ToolbarButton({ active, disabled, onClick, label, children, }: { active?: boolean disabled?: boolean onClick: () => void label: string children: ReactNode }) { return ( ) } export function RichTextEditor({ value = "", onChange, placeholder = "Write here…", maxLength, className, editorClassName, disabled = false, }: RichTextEditorProps) { const editor = useEditor({ extensions: [ StarterKit.configure({ heading: false, codeBlock: false, blockquote: false, horizontalRule: false, }), Placeholder.configure({ placeholder }), ], content: value || "", editable: !disabled, onUpdate: ({ editor: currentEditor }) => { const html = currentEditor.getHTML() if (maxLength != null && richTextPlainLength(html) > maxLength) { currentEditor.commands.setContent(value || "", { emitUpdate: false }) return } onChange(html === "

" ? "" : html) }, editorProps: { attributes: { class: cn( "min-h-[120px] px-4 py-3 text-sm leading-relaxed text-grayScale-800 outline-none", "prose prose-sm max-w-none prose-p:my-2 prose-ul:my-2 prose-ol:my-2", editorClassName, ), }, }, }) useEffect(() => { if (!editor) return const current = editor.getHTML() const normalizedCurrent = current === "

" ? "" : current const normalizedValue = value || "" if (normalizedCurrent !== normalizedValue) { editor.commands.setContent(normalizedValue || "", { emitUpdate: false }) } }, [editor, value]) useEffect(() => { if (!editor) return editor.setEditable(!disabled) }, [editor, disabled]) const plainLength = richTextPlainLength(value) const atLimit = maxLength != null && plainLength >= maxLength return (
editor?.chain().focus().toggleBold().run()} > editor?.chain().focus().toggleItalic().run()} > editor?.chain().focus().toggleBulletList().run()} > editor?.chain().focus().toggleOrderedList().run()} >
editor?.chain().focus().undo().run()} > editor?.chain().focus().redo().run()} > {maxLength != null ? ( {plainLength} / {maxLength} ) : null}
) }