import { createSignal, createEffect } from "solid-js"; import { cn } from "@/lib/cn"; import { sanitizeRichText } from "@/lib/rich-text"; import { useT } from "@/stores/preferences-context"; interface RichTextEditorProps { value: string; onChange: (value: string) => void; placeholder?: string; class?: string; minHeight?: string; } export function RichTextEditor(props: RichTextEditorProps) { const t = useT(); let editorRef: HTMLDivElement | undefined; const [isFocused, setIsFocused] = createSignal(false); // Sync value from props into editor when changed externally createEffect(() => { if (editorRef && editorRef.innerHTML !== props.value) { // If props value is empty string, clear innerHTML if (!props.value) { editorRef.innerHTML = ""; } else if (editorRef.innerHTML !== props.value) { // The value can come back from the server (a saved homework answer), // so it goes through the same sanitizer as every other stored HTML. editorRef.innerHTML = sanitizeRichText(props.value); } } }); const handleInput = () => { if (editorRef) { const html = editorRef.innerHTML; // If editor contains empty tags like
or


, treat as empty if (html === "
" || html === "


" || editorRef.innerText.trim() === "") { props.onChange(""); } else { props.onChange(html); } } }; const execCommand = (command: string, value: string | undefined = undefined) => { if (!editorRef) return; editorRef.focus(); document.execCommand(command, false, value); handleInput(); }; return (
{/* Gmail Style Rich Formatting Toolbar */}
{/* Contenteditable Editor Area */}
setIsFocused(true)} onBlur={() => setIsFocused(false)} /> {/* Placeholder overlay */} {!props.value && !isFocused() && (
{props.placeholder || t("editor.bodyPlaceholder")}
)}
); }