Skip to content

Commit

Permalink
Fix insertBefore children order.
Browse files Browse the repository at this point in the history
  • Loading branch information
edoardocavazza committed Nov 8, 2024
1 parent 1feb756 commit 1619112
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/six-taxis-march.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@chialab/quantum': patch
---

Fix `insertBefore` children order.
5 changes: 4 additions & 1 deletion src/Realm.js
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ export class Realm {
* @returns The nodes that were inserted.
*/
_insert(node, nodes) {
const io = this._childNodes.indexOf(node);
let io = this._childNodes.indexOf(node);
if (io === -1) {
throw new Error(
"Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node."
Expand All @@ -503,6 +503,9 @@ export class Realm {
const previousIndex = this._childNodes.indexOf(child);
if (previousIndex !== -1) {
this._childNodes.splice(previousIndex, 1);
if (previousIndex < io) {
io--;
}
}
});
this._childNodes.splice(io, 0, ...changed);
Expand Down
12 changes: 10 additions & 2 deletions tests/realm.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,19 +96,27 @@ describe('realm', () => {
expect(container.innerHTML).toBe('<span></span><div></div>');
});

test('Node.prototype.insertBefore should work in realm', () => {
test.only('Node.prototype.insertBefore should work in realm', () => {
const container = document.createElement('div');
const child = document.createElement('div');
const child2 = document.createElement('span');
const child3 = document.createElement('article');
attachRealm(container);
container.appendChild(child);
container.insertBefore(child2, child);
expect(container.childNodes.length).toBe(2);
container.appendChild(child3);
expect(container.childNodes.length).toBe(3);
expect(container.childNodes[0]).toBe(child2);
expect(container.childNodes[1]).toBe(child);
expect(container.childNodes[2]).toBe(child3);
expect(child.parentNode).toBe(container);
expect(child2.parentNode).toBe(container);
expect(child3.parentNode).toBe(container);
expect(container.innerHTML).toBe('');
container.insertBefore(child2, child3);
expect(container.childNodes[0]).toBe(child);
expect(container.childNodes[1]).toBe(child2);
expect(container.childNodes[2]).toBe(child3);
});

test('Node.prototype.hasChildNodes|firstChild|lastChild|parentNode|parentElement|previousSibling|nextSibling should work as usual', () => {
Expand Down

0 comments on commit 1619112

Please sign in to comment.