Skip to content

Instantly share code, notes, and snippets.

@dliebner
Last active December 5, 2023 04:48
Show Gist options
  • Save dliebner/eb7dcfea8e81ab412a63f490451e356a to your computer and use it in GitHub Desktop.
Save dliebner/eb7dcfea8e81ab412a63f490451e356a to your computer and use it in GitHub Desktop.
LitElement.ready( requireEntireDomTreeReady = false )
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