This repository has been archived by the owner on Jul 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Snackbar.kt
431 lines (414 loc) · 18 KB
/
Snackbar.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
/*
* Copyright 2021 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
*
* 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 androidx.compose.material3
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.tokens.SnackbarTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import kotlin.math.max
import kotlin.math.min
/**
* Material Design snackbar.
*
* Snackbars provide brief messages about app processes at the bottom of the screen.
*
* ![Snackbar image](https://developer.android.com/images/reference/androidx/compose/material3/snackbar.png)
*
* Snackbars inform users of a process that an app has performed or will perform. They appear
* temporarily, towards the bottom of the screen. They shouldn’t interrupt the user experience,
* and they don’t require user input to disappear.
*
* A Snackbar can contain a single action. "Dismiss" or "cancel" actions are optional.
*
* Snackbars with an action should not timeout or self-dismiss until the user performs another
* action. Here, moving the keyboard focus indicator to navigate through interactive elements in a
* page is not considered an action.
*
* This component provides only the visuals of the Snackbar. If you need to show a Snackbar
* with defaults on the screen, use [SnackbarHostState.showSnackbar]:
*
* @sample androidx.compose.material3.samples.ScaffoldWithSimpleSnackbar
*
* If you want to customize appearance of the Snackbar, you can pass your own version as a child
* of the [SnackbarHost] to the [Scaffold]:
* @sample androidx.compose.material3.samples.ScaffoldWithCustomSnackbar
*
* @param modifier the [Modifier] to be applied to this snackbar
* @param action action / button component to add as an action to the snackbar. Consider using
* [ColorScheme.inversePrimary] as the color for the action, if you do not have a predefined color
* you wish to use instead.
* @param dismissAction action / button component to add as an additional close affordance action
* when a snackbar is non self-dismissive. Consider using [ColorScheme.inverseOnSurface] as the
* color for the action, if you do not have a predefined color you wish to use instead.
* @param actionOnNewLine whether or not action should be put on a separate line. Recommended for
* action with long action text.
* @param shape defines the shape of this snackbar's container
* @param containerColor the color used for the background of this snackbar. Use [Color.Transparent]
* to have no color.
* @param contentColor the preferred color for content inside this snackbar
* @param actionContentColor the preferred content color for the optional [action] inside this
* snackbar
* @param dismissActionContentColor the preferred content color for the optional [dismissAction]
* inside this snackbar
* @param content content to show information about a process that an app has performed or will
* perform
*/
@Composable
fun Snackbar(
modifier: Modifier = Modifier,
action: @Composable (() -> Unit)? = null,
dismissAction: @Composable (() -> Unit)? = null,
actionOnNewLine: Boolean = false,
shape: Shape = SnackbarDefaults.Shape,
containerColor: Color = SnackbarDefaults.Color,
contentColor: Color = SnackbarDefaults.ContentColor,
actionContentColor: Color = SnackbarDefaults.ActionContentColor,
dismissActionContentColor: Color = SnackbarDefaults.DismissActionContentColor,
content: @Composable () -> Unit
) {
Surface(
modifier = modifier,
shape = shape,
color = containerColor,
contentColor = contentColor,
shadowElevation = SnackbarTokens.ContainerElevation
) {
val textStyle = MaterialTheme.typography.fromToken(SnackbarTokens.SupportingTextFont)
val actionTextStyle = MaterialTheme.typography.fromToken(SnackbarTokens.ActionLabelTextFont)
CompositionLocalProvider(LocalTextStyle provides textStyle) {
when {
action == null -> OneRowSnackbar(
text = content,
action = null,
dismissAction = dismissAction,
actionTextStyle,
actionContentColor,
dismissActionContentColor
)
actionOnNewLine -> NewLineButtonSnackbar(
content,
action,
dismissAction,
actionTextStyle,
actionContentColor,
dismissActionContentColor
)
else -> OneRowSnackbar(
text = content,
action = action,
dismissAction = dismissAction,
actionTextStyle,
actionContentColor,
dismissActionContentColor
)
}
}
}
}
/**
* Material Design snackbar.
*
* Snackbars provide brief messages about app processes at the bottom of the screen.
*
* ![Snackbar image](https://developer.android.com/images/reference/androidx/compose/material3/snackbar.png)
*
* Snackbars inform users of a process that an app has performed or will perform. They appear
* temporarily, towards the bottom of the screen. They shouldn’t interrupt the user experience,
* and they don’t require user input to disappear.
*
* A Snackbar can contain a single action. "Dismiss" or "cancel" actions are optional.
*
* Snackbars with an action should not timeout or self-dismiss until the user performs another
* action. Here, moving the keyboard focus indicator to navigate through interactive elements in a
* page is not considered an action.
*
* This version of snackbar is designed to work with [SnackbarData] provided by the
* [SnackbarHost], which is usually used inside of the [Scaffold].
*
* This components provides only the visuals of the Snackbar. If you need to show a Snackbar
* with defaults on the screen, use [SnackbarHostState.showSnackbar]:
*
* @sample androidx.compose.material3.samples.ScaffoldWithSimpleSnackbar
*
* If you want to customize appearance of the Snackbar, you can pass your own version as a child
* of the [SnackbarHost] to the [Scaffold]:
*
* @sample androidx.compose.material3.samples.ScaffoldWithCustomSnackbar
*
* When a [SnackbarData.visuals] sets the Snackbar's duration as [SnackbarDuration.Indefinite], it's
* recommended to display an additional close affordance action.
* See [SnackbarVisuals.withDismissAction]:
*
* @sample androidx.compose.material3.samples.ScaffoldWithIndefiniteSnackbar
*
* @param snackbarData data about the current snackbar showing via [SnackbarHostState]
* @param modifier the [Modifier] to be applied to this snackbar
* @param actionOnNewLine whether or not action should be put on a separate line. Recommended for
* action with long action text.
* @param shape defines the shape of this snackbar's container
* @param containerColor the color used for the background of this snackbar. Use [Color.Transparent]
* to have no color.
* @param contentColor the preferred color for content inside this snackbar
* @param actionColor the color of the snackbar's action
* @param actionContentColor the preferred content color for the optional action inside this
* snackbar. See [SnackbarVisuals.actionLabel].
* @param dismissActionContentColor the preferred content color for the optional dismiss action
* inside this snackbar. See [SnackbarVisuals.withDismissAction].
*/
@Composable
fun Snackbar(
snackbarData: SnackbarData,
modifier: Modifier = Modifier,
actionOnNewLine: Boolean = false,
shape: Shape = SnackbarDefaults.Shape,
containerColor: Color = SnackbarDefaults.Color,
contentColor: Color = SnackbarDefaults.ContentColor,
actionColor: Color = SnackbarDefaults.ActionColor,
actionContentColor: Color = SnackbarDefaults.ActionContentColor,
dismissActionContentColor: Color = SnackbarDefaults.DismissActionContentColor,
) {
val actionLabel = snackbarData.visuals.actionLabel
val actionComposable: (@Composable () -> Unit)? = if (actionLabel != null) {
@Composable {
TextButton(
colors = ButtonDefaults.textButtonColors(contentColor = actionColor),
onClick = { snackbarData.performAction() },
content = { Text(actionLabel) }
)
}
} else {
null
}
val dismissActionComposable: (@Composable () -> Unit)? =
if (snackbarData.visuals.withDismissAction) {
@Composable {
IconButton(
onClick = { snackbarData.dismiss() },
content = {
Icon(
Icons.Filled.Close,
contentDescription = null, // TODO add "Dismiss Snackbar" to Strings.
)
}
)
}
} else {
null
}
Snackbar(
modifier = modifier.padding(12.dp),
action = actionComposable,
dismissAction = dismissActionComposable,
actionOnNewLine = actionOnNewLine,
shape = shape,
containerColor = containerColor,
contentColor = contentColor,
actionContentColor = actionContentColor,
dismissActionContentColor = dismissActionContentColor,
content = { Text(snackbarData.visuals.message) }
)
}
@Composable
private fun NewLineButtonSnackbar(
text: @Composable () -> Unit,
action: @Composable () -> Unit,
dismissAction: @Composable (() -> Unit)?,
actionTextStyle: TextStyle,
actionContentColor: Color,
dismissActionContentColor: Color
) {
Column(
modifier = Modifier
// Fill max width, up to ContainerMaxWidth.
.widthIn(max = ContainerMaxWidth)
.fillMaxWidth()
.padding(
start = HorizontalSpacing,
bottom = SeparateButtonExtraY
)
) {
Box(
Modifier.paddingFromBaseline(HeightToFirstLine, LongButtonVerticalOffset)
.padding(end = HorizontalSpacingButtonSide)
) { text() }
Box(
Modifier.align(Alignment.End)
.padding(end = if (dismissAction == null) HorizontalSpacingButtonSide else 0.dp)
) {
Row {
CompositionLocalProvider(
LocalContentColor provides actionContentColor,
LocalTextStyle provides actionTextStyle,
content = action
)
if (dismissAction != null) {
CompositionLocalProvider(
LocalContentColor provides dismissActionContentColor,
content = dismissAction
)
}
}
}
}
}
@Composable
private fun OneRowSnackbar(
text: @Composable () -> Unit,
action: @Composable (() -> Unit)?,
dismissAction: @Composable (() -> Unit)?,
actionTextStyle: TextStyle,
actionTextColor: Color,
dismissActionColor: Color
) {
val textTag = "text"
val actionTag = "action"
val dismissActionTag = "dismissAction"
Layout(
{
Box(Modifier.layoutId(textTag).padding(vertical = SnackbarVerticalPadding)) { text() }
if (action != null) {
Box(Modifier.layoutId(actionTag)) {
CompositionLocalProvider(
LocalContentColor provides actionTextColor,
LocalTextStyle provides actionTextStyle,
content = action
)
}
}
if (dismissAction != null) {
Box(Modifier.layoutId(dismissActionTag)) {
CompositionLocalProvider(
LocalContentColor provides dismissActionColor,
content = dismissAction
)
}
}
},
modifier = Modifier.padding(
start = HorizontalSpacing,
end = if (dismissAction == null) HorizontalSpacingButtonSide else 0.dp
)
) { measurables, constraints ->
val containerWidth = min(constraints.maxWidth, ContainerMaxWidth.roundToPx())
val actionButtonPlaceable =
measurables.firstOrNull { it.layoutId == actionTag }?.measure(constraints)
val dismissButtonPlaceable =
measurables.firstOrNull { it.layoutId == dismissActionTag }?.measure(constraints)
val actionButtonWidth = actionButtonPlaceable?.width ?: 0
val actionButtonHeight = actionButtonPlaceable?.height ?: 0
val dismissButtonWidth = dismissButtonPlaceable?.width ?: 0
val dismissButtonHeight = dismissButtonPlaceable?.height ?: 0
val extraSpacingWidth = if (dismissButtonWidth == 0) TextEndExtraSpacing.roundToPx() else 0
val textMaxWidth =
(containerWidth - actionButtonWidth - dismissButtonWidth - extraSpacingWidth)
.coerceAtLeast(constraints.minWidth)
val textPlaceable = measurables.first { it.layoutId == textTag }.measure(
constraints.copy(minHeight = 0, maxWidth = textMaxWidth)
)
val firstTextBaseline = textPlaceable[FirstBaseline]
require(firstTextBaseline != AlignmentLine.Unspecified) { "No baselines for text" }
val lastTextBaseline = textPlaceable[LastBaseline]
require(lastTextBaseline != AlignmentLine.Unspecified) { "No baselines for text" }
val isOneLine = firstTextBaseline == lastTextBaseline
val dismissButtonPlaceX = containerWidth - dismissButtonWidth
val actionButtonPlaceX = dismissButtonPlaceX - actionButtonWidth
val textPlaceY: Int
val containerHeight: Int
val actionButtonPlaceY: Int
if (isOneLine) {
val minContainerHeight = SnackbarTokens.SingleLineContainerHeight.roundToPx()
val contentHeight = max(actionButtonHeight, dismissButtonHeight)
containerHeight = max(minContainerHeight, contentHeight)
textPlaceY = (containerHeight - textPlaceable.height) / 2
actionButtonPlaceY = if (actionButtonPlaceable != null) {
actionButtonPlaceable[FirstBaseline].let {
if (it != AlignmentLine.Unspecified) {
textPlaceY + firstTextBaseline - it
} else {
0
}
}
} else {
0
}
} else {
val baselineOffset = HeightToFirstLine.roundToPx()
textPlaceY = baselineOffset - firstTextBaseline
val minContainerHeight = SnackbarTokens.TwoLinesContainerHeight.roundToPx()
val contentHeight = textPlaceY + textPlaceable.height
containerHeight = max(minContainerHeight, contentHeight)
actionButtonPlaceY = if (actionButtonPlaceable != null) {
(containerHeight - actionButtonPlaceable.height) / 2
} else {
0
}
}
val dismissButtonPlaceY = if (dismissButtonPlaceable != null) {
(containerHeight - dismissButtonPlaceable.height) / 2
} else {
0
}
layout(containerWidth, containerHeight) {
textPlaceable.placeRelative(0, textPlaceY)
dismissButtonPlaceable?.placeRelative(dismissButtonPlaceX, dismissButtonPlaceY)
actionButtonPlaceable?.placeRelative(actionButtonPlaceX, actionButtonPlaceY)
}
}
}
/**
* Contains the default values used for [Snackbar].
*/
object SnackbarDefaults {
/** Default shape of a snackbar. */
val Shape: Shape @Composable get() = SnackbarTokens.ContainerShape.toShape()
/** Default color of a snackbar. */
val Color: Color @Composable get() = SnackbarTokens.ContainerColor.toColor()
/** Default content color of a snackbar. */
val ContentColor: Color @Composable get() = SnackbarTokens.SupportingTextColor.toColor()
/** Default action color of a snackbar. */
val ActionColor: Color @Composable get() = SnackbarTokens.ActionLabelTextColor.toColor()
/** Default action content color of a snackbar. */
val ActionContentColor: Color @Composable get() = SnackbarTokens.ActionLabelTextColor.toColor()
/** Default dismiss action content color of a snackbar. */
val DismissActionContentColor: Color @Composable get() = SnackbarTokens.IconColor.toColor()
}
private val ContainerMaxWidth = 600.dp
private val HeightToFirstLine = 30.dp
private val HorizontalSpacing = 16.dp
private val HorizontalSpacingButtonSide = 8.dp
private val SeparateButtonExtraY = 2.dp
private val SnackbarVerticalPadding = 6.dp
private val TextEndExtraSpacing = 8.dp
private val LongButtonVerticalOffset = 12.dp