@@ -245,46 +245,44 @@ export async function destroyElement(
245
245
| null
246
246
| null [ ] ,
247
247
) {
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 ) ;
258
260
}
259
- const nodes = component [ $nodes ] ;
261
+
262
+ const nodes = item [ $nodes ] ;
260
263
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 ) {
272
268
nodesToDestroy . add ( startNode ) ;
269
+ startNode = startNode . nextSibling ;
273
270
}
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 ) ;
283
276
}
284
277
} else {
285
- await destroyNode ( component [ $node ] ) ;
278
+ nodesToDestroy . add ( item [ $node ] ) ;
286
279
}
287
280
}
281
+
282
+ // Await all destructors
283
+ await Promise . all ( destructors ) ;
284
+ // Destroy all nodes
285
+ await Promise . all ( Array . from ( nodesToDestroy ) . map ( destroyNode ) ) ;
288
286
}
289
287
290
288
var $newDestructors = new WeakMap < any , Destructors > ( ) ;
0 commit comments