Switch to a method of re-applying HTML content to drafts that works reliably

This commit is contained in:
Ben Gotow 2020-04-20 11:01:31 -05:00
parent fa71b5d6b1
commit 80dc0b0461

View file

@ -69,19 +69,25 @@ function hotwireDraftBodyState(draft: any, session: DraftEditingSession): Messag
const inHTMLEditorValue = convertFromHTML(inHTML); const inHTMLEditorValue = convertFromHTML(inHTML);
try { try {
// try to apply the new value to the existing document to preserve undo history. // try to apply the new value to the existing document to preserve undo history.
_bodyEditorValue = session._mountedEditor let edits = session._mountedEditor.moveToStartOfDocument();
.moveToRangeOfDocument()
.delete()
.insertFragment(inHTMLEditorValue.document)
.moveToRangeOfDocument()
.moveToStart().value;
// occasionally inserting the new document adds a new line at the beginning of the value. // remove all but the very first node in the document
// It's unclaer why this happens... const [first, ...rest] = edits.value.document.nodes.toArray();
const firstBlock = _bodyEditorValue.document.getBlocks().first(); for (const item of rest) {
if (firstBlock.text === '') { if (edits.value.document.getPath(item.key)) {
_bodyEditorValue = session._mountedEditor.removeNodeByKey(firstBlock.key).value; edits = edits.removeNodeByKey(item.key);
}
} }
const [newFirst, ...newRest] = inHTMLEditorValue.document.nodes.toArray();
// replace the first node in the document with the first node of the new
// document, and then "insert" the remaining new nodes at the end.
edits = edits.replaceNodeByKey(first.key, newFirst).moveToEndOfDocument();
for (const block of newRest) {
edits = edits.insertBlock(block);
}
_bodyEditorValue = edits.moveToStart().value;
} catch (err) { } catch (err) {
// deleting and re-inserting the whole document seems to push Slate pretty hard and it // deleting and re-inserting the whole document seems to push Slate pretty hard and it
// sometimes fails with odd schema issues (undefined node, invalid range.) Just fall // sometimes fails with odd schema issues (undefined node, invalid range.) Just fall