here is my function, i want to remove the prefix after the style is applied, do not…
- User
here is my function, i want to remove the prefix after the style is applied, do not change the cursor position, just remove the prefix
import React, { useState, useEffect } from "react"; import { Editor, EditorState, RichUtils, convertToRaw, convertFromRaw, Modifier, } from "draft-js"; import "draft-js/dist/Draft.css"; import "./DemoEditor.css";
const DemoEditor = () => { const [editorState, setEditorState] = useState(() => { const savedContent = localStorage.getItem("draftContent"); if (savedContent) { return EditorState.createWithContent( convertFromRaw(JSON.parse(savedContent)) ); } return EditorState.createEmpty(); });
const handleEditorChange = (newEditorState) => { const content = newEditorState.getCurrentContent(); const selection = newEditorState.getSelection(); const block = content.getBlockForKey(selection.getStartKey()); const text = block.getText();
let updatedEditorState = newEditorState; const styles = [ { prefix: "# ", style: "HEADER" }, { prefix: "* ", style: "BOLD" }, { prefix: "** ", style: "RED" }, { prefix: "*** ", style: "UNDERLINE" }, ]; styles.forEach(({ prefix, style }) => { const hasStyle = updatedEditorState.getCurrentInlineStyle().has(style); const shouldHaveStyle = text.startsWith(prefix); if (hasStyle !== shouldHaveStyle) { updatedEditorState = RichUtils.toggleInlineStyle( updatedEditorState, style ); } }); setEditorState(updatedEditorState);};
const handleKeyCommand = (command, editorState) => { const newState = RichUtils.handleKeyCommand(editorState, command); if (newState) { handleEditorChange(newState); return "handled"; } return "not-handled"; };
const saveContent = () => { const content = editorState.getCurrentContent(); localStorage.setItem("draftContent", JSON.stringify(convertToRaw(content))); };
const handleSave = () => { saveContent(); console.log("Content saved to localStorage"); // Implement any additional save logic here };
const customStyleMap = { HEADER: { fontSize: "24px", fontWeight: "bold", }, RED: { color: "red", }, };
return ( Demo editor by <Name> Save ); };
export default DemoEditor;
- Assistant