import { EditorContent, useEditor, useEditorState } from "@tiptap/react"; import StarterKit from "@tiptap/starter-kit"; import { TextStyleKit } from "@tiptap/extension-text-style"; import Placeholder from "@tiptap/extension-placeholder"; import { useEffect } from "react"; const extensions = [ StarterKit.configure({ heading: { levels: [2, 3] } }), TextStyleKit.configure({ backgroundColor: false, color: false, fontFamily: false, lineHeight: false, }), Placeholder.configure({ placeholder: "Start with the idea you want the reader to keep…", }), ]; function ToolbarButton({ active = false, children, label, onClick }) { return ( ); } export default function RichTextEditor({ onChange, content = "" }) { const editor = useEditor({ extensions, content, editorProps: { attributes: { "aria-label": "Article body" } }, onUpdate: ({ editor: currentEditor }) => { onChange(currentEditor.getJSON(), currentEditor.getText().trim()); }, }); const state = useEditorState({ editor, selector: ({ editor: currentEditor }) => ({ bold: currentEditor?.isActive("bold") ?? false, italic: currentEditor?.isActive("italic") ?? false, underline: currentEditor?.isActive("underline") ?? false, heading2: currentEditor?.isActive("heading", { level: 2 }) ?? false, heading3: currentEditor?.isActive("heading", { level: 3 }) ?? false, bulletList: currentEditor?.isActive("bulletList") ?? false, orderedList: currentEditor?.isActive("orderedList") ?? false, fontSize: currentEditor?.getAttributes("textStyle").fontSize ?? "", }), }); if (!editor) return
Preparing editor…
; return (
editor.chain().focus().toggleBold().run()}>B editor.chain().focus().toggleItalic().run()}>I editor.chain().focus().toggleUnderline().run()}>U
editor.chain().focus().toggleHeading({ level: 2 }).run()}>Section heading editor.chain().focus().toggleHeading({ level: 3 }).run()}>H3 { if (editor.isEmpty) { editor.chain().focus().setContent({ type: "doc", content: [ { type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Section title" }] }, { type: "paragraph" }, ] }).setTextSelection({ from: 1, to: 14 }).run(); return; } const end = editor.state.doc.content.size; editor.chain().focus().insertContentAt(end, [ { type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Section title" }] }, { type: "paragraph" }, ]).setTextSelection({ from: end + 1, to: end + 14 }).run(); }}>+ Section
editor.chain().focus().toggleBulletList().run()}>• List editor.chain().focus().toggleOrderedList().run()}>1. List
editor.chain().focus().undo().run()}>↶ editor.chain().focus().redo().run()}>↷
); } export function RichTextArticle({ content }) { const editor = useEditor({ extensions, content, editable: false, }); useEffect(() => { if (editor) editor.commands.setContent(content); }, [content, editor]); if (!editor) return null; return ; }