Scoop API

scoop:scoop.ui:0.1.0

src/state/state.scoop

Selected production source · src/state/state.scoop

1package scoop.ui
3import scoop.platform.concurrent.currentThreadId
5/** Owner-thread observable storage, independent of any single mounted component. */
6public class State<T> internal constructor(initial: T) {
7 private val thread = currentThreadId()
8 private var current = initial
9 private val signal = StateSignal()
11 public var value: T
12 get() {
13 checkUiThread(thread)
14 when (currentEvaluation()) {
15 case Some(val evaluation) -> evaluation.collector?.read(signal)
16 case None -> {}
17 }
18 return current
19 }
20 set(value) {
21 checkMutation()
22 publish(value)
23 }
25 /** Checks the owner and evaluation phase before mutating an external model; has no state effects. */
26 public fun checkMutation() {
27 checkUiThread(thread)
28 when (currentEvaluation()) {
29 case Some(_) -> throw IllegalStateException(
30 Some("State cannot change during render, measure, scene or draw")
31 )
32 case None -> {}
33 }
34 }
36 /** Publishes a synchronous transaction whose caller already passed checkMutation. */
37 internal fun publish(value: T) {
38 current = value
39 signal.changed()
40 }
42 public operator fun getValue(thisRef: Any): T = value
43 public operator fun setValue(thisRef: Any, value: T) {
44 this.value = value
45 }
46 public fun binding(): Binding<T> = binding(get = { value }, set = { next -> value = next })
49public fun <T> state(initial: T): State<T> = State(initial)
51/** Explicit access to a current value; it does not create a second copy of that value. */
52public class Binding<T> internal constructor(
53 private val read: () -> T,
54 private val write: (T) -> Unit
55) {
56 public var value: T
57 get() = read()
58 set(value) {
59 write(value)
60 }
63public fun <T> binding(get: () -> T, set: (T) -> Unit): Binding<T> = Binding(get, set)
65/** An explicit, stable rule for comparing inputs consumed by render or update. */
66public class InputComparison<P> public constructor(internal val equivalent: (P, P) -> Boolean)
68/** The latest parent input, replaced even when the input comparison skips evaluation. */
69public class Props<P> internal constructor(initial: P, comparison: InputComparison<P>? = None) {
70 private val thread = currentThreadId()
71 private var current = initial
72 private var comparison = comparison
73 public val value: P get() {
74 checkUiThread(thread)
75 return current
76 }
77 internal fun replace(next: P, rule: InputComparison<P>? = None): Boolean {
78 checkUiThread(thread)
79 val previous = current
80 val previousRule = comparison
81 current = next
82 comparison = rule
83 return when ((previousRule, rule)) {
84 case(Some(val before), Some(val after)) -> before ===
85 after &&
86 evaluateUi<Boolean>(None) { after.equivalent(previous, next) }
87 else -> false
88 }
89 }