Scoop API

scoop:scoop.ui.component:0.1.0

src/tree/state.scoop

Selected production source · src/tree/state.scoop

1package scoop.ui.component
3import scoop.ui.*
5/** Application-owned tree state; bindings remain the only truth for controlled values. */
6public class TreeState<T> public constructor(
7 data: TreeData<T>,
8 columns: TreeColumns<T>? = None,
9 public val selection: TreeSelectionMode = TreeSelectionMode.Single,
10 public val checking: TreeChecking = TreeChecking.Off,
11 initialExpandedKeys: Array<ViewKey> = [],
12 initialSelectedKeys: Array<ViewKey> = [],
13 initialExpandAll: Boolean = false,
14 initialExpandParent: Boolean = true,
15 expanded: Binding<Array<ViewKey>>? = None,
16 selected: Binding<Array<ViewKey>>? = None,
17 initialQuery: TreeQuery<T> = TreeQuery<T>(),
18 query: Binding<TreeQuery<T>>? = None,
19 columnState: Binding<TreeColumnState<T>>? = None,
20 private val onExpand: (TreeKeyChange<T>) -> Unit = { _ -> },
21 private val onSelect: (TreeKeyChange<T>) -> Unit = { _ -> },
22 onCheck: (TreeCheckChange<T>) -> Unit = { _ -> },
23 onColumnsChange: (TreeColumnChange<T>) -> Unit = { _ -> },
24 loader: TreeLoader<T>? = None,
25 onLoad: (TreeLoadEvent<T>) -> Unit = { _ -> },
26 onLoadError: (TreeLoadError<T>) -> Unit = { _ -> }
27) : Closeable {
28 private val dataStore = state(data)
29 private val expansion = expanded ?:
30 state(
31 treeInitialExpansion(data, initialExpandedKeys, initialExpandAll, initialExpandParent)
32 )
33 .binding()
34 private val choice = selected ?:
35 state(treeSelectionKeys(initialSelectedKeys, selection)).binding()
36 private val queryInput = query ?: state(initialQuery).binding()
37 private val columnModel = TreeColumnModel(
38 columnState ?: state(TreeColumnState(columns)).binding(),
39 { dataStore.checkMutation() }, onColumnsChange
40 )
41 private val checks = TreeChecks(
42 checking,
43 { dataStore.value },
44 { dataStore.checkMutation() },
45 onCheck
46 )
47 private val loading = TreeLoading(
48 loader, { dataStore.value }, { next -> replaceData(next) },
49 { dataStore.checkMutation() }, onLoad, onLoadError
50 )
51 private val range = TreeRangeSelection()
52 private var expandedMemo: TreeKeySnapshot? = None
53 private var selectedMemo: TreeKeySnapshot? = None
54 private var orderMemo: TreeOrder<T>? = None
55 private var matchMemo: TreeMatches<T>? = None
56 private var projectionMemo: TreeProjectionCache<T>? = None
58 init {
59 treeUniqueKeys(expansion.value)
60 treeSelectionKeys(choice.value, selection)
61 }
63 public val data: TreeData<T> get() = dataStore.value
64 public val expandedKeys: Array<ViewKey> get() = expandedSnapshot().unique
65 public val selectedKeys: Array<ViewKey> get() = selectedSnapshot().unique
66 public val query: TreeQuery<T> get() = queryInput.value
67 public val columnState: TreeColumnState<T> get() = columnModel.value
68 public val columns: TreeColumns<T>? get() = columnState.columns
69 public val visibleColumns: Array<TreeColumn<T>> get() = columnState.visibleColumns
70 public val sort: TableSort? get() = columnState.sorting
71 public val checkedKeys: Array<ViewKey> get() = checks.value.checkedKeys
72 public val halfCheckedKeys: Array<ViewKey> get() = checks.value.halfCheckedKeys
73 public val checkValue: TreeCheckValue get() = checks.value
74 public val loader: TreeLoader<T>? get() = loading.loader
75 public val loadingKeys: Array<ViewKey> get() = loading.loadingKeys
76 public val loadedKeys: Array<ViewKey> get() = data.loadedKeys
77 public fun loadStatus(key: ViewKey): TreeLoadStatus = loading.status(key)
78 public fun setLoader(value: TreeLoader<T>?) {
79 loading.setLoader(value)
80 synchronizeLoading()
81 }
82 public fun loadChildren(key: ViewKey): Boolean = loading.start(key, false)
83 public fun retryLoad(key: ViewKey): Boolean = loading.start(key, true)
84 public fun cancelLoad(key: ViewKey): Boolean = loading.cancel(key)
85 public override fun close() {
86 loading.close()
87 }
88 internal fun synchronizeLoading(interactive: Boolean = false) {
89 loading.synchronize(expandedKeys, interactive)
90 }
91 public fun dropTarget(
92 source: ViewKey,
93 target: ViewKey,
94 position: TreeDropPosition
95 ): TreeDrop<T>? = treeDrop(data, source, target, position, sort != None)
97 /** Replaces loaded data without pruning application-owned expansion, selection or check keys. */
98 public fun replaceData(value: TreeData<T>) {
99 dataStore.checkMutation()
100 if (dataStore.value !== value) {
101 loading.reconcile(value)
102 dataStore.value = value
103 }
104 }
105 public fun pathTo(key: ViewKey): Array<ViewKey>? = data.pathTo(key)
106 public fun isExpanded(key: ViewKey): Boolean = expandedSnapshot().lookup.contains(key)
107 public fun isSelected(key: ViewKey): Boolean = selectedSnapshot().lookup.contains(key)
108 public fun checkState(key: ViewKey): CheckState = checks.state(key)
109 public fun setQuery(value: TreeQuery<T>): Boolean {
110 dataStore.checkMutation()
111 if (queryInput.value !== value) queryInput.value = value
112 return queryInput.value === value
113 }
115 /** Restores expansion keys, optionally adding known ancestors for this update only. */
116 public fun setExpanded(
117 keys: Array<ViewKey>,
118 expandAncestors: Boolean = false,
119 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
120 ): Boolean {
121 dataStore.checkMutation()
122 return writeExpansion(treeExpandedAncestors(data, keys, expandAncestors), None, origin)
123 }
125 /** Changes an enabled branch and reports whether the controlled binding accepted its state. */
126 public fun setExpanded(
127 key: ViewKey,
128 expanded: Boolean,
129 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
130 ): Boolean {
131 dataStore.checkMutation()
132 val node = data.node(key) ?: return false
133 if (!node.enabled || !node.expandable) return false
134 if (isExpanded(key) == expanded) return true
135 val next = treeChangedKey(expandedKeys, key, expanded)
136 writeExpansion(next, Some(key), origin)
137 return isExpanded(key) == expanded
138 }
139 public fun setSelected(
140 keys: Array<ViewKey>,
141 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
142 ): Boolean {
143 dataStore.checkMutation()
144 val result = writeSelection(keys, None, origin)
145 range.reset()
146 return result
147 }
148 /** Applies a selection gesture in projected row order; focus is only a fallback range anchor. */
149 public fun select(
150 key: ViewKey,
151 action: TreeSelectionAction = TreeSelectionAction.Replace,
152 focused: ViewKey? = None,
153 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
154 ): Boolean {
155 dataStore.checkMutation()
156 val node = data.node(key) ?: return false
157 if (selection == TreeSelectionMode.None || !node.canSelect) return false
158 if ((action == TreeSelectionAction.Range || action == TreeSelectionAction.AddRange) &&
159 projection.indexOfKey(key) ==
160 None
161 )
162 return false
163 val current = selectedKeys
164 val plan = range
165 .plan(
166 projection, current, key,
167 if (selection == TreeSelectionMode.Single && action != TreeSelectionAction.Toggle)
168 TreeSelectionAction.Replace
169 else
170 action,
171 focused,
172 selection
173 )
174 val accepted = writeSelection(plan.keys, Some(key), origin)
175 if (accepted) range.accept(plan, selectedKeys)
176 return accepted
177 }
178 public fun setChecked(
179 key: ViewKey,
180 value: Boolean,
181 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
182 ): Boolean = checks.set(key, value, origin)
183 /** Restores cascade intents. Use setChecks for independent checked and mixed values. */
184 public fun setCheckedKeys(
185 keys: Array<ViewKey>,
186 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
187 ): Boolean = checks.replaceCascade(keys, origin)
188 /** Replaces the complete independent check value; cascade mode derives mixed ancestors itself. */
189 public fun setChecks(
190 value: TreeCheckValue,
191 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
192 ): Boolean = checks.replaceIndependent(value, origin)
194 /** Atomically replaces column definitions and retains valid state by id; None restores implicit columns. */
195 public fun replaceColumns(
196 columns: TreeColumns<T>?,
197 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
198 ): Boolean = columnModel.replace(columns, origin)
199 public fun setColumnVisible(
200 id: String,
201 visible: Boolean,
202 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
203 ): Boolean = columnModel.show(id, visible, origin)
204 /** Constrains a logical width to the column's bounds; a controlled binding may reject it. */
205 public fun resizeColumn(
206 id: String,
207 width: Double,
208 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
209 ): Boolean = columnModel.resize(id, Some(width), origin)
210 public fun resetColumnWidth(
211 id: String,
212 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
213 ): Boolean = columnModel.resize(id, None, origin)
214 public fun setSort(
215 value: TableSort?,
216 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
217 ): Boolean = columnModel.sort(value, origin)
218 public fun toggleSort(
219 id: String,
220 origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic
221 ): Boolean = columnModel.toggleSort(id, origin)
223 /** Memoized visible rows. Selection, checking, visibility and width changes preserve this snapshot. */
224 public val projection: TreeProjection<T>
225 get() {
226 val current = data
227 val expansion = expandedSnapshot()
228 val columnState = this.columnState
229 val definition = columnState.columns
230 var order = orderMemo
231 val sameOrder = when (order) {
232 case Some(val old) -> {
233 val sameDefinition = when ((old.definition, definition)) {
234 case(Some(val a), Some(val b)) -> a === b
235 case(None, None) -> true
236 else -> false
237 }
238 old.data === current && sameDefinition && old.sorting == columnState.sorting
239 }
241 case None -> false
242 }
243 if (!sameOrder) {
244 order = Some(TreeOrder(current, definition, columnState.sorting))
245 orderMemo = order
246 }
247 val query = this.query
248 var matches = matchMemo
249 val sameMatches = when (matches) {
250 case Some(val old) -> old.data === current && old.query === query
251 case None -> false
252 }
253 if (!sameMatches) {
254 matches = Some(TreeMatches(current, query))
255 matchMemo = matches
256 }
257 when (projectionMemo) {
258 case Some(val previous) ->
259 if (previous.order ===
260 order!! &&
261 previous.matches ===
262 matches!! &&
263 previous.expanded ===
264 expansion
265 )
266 return previous.projection
267 case None -> {}
268 }
269 val result = TreeProjectionCache(order!!, matches!!, expansion)
270 projectionMemo = Some(result)
271 return result.projection
272 }
274 private fun expandedSnapshot(): TreeKeySnapshot {
275 val keys = expansion.value
276 when (expandedMemo) {
277 case Some(val old) -> if (old.keys === keys) return old
278 case None -> {}
279 }
280 val result = TreeKeySnapshot(keys)
281 expandedMemo = Some(result)
282 return result
283 }
284 private fun selectedSnapshot(): TreeKeySnapshot {
285 val keys = choice.value
286 when (selectedMemo) {
287 case Some(val old) -> if (old.keys === keys) return old
288 case None -> {}
289 }
290 treeSelectionKeys(keys, selection)
291 val result = TreeKeySnapshot(keys)
292 selectedMemo = Some(result)
293 return result
294 }
295 private fun writeExpansion(
296 keys: Array<ViewKey>,
297 key: ViewKey?,
298 origin: TreeChangeOrigin
299 ): Boolean {
300 dataStore.checkMutation()
301 val before = expandedKeys
302 if (treeKeysEqual(before, keys)) {
303 synchronizeLoading()
304 return true
305 }
306 expansion.value = keys
307 val actual = expandedKeys
308 if (!treeKeysEqual(before, actual))
309 onExpand(TreeKeyChange(key, nodeAt(key), actual, origin))
310 synchronizeLoading()
311 return treeKeysEqual(actual, keys)
312 }
313 private fun writeSelection(
314 keys: Array<ViewKey>,
315 key: ViewKey?,
316 origin: TreeChangeOrigin
317 ): Boolean {
318 val next = treeSelectionKeys(keys, selection)
319 val before = selectedKeys
320 if (treeKeysEqual(before, next)) return true
321 choice.value = next
322 val actual = selectedKeys
323 if (!treeKeysEqual(before, actual))
324 onSelect(TreeKeyChange(key, nodeAt(key), actual, origin))
325 return treeKeysEqual(actual, next)
326 }
327 private fun nodeAt(key: ViewKey?): TreeNode<T>? = when (key) {
328 case Some(val value) -> data.node(value)
329 case None -> None
330 }
333internal fun treeSelectionKeys(keys: Array<ViewKey>, mode: TreeSelectionMode): Array<ViewKey> {
334 val unique = treeUniqueKeys(keys)
335 requireComponent(
336 mode != TreeSelectionMode.Single || unique.size <= 1L,
337 "single tree selection accepts at most one key"
338 )
339 return unique
342internal fun treeChangedKey(keys: Array<ViewKey>, key: ViewKey, included: Boolean): Array<ViewKey> {
343 val result = ArrayList<ViewKey>()
344 for (value in keys)
345 if (value != key) result.add(value)
346 if (included) result.add(key)
347 return result.toArray()