Skip to content

Commit 8c17d60

Browse files
fix issue when newContent has siblings that shouldn't be included in the morph.
1 parent c3c4a69 commit 8c17d60

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

src/idiomorph.js

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1129,7 +1129,15 @@ var Idiomorph = (function () {
11291129
/** @type {Map<Node, Set<string>>} */
11301130
let idMap = new Map();
11311131
populateIdMapForNode(oldContent, oldElts, persistentIds, idMap);
1132-
populateIdMapForNode(newContent, newElts, persistentIds, idMap);
1132+
1133+
let newRoot = newContent;
1134+
// if newContent is a duck-typed parent, pass its single child node as the root to halt upwards iteration
1135+
/** @ts-ignore */
1136+
if (newContent.__idiomorphDummyParent) {
1137+
newRoot = /** @type {Element} */ (newContent.childNodes[0]);
1138+
}
1139+
populateIdMapForNode(newRoot, newElts, persistentIds, idMap);
1140+
11331141
return { persistentIds, idMap };
11341142
}
11351143

@@ -1173,7 +1181,28 @@ var Idiomorph = (function () {
11731181
return /** @type {Element} */ (newContent);
11741182
} else if (newContent instanceof Node) {
11751183
if (newContent.parentNode) {
1176-
return /** @type {Element} */ (newContent.parentNode);
1184+
// we can't use the parent directly because newContent may have siblings
1185+
// that we don't want in the morph. we can't reparent either, because we
1186+
// want to preserve hidden state. so we create a duck-typed parent.
1187+
return /** @type {Element} */ (
1188+
/** @type {unknown} */ ({
1189+
childNodes: [newContent],
1190+
/** @ts-ignore - cover your eyes for a minute, tsc */
1191+
querySelectorAll: (s) => {
1192+
/** @ts-ignore */
1193+
const elements = newContent.querySelectorAll(s);
1194+
/** @ts-ignore */
1195+
return newContent.matches(s)
1196+
? [newContent, ...elements]
1197+
: elements;
1198+
},
1199+
/** @ts-ignore */
1200+
insertBefore: (n, r) => newContent.parentNode.insertBefore(n, r),
1201+
/** @ts-ignore */
1202+
moveBefore: (n, r) => newContent.parentNode.moveBefore(n, r),
1203+
__idiomorphDummyParent: true,
1204+
})
1205+
);
11771206
} else {
11781207
// a single node is added as a child to a dummy parent
11791208
const dummyParent = document.createElement("div");

0 commit comments

Comments
 (0)