diff --git a/src/renderer/widgets/note/widget.tsx b/src/renderer/widgets/note/widget.tsx index 42cb0ea2..53baa0e4 100644 --- a/src/renderer/widgets/note/widget.tsx +++ b/src/renderer/widgets/note/widget.tsx @@ -14,6 +14,10 @@ import { Editor } from 'tiny-markdown-editor'; const keyNote = 'note'; +interface TinyMDEChangeEvent { + content: string; +} + function WidgetComp({widgetApi, settings}: WidgetReactComponentProps) { const {updateActionBar, setContextMenuFactory, dataStorage} = widgetApi; const textAreaRef = useRef(null); @@ -29,14 +33,13 @@ function WidgetComp({widgetApi, settings}: WidgetReactComponentProps) const saveNote = useMemo(() => debounce((note: string) => dataStorage.setText(keyNote, note), 3000), [dataStorage]); const updNote = useCallback((note: string) => { - // setLoadedNote(note); saveNote(note); - }, [saveNote]) + }, [saveNote]); const handleChange = useCallback>((e) => { const newNote = e.target.value; - updNote(newNote) - }, [updNote]) + updNote(newNote); + }, [updNote]); useEffect(() => { async function loadNote() { @@ -44,27 +47,45 @@ function WidgetComp({widgetApi, settings}: WidgetReactComponentProps) setIsLoaded(true); } loadNote(); - }, [dataStorage]) + }, [dataStorage]); + // Inicialização e Ciclo de Vida do Editor Markdown (TinyMDE) useEffect(() => { - if (textAreaRef.current) { - if (settings.markdown) { - const tinyMDE = new Editor({textarea: textAreaRef.current}); - tinyMDE.addEventListener('change', (e) => updNote(e.content)); - (textAreaRef.current.nextSibling as HTMLElement).spellcheck = settings.spellCheck; - } else { - setLoadedNote(textAreaRef.current.value); - Array.from(textAreaRef.current.parentElement?.children || []) - .filter(child => child.classList.contains('TinyMDE')) - .forEach(child => child.remove()); + if (!isLoaded || !textAreaRef.current) { + return undefined; + } + + const currentTextArea = textAreaRef.current; + + const removeExistingEditorDOM = () => { + Array.from(currentTextArea.parentElement?.children || []) + .filter(child => child.classList.contains('TinyMDE')) + .forEach(child => child.remove()); + }; + + if (settings.markdown) { + removeExistingEditorDOM(); + + const tinyMDE = new Editor({textarea: currentTextArea}); + tinyMDE.addEventListener('change', (e: TinyMDEChangeEvent) => updNote(e.content)); + + if (currentTextArea.nextSibling && 'spellcheck' in currentTextArea.nextSibling) { + (currentTextArea.nextSibling as HTMLElement).spellcheck = settings.spellCheck; } + } else { + setLoadedNote(currentTextArea.value); + removeExistingEditorDOM(); } - }, [settings.markdown, settings.spellCheck, updNote]) + + return () => { + removeExistingEditorDOM(); + }; + }, [isLoaded, settings.markdown, settings.spellCheck, updNote]); return ( isLoaded ? : <>Loading Note... - ) + ); } export const widgetComp: ReactComponent> = { type: 'react', Comp: WidgetComp -} +};