-
Notifications
You must be signed in to change notification settings - Fork 19
/
AuroraComboBox.kt
491 lines (450 loc) · 21 KB
/
AuroraComboBox.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*
* Copyright 2020-2022 Aurora, Kirill Grouchnikov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pushingpixels.aurora.component
import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.ClipOp
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.OnGloballyPositionedModifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFontLoader
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.text.resolveDefaults
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import org.pushingpixels.aurora.common.AuroraInternalApi
import org.pushingpixels.aurora.common.withAlpha
import org.pushingpixels.aurora.component.model.*
import org.pushingpixels.aurora.component.utils.*
import org.pushingpixels.aurora.theming.*
import org.pushingpixels.aurora.theming.utils.MutableColorScheme
import kotlin.math.max
@Immutable
private class ComboBoxDrawingCache(
val colorScheme: MutableColorScheme = MutableColorScheme(
displayName = "Internal mutable",
isDark = false
)
)
private class ComboBoxLocator(val topLeftOffset: AuroraOffset, val size: AuroraSize) :
OnGloballyPositionedModifier {
override fun onGloballyPositioned(coordinates: LayoutCoordinates) {
// Convert the top left corner of the component to the root coordinates
val converted = coordinates.localToRoot(Offset.Zero)
topLeftOffset.x = converted.x
topLeftOffset.y = converted.y
// And store the component size
size.width = coordinates.size.width
size.height = coordinates.size.height
}
}
@Composable
private fun Modifier.comboBoxLocator(topLeftOffset: AuroraOffset, size: AuroraSize) = this.then(
ComboBoxLocator(topLeftOffset, size)
)
@OptIn(ExperimentalComposeUiApi::class, ExperimentalComposeApi::class, AuroraInternalApi::class)
@Composable
internal fun <E> AuroraComboBox(
modifier: Modifier,
interactionSource: MutableInteractionSource,
contentModel: ComboBoxContentModel<E>,
presentationModel: ComboBoxPresentationModel<E>
) {
val drawingCache = remember { ComboBoxDrawingCache() }
val rollover by interactionSource.collectIsHoveredAsState()
val isPressed by interactionSource.collectIsPressedAsState()
val currentState = remember {
mutableStateOf(
ComponentState.getState(
isEnabled = contentModel.enabled,
isRollover = rollover,
isSelected = false,
isPressed = isPressed
)
)
}
val decorationAreaType = AuroraSkin.decorationAreaType
val skinColors = AuroraSkin.colors
val painters = AuroraSkin.painters
val buttonShaper = AuroraSkin.buttonShaper
val window = LocalWindow.current
val comboBoxTopLeftOffset = AuroraOffset(0.0f, 0.0f)
val comboBoxSize = AuroraSize(0, 0)
val density = LocalDensity.current
val layoutDirection = LocalLayoutDirection.current
val textStyle = LocalTextStyle.current
val resourceLoader = LocalFontLoader.current
val resolvedTextStyle = remember { resolveDefaults(textStyle, layoutDirection) }
// Transition for the selection state
val selectionTransition = updateTransition(false)
val selectedFraction by selectionTransition.animateFloat(
transitionSpec = {
tween(durationMillis = AuroraSkin.animationConfig.regular)
}
) {
when (it) {
false -> 0.0f
true -> 1.0f
}
}
// Transition for the rollover state
val rolloverTransition = updateTransition(rollover)
val rolloverFraction by rolloverTransition.animateFloat(
transitionSpec = {
tween(durationMillis = AuroraSkin.animationConfig.regular)
}
) {
when (it) {
false -> 0.0f
true -> 1.0f
}
}
// Transition for the pressed state
val pressedTransition = updateTransition(isPressed)
val pressedFraction by pressedTransition.animateFloat(
transitionSpec = {
tween(durationMillis = AuroraSkin.animationConfig.regular)
}
) {
when (it) {
false -> 0.0f
true -> 1.0f
}
}
// Transition for the enabled state
val enabledTransition = updateTransition(contentModel.enabled)
val enabledFraction by enabledTransition.animateFloat(
transitionSpec = {
tween(durationMillis = AuroraSkin.animationConfig.regular)
}
) {
when (it) {
false -> 0.0f
true -> 1.0f
}
}
// TODO - figure out why the animations are not running without looking
// at the result (and how it looks like in the new animation APIs)
val totalFraction = selectedFraction + rolloverFraction +
pressedFraction + enabledFraction
val modelStateInfo = remember { ModelStateInfo(currentState.value) }
val transitionInfo = remember { mutableStateOf<TransitionInfo?>(null) }
StateTransitionTracker(
modelStateInfo = modelStateInfo,
currentState = currentState,
transitionInfo = transitionInfo,
enabled = contentModel.enabled,
selected = false,
rollover = rollover,
pressed = isPressed,
duration = AuroraSkin.animationConfig.regular
)
if (transitionInfo.value != null) {
LaunchedEffect(currentState.value) {
val transitionFloat = Animatable(transitionInfo.value!!.from)
val result = transitionFloat.animateTo(
targetValue = transitionInfo.value!!.to,
animationSpec = tween(durationMillis = transitionInfo.value!!.duration)
) {
modelStateInfo.updateActiveStates(value)
}
if (result.endReason == AnimationEndReason.Finished) {
modelStateInfo.updateActiveStates(1.0f)
modelStateInfo.clear(currentState.value)
}
}
}
val commandMenuContentModel = CommandMenuContentModel(
group = CommandGroup(
commands = contentModel.items.map {
Command(
text = presentationModel.displayConverter.invoke(it),
icon = presentationModel.displayIconConverter?.invoke(it),
isActionEnabled = true,
action = { contentModel.onTriggerItemSelectedChange.invoke(it) }
)
}
)
)
val contentModelState = rememberUpdatedState(commandMenuContentModel)
val compositionLocalContext by rememberUpdatedState(currentCompositionLocalContext)
Box(
modifier = modifier.auroraRichTooltip(
richTooltip = contentModel.richTooltip,
presentationModel = presentationModel.richTooltipPresentationModel
).clickable(
enabled = contentModel.enabled,
onClick = {
displayPopupContent(
currentWindow = window,
layoutDirection = layoutDirection,
density = density,
textStyle = resolvedTextStyle,
resourceLoader = resourceLoader,
skinColors = skinColors,
skinPainters = painters,
decorationAreaType = decorationAreaType,
compositionLocalContext = compositionLocalContext,
anchorBoundsInWindow = Rect(
offset = comboBoxTopLeftOffset.asOffset(density),
size = comboBoxSize.asSize(density)
),
contentModel = contentModelState,
presentationModel = CommandPopupMenuPresentationModel(
menuPresentationState = DefaultCommandPopupMenuPresentationState,
maxVisibleMenuCommands = presentationModel.popupMaxVisibleItems,
popupPlacementStrategy = presentationModel.popupPlacementStrategy
),
toDismissPopupsOnActivation = true,
toUseBackgroundStriping = true,
popupPlacementStrategy = presentationModel.popupPlacementStrategy,
overlays = emptyMap()
)
},
interactionSource = interactionSource,
indication = null
).comboBoxLocator(comboBoxTopLeftOffset, comboBoxSize),
contentAlignment = Alignment.TopStart
) {
// Compute the text color
val textColor = getTextColor(
modelStateInfo = modelStateInfo,
currState = currentState.value,
skinColors = skinColors,
decorationAreaType = decorationAreaType,
colorSchemeAssociationKind = ColorSchemeAssociationKind.Fill,
isTextInFilledArea = true
)
// And the arrow color
val arrowColor = getStateAwareColor(
modelStateInfo, currentState.value,
decorationAreaType, ColorSchemeAssociationKind.Mark
) { it.markColor }
if (presentationModel.backgroundAppearanceStrategy != BackgroundAppearanceStrategy.Never) {
// Populate the cached color scheme for filling the combobox
// based on the current model state info
populateColorScheme(
drawingCache.colorScheme, modelStateInfo, currentState.value, decorationAreaType,
ColorSchemeAssociationKind.Fill
)
// And retrieve the container fill colors
val fillUltraLight = drawingCache.colorScheme.ultraLightColor
val fillExtraLight = drawingCache.colorScheme.extraLightColor
val fillLight = drawingCache.colorScheme.lightColor
val fillMid = drawingCache.colorScheme.midColor
val fillDark = drawingCache.colorScheme.darkColor
val fillUltraDark = drawingCache.colorScheme.ultraDarkColor
val fillIsDark = drawingCache.colorScheme.isDark
// Populate the cached color scheme for drawing the border
// based on the current model state info
populateColorScheme(
drawingCache.colorScheme, modelStateInfo, currentState.value, decorationAreaType,
ColorSchemeAssociationKind.Border
)
// And retrieve the border colors
val borderUltraLight = drawingCache.colorScheme.ultraLightColor
val borderExtraLight = drawingCache.colorScheme.extraLightColor
val borderLight = drawingCache.colorScheme.lightColor
val borderMid = drawingCache.colorScheme.midColor
val borderDark = drawingCache.colorScheme.darkColor
val borderUltraDark = drawingCache.colorScheme.ultraDarkColor
val borderIsDark = drawingCache.colorScheme.isDark
val fillPainter = AuroraSkin.painters.fillPainter
val borderPainter = AuroraSkin.painters.borderPainter
val alpha =
if (presentationModel.backgroundAppearanceStrategy == BackgroundAppearanceStrategy.Flat) {
if (currentState.value == ComponentState.DisabledSelected) {
// Respect the alpha in disabled+selected state
skinColors.getAlpha(decorationAreaType, currentState.value)
} else {
// For flat comboboxes, compute the combined contribution of all
// non-disabled states - ignoring ComponentState.ENABLED
modelStateInfo.stateContributionMap
.filter { !it.key.isDisabled && (it.key != ComponentState.Enabled) }
.values.sumOf { it.contribution.toDouble() }.toFloat()
}
} else {
if (currentState.value.isDisabled)
AuroraSkin.colors.getAlpha(decorationAreaType, currentState.value) else 1.0f
}
Canvas(Modifier.matchParentSize()) {
val width = this.size.width
val height = this.size.height
withTransform({
clipRect(
left = 0.0f,
top = 0.0f,
right = width,
bottom = height,
clipOp = ClipOp.Intersect
)
}) {
val outline = buttonShaper.getButtonOutline(
width = width,
height = height,
extraInsets = 0.5f,
isInner = false,
sides = Sides(),
drawScope = this
)
val outlineBoundingRect = outline.bounds
if (outlineBoundingRect.isEmpty) {
return@withTransform
}
// Populate the cached color scheme for filling the combobox
drawingCache.colorScheme.ultraLight = fillUltraLight
drawingCache.colorScheme.extraLight = fillExtraLight
drawingCache.colorScheme.light = fillLight
drawingCache.colorScheme.mid = fillMid
drawingCache.colorScheme.dark = fillDark
drawingCache.colorScheme.ultraDark = fillUltraDark
drawingCache.colorScheme.isDark = fillIsDark
drawingCache.colorScheme.foreground = textColor
fillPainter.paintContourBackground(
this, this.size, outline, drawingCache.colorScheme, alpha
)
// Populate the cached color scheme for drawing the border
drawingCache.colorScheme.ultraLight = borderUltraLight
drawingCache.colorScheme.extraLight = borderExtraLight
drawingCache.colorScheme.light = borderLight
drawingCache.colorScheme.mid = borderMid
drawingCache.colorScheme.dark = borderDark
drawingCache.colorScheme.ultraDark = borderUltraDark
drawingCache.colorScheme.isDark = borderIsDark
drawingCache.colorScheme.foreground = textColor
val innerOutline = if (borderPainter.isPaintingInnerOutline)
buttonShaper.getButtonOutline(
width = width,
height = height,
extraInsets = 1.0f,
isInner = true,
sides = Sides(),
drawScope = this
) else null
borderPainter.paintBorder(
this, this.size, outline, innerOutline, drawingCache.colorScheme, alpha
)
val arrowWidth = if (presentationModel.popupPlacementStrategy.isHorizontal)
ComboBoxSizingConstants.DefaultComboBoxArrowHeight.toPx() else
ComboBoxSizingConstants.DefaultComboBoxArrowWidth.toPx()
val arrowHeight =
if (presentationModel.popupPlacementStrategy.isHorizontal)
ComboBoxSizingConstants.DefaultComboBoxArrowWidth.toPx() else
ComboBoxSizingConstants.DefaultComboBoxArrowHeight.toPx()
val arrowOffsetX = if (layoutDirection == LayoutDirection.Ltr)
width - ComboBoxSizingConstants.DefaultComboBoxContentPadding.calculateRightPadding(
layoutDirection
).toPx() - arrowWidth
else
ComboBoxSizingConstants.DefaultComboBoxContentPadding.calculateLeftPadding(
layoutDirection
).toPx()
val arrowOffsetY = (height - arrowHeight) / 2.0f
translate(
left = arrowOffsetX,
top = arrowOffsetY
) {
drawArrow(
drawScope = this,
width = arrowWidth,
height = arrowHeight,
strokeWidth = ArrowSizingConstants.DefaultArrowStroke.toPx(),
direction = presentationModel.popupPlacementStrategy,
layoutDirection = layoutDirection,
color = arrowColor.withAlpha(alpha)
)
}
}
}
}
// Pass our text color and model state snapshot to the children
CompositionLocalProvider(
LocalTextColor provides textColor,
LocalModelStateInfoSnapshot provides modelStateInfo.getSnapshot(currentState.value)
) {
Layout(
// TODO - revisit this maybe
modifier = Modifier.padding(
PaddingValues(
start = ComboBoxSizingConstants.DefaultComboBoxContentPadding.calculateStartPadding(
layoutDirection
),
end = ComboBoxSizingConstants.DefaultComboBoxContentPadding.calculateEndPadding(
layoutDirection
) + ComboBoxSizingConstants.DefaultComboBoxContentArrowGap
+ ComboBoxSizingConstants.DefaultComboBoxArrowWidth,
top = ComboBoxSizingConstants.DefaultComboBoxContentPadding.calculateTopPadding(),
bottom = ComboBoxSizingConstants.DefaultComboBoxContentPadding.calculateBottomPadding()
)
),
content = {
AuroraText(presentationModel.displayConverter.invoke(contentModel.selectedItem))
}
) { measurables, constraints ->
// Measure each child so that we know how much space they need
val placeables = measurables.map { measurable ->
// Measure each child
measurable.measure(constraints)
}
// The children are laid out in a row
val contentTotalWidth = placeables.sumOf { it.width }
// And the height of the row is determined by the height of the tallest child
val contentMaxHeight = placeables.maxOf { it.height }
// Get the preferred size
var uiPreferredWidth = contentTotalWidth
var uiPreferredHeight = contentMaxHeight
// Bump up to default minimums if necessary
uiPreferredWidth = max(
uiPreferredWidth,
ComboBoxSizingConstants.DefaultComboBoxContentWidth.roundToPx()
)
uiPreferredHeight = max(
uiPreferredHeight,
ComboBoxSizingConstants.DefaultComboBoxContentHeight.roundToPx()
)
// And ask the button shaper for the final sizing
val finalSize = buttonShaper.getPreferredSize(
uiPreferredWidth.toFloat(), uiPreferredHeight.toFloat()
)
// Center children vertically within the vertical space
layout(width = finalSize.width.toInt(), height = finalSize.height.toInt()) {
var xPosition = 0
placeables.forEach { placeable ->
placeable.placeRelative(
x = xPosition,
y = (finalSize.height.toInt() - placeable.height) / 2
)
xPosition += placeable.width
}
}
}
}
}
}