Skip to content

Commit bec34f0

Browse files
committed
+
1 parent e648cc6 commit bec34f0

File tree

1 file changed

+30
-32
lines changed

1 file changed

+30
-32
lines changed

src/utils/component.ts

+30-32
Original file line numberDiff line numberDiff line change
@@ -245,46 +245,44 @@ export async function destroyElement(
245245
| null
246246
| null[],
247247
) {
248-
if (Array.isArray(component)) {
249-
await Promise.all(component.map((component) => destroyElement(component)));
250-
} else {
251-
if (component === null) {
252-
return;
253-
}
254-
if ($nodes in component) {
255-
const destructors: Array<Promise<void>> = [];
256-
if (component.ctx) {
257-
runDestructors(component.ctx, destructors);
248+
// Flatten the array if it's an array of components
249+
const components = Array.isArray(component) ? component.flat() : [component];
250+
251+
const destructors: Array<Promise<void>> = [];
252+
const nodesToDestroy: Set<Node> = new Set();
253+
254+
for (const item of components) {
255+
if (item === null) continue;
256+
257+
if ($nodes in item) {
258+
if (item.ctx) {
259+
runDestructors(item.ctx, destructors);
258260
}
259-
const nodes = component[$nodes];
261+
262+
const nodes = item[$nodes];
260263
let startNode: null | Node = nodes[0];
261-
const endNode =
262-
nodes.length === 1 ? null : nodes[nodes.length - 1] || null;
263-
const nodesToDestroy = new Set(nodes);
264-
while (true && endNode !== null) {
265-
startNode = startNode.nextSibling;
266-
if (startNode === null) {
267-
break;
268-
} else if (startNode === endNode) {
269-
nodesToDestroy.add(endNode);
270-
break;
271-
} else {
264+
const endNode = nodes.length > 1 ? nodes[nodes.length - 1] : null;
265+
if (endNode !== null) {
266+
// Collect nodes to destroy
267+
while (startNode && startNode !== endNode) {
272268
nodesToDestroy.add(startNode);
269+
startNode = startNode.nextSibling;
273270
}
274-
}
275-
await Promise.all(destructors);
276-
try {
277-
await Promise.all(Array.from(nodesToDestroy).map(destroyNode));
278-
} catch (e) {
279-
console.warn(
280-
`Woops, looks like node we trying to destroy no more in DOM`,
281-
e,
282-
);
271+
if (endNode !== null) {
272+
nodesToDestroy.add(endNode);
273+
}
274+
} else {
275+
nodesToDestroy.add(startNode);
283276
}
284277
} else {
285-
await destroyNode(component[$node]);
278+
nodesToDestroy.add(item[$node]);
286279
}
287280
}
281+
282+
// Await all destructors
283+
await Promise.all(destructors);
284+
// Destroy all nodes
285+
await Promise.all(Array.from(nodesToDestroy).map(destroyNode));
288286
}
289287

290288
var $newDestructors = new WeakMap<any, Destructors>();

0 commit comments

Comments
 (0)