scoop:scoop.ui:0.1.0
src/state/state.scoop
Selected production source · src/state/state.scoop
1
package scoop.ui3
import scoop.platform.concurrent.currentThreadId5
/** Owner-thread observable storage, independent of any single mounted component. */6
public class State<T> internal constructor(initial: T) {7
private val thread = currentThreadId()8
private var current = initial9
private val signal = StateSignal()11
public var value: T12
get() {13
checkUiThread(thread)14
when (currentEvaluation()) {15
case Some(val evaluation) -> evaluation.collector?.read(signal)16
case None -> {}17
}18
return current19
}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 = value39
signal.changed()40
}42
public operator fun getValue(thisRef: Any): T = value43
public operator fun setValue(thisRef: Any, value: T) {44
this.value = value45
}46
public fun binding(): Binding<T> = binding(get = { value }, set = { next -> value = next })47
}49
public 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. */52
public class Binding<T> internal constructor(53
private val read: () -> T,54
private val write: (T) -> Unit55
) {56
public var value: T57
get() = read()58
set(value) {59
write(value)60
}61
}63
public 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. */66
public class InputComparison<P> public constructor(internal val equivalent: (P, P) -> Boolean)68
/** The latest parent input, replaced even when the input comparison skips evaluation. */69
public class Props<P> internal constructor(initial: P, comparison: InputComparison<P>? = None) {70
private val thread = currentThreadId()71
private var current = initial72
private var comparison = comparison73
public val value: P get() {74
checkUiThread(thread)75
return current76
}77
internal fun replace(next: P, rule: InputComparison<P>? = None): Boolean {78
checkUiThread(thread)79
val previous = current80
val previousRule = comparison81
current = next82
comparison = rule83
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 -> false88
}89
}90
}