-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
InterestsScreen.kt
606 lines (575 loc) · 21.7 KB
/
InterestsScreen.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
/*
* 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
*
* 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.jetnews.ui.interests
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.annotation.StringRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.ScaffoldState
import androidx.compose.material.ScrollableTabRow
import androidx.compose.material.Surface
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.constrainHeight
import androidx.compose.ui.unit.constrainWidth
import androidx.compose.ui.unit.dp
import com.example.jetnews.R
import com.example.jetnews.data.Result
import com.example.jetnews.data.interests.InterestSection
import com.example.jetnews.data.interests.TopicSelection
import com.example.jetnews.data.interests.impl.FakeInterestsRepository
import com.example.jetnews.ui.theme.JetnewsTheme
import kotlinx.coroutines.runBlocking
import kotlin.math.max
enum class Sections(@StringRes val titleResId: Int) {
Topics(R.string.interests_section_topics),
People(R.string.interests_section_people),
Publications(R.string.interests_section_publications)
}
/**
* TabContent for a single tab of the screen.
*
* This is intended to encapsulate a tab & it's content as a single object. It was added to avoid
* passing several parameters per-tab from the stateful composable to the composable that displays
* the current tab.
*
* @param section the tab that this content is for
* @param section content of the tab, a composable that describes the content
*/
class TabContent(val section: Sections, val content: @Composable () -> Unit)
/**
* Stateless interest screen displays the tabs specified in [tabContent] adapting the UI to
* different screen sizes.
*
* @param tabContent (slot) the tabs and their content to display on this screen, must be a
* non-empty list, tabs are displayed in the order specified by this list
* @param currentSection (state) the current tab to display, must be in [tabContent]
* @param isExpandedScreen (state) true if the screen is expanded
* @param onTabChange (event) request a change in [currentSection] to another tab from [tabContent]
* @param openDrawer (event) request opening the app drawer
* @param scaffoldState (state) the state for the screen's [Scaffold]
*/
@Composable
fun InterestsScreen(
tabContent: List<TabContent>,
currentSection: Sections,
isExpandedScreen: Boolean,
onTabChange: (Sections) -> Unit,
openDrawer: () -> Unit,
scaffoldState: ScaffoldState
) {
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(R.string.cd_interests),
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center
)
},
navigationIcon = if (!isExpandedScreen) {
{
IconButton(onClick = openDrawer) {
Icon(
painter = painterResource(R.drawable.ic_jetnews_logo),
contentDescription = stringResource(R.string.cd_open_navigation_drawer),
tint = MaterialTheme.colors.primary
)
}
}
} else {
null
},
actions = {
IconButton(
onClick = { /* TODO: Open search */ }
) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = stringResource(R.string.cd_search)
)
}
},
backgroundColor = MaterialTheme.colors.surface,
elevation = 0.dp
)
}
) { innerPadding ->
val screenModifier = Modifier.padding(innerPadding)
InterestScreenContent(currentSection, isExpandedScreen, onTabChange, tabContent, screenModifier)
}
}
/**
* Remembers the content for each tab on the Interests screen
* gathering application data from [InterestsViewModel]
*/
@Composable
fun rememberTabContent(interestsViewModel: InterestsViewModel): List<TabContent> {
// UiState of the InterestsScreen
val uiState by interestsViewModel.uiState.collectAsState()
// Describe the screen sections here since each section needs 2 states and 1 event.
// Pass them to the stateless InterestsScreen using a tabContent.
val topicsSection = TabContent(Sections.Topics) {
val selectedTopics by interestsViewModel.selectedTopics.collectAsState()
TabWithSections(
sections = uiState.topics,
selectedTopics = selectedTopics,
onTopicSelect = { interestsViewModel.toggleTopicSelection(it) }
)
}
val peopleSection = TabContent(Sections.People) {
val selectedPeople by interestsViewModel.selectedPeople.collectAsState()
TabWithTopics(
topics = uiState.people,
selectedTopics = selectedPeople,
onTopicSelect = { interestsViewModel.togglePersonSelected(it) }
)
}
val publicationSection = TabContent(Sections.Publications) {
val selectedPublications by interestsViewModel.selectedPublications.collectAsState()
TabWithTopics(
topics = uiState.publications,
selectedTopics = selectedPublications,
onTopicSelect = { interestsViewModel.togglePublicationSelected(it) }
)
}
return listOf(topicsSection, peopleSection, publicationSection)
}
/**
* Displays a tab row with [currentSection] selected and the body of the corresponding [tabContent].
*
* @param currentSection (state) the tab that is currently selected
* @param isExpandedScreen (state) whether or not the screen is expanded
* @param updateSection (event) request a change in tab selection
* @param tabContent (slot) tabs and their content to display, must be a non-empty list, tabs are
* displayed in the order of this list
*/
@Composable
private fun InterestScreenContent(
currentSection: Sections,
isExpandedScreen: Boolean,
updateSection: (Sections) -> Unit,
tabContent: List<TabContent>,
modifier: Modifier = Modifier
) {
val selectedTabIndex = tabContent.indexOfFirst { it.section == currentSection }
Column(modifier) {
InterestsTabRow(selectedTabIndex, updateSection, tabContent, isExpandedScreen)
Divider(
color = MaterialTheme.colors.onSurface.copy(alpha = 0.1f)
)
Box(modifier = Modifier.weight(1f)) {
// display the current tab content which is a @Composable () -> Unit
tabContent[selectedTabIndex].content()
}
}
}
/**
* Modifier for UI containers that show interests items
*/
private val tabContainerModifier = Modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.CenterHorizontally)
.navigationBarsPadding()
/**
* Display a simple list of topics
*
* @param topics (state) topics to display
* @param selectedTopics (state) currently selected topics
* @param onTopicSelect (event) request a topic selection be changed
*/
@Composable
private fun TabWithTopics(
topics: List<String>,
selectedTopics: Set<String>,
onTopicSelect: (String) -> Unit
) {
InterestsAdaptiveContentLayout(
topPadding = 16.dp,
modifier = tabContainerModifier.verticalScroll(rememberScrollState())
) {
topics.forEach { topic ->
TopicItem(
itemTitle = topic,
selected = selectedTopics.contains(topic),
onToggle = { onTopicSelect(topic) },
)
}
}
}
/**
* Display a sectioned list of topics
*
* @param sections (state) topics to display, grouped by sections
* @param selectedTopics (state) currently selected topics
* @param onTopicSelect (event) request a topic+section selection be changed
*/
@Composable
private fun TabWithSections(
sections: List<InterestSection>,
selectedTopics: Set<TopicSelection>,
onTopicSelect: (TopicSelection) -> Unit
) {
Column(tabContainerModifier.verticalScroll(rememberScrollState())) {
sections.forEach { (section, topics) ->
Text(
text = section,
modifier = Modifier
.padding(16.dp)
.semantics { heading() },
style = MaterialTheme.typography.subtitle1
)
InterestsAdaptiveContentLayout {
topics.forEach { topic ->
TopicItem(
itemTitle = topic,
selected = selectedTopics.contains(TopicSelection(section, topic)),
onToggle = { onTopicSelect(TopicSelection(section, topic)) },
)
}
}
}
}
}
/**
* Display a full-width topic item
*
* @param itemTitle (state) topic title
* @param selected (state) is topic currently selected
* @param onToggle (event) toggle selection for topic
*/
@Composable
private fun TopicItem(
itemTitle: String,
selected: Boolean,
onToggle: () -> Unit,
modifier: Modifier = Modifier
) {
Column(Modifier.padding(horizontal = 16.dp)) {
Row(
modifier = modifier.toggleable(
value = selected,
onValueChange = { onToggle() }
),
verticalAlignment = Alignment.CenterVertically
) {
val image = painterResource(R.drawable.placeholder_1_1)
Image(
painter = image,
contentDescription = null, // decorative
modifier = Modifier
.size(56.dp)
.clip(RoundedCornerShape(4.dp))
)
Text(
text = itemTitle,
modifier = Modifier
.padding(16.dp)
.weight(1f), // Break line if the title is too long
style = MaterialTheme.typography.subtitle1
)
Spacer(Modifier.weight(0.01f))
SelectTopicButton(selected = selected)
}
Divider(
modifier = modifier.padding(start = 72.dp, top = 8.dp, bottom = 8.dp),
color = MaterialTheme.colors.onSurface.copy(alpha = 0.1f)
)
}
}
/**
* TabRow for the InterestsScreen
*/
@Composable
private fun InterestsTabRow(
selectedTabIndex: Int,
updateSection: (Sections) -> Unit,
tabContent: List<TabContent>,
isExpandedScreen: Boolean
) {
when (isExpandedScreen) {
false -> {
TabRow(
selectedTabIndex = selectedTabIndex,
backgroundColor = MaterialTheme.colors.onPrimary,
contentColor = MaterialTheme.colors.primary
) {
InterestsTabRowContent(selectedTabIndex, updateSection, tabContent)
}
}
true -> {
ScrollableTabRow(
selectedTabIndex = selectedTabIndex,
backgroundColor = MaterialTheme.colors.onPrimary,
contentColor = MaterialTheme.colors.primary,
edgePadding = 0.dp
) {
InterestsTabRowContent(
selectedTabIndex = selectedTabIndex,
updateSection = updateSection,
tabContent = tabContent,
modifier = Modifier.padding(horizontal = 8.dp)
)
}
}
}
}
@Composable
private fun InterestsTabRowContent(
selectedTabIndex: Int,
updateSection: (Sections) -> Unit,
tabContent: List<TabContent>,
modifier: Modifier = Modifier
) {
tabContent.forEachIndexed { index, content ->
val colorText = if (selectedTabIndex == index) {
MaterialTheme.colors.primary
} else {
MaterialTheme.colors.onSurface.copy(alpha = 0.8f)
}
Tab(
selected = selectedTabIndex == index,
onClick = { updateSection(content.section) },
modifier = Modifier.heightIn(min = 48.dp)
) {
Text(
text = stringResource(id = content.section.titleResId),
color = colorText,
style = MaterialTheme.typography.subtitle2,
modifier = modifier.paddingFromBaseline(top = 20.dp)
)
}
}
}
/**
* Custom layout for the Interests screen that places items on the screen given the available size.
*
* For example: Given a list of items (A, B, C, D, E) and a screen size that allows 2 columns,
* the items will be displayed on the screen as follows:
* A B
* C D
* E
*/
@Composable
private fun InterestsAdaptiveContentLayout(
modifier: Modifier = Modifier,
topPadding: Dp = 0.dp,
itemSpacing: Dp = 4.dp,
itemMaxWidth: Dp = 450.dp,
multipleColumnsBreakPoint: Dp = 600.dp,
content: @Composable () -> Unit,
) {
Layout(modifier = modifier, content = content) { measurables, outerConstraints ->
// Convert parameters to Px. Safe to do as `Layout` measure block runs in a `Density` scope
val multipleColumnsBreakPointPx = multipleColumnsBreakPoint.roundToPx()
val topPaddingPx = topPadding.roundToPx()
val itemSpacingPx = itemSpacing.roundToPx()
val itemMaxWidthPx = itemMaxWidth.roundToPx()
// Number of columns to display on the screen. This is harcoded to 2 due to
// the design mocks, but this logic could change in the future.
val columns = if (outerConstraints.maxWidth < multipleColumnsBreakPointPx) 1 else 2
// Max width for each item taking into account available space, spacing and `itemMaxWidth`
val itemWidth = if (columns == 1) {
outerConstraints.maxWidth
} else {
val maxWidthWithSpaces = outerConstraints.maxWidth - (columns - 1) * itemSpacingPx
(maxWidthWithSpaces / columns).coerceIn(0, itemMaxWidthPx)
}
val itemConstraints = outerConstraints.copy(maxWidth = itemWidth)
// Keep track of the height of each row to calculate the layout's final size
val rowHeights = IntArray(measurables.size / columns + 1)
// Measure elements with their maximum width and keep track of the height
val placeables = measurables.mapIndexed { index, measureable ->
val placeable = measureable.measure(itemConstraints)
// Update the height for each row
val row = index.floorDiv(columns)
rowHeights[row] = max(rowHeights[row], placeable.height)
placeable
}
// Calculate maxHeight of the Interests layout. Heights of the row + top padding
val layoutHeight = topPaddingPx + rowHeights.sum()
// Calculate maxWidth of the Interests layout
val layoutWidth = itemWidth * columns + (itemSpacingPx * (columns - 1))
// Lay out given the max width and height
layout(
width = outerConstraints.constrainWidth(layoutWidth),
height = outerConstraints.constrainHeight(layoutHeight)
) {
// Track the y co-ord we have placed children up to
var yPosition = topPaddingPx
// Split placeables in lists that don't exceed the number of columns
// and place them taking into account their width and spacing
placeables.chunked(columns).forEachIndexed { rowIndex, row ->
var xPosition = 0
row.forEach { placeable ->
placeable.placeRelative(x = xPosition, y = yPosition)
xPosition += placeable.width + itemSpacingPx
}
yPosition += rowHeights[rowIndex]
}
}
}
}
@Preview("Interests screen", "Interests")
@Preview("Interests screen (dark)", "Interests", uiMode = UI_MODE_NIGHT_YES)
@Preview("Interests screen (big font)", "Interests", fontScale = 1.5f)
@Composable
fun PreviewInterestsScreenDrawer() {
JetnewsTheme {
val tabContent = getFakeTabsContent()
val (currentSection, updateSection) = rememberSaveable {
mutableStateOf(tabContent.first().section)
}
InterestsScreen(
tabContent = tabContent,
currentSection = currentSection,
isExpandedScreen = false,
onTabChange = updateSection,
openDrawer = { },
scaffoldState = rememberScaffoldState()
)
}
}
@Preview("Interests screen navrail", "Interests", device = Devices.PIXEL_C)
@Preview(
"Interests screen navrail (dark)", "Interests",
uiMode = UI_MODE_NIGHT_YES, device = Devices.PIXEL_C
)
@Preview(
"Interests screen navrail (big font)", "Interests",
fontScale = 1.5f, device = Devices.PIXEL_C
)
@Composable
fun PreviewInterestsScreenNavRail() {
JetnewsTheme {
val tabContent = getFakeTabsContent()
val (currentSection, updateSection) = rememberSaveable {
mutableStateOf(tabContent.first().section)
}
InterestsScreen(
tabContent = tabContent,
currentSection = currentSection,
isExpandedScreen = true,
onTabChange = updateSection,
openDrawer = { },
scaffoldState = rememberScaffoldState()
)
}
}
@Preview("Interests screen topics tab", "Topics")
@Preview("Interests screen topics tab (dark)", "Topics", uiMode = UI_MODE_NIGHT_YES)
@Composable
fun PreviewTopicsTab() {
val topics = runBlocking {
(FakeInterestsRepository().getTopics() as Result.Success).data
}
JetnewsTheme {
Surface {
TabWithSections(topics, setOf()) { }
}
}
}
@Preview("Interests screen people tab", "People")
@Preview("Interests screen people tab (dark)", "People", uiMode = UI_MODE_NIGHT_YES)
@Composable
fun PreviewPeopleTab() {
val people = runBlocking {
(FakeInterestsRepository().getPeople() as Result.Success).data
}
JetnewsTheme {
Surface {
TabWithTopics(people, setOf()) { }
}
}
}
@Preview("Interests screen publications tab", "Publications")
@Preview("Interests screen publications tab (dark)", "Publications", uiMode = UI_MODE_NIGHT_YES)
@Composable
fun PreviewPublicationsTab() {
val publications = runBlocking {
(FakeInterestsRepository().getPublications() as Result.Success).data
}
JetnewsTheme {
Surface {
TabWithTopics(publications, setOf()) { }
}
}
}
private fun getFakeTabsContent(): List<TabContent> {
val interestsRepository = FakeInterestsRepository()
val topicsSection = TabContent(Sections.Topics) {
TabWithSections(
runBlocking { (interestsRepository.getTopics() as Result.Success).data },
emptySet()
) { }
}
val peopleSection = TabContent(Sections.People) {
TabWithTopics(
runBlocking { (interestsRepository.getPeople() as Result.Success).data },
emptySet()
) { }
}
val publicationSection = TabContent(Sections.Publications) {
TabWithTopics(
runBlocking { (interestsRepository.getPublications() as Result.Success).data },
emptySet()
) { }
}
return listOf(topicsSection, peopleSection, publicationSection)
}