forked from android/compose-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Home.kt
373 lines (351 loc) · 13 KB
/
Home.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
/*
* Copyright 2020 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.jetsnack.ui.home
import androidx.annotation.FloatRange
import androidx.annotation.StringRes
import androidx.compose.animation.AnimatedFloatModel
import androidx.compose.animation.Crossfade
import androidx.compose.animation.animate
import androidx.compose.animation.animatedFloat
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.SpringSpec
import androidx.compose.foundation.Box
import androidx.compose.foundation.ContentGravity
import androidx.compose.foundation.Icon
import androidx.compose.foundation.Text
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.preferredHeight
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AccountCircle
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.outlined.ShoppingCart
import androidx.compose.runtime.Composable
import androidx.compose.runtime.onCommit
import androidx.compose.runtime.remember
import androidx.compose.runtime.savedinstancestate.savedInstanceState
import androidx.compose.ui.Layout
import androidx.compose.ui.MeasureScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.Placeable
import androidx.compose.ui.TransformOrigin
import androidx.compose.ui.draw.clip
import androidx.compose.ui.drawLayer
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.vector.VectorAsset
import androidx.compose.ui.layout.id
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.AnimationClockAmbient
import androidx.compose.ui.platform.ConfigurationAmbient
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import androidx.core.os.ConfigurationCompat
import androidx.ui.tooling.preview.Preview
import com.example.jetsnack.R
import com.example.jetsnack.ui.components.JetsnackScaffold
import com.example.jetsnack.ui.components.JetsnackSurface
import com.example.jetsnack.ui.home.search.Search
import com.example.jetsnack.ui.theme.JetsnackTheme
import com.example.jetsnack.ui.utils.navigationBarsPadding
@Composable
fun Home(onSnackSelected: (Long) -> Unit) {
val (currentSection, setCurrentSection) = savedInstanceState { HomeSections.Feed }
val navItems = HomeSections.values().toList()
JetsnackScaffold(
bottomBar = {
JetsnackBottomNav(
currentSection = currentSection,
onSectionSelected = setCurrentSection,
items = navItems
)
}
) { innerPadding ->
val modifier = Modifier.padding(innerPadding)
Crossfade(currentSection) { section ->
when (section) {
HomeSections.Feed -> Feed(
onSnackClick = onSnackSelected,
modifier = modifier
)
HomeSections.Search -> Search(onSnackSelected, modifier)
HomeSections.Cart -> Cart(modifier)
HomeSections.Profile -> Profile(modifier)
}
}
}
}
@Composable
private fun JetsnackBottomNav(
currentSection: HomeSections,
onSectionSelected: (HomeSections) -> Unit,
items: List<HomeSections>,
color: Color = JetsnackTheme.colors.iconPrimary,
contentColor: Color = JetsnackTheme.colors.iconInteractive
) {
JetsnackSurface(
color = color,
contentColor = contentColor
) {
val springSpec = remember {
SpringSpec<Float>(
// Determined experimentally
stiffness = 800f,
dampingRatio = 0.8f
)
}
JetsnackBottomNavLayout(
selectedIndex = currentSection.ordinal,
itemCount = items.size,
indicator = { JetsnackBottomNavIndicator() },
animSpec = springSpec,
modifier = Modifier.navigationBarsPadding(left = false, right = false)
) {
items.forEach { section ->
val selected = section == currentSection
val tint = animate(
if (selected) {
JetsnackTheme.colors.iconInteractive
} else {
JetsnackTheme.colors.iconInteractiveInactive
}
)
JetsnackBottomNavigationItem(
icon = {
Icon(
asset = section.icon,
tint = tint
)
},
text = {
Text(
text = stringResource(section.title).toUpperCase(
ConfigurationCompat.getLocales(
ConfigurationAmbient.current
).get(0)
),
color = tint,
style = MaterialTheme.typography.button,
maxLines = 1
)
},
selected = selected,
onSelected = { onSectionSelected(section) },
animSpec = springSpec,
modifier = BottomNavigationItemPadding
.clip(BottomNavIndicatorShape)
)
}
}
}
}
@Composable
private fun JetsnackBottomNavLayout(
selectedIndex: Int,
itemCount: Int,
animSpec: AnimationSpec<Float>,
indicator: @Composable () -> Unit,
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
// Track how "selected" each item is [0, 1]
val clock = AnimationClockAmbient.current
val selectionFractions = remember(itemCount) {
List(itemCount) { i ->
AnimatedFloatModel(if (i == selectedIndex) 1f else 0f, clock)
}
}
// When selection changes, animate the selection fractions
onCommit(selectedIndex) {
selectionFractions.forEachIndexed { index, selectionFraction ->
val target = if (index == selectedIndex) 1f else 0f
if (selectionFraction.targetValue != target) {
selectionFraction.animateTo(target, animSpec)
}
}
}
// Animate the position of the indicator
val indicatorLeft = animatedFloat(0f)
Layout(
modifier = modifier.preferredHeight(BottomNavHeight),
children = {
content()
Box(Modifier.layoutId("indicator"), children = indicator)
}
) { measurables, constraints ->
check(itemCount == (measurables.size - 1)) // account for indicator
// Divide the width into n+1 slots and give the selected item 2 slots
val unselectedWidth = constraints.maxWidth / (itemCount + 1)
val selectedWidth = constraints.maxWidth - (itemCount - 1) * unselectedWidth
val indicatorMeasurable = measurables.first { it.id == "indicator" }
val itemPlaceables = measurables
.filterNot { it == indicatorMeasurable }
.mapIndexed { index, measurable ->
// Animate item's width based upon the selection amount
val width = lerp(unselectedWidth, selectedWidth, selectionFractions[index].value)
measurable.measure(
constraints.copy(
minWidth = width,
maxWidth = width
)
)
}
val indicatorPlaceable = indicatorMeasurable.measure(
constraints.copy(
minWidth = selectedWidth,
maxWidth = selectedWidth
)
)
// Animate the indicator position
val targetIndicatorLeft = selectedIndex * unselectedWidth.toFloat()
if (indicatorLeft.targetValue != targetIndicatorLeft) {
indicatorLeft.animateTo(targetIndicatorLeft, animSpec)
}
layout(
width = constraints.maxWidth,
height = itemPlaceables.maxByOrNull { it.height }?.height ?: 0
) {
indicatorPlaceable.place(x = indicatorLeft.value.toInt(), y = 0)
var x = 0
itemPlaceables.forEach { placeable ->
placeable.place(x = x, y = 0)
x += placeable.width
}
}
}
}
@Composable
fun JetsnackBottomNavigationItem(
icon: @Composable () -> Unit,
text: @Composable () -> Unit,
selected: Boolean,
onSelected: () -> Unit,
animSpec: AnimationSpec<Float>,
modifier: Modifier = Modifier
) {
Box(
modifier = modifier.selectable(selected = selected, onClick = onSelected),
gravity = ContentGravity.Center
) {
// Animate the icon/text positions within the item based on selection
val animationProgress = animate(if (selected) 1f else 0f, animSpec)
JetsnackBottomNavItemLayout(
icon = icon,
text = text,
animationProgress = animationProgress
)
}
}
@Composable
private fun JetsnackBottomNavItemLayout(
icon: @Composable () -> Unit,
text: @Composable () -> Unit,
@FloatRange(from = 0.0, to = 1.0) animationProgress: Float
) {
Layout(
children = {
Box(Modifier.layoutId("icon"), children = icon)
val scale = lerp(0.6f, 1f, animationProgress)
Box(
modifier = Modifier
.layoutId("text")
.drawLayer(
alpha = animationProgress,
scaleX = scale,
scaleY = scale,
transformOrigin = BottomNavLabelTransformOrigin
),
paddingStart = TextIconSpacing,
children = text
)
}
) { measurables, constraints ->
val iconPlaceable = measurables.first { it.id == "icon" }.measure(constraints)
val textPlaceable = measurables.first { it.id == "text" }.measure(constraints)
placeTextAndIcon(
textPlaceable,
iconPlaceable,
constraints.maxWidth,
constraints.maxHeight,
animationProgress
)
}
}
private fun MeasureScope.placeTextAndIcon(
textPlaceable: Placeable,
iconPlaceable: Placeable,
width: Int,
height: Int,
@FloatRange(from = 0.0, to = 1.0) animationProgress: Float
): MeasureScope.MeasureResult {
val iconY = (height - iconPlaceable.height) / 2
val textY = (height - textPlaceable.height) / 2
val textWidth = textPlaceable.width * animationProgress
val iconX = (width - textWidth - iconPlaceable.width) / 2
val textX = iconX + iconPlaceable.width
return layout(width, height) {
iconPlaceable.place(iconX.toInt(), iconY)
if (animationProgress != 0f) {
textPlaceable.place(textX.toInt(), textY)
}
}
}
@Composable
private fun JetsnackBottomNavIndicator(
strokeWidth: Dp = 2.dp,
color: Color = JetsnackTheme.colors.iconInteractive,
shape: Shape = BottomNavIndicatorShape
) {
Spacer(
modifier = Modifier
.fillMaxSize()
.then(BottomNavigationItemPadding)
.border(strokeWidth, color, shape)
)
}
private val TextIconSpacing = 4.dp
private val BottomNavHeight = 56.dp
private val BottomNavLabelTransformOrigin = TransformOrigin(0f, 0.5f)
private val BottomNavIndicatorShape = RoundedCornerShape(percent = 50)
private val BottomNavigationItemPadding = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
private enum class HomeSections(
@StringRes val title: Int,
val icon: VectorAsset
) {
Feed(R.string.home_feed, Icons.Outlined.Home),
Search(R.string.home_search, Icons.Outlined.Search),
Cart(R.string.home_cart, Icons.Outlined.ShoppingCart),
Profile(R.string.home_profile, Icons.Outlined.AccountCircle)
}
@Preview
@Composable
private fun JsetsnackBottomNavPreview() {
JetsnackTheme {
JetsnackBottomNav(
currentSection = HomeSections.Feed,
onSectionSelected = { },
items = HomeSections.values().toList()
)
}
}