Skip to content

Commit 06aa50d

Browse files
committed
chore(find): proper typings
1 parent 656adc2 commit 06aa50d

File tree

1 file changed

+48
-11
lines changed

1 file changed

+48
-11
lines changed

src/utils/find.ts

Lines changed: 48 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import { VNode, ComponentPublicInstance } from 'vue'
1+
import {
2+
ComponentPublicInstance,
3+
VNode,
4+
VNodeArrayChildren,
5+
VNodeNormalizedChildren
6+
} from 'vue'
27
import { FindAllComponentsSelector } from '../types'
38
import { matchName } from './matchName'
49

@@ -28,26 +33,55 @@ function matches(node: VNode, selector: FindAllComponentsSelector): boolean {
2833
return false
2934
}
3035

36+
/**
37+
* Filters out the null, undefined and primitive values,
38+
* to only keep VNode and VNodeArrayChildren values
39+
* @param value
40+
*/
41+
function nodesAsObject<Node>(
42+
value:
43+
| string
44+
| number
45+
| boolean
46+
| VNodeArrayChildren
47+
| VNode
48+
| null
49+
| undefined
50+
| void
51+
): value is VNodeArrayChildren | VNode {
52+
return !!value && typeof value === 'object'
53+
}
54+
3155
/**
3256
* Collect all children
3357
* @param nodes
3458
* @param children
3559
*/
36-
function aggregateChildren(nodes, children) {
60+
function aggregateChildren(nodes: VNode[], children: VNodeNormalizedChildren) {
3761
if (children && Array.isArray(children)) {
38-
;[...children].reverse().forEach((n: VNode) => {
39-
nodes.unshift(n)
62+
const reversedNodes = [...children].reverse().filter(nodesAsObject)
63+
reversedNodes.forEach((node: VNodeArrayChildren | VNode) => {
64+
if (Array.isArray(node)) {
65+
aggregateChildren(nodes, node)
66+
} else {
67+
nodes.unshift(node)
68+
}
4069
})
4170
}
4271
}
4372

44-
function findAllVNodes(vnode: VNode, selector: any): VNode[] {
45-
const matchingNodes = []
46-
const nodes = [vnode]
73+
function findAllVNodes(
74+
vnode: VNode,
75+
selector: FindAllComponentsSelector
76+
): VNode[] {
77+
const matchingNodes: VNode[] = []
78+
const nodes: VNode[] = [vnode]
4779
while (nodes.length) {
48-
const node = nodes.shift()
80+
const node = nodes.shift()!
4981
aggregateChildren(nodes, node.children)
50-
aggregateChildren(nodes, node.component?.subTree.children)
82+
if (node.component) {
83+
aggregateChildren(nodes, node.component.subTree.children)
84+
}
5185
if (matches(node, selector)) {
5286
matchingNodes.push(node)
5387
}
@@ -56,8 +90,11 @@ function findAllVNodes(vnode: VNode, selector: any): VNode[] {
5690
return matchingNodes
5791
}
5892

59-
export function find(root: VNode, selector: any): ComponentPublicInstance[] {
93+
export function find(
94+
root: VNode,
95+
selector: FindAllComponentsSelector
96+
): ComponentPublicInstance[] {
6097
return findAllVNodes(root, selector).map(
61-
(vnode: VNode) => vnode.component.proxy
98+
(vnode: VNode) => vnode.component!.proxy!
6299
)
63100
}

0 commit comments

Comments
 (0)