Last active
December 5, 2023 04:48
-
-
Save dliebner/eb7dcfea8e81ab412a63f490451e356a to your computer and use it in GitHub Desktop.
LitElement.ready( requireEntireDomTreeReady = false )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExtendedLitElement extends LitElement { | |
static getDuckTypedDescendants(parent, qualifyingPropertyName, stopTraversalOnMatch = true) { | |
const descendants = []; | |
/** | |
* Use a depth-first search (DFS) algorithm to traverse the DOM tree | |
* @param {Node} node | |
*/ | |
const traverse = node => { | |
if( node !== parent && qualifyingPropertyName in node ) { | |
descendants.push(node); | |
if( stopTraversalOnMatch ) return; // Stop the traversal when a custom element node is encountered | |
} | |
for( const childNode of node.childNodes ) { | |
traverse(childNode); | |
} | |
}; | |
traverse(parent); | |
return descendants; | |
} | |
async ready( requireEntireDomTreeReady = false ) { | |
const thisUpdateComplete = await this.updateComplete; | |
if( !requireEntireDomTreeReady ) return thisUpdateComplete; | |
const descendantsUpdateComplete = await Promise.all( | |
Array.from( | |
ExtendedLitElement.getDuckTypedDescendants(this, 'updateComplete'), | |
node => typeof node.ready === 'function' ? node.ready(true) : node.updateComplete | |
).filter(x => !!x) | |
); | |
return thisUpdateComplete && descendantsUpdateComplete.every(x => !!x); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment