tiptap/packages/react/src/useEditor.ts

35 lines
779 B
TypeScript
Raw Normal View History

import { useState, useEffect, DependencyList } from 'react'
2021-03-09 05:16:32 +08:00
import { EditorOptions } from '@tiptap/core'
2021-03-09 05:00:07 +08:00
import { Editor } from './Editor'
function useForceUpdate() {
2021-03-09 06:10:10 +08:00
const [, setValue] = useState(0)
2021-03-09 05:00:07 +08:00
return () => setValue(value => value + 1)
}
export const useEditor = (options: Partial<EditorOptions> = {}, deps: DependencyList = []) => {
2021-03-09 05:16:32 +08:00
const [editor, setEditor] = useState<Editor | null>(null)
2021-03-09 05:00:07 +08:00
const forceUpdate = useForceUpdate()
useEffect(() => {
const instance = new Editor(options)
setEditor(instance)
2021-10-22 14:52:54 +08:00
instance.on('transaction', () => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
forceUpdate()
})
})
})
2021-03-09 05:00:07 +08:00
return () => {
instance.destroy()
}
}, deps)
2021-03-09 05:00:07 +08:00
return editor
}