scoop:scoop.ui:0.1.0
src/runtime/sibling_matches.scoop
Selected production source · src/runtime/sibling_matches.scoop
1
package scoop.ui3
import scoop.collections.HashMap4
import scoop.collections.HashSet6
internal class SiblingMatches(val positions: Array<Long?>, val used: MutableArray<Boolean>)8
/** Shared positional/key matching for visual children and native application entries. */9
internal fun <N, D> matchSiblings(10
previous: Array<N>,11
descriptions: Array<D>,12
oldKey: (N) -> ViewKey,13
newKey: (D) -> ViewKey,14
canReuse: (N, D) -> Boolean15
): SiblingMatches {16
val keys = HashSet<ViewKey>()17
for (description in descriptions) {18
val key = newKey(description)19
if (key != ViewKey.Position)20
requireUi(keys.add(key), "duplicate sibling ViewKey")21
}22
val keyed = HashMap<ViewKey, Long>()23
for (index in 0L ..< previous.size) {24
val key = oldKey(previous[index])25
if (key != ViewKey.Position)26
keyed.put(key, index)27
}28
val used = MutableArray<Boolean>(previous.size) { _ -> false }29
val positions =30
Array<Long?>(descriptions.size) {31
index ->32
val description = descriptions[index]33
val key = newKey(description)34
val candidate =35
if (key == ViewKey.Position) {36
if (index < previous.size && oldKey(previous[index]) == ViewKey.Position)37
Some(index)38
else39
None40
} else41
keyed[key]42
when (candidate) {43
case Some(val position) -> if (canReuse(previous[position], description)) {44
used[position] = true45
Some(position)46
} else47
None48
case None -> None49
}50
}51
return SiblingMatches(positions, used)52
}