Scoop API

scoop:scoop.ui:0.1.0

src/lazy/items.scoop

Selected production source · src/lazy/items.scoop

1package scoop.ui
3import scoop.collections.HashMap
4import scoop.collections.HashSet
5import scoop.collections.contains
6import scoop.collections.sortedBy
7import scoop.platform.time.MonotonicInstant
8import scoop.surface.FrameSubmission
10private class LazyItemInput(val source: ItemSource, val index: Long)
12/** Reuses ordinary render dependencies and keyed child reconciliation. */
13private class LazyItem(private val props: Props<LazyItemInput>, scope: ComponentScope): Component(
14 scope
15) {
16 public override fun render(): View = props.value.source.build(props.value.index)
19internal class LazyItemEntry(
20 val key: ViewKey,
21 var index: Long,
22 val node: MountedNode,
23 var lastUsed: MonotonicInstant
24) {
25 var selected = true
26 var semanticPins = 0
27 val pinned: Boolean get() =
28 node.active &&
29 (semanticPins > 0 || node.scope.hasInputActivity || node.root.focus.hasPendingIn(node))
32internal class LazyChildren(initial: ItemSource, private var capacity: Long) {
33 private var source = initial
34 private var total = itemCount(initial)
35 private var entries: Array<LazyItemEntry> = []
36 private val keyed = HashMap<ViewKey, LazyItemEntry>()
37 val count: Long get() = total
39 fun uses(value: ItemSource): Boolean = source === value
40 fun bindSemantics(parent: SemanticsHandle) {
41 for (entry in entries)
42 bindLazyItemSemantics(entry, parent)
43 }
44 fun unbindSemantics() {
45 for (entry in entries)
46 entry.node.semanticItem?.close()
47 }
49 fun keyAt(index: Long): ViewKey = checkedItemKey(source, total, index)
50 fun focusedEntry(): LazyItemEntry? {
51 for (entry in entries)
52 if (entry.node.active && entry.node.scope.input.activity.hasFocus)
53 return Some(entry)
54 return None
55 }
56 fun entryContaining(node: MountedNode): LazyItemEntry? {
57 for (entry in entries)
58 if (withinFocusScope(node, entry.node))
59 return Some(entry)
60 return None
61 }
62 fun entry(key: ViewKey): LazyItemEntry? = keyed[key]
63 fun indexOf(key: ViewKey): Long? {
64 when (keyed[key]) {
65 case Some(val entry) -> return Some(entry.index)
66 case None -> {}
67 }
68 return evaluateUi<Long?>(None) {
69 val index = source.indexOfKey(key) ?: return@evaluateUi None
70 requireUi(index >= 0L && index < total, "item reverse index is out of range")
71 requireUi(source.keyAt(index) == key, "item key mapping is inconsistent")
72 Some(index)
73 }
74 }
76 fun mount(node: MountedNode) {
77 node.scope.resource {
78 node.scope.input.observeActivity {
79 if (node.scope.isMounted)
80 node.scope.requestLayout()
81 }
82 }
83 }
84 fun replace(node: MountedNode, next: ItemSource, nextCapacity: Long, turn: UpdateTurn) {
85 if (capacity != nextCapacity || source !== next)
86 node.request(UiInvalidation.Layout)
87 capacity = nextCapacity
88 if (source === next) {
89 trim(node)
90 return
91 }
92 val nextCount = itemCount(next)
93 val positions = HashSet<Long>()
94 val keep = ArrayList<LazyItemEntry>()
95 evaluateUi<Unit>(None) {
96 for (entry in entries) {
97 when (next.indexOfKey(entry.key)) {
98 case Some(val index) -> {
99 requireUi(
100 index >= 0L && index < nextCount,
101 "item reverse index is out of range"
102 )
103 requireUi(
104 next.keyAt(index) == entry.key,
105 "item key mapping is inconsistent"
106 )
107 requireUi(positions.add(index), "item keys share a source index")
108 entry.index = index
109 keep.add(entry)
110 }
111 case None -> {}
112 }
113 }
114 }
115 retain(node, keep.toArray())
116 source = next
117 total = nextCount
118 node.lazyFocus?.sourceChanged()
119 trim(node)
120 if (!node.root.isOpen)
121 return
122 for (entry in entries) {
123 entry.node.replace(description(entry.index, entry.key))
124 entry.node.rebuild(turn)
125 }
126 }
127 fun prepare(node: MountedNode, index: Long, time: MonotonicInstant): LazyItemEntry {
128 val key = checkedItemKey(source, total, index)
129 when (keyed[key]) {
130 case Some(val entry) -> {
131 requireUi(entry.index == index, "duplicate item ViewKey")
132 entry.lastUsed = time
133 return entry
134 }
135 case None -> {}
136 }
137 val child = createNode(node.root, Some(node), description(index, key))
138 val entry = LazyItemEntry(key, index, child, time)
139 val previous = entries
140 entries =
141 Array<LazyItemEntry>(previous.size + 1L) {
142 position -> if (position < previous.size)
143 previous[position]
144 else
145 entry
146 }
147 keyed.put(key, entry)
148 // Keep the new mount reachable before any user render or lifecycle callback.
149 publishOrder(node)
150 when (node.lazySemantics) {
151 case Some(val parent) -> bindLazyItemSemantics(entry, parent)
152 case None -> {}
153 }
154 child.rebuild(UpdateTurn())
155 child.mountPending()
156 if (!node.root.isOpen)
157 throw UiLayoutEnded()
158 return entry
159 }
160 fun pinnedItems(node: MountedNode): Array<Long> {
161 val result = ArrayList<Long>()
162 for (entry in entries)
163 if (entry.pinned)
164 result.add(entry.index)
165 when (node.lazyFocus) {
166 case Some(val focus) -> when (focus.pendingIndex()) {
167 case Some(val index) -> if (!result.contains(index))
168 result.add(index)
169 case None -> {}
170 }
171 case None -> {}
172 }
173 return result.toArray()
174 }
175 fun finish(node: MountedNode, selection: Array<LazyLayoutItem>) {
176 val measured = HashMap<Long, LazyLayoutItem>()
177 for (item in selection)
178 measured.put(item.entry.index, item)
179 when (node.lazyFocus) {
180 case Some(val focus) -> when (focus.pendingIndex()) {
181 case Some(val index) -> if (!measured.containsKey(index))
182 throw IllegalStateException(
183 Some("a pending focus item must be measured and placed")
184 )
185 case None -> {}
186 }
187 case None -> {}
188 }
189 for (entry in entries) {
190 val result = measured[entry.index]
191 val placed = result?.placed ?: false
192 if (entry.pinned && !placed)
193 throw IllegalStateException(Some("an interaction item must be measured and placed"))
194 entry.selected =
195 when (result) {
196 case Some(_) -> true;
197 case None -> false
198 }
199 if (entry.node.participatesInFrame != placed)
200 node.root.addCompletion(entry.node) {
201 completion -> if (completion.submission == FrameSubmission.Accepted)
202 entry.node.setFrameParticipation(placed)
203 }
204 if (!placed)
205 entry.node.clearPaintSubtree()
206 }
207 prepareUi<Unit> { trim(node) }
208 if (!node.root.isOpen)
209 throw UiLayoutEnded()
210 }
211 private fun trim(node: MountedNode) {
212 val keep = ArrayList<LazyItemEntry>()
213 val idle = ArrayList<LazyItemEntry>()
214 for (entry in entries) {
215 if (entry.selected || entry.pinned)
216 keep.add(entry)
217 else
218 idle.add(entry)
219 }
220 if (idle.size <= capacity) {
221 for (entry in idle)
222 keep.add(entry)
223 } else
224 if (capacity > 0L) {
225 val ordered =
226 idle.sortedBy<LazyItemEntry, MonotonicInstant> { entry -> entry.lastUsed }
227 for (index in ordered.size - capacity ..< ordered.size)
228 keep.add(ordered[index])
229 }
230 retain(node, keep.toArray())
231 }
232 private fun description(index: Long, key: ViewKey): View =
233 component(
234 LazyItemInput(source, index),
235 { props, mount -> LazyItem(props, scope = mount) },
236 key
237 )
238 private fun publishOrder(node: MountedNode) {
239 entries = entries.sortedBy<LazyItemEntry, Long> { entry -> entry.index }.toArray()
240 var changed = node.children.size != entries.size
241 if (!changed)
242 for (index in 0L ..< entries.size)
243 if (node.children[index] !== entries[index].node)
244 changed = true
245 node.children = Array(entries.size) { index -> entries[index].node }
246 if (changed)
247 node.root.semantics?.structureChanged()
248 }
249 private fun retain(node: MountedNode, keep: Array<LazyItemEntry>) {
250 val previous = entries
251 entries = keep
252 keyed.clear()
253 for (entry in entries)
254 keyed.put(entry.key, entry)
255 publishOrder(node)
256 var failure: Throwable? = None
257 // Retire every removed route before invoking any unmount callback.
258 for (entry in previous)
259 if (!keyed.containsKey(entry.key))
260 failure = cleanupUi(failure) { entry.node.deactivate() }
261 for (entry in previous)
262 if (!keyed.containsKey(entry.key))
263 failure = cleanupUi(failure) { entry.node.unmount() }
264 throwUi(failure)
265 }
268private fun itemCount(source: ItemSource): Long =
269 evaluateUi<Long>(None) {
270 val count = source.count
271 requireUi(count >= 0L, "negative item count")
272 count
273 }
275internal fun checkedItemKey(source: ItemSource, count: Long, index: Long): ViewKey =
276 evaluateUi<ViewKey>(None) {
277 requireUi(index >= 0L && index < count, "item index is out of range")
278 val key = source.keyAt(index)
279 requireUi(key != ViewKey.Position, "lazy items require explicit ViewKeys")
280 requireUi(source.indexOfKey(key) == Some(index), "item key mapping is inconsistent")
281 key
282 }