File size: 1,530 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 |
import { RefObject } from 'react'
import { ReactEditor } from '../../plugin/react-editor'
import { isTrackedMutation } from 'slate-dom'
export type RestoreDOMManager = {
registerMutations: (mutations: MutationRecord[]) => void
restoreDOM: () => void
clear: () => void
}
export const createRestoreDomManager = (
editor: ReactEditor,
receivedUserInput: RefObject<boolean>
): RestoreDOMManager => {
let bufferedMutations: MutationRecord[] = []
const clear = () => {
bufferedMutations = []
}
const registerMutations = (mutations: MutationRecord[]) => {
if (!receivedUserInput.current) {
return
}
const trackedMutations = mutations.filter(mutation =>
isTrackedMutation(editor, mutation, mutations)
)
bufferedMutations.push(...trackedMutations)
}
function restoreDOM() {
if (bufferedMutations.length > 0) {
bufferedMutations.reverse().forEach(mutation => {
if (mutation.type === 'characterData') {
// We don't want to restore the DOM for characterData mutations
// because this interrupts the composition.
return
}
mutation.removedNodes.forEach(node => {
mutation.target.insertBefore(node, mutation.nextSibling)
})
mutation.addedNodes.forEach(node => {
mutation.target.removeChild(node)
})
})
// Clear buffered mutations to ensure we don't undo them twice
clear()
}
}
return {
registerMutations,
restoreDOM,
clear,
}
}
|