Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(2d): add querying helpers #852

Merged
merged 2 commits into from Nov 22, 2023

Conversation

aarthificial
Copy link
Contributor

@aarthificial aarthificial commented Nov 21, 2023

Introduces multiple helpers for querying the node hierarchy and dealing with type casting.

Node.findAll()

Finds all descendants of the node that match the given predicate:

const texts = node.findAll<Txt>(child => child instanceof Txt);

Node.findFirst()

Finds the first descendant that matches.
Uses depth-first traversal, like querySelector in DOM.

Node.findLast()

Finds the last descendant that matches.
Order is the same as in findFirst but in reverse.

Node.findAncestor()

Finds the first ancestor that matches.


is()

A helper function for creating instanceof predicates.
It's less verbose than manually writing instanceof and, thanks to type guards, TypeScript can infer the type of the resulting array automatically:

const texts = node.find(is(Txt));

Node.[child/children/parent]As()

A set of helpers for easier casting. They remove the need for a (...) wrapper that stems from using as.
Solely for convenience, they don't actually use instanceof to type-check anything:

// old way:
(node.children()[2] as Txt).fill('white');
// new way
node.childAs<Txt>(2).fill('white');
// old way:
yield* all(...node.children().map(child => (child as Txt).fill('white', 2)));
// new way
yield* all(...node.childrenAs<Txt>().map(child => child.fill('white', 2)));
// old way:
(node.parent() as Txt).fill('white');
// new way
(node.parentAs<Txt>().fill('white');

@aarthificial aarthificial merged commit 614de6b into motion-canvas:main Nov 22, 2023
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants