Scoop API

scoop:scoop.ui.component:0.1.0

src/tree/query.scoop

Selected production source · src/tree/query.scoop

1package scoop.ui.component
3import scoop.charset.unicodeCasefold
4import scoop.collections.HashMap
5import scoop.collections.HashSet
6import scoop.collections.sortWith
7import scoop.comparisons.comparatorOf
8import scoop.text.contains
9import scoop.ui.ViewKey
11internal class TreeOrder<T>(
12 val data: TreeData<T>,
13 val definition: TreeColumns<T>?,
14 val sorting: TableSort?
15) {
16 private val groups = HashMap<Long, Array<Long>>()
17 private val roots = ordered(data.rootIndices)
18 init {
19 when (sorting) {
20 case Some(_) ->
21 for (index in 0L..<data.count) {
22 val children = data.records[index].children
23 if (children.size > 1L) groups[index] = ordered(children)
24 }
25 case None -> {}
26 }
27 }
28 fun children(parent: Long?): Array<Long> = when (parent) {
29 case Some(val index) -> groups[index] ?: data.records[index].children
30 case None -> roots
31 }
32 private fun ordered(indices: Array<Long>): Array<Long> {
33 val sort = sorting ?: return indices
34 if (indices.size < 2L) return indices
35 val compare = definition!!.column(sort.column).compare!!
36 val result = ArrayList<Long>()
37 for (index in indices)
38 result.add(index)
39 result
40 .sortWith(
41 comparatorOf<Long> { left, right ->
42 val first = data.records[left].node.value
43 val second = data.records[right].node.value
44 val value = if (sort.direction == TableSortDirection.Ascending)
45 compare(first, second)
46 else
47 compare(second, first)
48 if (value != 0)
49 value.toLong()
50 else if (left < right) -1L else if (left > right) 1L else 0L
51 }
52 )
53 return result.toArray()
54 }
57internal class TreeMatches<T>(val data: TreeData<T>, val query: TreeQuery<T>) {
58 val matched = HashSet<ViewKey>()
59 val included = HashSet<Long>()
60 val expanded = HashSet<ViewKey>()
61 val active = query.text != ""
62 init {
63 if (active) {
64 val folded = unicodeCasefold(query.text)
65 for (index in 0L..<data.count) {
66 val node = data.records[index].node
67 val matches = when (query.matches) {
68 case Some(val test) -> test(node, query.text)
69 case None -> unicodeCasefold(node.label).contains(folded)
70 }
71 if (!matches) continue
72 matched.add(node.key)
73 included.add(index)
74 var parent = data.records[index].parent
75 while (true) {
76 val at = parent ?: break
77 expanded.add(data.records[at].node.key)
78 if (!included.add(at)) break
79 parent = data.records[at].parent
80 }
81 }
82 }
83 }
84 fun includes(index: Long): Boolean = !active ||
85 query.mode !=
86 TreeQueryMode.Filter ||
87 included.contains(index)
88 fun expands(key: ViewKey): Boolean = active &&
89 (query.mode == TreeQueryMode.Filter || query.expandMatches) &&
90 expanded.contains(key)