Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,17 @@ describe("helpers", () => {
),
).toBe(10);
});

it("reports the correct order when a sibling is a comment", () => {
const dom = parseDocument("<div><p></p><!--c--><a></a></div>")
.children[0] as Element;
const [p, comment, a] = dom.children;

expect(compareDocumentPosition(p, comment)).toBe(2);
expect(compareDocumentPosition(comment, p)).toBe(4);
expect(compareDocumentPosition(comment, a)).toBe(2);
expect(compareDocumentPosition(a, comment)).toBe(4);
});
});

describe("uniqueSort", () => {
Expand All @@ -92,6 +103,19 @@ describe("helpers", () => {
it("removes duplicate elements", () =>
expect(uniqueSort([p, a, p])).toStrictEqual([p, a]));

it("sorts a comment sibling into document order", () => {
const withComment = parseDocument(
"<div><p></p><!--c--><a></a></div>",
).children[0] as Element;
const [firstP, comment, lastA] = withComment.children;

expect(uniqueSort([lastA, comment, firstP])).toStrictEqual([
firstP,
comment,
lastA,
]);
});

it("sorts nodes in document order", () =>
expect(uniqueSort([a, dom, span, p])).toStrictEqual([
dom,
Expand Down
4 changes: 2 additions & 2 deletions src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ export function compareDocumentPosition(

const sharedParent = aParents[index - 1];
const siblings: AnyNode[] = sharedParent.children;
const aSibling = aParents[index];
const bSibling = bParents[index];
const aSibling = index < aParents.length ? aParents[index] : nodeA;
const bSibling = index < bParents.length ? bParents[index] : nodeB;

if (siblings.indexOf(aSibling) > siblings.indexOf(bSibling)) {
if (sharedParent === nodeB) {
Expand Down