Remove children of Document even if doc not in mirror (#923)

* Remove children of Document even if doc not in mirror

* fix flaky test

* Update packages/rrdom/test/diff.test.ts

Co-authored-by: Yun Feng <yun.feng@anu.edu.au>

Co-authored-by: Yun Feng <yun.feng@anu.edu.au>
This commit is contained in:
Justin Halsall
2026-04-01 12:00:00 +08:00
committed by GitHub
parent 0ca1e49509
commit c52368fd91
2 changed files with 19 additions and 1 deletions

View File

@@ -316,7 +316,7 @@ function diffChildren(
* We should delete it before insert a serialized one. Otherwise, an error 'Only one element on document allowed' will be thrown.
*/
if (
replayer.mirror.getMeta(parentNode)?.type === RRNodeType.Document &&
parentNode.nodeName === '#document' &&
replayer.mirror.getMeta(newNode)?.type === RRNodeType.Element &&
(parentNode as Document).documentElement
) {

View File

@@ -1056,6 +1056,24 @@ describe('diff algorithm for rrdom', () => {
expect(element.tagName).toBe('DIV');
expect(mirror.getId(element)).toEqual(2);
});
it('should remove children from document before adding new nodes', () => {
document.write('<style></style>'); // old document with elements that need removing
const rrDocument = new RRDocument();
const docType = rrDocument.createDocumentType('html', '', '');
rrDocument.mirror.add(docType, getDefaultSN(docType, 1));
rrDocument.appendChild(docType);
const htmlEl = rrDocument.createElement('html');
rrDocument.mirror.add(htmlEl, getDefaultSN(htmlEl, 2));
rrDocument.appendChild(htmlEl);
diff(document, rrDocument, replayer);
expect(document.childNodes.length).toBe(2);
const element = document.childNodes[0] as HTMLElement;
expect(element.nodeType).toBe(element.DOCUMENT_TYPE_NODE);
expect(mirror.getId(element)).toEqual(1);
});
});
describe('create or get a Node', () => {