scoop:scoop.ui.component:0.1.0
src/choice/choice.scoop
Selected production source · src/choice/choice.scoop
1
package scoop.ui.component3
import scoop.ui.*5
/** Ordered domain metadata shared by choice controls. */6
public class Choice<T: Equals<T>> public constructor(7
public val key: ViewKey,8
public val value: T,9
public val label: String,10
public val enabled: Boolean = true11
)13
internal fun <T: Equals<T>> validateChoices(items: Array<Choice<T>>) {14
for (index in 0L ..< items.size) {15
requireComponent(items[index].key != ViewKey.Position, "choice requires an explicit key")16
for (previous in 0L ..< index) {17
requireComponent(items[index].key != items[previous].key, "duplicate choice key")18
requireComponent(items[index].value != items[previous].value, "duplicate choice value")19
}20
}21
}23
private class ChoiceHandle(val key: ViewKey, val handle: FocusHandle)25
/** Retains only handles for the current keyed items; it owns no focus registration. */26
internal class ChoiceHandles {27
private var entries: Array<ChoiceHandle> = []28
fun resolve(keys: Array<ViewKey>, options: Array<FocusOptions>): Array<FocusHandle> {29
val next =30
Array<ChoiceHandle>(keys.size) {31
index ->32
val key = keys[index]33
var previous: FocusHandle? = None34
for (entry in entries)35
if (entry.key == key)36
previous = Some(entry.handle)37
ChoiceHandle(key, previous ?: FocusHandle())38
}39
entries = next40
return Array<FocusHandle>(next.size) {41
index -> options[index].handle ?: next[index].handle42
}43
}44
}46
internal fun choiceFocus(options: FocusOptions, handle: FocusHandle): FocusOptions =47
options.copy { this.handle = Some(handle) }49
public enum ToggleGroupSelection<T: Equals<T>> {50
Single(Binding<T?>), Multiple(Binding<Array<T>>)51
}53
internal fun <T: Equals<T>> choiceSelected(selection: ToggleGroupSelection<T>, value: T): Boolean =54
when (selection) {55
case Single(val binding) -> binding.value == Some(value)56
case Multiple(val binding) -> {57
var found = false58
for (entry in binding.value)59
if (entry == value)60
found = true61
found62
}63
}65
internal fun <T: Equals<T>> setChoice(66
selection: ToggleGroupSelection<T>,67
value: T,68
selected: Boolean69
) {70
when (selection) {71
case Single(val binding) -> if (selected)72
binding.value = Some(value)73
else74
if (binding.value == Some(value))75
binding.value = None76
case Multiple(val binding) -> {77
val entries = ArrayList<T>()78
var found = false79
for (entry in binding.value) {80
if (entry == value) {81
found = true82
if (selected)83
entries.add(entry)84
} else85
entries.add(entry)86
}87
if (selected && !found)88
entries.add(value)89
binding.value = entries.toArray()90
}91
}92
}