File size: 2,170 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
import React, {
Component,
ComponentType,
ContextType,
ReactNode,
RefObject,
} from 'react'
import { EditorContext } from '../../hooks/use-slate-static'
import { IS_ANDROID } from 'slate-dom'
import {
createRestoreDomManager,
RestoreDOMManager,
} from './restore-dom-manager'
const MUTATION_OBSERVER_CONFIG: MutationObserverInit = {
subtree: true,
childList: true,
characterData: true,
characterDataOldValue: true,
}
type RestoreDOMProps = {
children?: ReactNode
receivedUserInput: RefObject<boolean>
node: RefObject<HTMLDivElement>
}
// We have to use a class component here since we rely on `getSnapshotBeforeUpdate` which has no FC equivalent
// to run code synchronously immediately before react commits the component update to the DOM.
class RestoreDOMComponent extends Component<RestoreDOMProps> {
static contextType = EditorContext
context: ContextType<typeof EditorContext> = null
private manager: RestoreDOMManager | null = null
private mutationObserver: MutationObserver | null = null
observe() {
const { node } = this.props
if (!node.current) {
throw new Error('Failed to attach MutationObserver, `node` is undefined')
}
this.mutationObserver?.observe(node.current, MUTATION_OBSERVER_CONFIG)
}
componentDidMount() {
const { receivedUserInput } = this.props
const editor = this.context!
this.manager = createRestoreDomManager(editor, receivedUserInput)
this.mutationObserver = new MutationObserver(this.manager.registerMutations)
this.observe()
}
getSnapshotBeforeUpdate() {
const pendingMutations = this.mutationObserver?.takeRecords()
if (pendingMutations?.length) {
this.manager?.registerMutations(pendingMutations)
}
this.mutationObserver?.disconnect()
this.manager?.restoreDOM()
return null
}
componentDidUpdate() {
this.manager?.clear()
this.observe()
}
componentWillUnmount() {
this.mutationObserver?.disconnect()
}
render() {
return this.props.children
}
}
export const RestoreDOM: ComponentType<RestoreDOMProps> = IS_ANDROID
? RestoreDOMComponent
: ({ children }) => <>{children}</>
|