Scoop API

scoop:scoop.ui.component:0.1.0

src/choice/choice.scoop

Selected production source · src/choice/choice.scoop

1package scoop.ui.component
3import scoop.ui.*
5/** Ordered domain metadata shared by choice controls. */
6public 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 = true
13internal 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 }
23private class ChoiceHandle(val key: ViewKey, val handle: FocusHandle)
25/** Retains only handles for the current keyed items; it owns no focus registration. */
26internal 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? = None
34 for (entry in entries)
35 if (entry.key == key)
36 previous = Some(entry.handle)
37 ChoiceHandle(key, previous ?: FocusHandle())
38 }
39 entries = next
40 return Array<FocusHandle>(next.size) {
41 index -> options[index].handle ?: next[index].handle
42 }
43 }
46internal fun choiceFocus(options: FocusOptions, handle: FocusHandle): FocusOptions =
47 options.copy { this.handle = Some(handle) }
49public enum ToggleGroupSelection<T: Equals<T>> {
50 Single(Binding<T?>), Multiple(Binding<Array<T>>)
53internal 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 = false
58 for (entry in binding.value)
59 if (entry == value)
60 found = true
61 found
62 }
63 }
65internal fun <T: Equals<T>> setChoice(
66 selection: ToggleGroupSelection<T>,
67 value: T,
68 selected: Boolean
69) {
70 when (selection) {
71 case Single(val binding) -> if (selected)
72 binding.value = Some(value)
73 else
74 if (binding.value == Some(value))
75 binding.value = None
76 case Multiple(val binding) -> {
77 val entries = ArrayList<T>()
78 var found = false
79 for (entry in binding.value) {
80 if (entry == value) {
81 found = true
82 if (selected)
83 entries.add(entry)
84 } else
85 entries.add(entry)
86 }
87 if (selected && !found)
88 entries.add(value)
89 binding.value = entries.toArray()
90 }
91 }