-
Notifications
You must be signed in to change notification settings - Fork 145
/
Interactions.kt
643 lines (587 loc) · 22.4 KB
/
Interactions.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/*
* Copyright 2024 The Android Open Source Project
*
* 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
*
* https://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 com.example.compose.snippets.touchinput
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.IndicationNodeFactory
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.DragInteraction
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.material.ripple
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ButtonElevation
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.center
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Brush.Companion.linearGradient
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.drawOutline
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.node.DelegatableNode
import androidx.compose.ui.node.DrawModifierNode
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlin.math.abs
import kotlin.math.sign
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
@Composable
private fun InteractionsSnippet1() {
// [START android_compose_interactions_interaction_state]
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
Button(
/* do something */ },
interactionSource = interactionSource
) {
Text(if (isPressed) "Pressed!" else "Not pressed")
}
// [END android_compose_interactions_interaction_state]
}
// [START android_compose_interactions_interaction_source_input]
fun Modifier.focusBorder(interactionSource: InteractionSource): Modifier {
// [START_EXCLUDE]
return this
// [END_EXCLUDE]
}
// [END android_compose_interactions_interaction_source_input]
// [START android_compose_interactions_mutable_interaction_source_input]
fun Modifier.hover(interactionSource: MutableInteractionSource, enabled: Boolean): Modifier {
// [START_EXCLUDE]
return this
// [END_EXCLUDE]
}
// [END android_compose_interactions_mutable_interaction_source_input]
// [START android_compose_interactions_high_level_component]
@Composable
fun Button(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
// exposes MutableInteractionSource as a parameter
interactionSource: MutableInteractionSource? = null,
elevation: ButtonElevation? = ButtonDefaults.elevatedButtonElevation(),
shape: Shape = MaterialTheme.shapes.small,
border: BorderStroke? = null,
colors: ButtonColors = ButtonDefaults.buttonColors(),
contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
content: @Composable RowScope.() -> Unit
) { /* content() */ }
// [END android_compose_interactions_high_level_component]
@Composable
fun HoverExample() {
// [START android_compose_interactions_hoverable]
// This InteractionSource will emit hover interactions
val interactionSource = remember { MutableInteractionSource() }
Box(
Modifier
.size(100.dp)
.hoverable(interactionSource = interactionSource),
contentAlignment = Alignment.Center
) {
Text("Hello!")
}
// [END android_compose_interactions_hoverable]
}
@Composable
fun FocusableExample() {
// [START android_compose_interactions_focusable]
// This InteractionSource will emit hover and focus interactions
val interactionSource = remember { MutableInteractionSource() }
Box(
Modifier
.size(100.dp)
.hoverable(interactionSource = interactionSource)
.focusable(interactionSource = interactionSource),
contentAlignment = Alignment.Center
) {
Text("Hello!")
}
// [END android_compose_interactions_focusable]
}
@Composable
fun ClickableExample() {
// [START android_compose_interactions_clickable]
// This InteractionSource will emit hover, focus, and press interactions
val interactionSource = remember { MutableInteractionSource() }
Box(
Modifier
.size(100.dp)
.clickable(
>
interactionSource = interactionSource,
// Also show a ripple effect
indication = ripple()
),
contentAlignment = Alignment.Center
) {
Text("Hello!")
}
// [END android_compose_interactions_clickable]
}
@Composable
private fun InteractionsSnippet2() {
// [START android_compose_interactions_flow_apis]
val interactionSource = remember { MutableInteractionSource() }
val interactions = remember { mutableStateListOf<Interaction>() }
LaunchedEffect(interactionSource) {
interactionSource.interactions.collect { interaction ->
when (interaction) {
is PressInteraction.Press -> {
interactions.add(interaction)
}
is DragInteraction.Start -> {
interactions.add(interaction)
}
}
}
}
// [END android_compose_interactions_flow_apis]
}
@Composable
private fun InteractionsSnippet3() {
// [START android_compose_interactions_add_remove]
val interactionSource = remember { MutableInteractionSource() }
val interactions = remember { mutableStateListOf<Interaction>() }
LaunchedEffect(interactionSource) {
interactionSource.interactions.collect { interaction ->
when (interaction) {
is PressInteraction.Press -> {
interactions.add(interaction)
}
is PressInteraction.Release -> {
interactions.remove(interaction.press)
}
is PressInteraction.Cancel -> {
interactions.remove(interaction.press)
}
is DragInteraction.Start -> {
interactions.add(interaction)
}
is DragInteraction.Stop -> {
interactions.remove(interaction.start)
}
is DragInteraction.Cancel -> {
interactions.remove(interaction.start)
}
}
}
}
// [END android_compose_interactions_add_remove]
// [START android_compose_interactions_is_pressed_or_dragged]
val isPressedOrDragged = interactions.isNotEmpty()
// [END android_compose_interactions_is_pressed_or_dragged]
// [START android_compose_interactions_last]
val lastInteraction = when (interactions.lastOrNull()) {
is DragInteraction.Start -> "Dragged"
is PressInteraction.Press -> "Pressed"
else -> "No state"
}
// [END android_compose_interactions_last]
}
@Composable
private fun InteractionsSnippet4() {
// [START android_compose_interactions_batched]
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
Button( /* do something */ }, interactionSource = interactionSource) {
Text(if (isPressed) "Pressed!" else "Not pressed")
}
// [END android_compose_interactions_batched]
}
// [START android_compose_interactions_press_icon_button]
@Composable
fun PressIconButton(
onClick: () -> Unit,
icon: @Composable () -> Unit,
text: @Composable () -> Unit,
modifier: Modifier = Modifier,
interactionSource: MutableInteractionSource? = null
) {
val isPressed = interactionSource?.collectIsPressedAsState()?.value ?: false
Button(
>
modifier = modifier,
interactionSource = interactionSource
) {
AnimatedVisibility(visible = isPressed) {
if (isPressed) {
Row {
icon()
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
}
}
}
text()
}
}
// [END android_compose_interactions_press_icon_button]
@Composable
fun PressIconButtonUsage() {
// [START android_compose_interactions_press_icon_button_usage]
PressIconButton(
>
icon = { Icon(Icons.Filled.ShoppingCart, contentDescription = null) },
text = { Text("Add to cart") }
)
// [END android_compose_interactions_press_icon_button_usage]
}
@Composable
fun InteractionsSnippet5() {
// [START android_compose_interactions_indication]
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val scale by animateFloatAsState(targetValue = if (isPressed) 0.9f else 1f, label = "scale")
Button(
modifier = Modifier.scale(scale),
},
interactionSource = interactionSource
) {
Text(if (isPressed) "Pressed!" else "Not pressed")
}
// [END android_compose_interactions_indication]
}
// [START android_compose_interactions_scale_node]
private class ScaleNode(private val interactionSource: InteractionSource) :
Modifier.Node(), DrawModifierNode {
var currentPressPosition: Offset = Offset.Zero
val animatedScalePercent = Animatable(1f)
private suspend fun animateToPressed(pressPosition: Offset) {
currentPressPosition = pressPosition
animatedScalePercent.animateTo(0.9f, spring())
}
private suspend fun animateToResting() {
animatedScalePercent.animateTo(1f, spring())
}
override fun onAttach() {
coroutineScope.launch {
interactionSource.interactions.collectLatest { interaction ->
when (interaction) {
is PressInteraction.Press -> animateToPressed(interaction.pressPosition)
is PressInteraction.Release -> animateToResting()
is PressInteraction.Cancel -> animateToResting()
}
}
}
}
override fun ContentDrawScope.draw() {
scale(
scale = animatedScalePercent.value,
pivot = currentPressPosition
) {
this@draw.drawContent()
}
}
}
// [END android_compose_interactions_scale_node]
// [START android_compose_interactions_scale_node_factory]
object ScaleIndication : IndicationNodeFactory {
override fun create(interactionSource: InteractionSource): DelegatableNode {
return ScaleNode(interactionSource)
}
override fun equals(other: Any?): Boolean = other === ScaleIndication
override fun hashCode() = 100
}
// [END android_compose_interactions_scale_node_factory]
@Composable
fun InteractionSnippets6() {
// [START android_compose_interactions_button_indication]
Box(
modifier = Modifier
.size(100.dp)
.clickable(
>
indication = ScaleIndication,
interactionSource = null
)
.background(Color.Blue),
contentAlignment = Alignment.Center
) {
Text("Hello!", color = Color.White)
}
// [END android_compose_interactions_button_indication]
}
// [START android_compose_interactions_scale_button]
@Composable
fun ScaleButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
interactionSource: MutableInteractionSource? = null,
shape: Shape = CircleShape,
content: @Composable RowScope.() -> Unit
) {
Row(
modifier = modifier
.defaultMinSize(minWidth = 76.dp, minHeight = 48.dp)
.clickable(
enabled = enabled,
indication = ScaleIndication,
interactionSource = interactionSource,
>
)
.border(width = 2.dp, color = Color.Blue, shape = shape)
.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
content = content
)
}
// [END android_compose_interactions_scale_button]
@Composable
fun ScaleButtonExample() {
// [START android_compose_interactions_scale_button_example]
ScaleButton( {
Icon(Icons.Filled.ShoppingCart, "")
Spacer(Modifier.padding(10.dp))
Text(text = "Add to cart!")
}
// [END android_compose_interactions_scale_button_example]
}
// [START android_compose_interactions_neon_node]
private class NeonNode(
private val shape: Shape,
private val borderWidth: Dp,
private val interactionSource: InteractionSource
) : Modifier.Node(), DrawModifierNode {
var currentPressPosition: Offset = Offset.Zero
val animatedProgress = Animatable(0f)
val animatedPressAlpha = Animatable(1f)
var pressedAnimation: Job? = null
var restingAnimation: Job? = null
private suspend fun animateToPressed(pressPosition: Offset) {
// Finish any existing animations, in case of a new press while we are still showing
// an animation for a previous one
restingAnimation?.cancel()
pressedAnimation?.cancel()
pressedAnimation = coroutineScope.launch {
currentPressPosition = pressPosition
animatedPressAlpha.snapTo(1f)
animatedProgress.snapTo(0f)
animatedProgress.animateTo(1f, tween(450))
}
}
private fun animateToResting() {
restingAnimation = coroutineScope.launch {
// Wait for the existing press animation to finish if it is still ongoing
pressedAnimation?.join()
animatedPressAlpha.animateTo(0f, tween(250))
animatedProgress.snapTo(0f)
}
}
override fun onAttach() {
coroutineScope.launch {
interactionSource.interactions.collect { interaction ->
when (interaction) {
is PressInteraction.Press -> animateToPressed(interaction.pressPosition)
is PressInteraction.Release -> animateToResting()
is PressInteraction.Cancel -> animateToResting()
}
}
}
}
override fun ContentDrawScope.draw() {
val (startPosition, endPosition) = calculateGradientStartAndEndFromPressPosition(
currentPressPosition, size
)
val brush = animateBrush(
startPosition = startPosition,
endPosition = endPosition,
progress = animatedProgress.value
)
val alpha = animatedPressAlpha.value
drawContent()
val outline = shape.createOutline(size, layoutDirection, this)
// Draw overlay on top of content
drawOutline(
outline = outline,
brush = brush,
alpha = alpha * 0.1f
)
// Draw border on top of overlay
drawOutline(
outline = outline,
brush = brush,
alpha = alpha,
style = Stroke(width = borderWidth.toPx())
)
}
/**
* Calculates a gradient start / end where start is the point on the bounding rectangle of
* size [size] that intercepts with the line drawn from the center to [pressPosition],
* and end is the intercept on the opposite end of that line.
*/
private fun calculateGradientStartAndEndFromPressPosition(
pressPosition: Offset,
size: Size
): Pair<Offset, Offset> {
// Convert to offset from the center
val offset = pressPosition - size.center
// y = mx + c, c is 0, so just test for x and y to see where the intercept is
val gradient = offset.y / offset.x
// We are starting from the center, so halve the width and height - convert the sign
// to match the offset
val width = (size.width / 2f) * sign(offset.x)
val height = (size.height / 2f) * sign(offset.y)
val x = height / gradient
val y = gradient * width
// Figure out which intercept lies within bounds
val intercept = if (abs(y) <= abs(height)) {
Offset(width, y)
} else {
Offset(x, height)
}
// Convert back to offsets from 0,0
val start = intercept + size.center
val end = Offset(size.width - start.x, size.height - start.y)
return start to end
}
private fun animateBrush(
startPosition: Offset,
endPosition: Offset,
progress: Float
): Brush {
if (progress == 0f) return TransparentBrush
// This is *expensive* - we are doing a lot of allocations on each animation frame. To
// recreate a similar effect in a performant way, it would be better to create one large
// gradient and translate it on each frame, instead of creating a whole new gradient
// and shader. The current approach will be janky!
val colorStops = buildList {
when {
progress < 1 / 6f -> {
val adjustedProgress = progress * 6f
add(0f to Blue)
add(adjustedProgress to Color.Transparent)
}
progress < 2 / 6f -> {
val adjustedProgress = (progress - 1 / 6f) * 6f
add(0f to Purple)
add(adjustedProgress * MaxBlueStop to Blue)
add(adjustedProgress to Blue)
add(1f to Color.Transparent)
}
progress < 3 / 6f -> {
val adjustedProgress = (progress - 2 / 6f) * 6f
add(0f to Pink)
add(adjustedProgress * MaxPurpleStop to Purple)
add(MaxBlueStop to Blue)
add(1f to Blue)
}
progress < 4 / 6f -> {
val adjustedProgress = (progress - 3 / 6f) * 6f
add(0f to Orange)
add(adjustedProgress * MaxPinkStop to Pink)
add(MaxPurpleStop to Purple)
add(MaxBlueStop to Blue)
add(1f to Blue)
}
progress < 5 / 6f -> {
val adjustedProgress = (progress - 4 / 6f) * 6f
add(0f to Yellow)
add(adjustedProgress * MaxOrangeStop to Orange)
add(MaxPinkStop to Pink)
add(MaxPurpleStop to Purple)
add(MaxBlueStop to Blue)
add(1f to Blue)
}
else -> {
val adjustedProgress = (progress - 5 / 6f) * 6f
add(0f to Yellow)
add(adjustedProgress * MaxYellowStop to Yellow)
add(MaxOrangeStop to Orange)
add(MaxPinkStop to Pink)
add(MaxPurpleStop to Purple)
add(MaxBlueStop to Blue)
add(1f to Blue)
}
}
}
return linearGradient(
colorStops = colorStops.toTypedArray(),
start = startPosition,
end = endPosition
)
}
companion object {
val TransparentBrush = SolidColor(Color.Transparent)
val Blue = Color(0xFF30C0D8)
val Purple = Color(0xFF7848A8)
val Pink = Color(0xFFF03078)
val Orange = Color(0xFFF07800)
val Yellow = Color(0xFFF0D800)
const val MaxYellowStop = 0.16f
const val MaxOrangeStop = 0.33f
const val MaxPinkStop = 0.5f
const val MaxPurpleStop = 0.67f
const val MaxBlueStop = 0.83f
}
}
// [END android_compose_interactions_neon_node]
// [START android_compose_interactions_neon_indication]
data class NeonIndication(private val shape: Shape, private val borderWidth: Dp) : IndicationNodeFactory {
override fun create(interactionSource: InteractionSource): DelegatableNode {
return NeonNode(
shape,
// Double the border size for a stronger press effect
borderWidth * 2,
interactionSource
)
}
}
// [END android_compose_interactions_neon_indication]
You can’t perform that action at this time.