Skip to content

Commit

Permalink
perf: getDescendants
Browse files Browse the repository at this point in the history
  • Loading branch information
lisonge committed Nov 6, 2023
1 parent f90ff14 commit ae498fc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
2 changes: 1 addition & 1 deletion app/src/main/java/li/songe/gkd/service/AbExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ val abTransform = Transform(
getParent = { node -> node.parent },
getDescendants = { node ->
sequence {
val stack = mutableListOf(node)
val stack = getChildren(node).toMutableList()
val tempNodes = mutableListOf<AccessibilityNodeInfo>()
do {
val top = stack.removeLast()
Expand Down
18 changes: 13 additions & 5 deletions selector/src/commonMain/kotlin/li/songe/selector/Transform.kt
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,20 @@ class Transform<T>(
)
},

/**
* 遍历下面所有子孙节点,不包含自己
*/
val getDescendants: (T) -> Sequence<T> = { node ->
sequence { // 深度优先 先序遍历
// https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelector
val stack = mutableListOf(node)
val stack = getChildren(node).toMutableList()
stack.reverse()
val tempNodes = mutableListOf<T>()
do {
val top = stack.removeLast()
yield(top)
for (childNode in getChildren(top)) {
// 可针对 sequence 优化
tempNodes.add(childNode)
}
if (tempNodes.isNotEmpty()) {
Expand All @@ -71,10 +76,13 @@ class Transform<T>(

val querySelectorAll: (T, Selector) -> Sequence<T> = { node, selector ->
sequence {
// cache trackNodes
val trackNodes: MutableList<T> = mutableListOf()
val r0 = selector.match(node, this@Transform, trackNodes)
if (r0 != null) yield(r0)
getDescendants(node).forEach { childNode ->
val r = selector.match(childNode, this@Transform, trackNodes)
trackNodes.clear()
val r = selector.match(childNode, this@Transform, trackNodes)
if (r != null) yield(r)
}
}
Expand All @@ -86,10 +94,10 @@ class Transform<T>(
}
val querySelectorTrackAll: (T, Selector) -> Sequence<List<T>> = { node, selector ->
sequence {
val trackNodes: MutableList<T> = mutableListOf()
val r0 = selector.matchTracks(node, this@Transform)
if (r0 != null) yield(r0)
getDescendants(node).forEach { childNode ->
val r = selector.matchTracks(childNode, this@Transform, trackNodes)?.toList()
trackNodes.clear()
val r = selector.matchTracks(childNode, this@Transform)
if (r != null) yield(r)
}
}
Expand Down

0 comments on commit ae498fc

Please sign in to comment.