import debounce from 'lodash/debounce'; import type { EditorBridge } from '../types'; import { useEffect, useState } from 'react'; import type { EditorContentType } from '../bridges/core'; interface Options { type?: T; debounceInterval?: number; } const DEFAULT_OPTIONS: Required> = { type: 'html', debounceInterval: 10, }; type ContentType = T extends 'json' ? object : string; export function useEditorContent( editor: EditorBridge, { debounceInterval, type }: Options = DEFAULT_OPTIONS as Options ) { const [content, setContent] = useState>(); useEffect(() => { const updateContent = debounce(async () => { switch (type) { case 'json': const json = await editor.getJSON(); setContent(json as ContentType); break; case 'text': const text = await editor.getText(); setContent(text as ContentType); break; case 'html': default: const html = await editor.getHTML(); setContent(html as ContentType); break; } }, debounceInterval); const unsubscribe = editor._subscribeToEditorStateUpdate(() => { updateContent(); }); return () => { unsubscribe(); }; }, [editor, debounceInterval, type]); return content; }