scoop:scoop.ui.component:0.1.0
src/tree/state.scoop
Selected production source · src/tree/state.scoop
1
package scoop.ui.component3
import scoop.ui.*5
/** Application-owned tree state; bindings remain the only truth for controlled values. */6
public 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() }, onColumnsChange40
)41
private val checks = TreeChecks(42
checking,43
{ dataStore.value },44
{ dataStore.checkMutation() },45
onCheck46
)47
private val loading = TreeLoading(48
loader, { dataStore.value }, { next -> replaceData(next) },49
{ dataStore.checkMutation() }, onLoad, onLoadError50
)51
private val range = TreeRangeSelection()52
private var expandedMemo: TreeKeySnapshot? = None53
private var selectedMemo: TreeKeySnapshot? = None54
private var orderMemo: TreeOrder<T>? = None55
private var matchMemo: TreeMatches<T>? = None56
private var projectionMemo: TreeProjectionCache<T>? = None58
init {59
treeUniqueKeys(expansion.value)60
treeSelectionKeys(choice.value, selection)61
}63
public val data: TreeData<T> get() = dataStore.value64
public val expandedKeys: Array<ViewKey> get() = expandedSnapshot().unique65
public val selectedKeys: Array<ViewKey> get() = selectedSnapshot().unique66
public val query: TreeQuery<T> get() = queryInput.value67
public val columnState: TreeColumnState<T> get() = columnModel.value68
public val columns: TreeColumns<T>? get() = columnState.columns69
public val visibleColumns: Array<TreeColumn<T>> get() = columnState.visibleColumns70
public val sort: TableSort? get() = columnState.sorting71
public val checkedKeys: Array<ViewKey> get() = checks.value.checkedKeys72
public val halfCheckedKeys: Array<ViewKey> get() = checks.value.halfCheckedKeys73
public val checkValue: TreeCheckValue get() = checks.value74
public val loader: TreeLoader<T>? get() = loading.loader75
public val loadingKeys: Array<ViewKey> get() = loading.loadingKeys76
public val loadedKeys: Array<ViewKey> get() = data.loadedKeys77
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: TreeDropPosition95
): 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 = value103
}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 = value112
return queryInput.value === value113
}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.Programmatic120
): 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.Programmatic130
): Boolean {131
dataStore.checkMutation()132
val node = data.node(key) ?: return false133
if (!node.enabled || !node.expandable) return false134
if (isExpanded(key) == expanded) return true135
val next = treeChangedKey(expandedKeys, key, expanded)136
writeExpansion(next, Some(key), origin)137
return isExpanded(key) == expanded138
}139
public fun setSelected(140
keys: Array<ViewKey>,141
origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic142
): Boolean {143
dataStore.checkMutation()144
val result = writeSelection(keys, None, origin)145
range.reset()146
return result147
}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.Programmatic154
): Boolean {155
dataStore.checkMutation()156
val node = data.node(key) ?: return false157
if (selection == TreeSelectionMode.None || !node.canSelect) return false158
if ((action == TreeSelectionAction.Range || action == TreeSelectionAction.AddRange) &&159
projection.indexOfKey(key) ==160
None161
)162
return false163
val current = selectedKeys164
val plan = range165
.plan(166
projection, current, key,167
if (selection == TreeSelectionMode.Single && action != TreeSelectionAction.Toggle)168
TreeSelectionAction.Replace169
else170
action,171
focused,172
selection173
)174
val accepted = writeSelection(plan.keys, Some(key), origin)175
if (accepted) range.accept(plan, selectedKeys)176
return accepted177
}178
public fun setChecked(179
key: ViewKey,180
value: Boolean,181
origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic182
): 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.Programmatic187
): 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.Programmatic192
): 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.Programmatic198
): Boolean = columnModel.replace(columns, origin)199
public fun setColumnVisible(200
id: String,201
visible: Boolean,202
origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic203
): 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.Programmatic209
): Boolean = columnModel.resize(id, Some(width), origin)210
public fun resetColumnWidth(211
id: String,212
origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic213
): Boolean = columnModel.resize(id, None, origin)214
public fun setSort(215
value: TableSort?,216
origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic217
): Boolean = columnModel.sort(value, origin)218
public fun toggleSort(219
id: String,220
origin: TreeChangeOrigin = TreeChangeOrigin.Programmatic221
): 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 = data227
val expansion = expandedSnapshot()228
val columnState = this.columnState229
val definition = columnState.columns230
var order = orderMemo231
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 === b235
case(None, None) -> true236
else -> false237
}238
old.data === current && sameDefinition && old.sorting == columnState.sorting239
}241
case None -> false242
}243
if (!sameOrder) {244
order = Some(TreeOrder(current, definition, columnState.sorting))245
orderMemo = order246
}247
val query = this.query248
var matches = matchMemo249
val sameMatches = when (matches) {250
case Some(val old) -> old.data === current && old.query === query251
case None -> false252
}253
if (!sameMatches) {254
matches = Some(TreeMatches(current, query))255
matchMemo = matches256
}257
when (projectionMemo) {258
case Some(val previous) ->259
if (previous.order ===260
order!! &&261
previous.matches ===262
matches!! &&263
previous.expanded ===264
expansion265
)266
return previous.projection267
case None -> {}268
}269
val result = TreeProjectionCache(order!!, matches!!, expansion)270
projectionMemo = Some(result)271
return result.projection272
}274
private fun expandedSnapshot(): TreeKeySnapshot {275
val keys = expansion.value276
when (expandedMemo) {277
case Some(val old) -> if (old.keys === keys) return old278
case None -> {}279
}280
val result = TreeKeySnapshot(keys)281
expandedMemo = Some(result)282
return result283
}284
private fun selectedSnapshot(): TreeKeySnapshot {285
val keys = choice.value286
when (selectedMemo) {287
case Some(val old) -> if (old.keys === keys) return old288
case None -> {}289
}290
treeSelectionKeys(keys, selection)291
val result = TreeKeySnapshot(keys)292
selectedMemo = Some(result)293
return result294
}295
private fun writeExpansion(296
keys: Array<ViewKey>,297
key: ViewKey?,298
origin: TreeChangeOrigin299
): Boolean {300
dataStore.checkMutation()301
val before = expandedKeys302
if (treeKeysEqual(before, keys)) {303
synchronizeLoading()304
return true305
}306
expansion.value = keys307
val actual = expandedKeys308
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: TreeChangeOrigin317
): Boolean {318
val next = treeSelectionKeys(keys, selection)319
val before = selectedKeys320
if (treeKeysEqual(before, next)) return true321
choice.value = next322
val actual = selectedKeys323
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 -> None330
}331
}333
internal 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 unique340
}342
internal 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()348
}