scoop:scoop.ui:0.1.0
src/layout/input.scoop
Selected production source · src/layout/input.scoop
1
package scoop.ui3
/** An immutable input snapshot supplied only while a child subtree is measured. */4
public class LayoutInput<T> public constructor(internal val value: T) {5
private var environment: LayoutEnvironment? = None7
internal fun environmentFor(parent: LayoutEnvironment?): LayoutEnvironment {8
when (environment) {9
case Some(val previous) -> if (sameLayoutEnvironment(previous.parent, parent))10
return previous11
case None -> {}12
}13
val next = LayoutEnvironment(parent)14
environment = Some(next)15
return next16
}17
}19
/** Identity includes the enclosing input, without retaining a history of combinations. */20
internal class LayoutEnvironment(val parent: LayoutEnvironment?)22
internal fun currentLayoutEnvironment(): LayoutEnvironment? = contextOrNone<LayoutEnvironment>()24
internal fun sameLayoutEnvironment(left: LayoutEnvironment?, right: LayoutEnvironment?): Boolean =25
when (left) {26
case Some(val value) -> when (right) {27
case Some(val other) -> value === other28
case None -> false29
}30
case None -> when (right) {31
case Some(_) -> false32
case None -> true33
}34
}36
internal fun checkLayoutInputAccess(node: MountedNode) {37
val evaluation =38
currentEvaluation() ?:39
throw IllegalStateException(Some("layout input requires the current measure context"))40
when (evaluation.measurement) {41
case Some(val current) -> if (current === node)42
return43
case None -> {}44
}45
throw IllegalStateException(Some("layout input requires the current measure context"))46
}48
internal fun <T> readLayoutInput(node: MountedNode): T {49
checkLayoutInputAccess(node)50
val input =51
contextOrNone<LayoutInput<T>>() ?:52
throw IllegalStateException(Some("layout input was not provided"))53
return input.value54
}56
internal fun <T, R> withLayoutInput(input: LayoutInput<T>, block: () -> R): R {57
val environment = input.environmentFor(currentLayoutEnvironment())58
context(environment) {59
context(input) {60
return block()61
}62
}63
}