Scoop API

scoop:scoop.ui.component:0.1.0

src/layout/flex_allocation.scoop

Selected production source · src/layout/flex_allocation.scoop

1package scoop.ui.component
3/** Distributes only remaining space and freezes each reached bound once. */
4internal fun allocateFlex(
5 bases: Array<Double>,
6 options: Array<FlexItemOptions>,
7 target: Double
8): Array<Double> {
9 nonnegative(target, "invalid flex allocation")
10 val values =
11 MutableArray<Double>(bases.size) { index -> flexClamp(bases[index], options[index]) }
12 val frozen = MutableArray<Boolean>(bases.size) { _ -> false }
13 var total = 0.0
14 for (value in values)
15 total += value
16 nonnegative(total, "flex extents overflow")
17 val growing = target >= total
18 var largestWeight = 0.0
19 var largestBasis = 0.0
20 for (index in 0L ..< bases.size) {
21 val value = options[index]
22 largestWeight =
23 lowerBound(
24 largestWeight,
25 if (growing)
26 value.grow
27 else
28 value.shrink
29 )
30 largestBasis = lowerBound(largestBasis, bases[index])
31 }
32 if (largestWeight == 0.0 || (!growing && largestBasis == 0.0))
33 return Array(values.size) { index -> values[index] }
34 val weightScale = largestWeight
35 val basisScale = largestBasis
36 val weights =
37 Array<Double>(bases.size) {
38 index ->
39 val value = options[index]
40 if (growing)
41 value.grow / weightScale
42 else
43 (value.shrink / weightScale) * (bases[index] / basisScale)
44 }
45 while (true) {
46 var weight = 0.0
47 total = 0.0
48 for (index in 0L ..< values.size) {
49 total += values[index]
50 if (!frozen[index])
51 weight += weights[index]
52 }
53 val remaining = target - total
54 if (weight == 0.0 || remaining == 0.0)
55 break
56 var limited = false
57 for (index in 0L ..< values.size) {
58 if (frozen[index] || weights[index] == 0.0)
59 continue
60 val proposed = values[index] + remaining * (weights[index] / weight)
61 val accepted = flexClamp(proposed, options[index])
62 values[index] = accepted
63 if (accepted != proposed) {
64 frozen[index] = true
65 limited = true
66 }
67 }
68 if (!limited)
69 break
70 }
71 return Array(values.size) { index -> values[index] }
74internal fun flexClamp(value: Double, options: FlexItemOptions): Double {
75 val lower = lowerBound(value, options.min)
76 return when (options.max) {
77 case Some(val upper) -> upperBound(lower, upper)
78 case None -> lower
79 }