2021-03-09 05:16:32 +08:00
|
|
|
import { EditorOptions } from '@tiptap/core'
|
2022-06-08 20:10:25 +08:00
|
|
|
import { DependencyList, useEffect, useState } from 'react'
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2021-05-25 20:51:36 +08:00
|
|
|
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(() => {
|
2022-06-24 23:46:54 +08:00
|
|
|
let isMounted = true
|
|
|
|
|
2021-03-09 05:00:07 +08:00
|
|
|
const instance = new Editor(options)
|
|
|
|
|
|
|
|
setEditor(instance)
|
|
|
|
|
2021-10-22 14:52:54 +08:00
|
|
|
instance.on('transaction', () => {
|
|
|
|
requestAnimationFrame(() => {
|
|
|
|
requestAnimationFrame(() => {
|
2022-06-24 23:46:54 +08:00
|
|
|
if (isMounted) {
|
|
|
|
forceUpdate()
|
|
|
|
}
|
2021-10-22 14:52:54 +08:00
|
|
|
})
|
|
|
|
})
|
|
|
|
})
|
2021-03-09 05:00:07 +08:00
|
|
|
|
|
|
|
return () => {
|
|
|
|
instance.destroy()
|
2022-06-24 23:46:54 +08:00
|
|
|
isMounted = false
|
2021-03-09 05:00:07 +08:00
|
|
|
}
|
2021-05-25 20:51:36 +08:00
|
|
|
}, deps)
|
2021-03-09 05:00:07 +08:00
|
|
|
|
|
|
|
return editor
|
|
|
|
}
|