Skip to content

Instantly share code, notes, and snippets.

@zazk
Created August 13, 2024 14:11
Show Gist options
  • Save zazk/38dbf5c17a31492dc74e9c3e75071129 to your computer and use it in GitHub Desktop.
Save zazk/38dbf5c17a31492dc74e9c3e75071129 to your computer and use it in GitHub Desktop.
useEditor.tsx Trix
import { useEffect, useRef } from 'react';
import { UseFormReturn } from 'react-hook-form';
interface UseEditorProps {
form: UseFormReturn<any>; // Replace `any` with your specific form type if possible
noteContent: string;
inputRef: React.RefObject<HTMLInputElement>;
}
export const useEditor = ({ form, noteContent, inputRef }: UseEditorProps) => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleTrixChange = () => {
form.setValue('patientNote', inputRef.current?.value || '', {
shouldDirty: true,
shouldTouch: true,
});
};
const handleTrixInitialize = () => {
// Use a retry mechanism to ensure button removal
const removeButtonInterval = setTimeout(() => {
const button = document.querySelector('.trix-button-group--file-tools');
if (button) {
button.remove();
clearTimeout(removeButtonInterval);
}
}, 0);
if (ref.current) {
ref.current.addEventListener('trix-change', handleTrixChange);
ref.current.addEventListener('trix-initialize', handleTrixInitialize);
ref.current.addEventListener('trix-file-accept', (event) => {
event.preventDefault();
});
}
};
if (ref.current) {
handleTrixInitialize();
}
return () => {
if (ref.current) {
ref.current.removeEventListener('trix-change', handleTrixChange);
ref.current.removeEventListener('trix-initialize', handleTrixInitialize);
}
};
}, [form, inputRef, noteContent]);
return ref;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment