From 7e3faad699105fdd8cfced1a0debc30a0ae94fd4 Mon Sep 17 00:00:00 2001 From: Alex Vanyo Date: Wed, 10 Aug 2022 11:37:48 -0700 Subject: [PATCH 01/22] Add data logic for theme switcher Change-Id: Ifffadb897de4f6e08f7115103f99c156a7098b70 --- app/build.gradle.kts | 4 + .../samples/apps/nowinandroid/MainActivity.kt | 98 ++++++++++++++++++- .../samples/apps/nowinandroid/ui/NiaApp.kt | 94 +++++++++--------- .../OfflineFirstUserDataRepository.kt | 8 ++ .../data/repository/UserDataRepository.kt | 12 +++ .../repository/fake/FakeUserDataRepository.kt | 10 ++ .../OfflineFirstUserDataRepositoryTest.kt | 58 +++++++++++ .../datastore/NiaPreferencesDataSource.kt | 43 ++++++++ .../nowinandroid/data/dark_theme_config.proto | 27 +++++ .../apps/nowinandroid/data/theme_brand.proto | 26 +++++ .../nowinandroid/data/user_preferences.proto | 5 + .../core/designsystem/ThemeTest.kt | 40 ++------ .../core/designsystem/component/Background.kt | 8 +- .../core/designsystem/theme/Theme.kt | 78 ++++++++------- .../core/model/data/DarkThemeConfig.kt | 21 ++++ .../core/model/data/ThemeBrand.kt | 21 ++++ .../nowinandroid/core/model/data/UserData.kt | 2 + .../repository/TestUserDataRepository.kt | 18 +++- gradle/libs.versions.toml | 1 + 19 files changed, 455 insertions(+), 119 deletions(-) create mode 100644 core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/dark_theme_config.proto create mode 100644 core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/theme_brand.proto create mode 100644 core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/DarkThemeConfig.kt create mode 100644 core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/ThemeBrand.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index fe1f1cb64..3ef79890e 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -83,8 +83,11 @@ dependencies { implementation(project(":feature:bookmarks")) implementation(project(":feature:topic")) + implementation(project(":core:common")) implementation(project(":core:ui")) implementation(project(":core:designsystem")) + implementation(project(":core:data")) + implementation(project(":core:model")) implementation(project(":sync:work")) implementation(project(":sync:sync-test")) @@ -96,6 +99,7 @@ dependencies { androidTestImplementation(libs.androidx.navigation.testing) debugImplementation(libs.androidx.compose.ui.testManifest) + implementation(libs.accompanist.systemuicontroller) implementation(libs.androidx.activity.compose) implementation(libs.androidx.appcompat) implementation(libs.androidx.core.ktx) diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt index e5b86f910..fae677bab 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt @@ -19,14 +19,34 @@ package com.google.samples.apps.nowinandroid import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.view.WindowCompat +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import androidx.metrics.performance.JankStats +import com.google.accompanist.systemuicontroller.rememberSystemUiController +import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository +import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand +import com.google.samples.apps.nowinandroid.core.model.data.UserData +import com.google.samples.apps.nowinandroid.core.result.Result +import com.google.samples.apps.nowinandroid.core.result.asResult import com.google.samples.apps.nowinandroid.ui.NiaApp import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) @AndroidEntryPoint @@ -38,16 +58,60 @@ class MainActivity : ComponentActivity() { @Inject lateinit var lazyStats: dagger.Lazy + @Inject + lateinit var userDataRepository: UserDataRepository + override fun onCreate(savedInstanceState: Bundle?) { - installSplashScreen() + val splashScreen = installSplashScreen() super.onCreate(savedInstanceState) + /** + * The current user data, updated here to drive the UI theme + */ + var userDataResult: Result by mutableStateOf(Result.Loading) + + // Update the user data + lifecycleScope.launch { + lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { + userDataRepository.userDataStream + .asResult() + .onEach { + userDataResult = it + } + .collect() + } + } + + // Keep the splash screen on-screen until the user data is loaded + splashScreen.setKeepOnScreenCondition { + when (userDataResult) { + Result.Loading -> true + is Result.Success, is Result.Error -> false + } + } + // Turn off the decor fitting system windows, which allows us to handle insets, // including IME animations WindowCompat.setDecorFitsSystemWindows(window, false) setContent { - NiaApp(calculateWindowSizeClass(this)) + val systemUiController = rememberSystemUiController() + val darkTheme = shouldUseDarkTheme(userDataResult) + + // Update the dark content of the system bars to match the theme + DisposableEffect(systemUiController, darkTheme) { + systemUiController.systemBarsDarkContentEnabled = !darkTheme + onDispose {} + } + + NiaTheme( + darkTheme = darkTheme, + androidTheme = shouldUseAndroidTheme(userDataResult) + ) { + NiaApp( + windowSizeClass = calculateWindowSizeClass(this), + ) + } } } @@ -61,3 +125,33 @@ class MainActivity : ComponentActivity() { lazyStats.get().isTrackingEnabled = false } } + +/** + * Returns `true` if the Android theme shoudl be used, as a function of the [userDataResult]. + */ +@Composable +fun shouldUseAndroidTheme( + userDataResult: Result, +): Boolean = when (userDataResult) { + Result.Loading, is Result.Error -> false + is Result.Success -> when (userDataResult.data.themeBrand) { + ThemeBrand.DEFAULT -> false + ThemeBrand.ANDROID -> true + } +} + +/** + * Returns `true` if dark theme should be used, as a function of the [userDataResult] and the + * current system context. + */ +@Composable +fun shouldUseDarkTheme( + userDataResult: Result, +): Boolean = when (userDataResult) { + Result.Loading, is Result.Error -> isSystemInDarkTheme() + is Result.Success -> when (userDataResult.data.darkThemeConfig) { + DarkThemeConfig.FOLLOW_SYSTEM -> isSystemInDarkTheme() + DarkThemeConfig.LIGHT -> false + DarkThemeConfig.DARK -> true + } +} diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt index 213374100..a4b32aca1 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt @@ -65,59 +65,56 @@ fun NiaApp( windowSizeClass: WindowSizeClass, appState: NiaAppState = rememberNiaAppState(windowSizeClass) ) { - NiaTheme { - val background: @Composable (@Composable () -> Unit) -> Unit = - when (appState.currentDestination?.route) { - TopLevelDestination.FOR_YOU.name -> { content -> - NiaGradientBackground(content = content) - } - else -> { content -> NiaBackground(content = content) } - } + val background: @Composable (@Composable () -> Unit) -> Unit = + when (appState.currentDestination?.route) { + TopLevelDestination.FOR_YOU.name -> { content -> NiaGradientBackground(content = content) } + else -> { content -> NiaBackground(content = content) } + } - background { - Scaffold( - modifier = Modifier.semantics { - testTagsAsResourceId = true - }, - containerColor = Color.Transparent, - contentColor = MaterialTheme.colorScheme.onBackground, - contentWindowInsets = WindowInsets(0, 0, 0, 0), - bottomBar = { - if (appState.shouldShowBottomBar) { - NiaBottomBar( - destinations = appState.topLevelDestinations, - onNavigateToDestination = appState::navigateToTopLevelDestination, - currentDestination = appState.currentDestination - ) - } + background { + Scaffold( + modifier = Modifier.semantics { + testTagsAsResourceId = true + }, + containerColor = Color.Transparent, + contentColor = MaterialTheme.colorScheme.onBackground, + contentWindowInsets = WindowInsets(0, 0, 0, 0), + bottomBar = { + if (appState.shouldShowBottomBar) { + NiaBottomBar( + destinations = appState.topLevelDestinations, + onNavigateToDestination = appState::navigateToTopLevelDestination, + currentDestination = appState.currentDestination + ) } - ) { padding -> - Row( - Modifier - .fillMaxSize() - .windowInsetsPadding( - WindowInsets.safeDrawing.only( - WindowInsetsSides.Horizontal - ) - ) - ) { - if (appState.shouldShowNavRail) { - NiaNavRail( - destinations = appState.topLevelDestinations, - onNavigateToDestination = appState::navigateToTopLevelDestination, - currentDestination = appState.currentDestination, - modifier = Modifier.safeDrawingPadding() + } + ) { padding -> + Row( + Modifier + .fillMaxSize() + .windowInsetsPadding( + WindowInsets.safeDrawing.only( + WindowInsetsSides.Horizontal ) - } - - NiaNavHost( - navController = appState.navController, - onBackClick = appState::onBackClick, - modifier = Modifier - .padding(padding) - .consumedWindowInsets(padding) + ) + ) { + if (appState.shouldShowNavRail) { + NiaNavRail( + destinations = appState.topLevelDestinations, + onNavigateToDestination = appState::navigateToTopLevelDestination, + currentDestination = appState.currentDestination, + modifier = Modifier.safeDrawingPadding() ) } + + NiaNavHost( + navController = appState.navController, + onBackClick = appState::onBackClick, + + modifier = Modifier + .padding(padding) + .consumedWindowInsets(padding) + ) } } } @@ -182,6 +179,7 @@ private fun NiaBottomBar( imageVector = icon.imageVector, contentDescription = null ) + is DrawableResourceIcon -> Icon( painter = painterResource(id = icon.id), contentDescription = null diff --git a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstUserDataRepository.kt b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstUserDataRepository.kt index 046189037..8af0d3711 100644 --- a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstUserDataRepository.kt +++ b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstUserDataRepository.kt @@ -17,6 +17,8 @@ package com.google.samples.apps.nowinandroid.core.data.repository import com.google.samples.apps.nowinandroid.core.datastore.NiaPreferencesDataSource +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand import com.google.samples.apps.nowinandroid.core.model.data.UserData import javax.inject.Inject import kotlinx.coroutines.flow.Flow @@ -42,4 +44,10 @@ class OfflineFirstUserDataRepository @Inject constructor( override suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) = niaPreferencesDataSource.toggleNewsResourceBookmark(newsResourceId, bookmarked) + + override suspend fun setThemeBrand(themeBrand: ThemeBrand) = + niaPreferencesDataSource.setThemeBrand(themeBrand) + + override suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) = + niaPreferencesDataSource.setDarkThemeConfig(darkThemeConfig) } diff --git a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/UserDataRepository.kt b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/UserDataRepository.kt index deea011cc..7554d3f03 100644 --- a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/UserDataRepository.kt +++ b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/UserDataRepository.kt @@ -16,6 +16,8 @@ package com.google.samples.apps.nowinandroid.core.data.repository +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand import com.google.samples.apps.nowinandroid.core.model.data.UserData import kotlinx.coroutines.flow.Flow @@ -50,4 +52,14 @@ interface UserDataRepository { * Updates the bookmarked status for a news resource */ suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) + + /** + * Sets the desired theme brand. + */ + suspend fun setThemeBrand(themeBrand: ThemeBrand) + + /** + * Sets the desired dark theme config. + */ + suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) } diff --git a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/fake/FakeUserDataRepository.kt b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/fake/FakeUserDataRepository.kt index 5feb5eab3..58714cf40 100644 --- a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/fake/FakeUserDataRepository.kt +++ b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/fake/FakeUserDataRepository.kt @@ -19,6 +19,8 @@ package com.google.samples.apps.nowinandroid.core.data.repository.fake import com.google.samples.apps.nowinandroid.core.data.repository.AuthorsRepository import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository import com.google.samples.apps.nowinandroid.core.datastore.NiaPreferencesDataSource +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand import com.google.samples.apps.nowinandroid.core.model.data.UserData import javax.inject.Inject import kotlinx.coroutines.flow.Flow @@ -53,4 +55,12 @@ class FakeUserDataRepository @Inject constructor( override suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) { niaPreferencesDataSource.toggleNewsResourceBookmark(newsResourceId, bookmarked) } + + override suspend fun setThemeBrand(themeBrand: ThemeBrand) { + niaPreferencesDataSource.setThemeBrand(themeBrand) + } + + override suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) { + niaPreferencesDataSource.setDarkThemeConfig(darkThemeConfig) + } } diff --git a/core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstUserDataRepositoryTest.kt b/core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstUserDataRepositoryTest.kt index d65820ea0..fd4b2ccde 100644 --- a/core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstUserDataRepositoryTest.kt +++ b/core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstUserDataRepositoryTest.kt @@ -18,6 +18,9 @@ package com.google.samples.apps.nowinandroid.core.data.repository import com.google.samples.apps.nowinandroid.core.datastore.NiaPreferencesDataSource import com.google.samples.apps.nowinandroid.core.datastore.test.testUserPreferencesDataStore +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand +import com.google.samples.apps.nowinandroid.core.model.data.UserData import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.test.runTest @@ -46,6 +49,21 @@ class OfflineFirstUserDataRepositoryTest { ) } + @Test + fun offlineFirstUserDataRepository_default_user_data_is_correct() = + runTest { + assertEquals( + UserData( + bookmarkedNewsResources = emptySet(), + followedTopics = emptySet(), + followedAuthors = emptySet(), + themeBrand = ThemeBrand.DEFAULT, + darkThemeConfig = DarkThemeConfig.FOLLOW_SYSTEM + ), + subject.userDataStream.first() + ) + } + @Test fun offlineFirstUserDataRepository_toggle_followed_topics_logic_delegates_to_nia_preferences() = runTest { @@ -129,4 +147,44 @@ class OfflineFirstUserDataRepositoryTest { .first() ) } + + @Test + fun offlineFirstUserDataRepository_set_theme_brand_delegates_to_nia_preferences() = + runTest { + subject.setThemeBrand(ThemeBrand.ANDROID) + + assertEquals( + ThemeBrand.ANDROID, + subject.userDataStream + .map { it.themeBrand } + .first() + ) + assertEquals( + ThemeBrand.ANDROID, + niaPreferencesDataSource + .userDataStream + .map { it.themeBrand } + .first() + ) + } + + @Test + fun offlineFirstUserDataRepository_set_dark_theme_config_delegates_to_nia_preferences() = + runTest { + subject.setDarkThemeConfig(DarkThemeConfig.DARK) + + assertEquals( + DarkThemeConfig.DARK, + subject.userDataStream + .map { it.darkThemeConfig } + .first() + ) + assertEquals( + DarkThemeConfig.DARK, + niaPreferencesDataSource + .userDataStream + .map { it.darkThemeConfig } + .first() + ) + } } diff --git a/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt b/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt index 68bd599cf..52757e235 100644 --- a/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt +++ b/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt @@ -18,6 +18,10 @@ package com.google.samples.apps.nowinandroid.core.datastore import android.util.Log import androidx.datastore.core.DataStore +import com.google.protobuf.kotlin.DslList +import com.google.protobuf.kotlin.DslProxy +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand import com.google.samples.apps.nowinandroid.core.model.data.UserData import java.io.IOException import javax.inject.Inject @@ -34,6 +38,21 @@ class NiaPreferencesDataSource @Inject constructor( bookmarkedNewsResources = it.bookmarkedNewsResourceIdsMap.keys, followedTopics = it.followedTopicIdsMap.keys, followedAuthors = it.followedAuthorIdsMap.keys, + themeBrand = when (it.themeBrand!!) { + ThemeBrandProto.THEME_BRAND_UNSPECIFIED, + ThemeBrandProto.UNRECOGNIZED, + ThemeBrandProto.THEME_BRAND_DEFAULT -> ThemeBrand.DEFAULT + ThemeBrandProto.THEME_BRAND_ANDROID -> ThemeBrand.ANDROID + }, + darkThemeConfig = when (it.darkThemeConfig!!) { + DarkThemeConfigProto.DARK_THEME_CONFIG_UNSPECIFIED, + DarkThemeConfigProto.UNRECOGNIZED, + DarkThemeConfigProto.DARK_THEME_CONFIG_FOLLOW_SYSTEM -> + DarkThemeConfig.FOLLOW_SYSTEM + DarkThemeConfigProto.DARK_THEME_CONFIG_LIGHT -> + DarkThemeConfig.LIGHT + DarkThemeConfigProto.DARK_THEME_CONFIG_DARK -> DarkThemeConfig.DARK + } ) } @@ -95,6 +114,30 @@ class NiaPreferencesDataSource @Inject constructor( } } + suspend fun setThemeBrand(themeBrand: ThemeBrand) { + userPreferences.updateData { + it.copy { + this.themeBrand = when (themeBrand) { + ThemeBrand.DEFAULT -> ThemeBrandProto.THEME_BRAND_DEFAULT + ThemeBrand.ANDROID -> ThemeBrandProto.THEME_BRAND_ANDROID + } + } + } + } + + suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) { + userPreferences.updateData { + it.copy { + this.darkThemeConfig = when (darkThemeConfig) { + DarkThemeConfig.FOLLOW_SYSTEM -> + DarkThemeConfigProto.DARK_THEME_CONFIG_FOLLOW_SYSTEM + DarkThemeConfig.LIGHT -> DarkThemeConfigProto.DARK_THEME_CONFIG_LIGHT + DarkThemeConfig.DARK -> DarkThemeConfigProto.DARK_THEME_CONFIG_DARK + } + } + } + } + suspend fun toggleNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) { try { userPreferences.updateData { diff --git a/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/dark_theme_config.proto b/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/dark_theme_config.proto new file mode 100644 index 000000000..82bac8366 --- /dev/null +++ b/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/dark_theme_config.proto @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2022 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. + */ + +syntax = "proto3"; + +option java_package = "com.google.samples.apps.nowinandroid.core.datastore"; +option java_multiple_files = true; + +enum DarkThemeConfigProto { + DARK_THEME_CONFIG_UNSPECIFIED = 0; + DARK_THEME_CONFIG_FOLLOW_SYSTEM = 1; + DARK_THEME_CONFIG_LIGHT = 2; + DARK_THEME_CONFIG_DARK = 3; +} diff --git a/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/theme_brand.proto b/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/theme_brand.proto new file mode 100644 index 000000000..8bcf5859b --- /dev/null +++ b/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/theme_brand.proto @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2022 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. + */ + +syntax = "proto3"; + +option java_package = "com.google.samples.apps.nowinandroid.core.datastore"; +option java_multiple_files = true; + +enum ThemeBrandProto { + THEME_BRAND_UNSPECIFIED = 0; + THEME_BRAND_DEFAULT = 1; + THEME_BRAND_ANDROID = 2; +} diff --git a/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/user_preferences.proto b/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/user_preferences.proto index 029502681..c20dc4adb 100644 --- a/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/user_preferences.proto +++ b/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/user_preferences.proto @@ -16,6 +16,9 @@ syntax = "proto3"; +import "com/google/samples/apps/nowinandroid/data/dark_theme_config.proto"; +import "com/google/samples/apps/nowinandroid/data/theme_brand.proto"; + option java_package = "com.google.samples.apps.nowinandroid.core.datastore"; option java_multiple_files = true; @@ -37,4 +40,6 @@ message UserPreferences { map followed_topic_ids = 13; map followed_author_ids = 14; map bookmarked_news_resource_ids = 15; + ThemeBrandProto theme_brand = 12; + DarkThemeConfigProto dark_theme_config = 13; } diff --git a/core/designsystem/src/androidTest/java/com/google/samples/apps/nowinandroid/core/designsystem/ThemeTest.kt b/core/designsystem/src/androidTest/java/com/google/samples/apps/nowinandroid/core/designsystem/ThemeTest.kt index d0fb5ff83..8710ba265 100644 --- a/core/designsystem/src/androidTest/java/com/google/samples/apps/nowinandroid/core/designsystem/ThemeTest.kt +++ b/core/designsystem/src/androidTest/java/com/google/samples/apps/nowinandroid/core/designsystem/ThemeTest.kt @@ -58,7 +58,7 @@ class ThemeTest { composeTestRule.setContent { NiaTheme( darkTheme = false, - dynamicColor = false, + disableDynamicTheming = true, androidTheme = false ) { val colorScheme = LightDefaultColorScheme @@ -79,7 +79,7 @@ class ThemeTest { composeTestRule.setContent { NiaTheme( darkTheme = true, - dynamicColor = false, + disableDynamicTheming = true, androidTheme = false ) { val colorScheme = DarkDefaultColorScheme @@ -100,7 +100,6 @@ class ThemeTest { composeTestRule.setContent { NiaTheme( darkTheme = false, - dynamicColor = true, androidTheme = false ) { val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { @@ -129,7 +128,6 @@ class ThemeTest { composeTestRule.setContent { NiaTheme( darkTheme = true, - dynamicColor = true, androidTheme = false ) { val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { @@ -154,7 +152,7 @@ class ThemeTest { composeTestRule.setContent { NiaTheme( darkTheme = false, - dynamicColor = false, + disableDynamicTheming = true, androidTheme = true ) { val colorScheme = LightAndroidColorScheme @@ -172,7 +170,7 @@ class ThemeTest { composeTestRule.setContent { NiaTheme( darkTheme = true, - dynamicColor = false, + disableDynamicTheming = true, androidTheme = true ) { val colorScheme = DarkAndroidColorScheme @@ -190,25 +188,13 @@ class ThemeTest { composeTestRule.setContent { NiaTheme( darkTheme = false, - dynamicColor = true, androidTheme = true ) { - val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - dynamicLightColorScheme(LocalContext.current) - } else { - LightDefaultColorScheme - } + val colorScheme = LightAndroidColorScheme assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) - val gradientColors = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - GradientColors() - } else { - LightDefaultGradientColors - } + val gradientColors = GradientColors() assertEquals(gradientColors, LocalGradientColors.current) - val backgroundTheme = BackgroundTheme( - color = colorScheme.surface, - tonalElevation = 2.dp - ) + val backgroundTheme = LightAndroidBackgroundTheme assertEquals(backgroundTheme, LocalBackgroundTheme.current) } } @@ -219,21 +205,13 @@ class ThemeTest { composeTestRule.setContent { NiaTheme( darkTheme = true, - dynamicColor = true, androidTheme = true ) { - val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - dynamicDarkColorScheme(LocalContext.current) - } else { - DarkDefaultColorScheme - } + val colorScheme = DarkAndroidColorScheme assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) val gradientColors = GradientColors() assertEquals(gradientColors, LocalGradientColors.current) - val backgroundTheme = BackgroundTheme( - color = colorScheme.surface, - tonalElevation = 2.dp - ) + val backgroundTheme = DarkAndroidBackgroundTheme assertEquals(backgroundTheme, LocalBackgroundTheme.current) } } diff --git a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/Background.kt b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/Background.kt index 985471534..833ec955d 100644 --- a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/Background.kt +++ b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/Background.kt @@ -144,7 +144,7 @@ annotation class ThemePreviews @ThemePreviews @Composable fun BackgroundDefault() { - NiaTheme { + NiaTheme(disableDynamicTheming = true) { NiaBackground(Modifier.size(100.dp), content = {}) } } @@ -152,7 +152,7 @@ fun BackgroundDefault() { @ThemePreviews @Composable fun BackgroundDynamic() { - NiaTheme(dynamicColor = true) { + NiaTheme { NiaBackground(Modifier.size(100.dp), content = {}) } } @@ -168,7 +168,7 @@ fun BackgroundAndroid() { @ThemePreviews @Composable fun GradientBackgroundDefault() { - NiaTheme { + NiaTheme(disableDynamicTheming = true) { NiaGradientBackground(Modifier.size(100.dp), content = {}) } } @@ -176,7 +176,7 @@ fun GradientBackgroundDefault() { @ThemePreviews @Composable fun GradientBackgroundDynamic() { - NiaTheme(dynamicColor = true) { + NiaTheme { NiaGradientBackground(Modifier.size(100.dp), content = {}) } } diff --git a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/theme/Theme.kt b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/theme/Theme.kt index efec108f8..10f0c3898 100644 --- a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/theme/Theme.kt +++ b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/theme/Theme.kt @@ -17,6 +17,7 @@ package com.google.samples.apps.nowinandroid.core.designsystem.theme import android.os.Build +import androidx.annotation.ChecksSdkIntAtLeast import androidx.annotation.VisibleForTesting import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme @@ -173,55 +174,63 @@ val DarkAndroidBackgroundTheme = BackgroundTheme(color = Color.Black) /** * Now in Android theme. * - * The order of precedence for the color scheme is: Dynamic color > Android theme > Default theme. - * Dark theme is independent as all the aforementioned color schemes have light and dark versions. - * The default theme color scheme is used by default. - * * @param darkTheme Whether the theme should use a dark color scheme (follows system by default). - * @param dynamicColor Whether the theme should use a dynamic color scheme (Android 12+ only). - * @param androidTheme Whether the theme should use the Android theme color scheme. + * @param androidTheme Whether the theme should use the Android theme color scheme instead of the + * default theme. If this is `false`, then dynamic theming will be used when supported. */ @Composable fun NiaTheme( darkTheme: Boolean = isSystemInDarkTheme(), - dynamicColor: Boolean = false, androidTheme: Boolean = false, - content: @Composable() () -> Unit + content: @Composable () -> Unit +) = NiaTheme( + darkTheme = darkTheme, + androidTheme = androidTheme, + disableDynamicTheming = false, + content = content +) + +/** + * Now in Android theme. This is an internal only version, to allow disabling dynamic theming + * in tests. + * + * @param darkTheme Whether the theme should use a dark color scheme (follows system by default). + * @param androidTheme Whether the theme should use the Android theme color scheme instead of the + * default theme. + * @param disableDynamicTheming If `true`, disables the use of dynamic theming, even when it is + * supported. This parameter has no effect if [androidTheme] is `true`. + */ +@Composable +internal fun NiaTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + androidTheme: Boolean = false, + disableDynamicTheming: Boolean, + content: @Composable () -> Unit ) { - val colorScheme = when { - dynamicColor -> { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - val context = LocalContext.current - if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) - } else { - if (darkTheme) DarkDefaultColorScheme else LightDefaultColorScheme - } - } - androidTheme -> if (darkTheme) DarkAndroidColorScheme else LightAndroidColorScheme - else -> if (darkTheme) DarkDefaultColorScheme else LightDefaultColorScheme + val colorScheme = if (androidTheme) { + if (darkTheme) DarkAndroidColorScheme else LightAndroidColorScheme + } else if (!disableDynamicTheming && supportsDynamicTheming()) { + val context = LocalContext.current + if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } else { + if (darkTheme) DarkDefaultColorScheme else LightDefaultColorScheme } val defaultGradientColors = GradientColors() - val gradientColors = when { - dynamicColor -> { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - defaultGradientColors - } else { - if (darkTheme) defaultGradientColors else LightDefaultGradientColors - } - } - androidTheme -> defaultGradientColors - else -> if (darkTheme) defaultGradientColors else LightDefaultGradientColors + val gradientColors = if (androidTheme || (!disableDynamicTheming && supportsDynamicTheming())) { + defaultGradientColors + } else { + if (darkTheme) defaultGradientColors else LightDefaultGradientColors } val defaultBackgroundTheme = BackgroundTheme( color = colorScheme.surface, tonalElevation = 2.dp ) - val backgroundTheme = when { - dynamicColor -> defaultBackgroundTheme - androidTheme -> if (darkTheme) DarkAndroidBackgroundTheme else LightAndroidBackgroundTheme - else -> defaultBackgroundTheme + val backgroundTheme = if (androidTheme) { + if (darkTheme) DarkAndroidBackgroundTheme else LightAndroidBackgroundTheme + } else { + defaultBackgroundTheme } CompositionLocalProvider( @@ -235,3 +244,6 @@ fun NiaTheme( ) } } + +@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S) +private fun supportsDynamicTheming() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S diff --git a/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/DarkThemeConfig.kt b/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/DarkThemeConfig.kt new file mode 100644 index 000000000..f130a70db --- /dev/null +++ b/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/DarkThemeConfig.kt @@ -0,0 +1,21 @@ +/* + * Copyright 2022 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.google.samples.apps.nowinandroid.core.model.data + +enum class DarkThemeConfig { + FOLLOW_SYSTEM, LIGHT, DARK +} diff --git a/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/ThemeBrand.kt b/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/ThemeBrand.kt new file mode 100644 index 000000000..d8953df3c --- /dev/null +++ b/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/ThemeBrand.kt @@ -0,0 +1,21 @@ +/* + * Copyright 2022 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.google.samples.apps.nowinandroid.core.model.data + +enum class ThemeBrand { + DEFAULT, ANDROID +} diff --git a/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/UserData.kt b/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/UserData.kt index 4535a14b4..13f1dd737 100644 --- a/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/UserData.kt +++ b/core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/UserData.kt @@ -23,4 +23,6 @@ data class UserData( val bookmarkedNewsResources: Set, val followedTopics: Set, val followedAuthors: Set, + val themeBrand: ThemeBrand, + val darkThemeConfig: DarkThemeConfig, ) diff --git a/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/repository/TestUserDataRepository.kt b/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/repository/TestUserDataRepository.kt index 748b4e724..4dfd573a1 100644 --- a/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/repository/TestUserDataRepository.kt +++ b/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/repository/TestUserDataRepository.kt @@ -17,6 +17,8 @@ package com.google.samples.apps.nowinandroid.core.testing.repository import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand import com.google.samples.apps.nowinandroid.core.model.data.UserData import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST import kotlinx.coroutines.flow.Flow @@ -26,7 +28,9 @@ import kotlinx.coroutines.flow.filterNotNull private val emptyUserData = UserData( bookmarkedNewsResources = emptySet(), followedTopics = emptySet(), - followedAuthors = emptySet() + followedAuthors = emptySet(), + themeBrand = ThemeBrand.DEFAULT, + darkThemeConfig = DarkThemeConfig.FOLLOW_SYSTEM ) class TestUserDataRepository : UserDataRepository { @@ -74,6 +78,18 @@ class TestUserDataRepository : UserDataRepository { } } + override suspend fun setThemeBrand(themeBrand: ThemeBrand) { + currentUserData.let { current -> + _userData.tryEmit(current.copy(themeBrand = themeBrand)) + } + } + + override suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) { + currentUserData.let { current -> + _userData.tryEmit(current.copy(darkThemeConfig = darkThemeConfig)) + } + } + /** * A test-only API to allow setting/unsetting of bookmarks. * diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index b63d2f937..cdf65d1b3 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -52,6 +52,7 @@ turbine = "0.8.0" [libraries] accompanist-flowlayout = { group = "com.google.accompanist", name = "accompanist-flowlayout", version.ref = "accompanist" } +accompanist-systemuicontroller = { group = "com.google.accompanist", name = "accompanist-systemuicontroller", version.ref = "accompanist" } android-desugarJdkLibs = { group = "com.android.tools", name = "desugar_jdk_libs", version.ref = "androidDesugarJdkLibs" } androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "androidxActivity" } androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "androidxAppCompat" } From b6cae161c28f759b5e6a76197a0af478121eaf07 Mon Sep 17 00:00:00 2001 From: Jolanda Verhoef Date: Tue, 11 Oct 2022 22:31:03 +0100 Subject: [PATCH 02/22] Add basic UI for theme switcher --- .../feature/foryou/ForYouScreen.kt | 129 +++++++++++++++++- .../feature/foryou/ForYouViewModel.kt | 30 ++++ 2 files changed, 158 insertions(+), 1 deletion(-) diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt index 252afb1ce..c482f0edf 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt @@ -18,6 +18,7 @@ package com.google.samples.apps.nowinandroid.feature.foryou import android.app.Activity import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints @@ -46,11 +47,16 @@ import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.rememberLazyGridState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.shape.CornerSize import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarDuration.Indefinite import androidx.compose.material3.SnackbarHost @@ -61,7 +67,9 @@ import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @@ -71,6 +79,7 @@ import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.max @@ -90,6 +99,13 @@ import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.domain.model.FollowableAuthor import com.google.samples.apps.nowinandroid.core.domain.model.FollowableTopic import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.DARK +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.FOLLOW_SYSTEM +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.LIGHT +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.ANDROID +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.DEFAULT import com.google.samples.apps.nowinandroid.core.model.data.previewAuthors import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources import com.google.samples.apps.nowinandroid.core.model.data.previewTopics @@ -108,6 +124,7 @@ internal fun ForYouRoute( val feedState by viewModel.feedState.collectAsStateWithLifecycle() val isOffline by viewModel.isOffline.collectAsStateWithLifecycle() val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle() + val themeState by viewModel.themeState.collectAsStateWithLifecycle() ForYouScreen( isOffline = isOffline, @@ -118,6 +135,9 @@ internal fun ForYouRoute( onAuthorCheckedChanged = viewModel::updateAuthorSelection, saveFollowedTopics = viewModel::saveFollowedInterests, onNewsResourcesCheckedChanged = viewModel::updateNewsResourceSaved, + themeState = themeState, + onChangeThemeBrand = viewModel::updateThemeBrand, + onChangeDarkThemeConfig = viewModel::updateDarkThemeConfig, modifier = modifier ) } @@ -134,8 +154,22 @@ internal fun ForYouScreen( saveFollowedTopics: () -> Unit, onNewsResourcesCheckedChanged: (String, Boolean) -> Unit, modifier: Modifier = Modifier, + themeState: Pair = Pair(DEFAULT, FOLLOW_SYSTEM), + onChangeThemeBrand: (themeBrand: ThemeBrand) -> Unit = {}, + onChangeDarkThemeConfig: (darkThemeConfig: DarkThemeConfig) -> Unit = {}, ) { val snackbarHostState = remember { SnackbarHostState() } + var openAccountDialog by remember { mutableStateOf(false) } + + if (openAccountDialog) { + AccountDialog( + onDismiss = { openAccountDialog = false }, + currentThemeBrand = themeState.first, + currentDarkThemeConfig = themeState.second, + onChangeThemeBrand = onChangeThemeBrand, + onChangeDarkThemeConfig = onChangeDarkThemeConfig + ) + } Scaffold( snackbarHost = { SnackbarHost(snackbarHostState) }, @@ -148,7 +182,8 @@ internal fun ForYouScreen( ), colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = Color.Transparent - ) + ), + onActionClick = { openAccountDialog = true } ) }, containerColor = Color.Transparent, @@ -268,6 +303,7 @@ private fun LazyGridScope.interestsSelection( ForYouInterestsSelectionUiState.Loading, ForYouInterestsSelectionUiState.LoadFailed, ForYouInterestsSelectionUiState.NoInterestsSelection -> Unit + is ForYouInterestsSelectionUiState.WithInterestsSelection -> { item(span = { GridItemSpan(maxLineSpan) }) { Column(modifier = interestsItemModifier) { @@ -433,6 +469,97 @@ fun TopicIcon( ) } +@Composable +fun AccountDialog( + onDismiss: () -> Unit, + currentThemeBrand: ThemeBrand, + currentDarkThemeConfig: DarkThemeConfig, + onChangeThemeBrand: (themeBrand: ThemeBrand) -> Unit, + onChangeDarkThemeConfig: (darkThemeConfig: DarkThemeConfig) -> Unit +) { + AlertDialog( + onDismissRequest = { onDismiss() }, + title = { + Text( + text = "Change theme and dark mode", + style = MaterialTheme.typography.titleLarge + ) + }, + text = { + Column { + Divider() + Column { + AccountDialogThemeChooserRow( + text = "Default", + selected = currentThemeBrand == DEFAULT, + onClick = { onChangeThemeBrand(DEFAULT) } + ) + AccountDialogThemeChooserRow( + text = "Android", + selected = currentThemeBrand == ANDROID, + onClick = { onChangeThemeBrand(ANDROID) } + ) + } + Divider() + Column(Modifier.selectableGroup()) { + AccountDialogThemeChooserRow( + text = "System default", + selected = currentDarkThemeConfig == FOLLOW_SYSTEM, + onClick = { onChangeDarkThemeConfig(FOLLOW_SYSTEM) } + ) + AccountDialogThemeChooserRow( + text = "Light", + selected = currentDarkThemeConfig == LIGHT, + onClick = { onChangeDarkThemeConfig(LIGHT) } + ) + AccountDialogThemeChooserRow( + text = "Dark", + selected = currentDarkThemeConfig == DARK, + onClick = { onChangeDarkThemeConfig(DARK) } + ) + } + Divider() + } + }, + confirmButton = { + Text( + text = "OK", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier + .padding(15.dp) + .clickable { onDismiss() } + ) + } + ) +} + +@Composable +fun AccountDialogThemeChooserRow( + text: String, + selected: Boolean, + onClick: () -> Unit +) { + Row( + Modifier + .fillMaxWidth() + .selectable( + selected = selected, + role = Role.RadioButton, + onClick = onClick + ) + .padding(8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + RadioButton( + selected = selected, + onClick = null + ) + Spacer(Modifier.width(8.dp)) + Text(text) + } +} + @DevicePreviews @Composable fun ForYouScreenPopulatedFeed() { diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt index 8cbf39c31..3c20719e6 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt @@ -31,6 +31,10 @@ import com.google.samples.apps.nowinandroid.core.domain.GetFollowableTopicsStrea import com.google.samples.apps.nowinandroid.core.domain.GetSaveableNewsResourcesStreamUseCase import com.google.samples.apps.nowinandroid.core.domain.GetSortedFollowableAuthorsStreamUseCase import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.FOLLOW_SYSTEM +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.DEFAULT import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState import com.google.samples.apps.nowinandroid.feature.foryou.FollowedInterestsUiState.FollowedInterests import com.google.samples.apps.nowinandroid.feature.foryou.FollowedInterestsUiState.None @@ -78,6 +82,20 @@ class ForYouViewModel @Inject constructor( initialValue = Unknown ) + /** + * The current theme of the app + */ + val themeState: StateFlow> = + userDataRepository.userDataStream + .map { userData -> + Pair(userData.themeBrand, userData.darkThemeConfig) + } + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5_000), + initialValue = Pair(DEFAULT, FOLLOW_SYSTEM) + ) + /** * The in-progress set of topics to be selected, persisted through process death with a * [SavedStateHandle]. @@ -226,6 +244,18 @@ class ForYouViewModel @Inject constructor( } } } + + fun updateThemeBrand(themeBrand: ThemeBrand) { + viewModelScope.launch { + userDataRepository.setThemeBrand(themeBrand) + } + } + + fun updateDarkThemeConfig(darkThemeConfig: DarkThemeConfig) { + viewModelScope.launch { + userDataRepository.setDarkThemeConfig(darkThemeConfig) + } + } } private fun Flow>.mapToFeedState(): Flow = From add486a0ab6df2297e22f6722015e0e5f913b4d4 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Tue, 18 Oct 2022 07:16:07 +0100 Subject: [PATCH 03/22] Fix spotless issues --- .../main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt | 1 - .../nowinandroid/core/datastore/NiaPreferencesDataSource.kt | 2 -- 2 files changed, 3 deletions(-) diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt index a4b32aca1..01c72499a 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt @@ -51,7 +51,6 @@ import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavig import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationRailItem import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.DrawableResourceIcon import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.ImageVectorIcon -import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.navigation.NiaNavHost import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination diff --git a/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt b/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt index 52757e235..96cdc7a13 100644 --- a/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt +++ b/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt @@ -18,8 +18,6 @@ package com.google.samples.apps.nowinandroid.core.datastore import android.util.Log import androidx.datastore.core.DataStore -import com.google.protobuf.kotlin.DslList -import com.google.protobuf.kotlin.DslProxy import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand import com.google.samples.apps.nowinandroid.core.model.data.UserData From b7500ea09b50eb7bdfab132430d9d295d3d922d2 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Tue, 18 Oct 2022 10:00:54 +0100 Subject: [PATCH 04/22] Fix typo --- .../java/com/google/samples/apps/nowinandroid/MainActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt index fae677bab..3f9af2a4d 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt @@ -127,7 +127,7 @@ class MainActivity : ComponentActivity() { } /** - * Returns `true` if the Android theme shoudl be used, as a function of the [userDataResult]. + * Returns `true` if the Android theme should be used, as a function of the [userDataResult]. */ @Composable fun shouldUseAndroidTheme( From 8c30ab9f80435643d283405a9907537ecc660d34 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Tue, 18 Oct 2022 18:44:08 +0100 Subject: [PATCH 05/22] Add settings module, refactor top bar --- app/build.gradle.kts | 1 + .../apps/nowinandroid/ui/NavigationTest.kt | 43 +++++++++++++++++++ .../apps/nowinandroid/ui/NiaAppStateTest.kt | 13 ++++++ .../navigation/TopLevelDestination.kt | 13 ++++-- .../samples/apps/nowinandroid/ui/NiaApp.kt | 20 +++++++++ .../apps/nowinandroid/ui/NiaAppState.kt | 6 ++- build.gradle.kts | 1 + .../nowinandroid/data/user_preferences.proto | 5 ++- .../core/designsystem/component/TopAppBar.kt | 4 +- .../core/designsystem/icon/NiaIcons.kt | 2 + .../src/main/res/values/strings.xml | 1 + .../navigation/NiaNavigationDestination.kt | 0 .../feature/bookmarks/BookmarksScreen.kt | 15 ------- .../bookmarks/src/main/res/values/strings.xml | 2 +- .../feature/foryou/ForYouScreen.kt | 15 ------- .../foryou/src/main/res/values/strings.xml | 1 - .../feature/interests/InterestsScreen.kt | 14 ------ .../interests/src/main/res/values/strings.xml | 2 + feature/settings/.gitignore | 1 + feature/settings/build.gradle.kts | 24 +++++++++++ feature/settings/proguard-rules.pro | 21 +++++++++ feature/settings/src/main/AndroidManifest.xml | 19 ++++++++ .../settings/src/main/res/values/strings.xml | 19 ++++++++ settings.gradle.kts | 1 + 24 files changed, 189 insertions(+), 54 deletions(-) create mode 100644 core/navigation/src/main/java/com/google/samples/apps/nowinandroid/core/navigation/NiaNavigationDestination.kt create mode 100644 feature/settings/.gitignore create mode 100644 feature/settings/build.gradle.kts create mode 100644 feature/settings/proguard-rules.pro create mode 100644 feature/settings/src/main/AndroidManifest.xml create mode 100644 feature/settings/src/main/res/values/strings.xml diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 3ef79890e..f7d561dbc 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -82,6 +82,7 @@ dependencies { implementation(project(":feature:foryou")) implementation(project(":feature:bookmarks")) implementation(project(":feature:topic")) + implementation(project(":feature:settings")) implementation(project(":core:common")) implementation(project(":core:ui")) diff --git a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt index 184d48507..abbf774fe 100644 --- a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt +++ b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt @@ -16,17 +16,22 @@ package com.google.samples.apps.nowinandroid.ui +import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.assertIsOn import androidx.compose.ui.test.assertIsSelected import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.test.espresso.Espresso import androidx.test.espresso.NoActivityResumedException import com.google.samples.apps.nowinandroid.MainActivity +import com.google.samples.apps.nowinandroid.R +import com.google.samples.apps.nowinandroid.feature.bookmarks.R as BookmarksR import com.google.samples.apps.nowinandroid.feature.foryou.R as FeatureForyouR import com.google.samples.apps.nowinandroid.feature.interests.R as FeatureInterestsR +import com.google.samples.apps.nowinandroid.feature.settings.R as SettingsR import dagger.hilt.android.testing.BindValue import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest @@ -67,6 +72,9 @@ class NavigationTest { private lateinit var forYou: String private lateinit var interests: String private lateinit var sampleTopic: String + private lateinit var appName: String + private lateinit var saved: String + private lateinit var settings: String @Before fun setup() { @@ -77,6 +85,9 @@ class NavigationTest { forYou = getString(FeatureForyouR.string.for_you) interests = getString(FeatureInterestsR.string.interests) sampleTopic = "Headlines" + appName = getString(R.string.app_name) + saved = getString(BookmarksR.string.saved) + settings = getString(SettingsR.string.top_app_bar_action_icon_description) } } @@ -146,6 +157,38 @@ class NavigationTest { } } + @Test + fun topLevelDestinations_showTopBarWithTitle() { + composeTestRule.apply { + + // Verify that the top bar contains the app name on the first screen. + onNodeWithText(appName).assertExists() + + // Go to the bookmarks tab, verify that the top bar contains the app name. + onNodeWithText(saved).performClick() + onNodeWithText(appName).assertExists() + + // Go to the interests tab, verify that the top bar contains "Interests". This means + // we'll have 2 elements with the text "Interests" on screen. One in the top bar, and + // one in the bottom navigation. + onNodeWithText(interests).performClick() + onAllNodesWithText(interests).assertCountEquals(2) + } + } + + @Test + fun topLevelDestinations_showSettingsIcon() { + composeTestRule.apply { + onNodeWithContentDescription(settings).assertExists() + + onNodeWithText(saved).performClick() + onNodeWithContentDescription(settings).assertExists() + + onNodeWithText(interests).performClick() + onNodeWithContentDescription(settings).assertExists() + } + } + /* * There should always be at most one instance of a top-level destination at the same time. */ diff --git a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt index c2e17700f..f6361d844 100644 --- a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt +++ b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt @@ -87,6 +87,19 @@ class NiaAppStateTest { assertTrue(state.topLevelDestinations[2].name.contains("interests", true)) } + @Test + fun niaAppState_showTopBarForTopLevelDestinations() { + composeTestRule.setContent { + val navController = rememberTestNavController() + state = rememberNiaAppState( + windowSizeClass = getCompactWindowClass(), + navController = navController + ) + + // Do nothing - we should already be + } + } + @Test fun niaAppState_showBottomBar_compact() { composeTestRule.setContent { diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/navigation/TopLevelDestination.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/navigation/TopLevelDestination.kt index 566997920..247b2934b 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/navigation/TopLevelDestination.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/navigation/TopLevelDestination.kt @@ -23,6 +23,7 @@ import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.feature.bookmarks.R as bookmarksR import com.google.samples.apps.nowinandroid.feature.foryou.R as forYouR import com.google.samples.apps.nowinandroid.feature.interests.R as interestsR +import com.google.samples.apps.nowinandroid.R /** * Type for the top level destinations in the application. Each of these destinations @@ -32,21 +33,25 @@ import com.google.samples.apps.nowinandroid.feature.interests.R as interestsR enum class TopLevelDestination( val selectedIcon: Icon, val unselectedIcon: Icon, - val iconTextId: Int + val iconTextId: Int, + val titleTextId: Int ) { FOR_YOU( selectedIcon = DrawableResourceIcon(NiaIcons.Upcoming), unselectedIcon = DrawableResourceIcon(NiaIcons.UpcomingBorder), - iconTextId = forYouR.string.for_you + iconTextId = forYouR.string.for_you, + titleTextId = R.string.app_name ), BOOKMARKS( selectedIcon = DrawableResourceIcon(NiaIcons.Bookmarks), unselectedIcon = DrawableResourceIcon(NiaIcons.BookmarksBorder), - iconTextId = bookmarksR.string.saved + iconTextId = bookmarksR.string.saved, + titleTextId = bookmarksR.string.saved ), INTERESTS( selectedIcon = ImageVectorIcon(NiaIcons.Grid3x3), unselectedIcon = ImageVectorIcon(NiaIcons.Grid3x3), - iconTextId = interestsR.string.interests + iconTextId = interestsR.string.interests, + titleTextId = interestsR.string.interests ) } diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt index 01c72499a..f28824c5a 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt @@ -32,6 +32,7 @@ import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.ui.ExperimentalComposeUiApi @@ -49,8 +50,11 @@ import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavig import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBarItem import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationRail import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationRailItem +import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopAppBar import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.DrawableResourceIcon import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.ImageVectorIcon +import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons +import com.google.samples.apps.nowinandroid.feature.settings.R as settingsR import com.google.samples.apps.nowinandroid.navigation.NiaNavHost import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination @@ -78,6 +82,22 @@ fun NiaApp( containerColor = Color.Transparent, contentColor = MaterialTheme.colorScheme.onBackground, contentWindowInsets = WindowInsets(0, 0, 0, 0), + topBar = { + val destination = appState.topLevelDestinations[appState.currentDestination?.route] + if (appState.shouldShowTopBar && destination != null) { + NiaTopAppBar( + titleRes = destination.titleTextId, + actionIcon = NiaIcons.Settings, + actionIconContentDescription = stringResource( + id = settingsR.string.top_app_bar_action_icon_description + ), + colors = TopAppBarDefaults.centerAlignedTopAppBarColors( + containerColor = Color.Transparent + ), + onActionClick = { /*openAccountDialog = true*/ } + ) + } + }, bottomBar = { if (appState.shouldShowBottomBar) { NiaBottomBar( diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt index 04e2f395f..250bdf5d1 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt @@ -59,6 +59,9 @@ class NiaAppState( @Composable get() = navController .currentBackStackEntryAsState().value?.destination + val shouldShowTopBar: Boolean + @Composable get() = (currentDestination?.route in topLevelDestinations) + val shouldShowBottomBar: Boolean get() = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact || windowSizeClass.heightSizeClass == WindowHeightSizeClass.Compact @@ -67,7 +70,8 @@ class NiaAppState( get() = !shouldShowBottomBar /** - * Top level destinations to be used in the BottomBar and NavRail + * Map of top level destinations to be used in the TopBar, BottomBar and NavRail. The key is the + * route. */ val topLevelDestinations: List = TopLevelDestination.values().asList() diff --git a/build.gradle.kts b/build.gradle.kts index 6f6d375d7..c663aadc9 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -31,4 +31,5 @@ plugins { alias(libs.plugins.kotlin.serialization) apply false alias(libs.plugins.hilt) apply false alias(libs.plugins.secrets) apply false + id("org.jetbrains.kotlin.android") version "1.7.10" apply false } \ No newline at end of file diff --git a/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/user_preferences.proto b/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/user_preferences.proto index c20dc4adb..f0eca3d32 100644 --- a/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/user_preferences.proto +++ b/core/datastore/src/main/proto/com/google/samples/apps/nowinandroid/data/user_preferences.proto @@ -40,6 +40,7 @@ message UserPreferences { map followed_topic_ids = 13; map followed_author_ids = 14; map bookmarked_news_resource_ids = 15; - ThemeBrandProto theme_brand = 12; - DarkThemeConfigProto dark_theme_config = 13; + + ThemeBrandProto theme_brand = 16; + DarkThemeConfigProto dark_theme_config = 17; } diff --git a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/TopAppBar.kt b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/TopAppBar.kt index d82c86989..20cc5c06b 100644 --- a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/TopAppBar.kt +++ b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/TopAppBar.kt @@ -32,7 +32,9 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.tooling.preview.Preview +import com.google.samples.apps.nowinandroid.core.designsystem.R @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -97,7 +99,7 @@ fun NiaTopAppBar( } }, colors = colors, - modifier = modifier + modifier = modifier, ) } diff --git a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/icon/NiaIcons.kt b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/icon/NiaIcons.kt index b6c06c8ee..c5367425d 100644 --- a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/icon/NiaIcons.kt +++ b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/icon/NiaIcons.kt @@ -32,6 +32,7 @@ import androidx.compose.material.icons.rounded.Grid3x3 import androidx.compose.material.icons.rounded.Person import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.Search +import androidx.compose.material.icons.rounded.Settings import androidx.compose.material.icons.rounded.ShortText import androidx.compose.material.icons.rounded.Tag import androidx.compose.material.icons.rounded.ViewDay @@ -64,6 +65,7 @@ object NiaIcons { val Person = Icons.Rounded.Person val PlayArrow = Icons.Rounded.PlayArrow val Search = Icons.Rounded.Search + val Settings = Icons.Rounded.Settings val ShortText = Icons.Rounded.ShortText val Tag = Icons.Rounded.Tag val Upcoming = R.drawable.ic_upcoming diff --git a/core/designsystem/src/main/res/values/strings.xml b/core/designsystem/src/main/res/values/strings.xml index 5d1158888..3cc19c6ef 100644 --- a/core/designsystem/src/main/res/values/strings.xml +++ b/core/designsystem/src/main/res/values/strings.xml @@ -18,4 +18,5 @@ Follow Unfollow Browse topic + Screen title diff --git a/core/navigation/src/main/java/com/google/samples/apps/nowinandroid/core/navigation/NiaNavigationDestination.kt b/core/navigation/src/main/java/com/google/samples/apps/nowinandroid/core/navigation/NiaNavigationDestination.kt new file mode 100644 index 000000000..e69de29bb diff --git a/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt b/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt index 849291df3..b7618dbb2 100644 --- a/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt +++ b/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt @@ -34,7 +34,6 @@ import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold -import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier @@ -46,8 +45,6 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaLoadingWheel -import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopAppBar -import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState import com.google.samples.apps.nowinandroid.core.ui.TrackScrollJank import com.google.samples.apps.nowinandroid.core.ui.newsFeed @@ -74,18 +71,6 @@ fun BookmarksScreen( modifier: Modifier = Modifier ) { Scaffold( - topBar = { - NiaTopAppBar( - titleRes = R.string.top_app_bar_title_saved, - actionIcon = NiaIcons.AccountCircle, - actionIconContentDescription = stringResource( - id = R.string.top_app_bar_action_menu - ), - colors = TopAppBarDefaults.centerAlignedTopAppBarColors( - containerColor = Color.Transparent - ) - ) - }, containerColor = Color.Transparent, contentWindowInsets = WindowInsets(0, 0, 0, 0) ) { innerPadding -> diff --git a/feature/bookmarks/src/main/res/values/strings.xml b/feature/bookmarks/src/main/res/values/strings.xml index bf59e2ec8..996c23dc2 100644 --- a/feature/bookmarks/src/main/res/values/strings.xml +++ b/feature/bookmarks/src/main/res/values/strings.xml @@ -17,7 +17,7 @@ Saved Loading saved… - Saved + Saved Search Menu \ No newline at end of file diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt index c482f0edf..a2aabcdc7 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt @@ -63,7 +63,6 @@ import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -93,7 +92,6 @@ import coil.compose.AsyncImage import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilledButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaOverlayLoadingWheel import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaToggleButton -import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopAppBar import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.domain.model.FollowableAuthor @@ -173,19 +171,6 @@ internal fun ForYouScreen( Scaffold( snackbarHost = { SnackbarHost(snackbarHostState) }, - topBar = { - NiaTopAppBar( - titleRes = R.string.top_app_bar_title, - actionIcon = NiaIcons.AccountCircle, - actionIconContentDescription = stringResource( - id = R.string.for_you_top_app_bar_action_my_account - ), - colors = TopAppBarDefaults.centerAlignedTopAppBarColors( - containerColor = Color.Transparent - ), - onActionClick = { openAccountDialog = true } - ) - }, containerColor = Color.Transparent, contentWindowInsets = WindowInsets(0, 0, 0, 0) ) { innerPadding -> diff --git a/feature/foryou/src/main/res/values/strings.xml b/feature/foryou/src/main/res/values/strings.xml index e8f432bf7..5a66a0645 100644 --- a/feature/foryou/src/main/res/values/strings.xml +++ b/feature/foryou/src/main/res/values/strings.xml @@ -22,7 +22,6 @@ What are you interested in? Updates from topics you follow will appear here. Follow some things to get started. Now in Android - My account Search ⚠️ You aren’t connected to the internet diff --git a/feature/interests/src/main/java/com/google/samples/apps/nowinandroid/feature/interests/InterestsScreen.kt b/feature/interests/src/main/java/com/google/samples/apps/nowinandroid/feature/interests/InterestsScreen.kt index d92579723..ab50ea0b6 100644 --- a/feature/interests/src/main/java/com/google/samples/apps/nowinandroid/feature/interests/InterestsScreen.kt +++ b/feature/interests/src/main/java/com/google/samples/apps/nowinandroid/feature/interests/InterestsScreen.kt @@ -19,12 +19,10 @@ package com.google.samples.apps.nowinandroid.feature.interests import androidx.compose.foundation.layout.Column import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi @@ -33,8 +31,6 @@ import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaBackg import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaLoadingWheel import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTab import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTabRow -import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopAppBar -import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.domain.model.FollowableAuthor import com.google.samples.apps.nowinandroid.core.domain.model.FollowableTopic @@ -90,16 +86,6 @@ internal fun InterestsScreen( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally ) { - NiaTopAppBar( - titleRes = R.string.interests, - actionIcon = NiaIcons.MoreVert, - actionIconContentDescription = stringResource( - id = R.string.interests_top_app_bar_action_menu - ), - colors = TopAppBarDefaults.centerAlignedTopAppBarColors( - containerColor = Color.Transparent - ) - ) when (uiState) { InterestsUiState.Loading -> NiaLoadingWheel( diff --git a/feature/interests/src/main/res/values/strings.xml b/feature/interests/src/main/res/values/strings.xml index e265c1e9e..d1c46a28d 100644 --- a/feature/interests/src/main/res/values/strings.xml +++ b/feature/interests/src/main/res/values/strings.xml @@ -15,6 +15,7 @@ limitations under the License. --> + Interests Topics People @@ -22,6 +23,7 @@ "No available data" Follow interest button Unfollow interest button + Interests Menu Search diff --git a/feature/settings/.gitignore b/feature/settings/.gitignore new file mode 100644 index 000000000..42afabfd2 --- /dev/null +++ b/feature/settings/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/feature/settings/build.gradle.kts b/feature/settings/build.gradle.kts new file mode 100644 index 000000000..dc88a74de --- /dev/null +++ b/feature/settings/build.gradle.kts @@ -0,0 +1,24 @@ +/* + * Copyright 2022 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. + */ +plugins { + id("nowinandroid.android.feature") + id("nowinandroid.android.library.compose") + id("nowinandroid.android.library.jacoco") +} + +android { + namespace = "com.google.samples.apps.nowinandroid.feature.settings" +} diff --git a/feature/settings/proguard-rules.pro b/feature/settings/proguard-rules.pro new file mode 100644 index 000000000..481bb4348 --- /dev/null +++ b/feature/settings/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/feature/settings/src/main/AndroidManifest.xml b/feature/settings/src/main/AndroidManifest.xml new file mode 100644 index 000000000..ec921f928 --- /dev/null +++ b/feature/settings/src/main/AndroidManifest.xml @@ -0,0 +1,19 @@ + + + + + \ No newline at end of file diff --git a/feature/settings/src/main/res/values/strings.xml b/feature/settings/src/main/res/values/strings.xml new file mode 100644 index 000000000..415c11e1d --- /dev/null +++ b/feature/settings/src/main/res/values/strings.xml @@ -0,0 +1,19 @@ + + + + Settings + \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts index c6e2d3bf5..d8ff0162c 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -51,6 +51,7 @@ include(":feature:foryou") include(":feature:interests") include(":feature:bookmarks") include(":feature:topic") +include(":feature:settings") include(":lint") include(":sync:work") include(":sync:sync-test") From d42881e5d4bb56587c4a9877b2ac87a9d61b1e12 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Wed, 19 Oct 2022 16:56:31 +0100 Subject: [PATCH 06/22] Add UI architecture for Settings dialog --- app/LICENSES.md | 931 ++++++++++++++++++ .../feature/foryou/ForYouScreen.kt | 124 --- .../feature/foryou/ForYouViewModel.kt | 23 - .../feature/settings/SettingsDialog.kt | 273 +++++ .../feature/settings/SettingsViewModel.kt | 77 ++ .../navigation/SettingsDestination.kt | 35 + .../settings/src/main/res/values/strings.xml | 10 + 7 files changed, 1326 insertions(+), 147 deletions(-) create mode 100644 app/LICENSES.md create mode 100644 feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt create mode 100644 feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt create mode 100644 feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt diff --git a/app/LICENSES.md b/app/LICENSES.md new file mode 100644 index 000000000..53893f800 --- /dev/null +++ b/app/LICENSES.md @@ -0,0 +1,931 @@ +# Open source licenses and copyright notices + +## [Coil](https://coil-kt.github.io/coil/#license) + +Copyright 2022 Coil Contributors + +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. + +## [Jacoco](https://github.com/jacoco/jacoco/blob/master/LICENSE.md) + +Copyright (c) 2009, 2022 Mountainminds GmbH & Co. KG and Contributors + +The JaCoCo Java Code Coverage Library and all included documentation is made available by Mountainminds GmbH & Co. KG, Munich. Except indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 2.0 ("EPL"). A copy of the EPL is available at https://www.eclipse.org/legal/epl-2.0/. + +Please visit http://www.jacoco.org/jacoco/trunk/doc/license.html for the complete license information including third party licenses and trademarks. + +## [JUnit 4](https://junit.org/junit4/license.html) + +Eclipse Public License - v 1.0 +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + +a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and + +b) in the case of each subsequent Contributor: + +i) changes to the Program, and + +ii) additions to the Program; + +where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. + +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. + +"Program" means the Contributions distributed in accordance with this Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. + +2. GRANT OF RIGHTS + +a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. + +b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. + +c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. + +d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. + +3. REQUIREMENTS + +A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: + +a) it complies with the terms and conditions of this Agreement; and + +b) its license agreement: + +i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; + +ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; + +iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and + +iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. + +When the Program is made available in source code form: + +a) it must be made available under this Agreement; and + +b) a copy of this Agreement must be included with each copy of the Program. + +Contributors may not remove or alter any copyright notices contained within the Program. + +Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. + +For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. + +## [ktlint](https://github.com/pinterest/ktlint/blob/master/LICENSE) + +Copyright 2019 Pinterest, Inc. +Copyright 2016-2019 Stanley Shyiko + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## [OkHttp](https://github.com/square/okhttp/blob/master/LICENSE.txt) + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +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. + +## [Retrofit](https://github.com/square/retrofit/blob/master/LICENSE.txt) + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +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. + +## [Spotless](https://github.com/diffplug/spotless/blob/main/LICENSE.txt) + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "{}" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + +Copyright {yyyy} {name of copyright owner} + +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. + +## [Turbine](https://github.com/cashapp/turbine/blob/trunk/LICENSE.txt) + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright {yyyy} {name of copyright owner} + +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. \ No newline at end of file diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt index a2aabcdc7..533d5ce97 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt @@ -18,7 +18,6 @@ package com.google.samples.apps.nowinandroid.feature.foryou import android.app.Activity import androidx.compose.animation.AnimatedVisibility -import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints @@ -47,16 +46,11 @@ import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.rememberLazyGridState -import androidx.compose.foundation.selection.selectable -import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.shape.CornerSize import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.RadioButton import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarDuration.Indefinite import androidx.compose.material3.SnackbarHost @@ -66,9 +60,7 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @@ -78,7 +70,6 @@ import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.max @@ -97,13 +88,6 @@ import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.domain.model.FollowableAuthor import com.google.samples.apps.nowinandroid.core.domain.model.FollowableTopic import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource -import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig -import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.DARK -import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.FOLLOW_SYSTEM -import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.LIGHT -import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand -import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.ANDROID -import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.DEFAULT import com.google.samples.apps.nowinandroid.core.model.data.previewAuthors import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources import com.google.samples.apps.nowinandroid.core.model.data.previewTopics @@ -122,7 +106,6 @@ internal fun ForYouRoute( val feedState by viewModel.feedState.collectAsStateWithLifecycle() val isOffline by viewModel.isOffline.collectAsStateWithLifecycle() val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle() - val themeState by viewModel.themeState.collectAsStateWithLifecycle() ForYouScreen( isOffline = isOffline, @@ -133,9 +116,6 @@ internal fun ForYouRoute( onAuthorCheckedChanged = viewModel::updateAuthorSelection, saveFollowedTopics = viewModel::saveFollowedInterests, onNewsResourcesCheckedChanged = viewModel::updateNewsResourceSaved, - themeState = themeState, - onChangeThemeBrand = viewModel::updateThemeBrand, - onChangeDarkThemeConfig = viewModel::updateDarkThemeConfig, modifier = modifier ) } @@ -152,22 +132,8 @@ internal fun ForYouScreen( saveFollowedTopics: () -> Unit, onNewsResourcesCheckedChanged: (String, Boolean) -> Unit, modifier: Modifier = Modifier, - themeState: Pair = Pair(DEFAULT, FOLLOW_SYSTEM), - onChangeThemeBrand: (themeBrand: ThemeBrand) -> Unit = {}, - onChangeDarkThemeConfig: (darkThemeConfig: DarkThemeConfig) -> Unit = {}, ) { val snackbarHostState = remember { SnackbarHostState() } - var openAccountDialog by remember { mutableStateOf(false) } - - if (openAccountDialog) { - AccountDialog( - onDismiss = { openAccountDialog = false }, - currentThemeBrand = themeState.first, - currentDarkThemeConfig = themeState.second, - onChangeThemeBrand = onChangeThemeBrand, - onChangeDarkThemeConfig = onChangeDarkThemeConfig - ) - } Scaffold( snackbarHost = { SnackbarHost(snackbarHostState) }, @@ -454,96 +420,6 @@ fun TopicIcon( ) } -@Composable -fun AccountDialog( - onDismiss: () -> Unit, - currentThemeBrand: ThemeBrand, - currentDarkThemeConfig: DarkThemeConfig, - onChangeThemeBrand: (themeBrand: ThemeBrand) -> Unit, - onChangeDarkThemeConfig: (darkThemeConfig: DarkThemeConfig) -> Unit -) { - AlertDialog( - onDismissRequest = { onDismiss() }, - title = { - Text( - text = "Change theme and dark mode", - style = MaterialTheme.typography.titleLarge - ) - }, - text = { - Column { - Divider() - Column { - AccountDialogThemeChooserRow( - text = "Default", - selected = currentThemeBrand == DEFAULT, - onClick = { onChangeThemeBrand(DEFAULT) } - ) - AccountDialogThemeChooserRow( - text = "Android", - selected = currentThemeBrand == ANDROID, - onClick = { onChangeThemeBrand(ANDROID) } - ) - } - Divider() - Column(Modifier.selectableGroup()) { - AccountDialogThemeChooserRow( - text = "System default", - selected = currentDarkThemeConfig == FOLLOW_SYSTEM, - onClick = { onChangeDarkThemeConfig(FOLLOW_SYSTEM) } - ) - AccountDialogThemeChooserRow( - text = "Light", - selected = currentDarkThemeConfig == LIGHT, - onClick = { onChangeDarkThemeConfig(LIGHT) } - ) - AccountDialogThemeChooserRow( - text = "Dark", - selected = currentDarkThemeConfig == DARK, - onClick = { onChangeDarkThemeConfig(DARK) } - ) - } - Divider() - } - }, - confirmButton = { - Text( - text = "OK", - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.primary, - modifier = Modifier - .padding(15.dp) - .clickable { onDismiss() } - ) - } - ) -} - -@Composable -fun AccountDialogThemeChooserRow( - text: String, - selected: Boolean, - onClick: () -> Unit -) { - Row( - Modifier - .fillMaxWidth() - .selectable( - selected = selected, - role = Role.RadioButton, - onClick = onClick - ) - .padding(8.dp), - verticalAlignment = Alignment.CenterVertically - ) { - RadioButton( - selected = selected, - onClick = null - ) - Spacer(Modifier.width(8.dp)) - Text(text) - } -} @DevicePreviews @Composable diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt index 3c20719e6..509087a9d 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt @@ -82,19 +82,6 @@ class ForYouViewModel @Inject constructor( initialValue = Unknown ) - /** - * The current theme of the app - */ - val themeState: StateFlow> = - userDataRepository.userDataStream - .map { userData -> - Pair(userData.themeBrand, userData.darkThemeConfig) - } - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000), - initialValue = Pair(DEFAULT, FOLLOW_SYSTEM) - ) /** * The in-progress set of topics to be selected, persisted through process death with a @@ -245,17 +232,7 @@ class ForYouViewModel @Inject constructor( } } - fun updateThemeBrand(themeBrand: ThemeBrand) { - viewModelScope.launch { - userDataRepository.setThemeBrand(themeBrand) - } - } - fun updateDarkThemeConfig(darkThemeConfig: DarkThemeConfig) { - viewModelScope.launch { - userDataRepository.setDarkThemeConfig(darkThemeConfig) - } - } } private fun Flow>.mapToFeedState(): Flow = diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt new file mode 100644 index 000000000..518262fa9 --- /dev/null +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt @@ -0,0 +1,273 @@ +/* + * Copyright 2022 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.google.samples.apps.nowinandroid.feature.settings + +import android.content.Intent +import android.net.Uri +import androidx.compose.foundation.clickable +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.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Divider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.DARK +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.FOLLOW_SYSTEM +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.LIGHT +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.ANDROID +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.DEFAULT +import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Loading +import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Success + +@ExperimentalLifecycleComposeApi +@Composable +internal fun SettingsDialog( + viewModel: SettingsViewModel = hiltViewModel(), + onDismiss: () -> Unit +) { + val settingsUiState by viewModel.settingsUiState.collectAsStateWithLifecycle() + SettingsDialog( + onDismiss = onDismiss, + settingsUiState = settingsUiState, + onChangeThemeBrand = viewModel::updateThemeBrand, + onChangeDarkThemeConfig = viewModel::updateDarkThemeConfig, + ) +} + +@Composable +fun SettingsDialog( + onDismiss: () -> Unit, + settingsUiState: SettingsUiState, + onChangeThemeBrand: (themeBrand: ThemeBrand) -> Unit, + onChangeDarkThemeConfig: (darkThemeConfig: DarkThemeConfig) -> Unit +) { + + AlertDialog( + onDismissRequest = { onDismiss() }, + title = { + Text( + text = stringResource(R.string.settings_title), + style = MaterialTheme.typography.titleLarge + ) + }, + text = { + Column { + Divider() + when (settingsUiState) { + Loading -> { + Text( + text = stringResource(R.string.loading), + modifier = Modifier.padding(vertical = 16.dp) + ) + } + is Success -> { + SettingsPanel( + settings = settingsUiState.settings, + onChangeThemeBrand = onChangeThemeBrand, + onChangeDarkThemeConfig = onChangeDarkThemeConfig + ) + } + } + Divider(Modifier.padding(top = 8.dp)) + LegalPanel() + } + }, + confirmButton = { + Text( + text = "OK", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier + .padding(horizontal = 8.dp) + .clickable { onDismiss() } + ) + } + ) +} + +@Composable +private fun SettingsPanel( + settings: UserEditableSettings, + onChangeThemeBrand: (themeBrand: ThemeBrand) -> Unit, + onChangeDarkThemeConfig: (darkThemeConfig: DarkThemeConfig) -> Unit +) { + SettingsDialogSectionTitle(text = stringResource(R.string.theme)) + Column { + SettingsDialogThemeChooserRow( + text = stringResource(R.string.brand_default), + selected = settings.brand == DEFAULT, + onClick = { onChangeThemeBrand(DEFAULT) } + ) + SettingsDialogThemeChooserRow( + text = stringResource(R.string.brand_android), + selected = settings.brand == ANDROID, + onClick = { onChangeThemeBrand(ANDROID) } + ) + } + SettingsDialogSectionTitle(text = "Dark mode preference") + Column(Modifier.selectableGroup()) { + SettingsDialogThemeChooserRow( + text = stringResource(R.string.dark_mode_config_system_default), + selected = settings.darkThemeConfig == FOLLOW_SYSTEM, + onClick = { onChangeDarkThemeConfig(FOLLOW_SYSTEM) } + ) + SettingsDialogThemeChooserRow( + text = stringResource(R.string.dark_mode_config_light), + selected = settings.darkThemeConfig == LIGHT, + onClick = { onChangeDarkThemeConfig(LIGHT) } + ) + SettingsDialogThemeChooserRow( + text = stringResource(R.string.dark_mode_config_dark), + selected = settings.darkThemeConfig == DARK, + onClick = { onChangeDarkThemeConfig(DARK) } + ) + } +} + +@Composable +private fun SettingsDialogSectionTitle(text: String) { + Text( + text = text, + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.padding(top = 16.dp, bottom = 8.dp) + ) +} + +@Composable +fun SettingsDialogThemeChooserRow( + text: String, + selected: Boolean, + onClick: () -> Unit +) { + Row( + Modifier + .fillMaxWidth() + .selectable( + selected = selected, + role = Role.RadioButton, + onClick = onClick + ) + .padding(8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + RadioButton( + selected = selected, + onClick = null + ) + Spacer(Modifier.width(8.dp)) + Text(text) + } +} + + +@Composable +private fun LegalPanel() { + Row( + modifier = Modifier.padding(top = 16.dp) + ) { + Column( + Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Row { + TextLink( + text = stringResource(R.string.privacy_policy), + url = PRIVACY_POLICY_URL + ) + Spacer(Modifier.width(16.dp)) + TextLink( + text = stringResource(R.string.licenses), + url = LICENSES_URL + ) + } + } + } +} + +@Composable +private fun TextLink(text: String, url: String) { + + val launchResourceIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) + val context = LocalContext.current + + Text( + text = text, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier + .clickable { + ContextCompat.startActivity(context, launchResourceIntent, null) + } + ) +} + +@Preview +@Composable +fun PreviewSettingsDialog() { + NiaTheme { + SettingsDialog( + onDismiss = {}, + settingsUiState = Success( + UserEditableSettings( + brand = DEFAULT, + darkThemeConfig = FOLLOW_SYSTEM + ) + ), + onChangeThemeBrand = { }, + onChangeDarkThemeConfig = { } + ) + } +} + +@Preview +@Composable +fun PreviewSettingsDialogLoading() { + NiaTheme { + SettingsDialog( + onDismiss = {}, + settingsUiState = Loading, + onChangeThemeBrand = { }, + onChangeDarkThemeConfig = { } + ) + } +} + +private const val PRIVACY_POLICY_URL = "https://policies.google.com/privacy" +private const val LICENSES_URL = "https://github.com/android/nowinandroid/blob/main/app/LICENSES.md" \ No newline at end of file diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt new file mode 100644 index 000000000..96394722c --- /dev/null +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt @@ -0,0 +1,77 @@ +/* + * Copyright 2022 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.google.samples.apps.nowinandroid.feature.settings + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.FOLLOW_SYSTEM +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.DEFAULT +import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Loading +import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Success +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import javax.inject.Inject + +@HiltViewModel +class SettingsViewModel @Inject constructor( + private val userDataRepository: UserDataRepository +) : ViewModel() { + val settingsUiState: StateFlow = + userDataRepository.userDataStream + .map { userData -> + Success( + settings = UserEditableSettings( + brand = userData.themeBrand, + darkThemeConfig = userData.darkThemeConfig + ) + ) + } + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5_000), + initialValue = Loading + ) + + fun updateThemeBrand(themeBrand: ThemeBrand) { + viewModelScope.launch { + userDataRepository.setThemeBrand(themeBrand) + } + } + + fun updateDarkThemeConfig(darkThemeConfig: DarkThemeConfig) { + viewModelScope.launch { + userDataRepository.setDarkThemeConfig(darkThemeConfig) + } + } +} + +/** + * Represents the settings which the user can edit within the app. + */ +data class UserEditableSettings(val brand: ThemeBrand, val darkThemeConfig: DarkThemeConfig) + +sealed interface SettingsUiState { + object Loading : SettingsUiState + class Success(val settings: UserEditableSettings) : SettingsUiState +} \ No newline at end of file diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt new file mode 100644 index 000000000..82b5e400d --- /dev/null +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt @@ -0,0 +1,35 @@ +/* + * Copyright 2022 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.google.samples.apps.nowinandroid.feature.settings.navigation + +import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi +import androidx.navigation.NavGraphBuilder +import androidx.navigation.compose.dialog +import com.google.samples.apps.nowinandroid.core.navigation.NiaNavigationDestination +import com.google.samples.apps.nowinandroid.feature.settings.SettingsDialog + +object SettingsDestination : NiaNavigationDestination { + override val route = "settings_route" + override val destinationId = "settings_destination" +} + +@OptIn(ExperimentalLifecycleComposeApi::class) +fun NavGraphBuilder.settingsDialog(onDismiss : () -> Unit) { + dialog(route = SettingsDestination.route) { + SettingsDialog(onDismiss = onDismiss) + } +} diff --git a/feature/settings/src/main/res/values/strings.xml b/feature/settings/src/main/res/values/strings.xml index 415c11e1d..85998ced4 100644 --- a/feature/settings/src/main/res/values/strings.xml +++ b/feature/settings/src/main/res/values/strings.xml @@ -16,4 +16,14 @@ --> Settings + Settings + Loading... + Privacy policy + Licenses + Theme + Default + Android + System default + Light + Dark \ No newline at end of file From 56c06458163f09c47b0682a836cff08dd0026cfd Mon Sep 17 00:00:00 2001 From: Don Turner Date: Wed, 19 Oct 2022 18:18:39 +0100 Subject: [PATCH 07/22] Add tests --- .../apps/nowinandroid/ui/NavigationTest.kt | 29 +++++++ .../feature/settings/SettingsDialogTest.kt | 83 +++++++++++++++++++ .../feature/settings/SettingsDialog.kt | 13 +-- .../feature/settings/SettingsViewModel.kt | 2 +- .../settings/src/main/res/values/strings.xml | 1 + .../feature/settings/SettingsViewModelTest.kt | 73 ++++++++++++++++ 6 files changed, 195 insertions(+), 6 deletions(-) create mode 100644 feature/settings/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialogTest.kt create mode 100644 feature/settings/src/test/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModelTest.kt diff --git a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt index abbf774fe..0d00f6ed5 100644 --- a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt +++ b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt @@ -75,6 +75,8 @@ class NavigationTest { private lateinit var appName: String private lateinit var saved: String private lateinit var settings: String + private lateinit var brand: String + private lateinit var ok: String @Before fun setup() { @@ -88,6 +90,8 @@ class NavigationTest { appName = getString(R.string.app_name) saved = getString(BookmarksR.string.saved) settings = getString(SettingsR.string.top_app_bar_action_icon_description) + brand = getString(SettingsR.string.brand_android) + ok = getString(SettingsR.string.dismiss_dialog_button_text) } } @@ -189,6 +193,31 @@ class NavigationTest { } } + @Test + fun whenSettingsIconIsClicked_settingsDialogIsShown() { + composeTestRule.apply { + onNodeWithContentDescription(settings).performClick() + + // Check that one of the settings is actually displayed. + onNodeWithText(brand).assertExists() + } + } + + @Test + fun whenSettingsDialogDismissed_previousScreenIsDisplayed(){ + + composeTestRule.apply { + + // Navigate to the saved screen, open the settings dialog, then close it. + onNodeWithText(saved).performClick() + onNodeWithContentDescription(settings).performClick() + onNodeWithText(ok).performClick() + + // Check that the saved screen is still visible and selected. + onNodeWithText(saved).assertIsSelected() + } + } + /* * There should always be at most one instance of a top-level destination at the same time. */ diff --git a/feature/settings/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialogTest.kt b/feature/settings/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialogTest.kt new file mode 100644 index 000000000..edd281c89 --- /dev/null +++ b/feature/settings/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialogTest.kt @@ -0,0 +1,83 @@ +/* + * Copyright 2022 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.google.samples.apps.nowinandroid.feature.settings + +import androidx.activity.ComponentActivity +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithText +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.DARK +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.ANDROID +import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Loading +import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Success +import org.junit.Rule +import org.junit.Test + +class SettingsDialogTest { + + @get:Rule + val composeTestRule = createAndroidComposeRule() + + private fun getString(id: Int) = composeTestRule.activity.resources.getString(id) + + @Test + fun whenLoading_showsLoadingText() { + + composeTestRule.setContent { + SettingsDialog( + settingsUiState = Loading, + onDismiss = { }, + onChangeThemeBrand = {}, + onChangeDarkThemeConfig = {} + ) + } + + composeTestRule + .onNodeWithText(getString(R.string.loading)) + .assertExists() + } + + @Test + fun whenStateIsSuccess_allSettingsAreDisplayed(){ + composeTestRule.setContent { + SettingsDialog( + settingsUiState = Success( + UserEditableSettings( + brand = ANDROID, + darkThemeConfig = DARK + ) + ), + onDismiss = { }, + onChangeThemeBrand = {}, + onChangeDarkThemeConfig = {} + ) + } + + // Check that all the possible settings are displayed. + composeTestRule.onNodeWithText(getString(R.string.brand_default)).assertExists() + composeTestRule.onNodeWithText(getString(R.string.brand_android)).assertExists() + composeTestRule.onNodeWithText( + getString(R.string.dark_mode_config_system_default) + ).assertExists() + composeTestRule.onNodeWithText(getString(R.string.dark_mode_config_light)).assertExists() + composeTestRule.onNodeWithText(getString(R.string.dark_mode_config_dark)).assertExists() + + // Check that the correct settings are selected. + composeTestRule.onNodeWithText(getString(R.string.brand_android)).assertIsSelected() + composeTestRule.onNodeWithText(getString(R.string.dark_mode_config_dark)).assertIsSelected() + } +} \ No newline at end of file diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt index 518262fa9..33ebd53b1 100644 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt @@ -25,8 +25,10 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme @@ -53,6 +55,7 @@ import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.LIGH import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.ANDROID import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.DEFAULT +import com.google.samples.apps.nowinandroid.feature.settings.R.string import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Loading import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Success @@ -73,8 +76,8 @@ internal fun SettingsDialog( @Composable fun SettingsDialog( - onDismiss: () -> Unit, settingsUiState: SettingsUiState, + onDismiss: () -> Unit, onChangeThemeBrand: (themeBrand: ThemeBrand) -> Unit, onChangeDarkThemeConfig: (darkThemeConfig: DarkThemeConfig) -> Unit ) { @@ -88,8 +91,8 @@ fun SettingsDialog( ) }, text = { - Column { - Divider() + Divider() + Column (Modifier.verticalScroll(rememberScrollState())) { when (settingsUiState) { Loading -> { Text( @@ -111,7 +114,7 @@ fun SettingsDialog( }, confirmButton = { Text( - text = "OK", + text = stringResource(string.dismiss_dialog_button_text), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary, modifier = Modifier @@ -182,7 +185,7 @@ fun SettingsDialogThemeChooserRow( .selectable( selected = selected, role = Role.RadioButton, - onClick = onClick + onClick = onClick, ) .padding(8.dp), verticalAlignment = Alignment.CenterVertically diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt index 96394722c..7ff9b0ca3 100644 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt @@ -73,5 +73,5 @@ data class UserEditableSettings(val brand: ThemeBrand, val darkThemeConfig: Dark sealed interface SettingsUiState { object Loading : SettingsUiState - class Success(val settings: UserEditableSettings) : SettingsUiState + data class Success(val settings: UserEditableSettings) : SettingsUiState } \ No newline at end of file diff --git a/feature/settings/src/main/res/values/strings.xml b/feature/settings/src/main/res/values/strings.xml index 85998ced4..e37ff439d 100644 --- a/feature/settings/src/main/res/values/strings.xml +++ b/feature/settings/src/main/res/values/strings.xml @@ -26,4 +26,5 @@ System default Light Dark + OK \ No newline at end of file diff --git a/feature/settings/src/test/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModelTest.kt b/feature/settings/src/test/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModelTest.kt new file mode 100644 index 000000000..a78cf14ab --- /dev/null +++ b/feature/settings/src/test/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModelTest.kt @@ -0,0 +1,73 @@ +/* + * Copyright 2022 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.google.samples.apps.nowinandroid.feature.settings + +import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.DARK +import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.ANDROID +import com.google.samples.apps.nowinandroid.core.testing.repository.TestUserDataRepository +import com.google.samples.apps.nowinandroid.core.testing.util.MainDispatcherRule +import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Loading +import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Success +import junit.framework.Assert.assertEquals +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.Before +import org.junit.Rule +import org.junit.Test + +class SettingsViewModelTest { + + @get:Rule + val mainDispatcherRule = MainDispatcherRule() + + private val userDataRepository = TestUserDataRepository() + + private lateinit var viewModel: SettingsViewModel + + @Before + fun setup() { + viewModel = SettingsViewModel(userDataRepository) + } + + @Test + fun stateIsInitiallyLoading() = runTest { + assertEquals(Loading, viewModel.settingsUiState.value) + } + + @Test + fun stateIsSuccessAfterUserDataLoaded() = runTest { + + val collectJob = + launch(UnconfinedTestDispatcher()) { viewModel.settingsUiState.collect() } + + userDataRepository.setThemeBrand(ANDROID) + userDataRepository.setDarkThemeConfig(DARK) + + assertEquals( + Success( + UserEditableSettings( + brand = ANDROID, + darkThemeConfig = DARK + ) + ), + viewModel.settingsUiState.value) + + collectJob.cancel() + } +} \ No newline at end of file From c3f7870412b2cd33e1290ac9ea5dba853484591c Mon Sep 17 00:00:00 2001 From: Don Turner Date: Wed, 19 Oct 2022 18:23:50 +0100 Subject: [PATCH 08/22] Fix spotless issues --- .../apps/nowinandroid/ui/NavigationTest.kt | 2 +- .../feature/foryou/ForYouScreen.kt | 1 - .../feature/foryou/ForYouViewModel.kt | 7 ----- .../feature/settings/SettingsDialogTest.kt | 26 +++++++++---------- .../feature/settings/SettingsDialog.kt | 23 ++++++++-------- .../feature/settings/SettingsViewModel.kt | 24 ++++++++--------- .../navigation/SettingsDestination.kt | 20 +++++++------- .../feature/settings/SettingsViewModelTest.kt | 25 +++++++++--------- 8 files changed, 59 insertions(+), 69 deletions(-) diff --git a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt index 0d00f6ed5..d7d092a26 100644 --- a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt +++ b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt @@ -204,7 +204,7 @@ class NavigationTest { } @Test - fun whenSettingsDialogDismissed_previousScreenIsDisplayed(){ + fun whenSettingsDialogDismissed_previousScreenIsDisplayed() { composeTestRule.apply { diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt index 533d5ce97..c15263d3b 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt @@ -420,7 +420,6 @@ fun TopicIcon( ) } - @DevicePreviews @Composable fun ForYouScreenPopulatedFeed() { diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt index 509087a9d..8cbf39c31 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt @@ -31,10 +31,6 @@ import com.google.samples.apps.nowinandroid.core.domain.GetFollowableTopicsStrea import com.google.samples.apps.nowinandroid.core.domain.GetSaveableNewsResourcesStreamUseCase import com.google.samples.apps.nowinandroid.core.domain.GetSortedFollowableAuthorsStreamUseCase import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource -import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig -import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.FOLLOW_SYSTEM -import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand -import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.DEFAULT import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState import com.google.samples.apps.nowinandroid.feature.foryou.FollowedInterestsUiState.FollowedInterests import com.google.samples.apps.nowinandroid.feature.foryou.FollowedInterestsUiState.None @@ -82,7 +78,6 @@ class ForYouViewModel @Inject constructor( initialValue = Unknown ) - /** * The in-progress set of topics to be selected, persisted through process death with a * [SavedStateHandle]. @@ -231,8 +226,6 @@ class ForYouViewModel @Inject constructor( } } } - - } private fun Flow>.mapToFeedState(): Flow = diff --git a/feature/settings/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialogTest.kt b/feature/settings/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialogTest.kt index edd281c89..71d6cceaa 100644 --- a/feature/settings/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialogTest.kt +++ b/feature/settings/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialogTest.kt @@ -1,17 +1,17 @@ /* * Copyright 2022 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 + * 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 + * 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. + * 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.google.samples.apps.nowinandroid.feature.settings @@ -40,7 +40,7 @@ class SettingsDialogTest { composeTestRule.setContent { SettingsDialog( settingsUiState = Loading, - onDismiss = { }, + onDismiss = { }, onChangeThemeBrand = {}, onChangeDarkThemeConfig = {} ) @@ -52,7 +52,7 @@ class SettingsDialogTest { } @Test - fun whenStateIsSuccess_allSettingsAreDisplayed(){ + fun whenStateIsSuccess_allSettingsAreDisplayed() { composeTestRule.setContent { SettingsDialog( settingsUiState = Success( @@ -61,7 +61,7 @@ class SettingsDialogTest { darkThemeConfig = DARK ) ), - onDismiss = { }, + onDismiss = { }, onChangeThemeBrand = {}, onChangeDarkThemeConfig = {} ) @@ -80,4 +80,4 @@ class SettingsDialogTest { composeTestRule.onNodeWithText(getString(R.string.brand_android)).assertIsSelected() composeTestRule.onNodeWithText(getString(R.string.dark_mode_config_dark)).assertIsSelected() } -} \ No newline at end of file +} diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt index 33ebd53b1..b51c5b6e7 100644 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt @@ -1,17 +1,17 @@ /* * Copyright 2022 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 + * 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 + * 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. + * 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.google.samples.apps.nowinandroid.feature.settings @@ -92,7 +92,7 @@ fun SettingsDialog( }, text = { Divider() - Column (Modifier.verticalScroll(rememberScrollState())) { + Column(Modifier.verticalScroll(rememberScrollState())) { when (settingsUiState) { Loading -> { Text( @@ -199,7 +199,6 @@ fun SettingsDialogThemeChooserRow( } } - @Composable private fun LegalPanel() { Row( @@ -273,4 +272,4 @@ fun PreviewSettingsDialogLoading() { } private const val PRIVACY_POLICY_URL = "https://policies.google.com/privacy" -private const val LICENSES_URL = "https://github.com/android/nowinandroid/blob/main/app/LICENSES.md" \ No newline at end of file +private const val LICENSES_URL = "https://github.com/android/nowinandroid/blob/main/app/LICENSES.md" diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt index 7ff9b0ca3..be2927546 100644 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt @@ -1,17 +1,17 @@ /* * Copyright 2022 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 + * 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 + * 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. + * 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.google.samples.apps.nowinandroid.feature.settings @@ -20,18 +20,16 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig -import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig.FOLLOW_SYSTEM import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand -import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand.DEFAULT import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Loading import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Success import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch -import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor( @@ -74,4 +72,4 @@ data class UserEditableSettings(val brand: ThemeBrand, val darkThemeConfig: Dark sealed interface SettingsUiState { object Loading : SettingsUiState data class Success(val settings: UserEditableSettings) : SettingsUiState -} \ No newline at end of file +} diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt index 82b5e400d..3eb9a6c92 100644 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt @@ -1,17 +1,17 @@ /* * Copyright 2022 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 + * 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 + * 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. + * 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.google.samples.apps.nowinandroid.feature.settings.navigation @@ -28,7 +28,7 @@ object SettingsDestination : NiaNavigationDestination { } @OptIn(ExperimentalLifecycleComposeApi::class) -fun NavGraphBuilder.settingsDialog(onDismiss : () -> Unit) { +fun NavGraphBuilder.settingsDialog(onDismiss: () -> Unit) { dialog(route = SettingsDestination.route) { SettingsDialog(onDismiss = onDismiss) } diff --git a/feature/settings/src/test/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModelTest.kt b/feature/settings/src/test/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModelTest.kt index a78cf14ab..b9df2fafd 100644 --- a/feature/settings/src/test/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModelTest.kt +++ b/feature/settings/src/test/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModelTest.kt @@ -1,17 +1,17 @@ /* * Copyright 2022 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 + * 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 + * 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. + * 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.google.samples.apps.nowinandroid.feature.settings @@ -47,7 +47,7 @@ class SettingsViewModelTest { @Test fun stateIsInitiallyLoading() = runTest { - assertEquals(Loading, viewModel.settingsUiState.value) + assertEquals(Loading, viewModel.settingsUiState.value) } @Test @@ -66,8 +66,9 @@ class SettingsViewModelTest { darkThemeConfig = DARK ) ), - viewModel.settingsUiState.value) + viewModel.settingsUiState.value + ) collectJob.cancel() } -} \ No newline at end of file +} From cf4dd1fbfff223e9c0b420da72a20120a80050d2 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Thu, 20 Oct 2022 12:22:01 +0100 Subject: [PATCH 09/22] Added null branches for reading user data from datastore --- .../nowinandroid/core/datastore/NiaPreferencesDataSource.kt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt b/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt index 96cdc7a13..433130679 100644 --- a/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt +++ b/core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt @@ -36,13 +36,15 @@ class NiaPreferencesDataSource @Inject constructor( bookmarkedNewsResources = it.bookmarkedNewsResourceIdsMap.keys, followedTopics = it.followedTopicIdsMap.keys, followedAuthors = it.followedAuthorIdsMap.keys, - themeBrand = when (it.themeBrand!!) { + themeBrand = when (it.themeBrand) { + null, ThemeBrandProto.THEME_BRAND_UNSPECIFIED, ThemeBrandProto.UNRECOGNIZED, ThemeBrandProto.THEME_BRAND_DEFAULT -> ThemeBrand.DEFAULT ThemeBrandProto.THEME_BRAND_ANDROID -> ThemeBrand.ANDROID }, - darkThemeConfig = when (it.darkThemeConfig!!) { + darkThemeConfig = when (it.darkThemeConfig) { + null, DarkThemeConfigProto.DARK_THEME_CONFIG_UNSPECIFIED, DarkThemeConfigProto.UNRECOGNIZED, DarkThemeConfigProto.DARK_THEME_CONFIG_FOLLOW_SYSTEM -> From 5e4100fafc36981cf2b65263585fb3b112ff695d Mon Sep 17 00:00:00 2001 From: Don Turner Date: Thu, 20 Oct 2022 12:39:41 +0100 Subject: [PATCH 10/22] Add MainActivity view model --- app/build.gradle.kts | 1 + .../samples/apps/nowinandroid/MainActivity.kt | 52 ++++++++----------- .../nowinandroid/MainActivityViewModel.kt | 48 +++++++++++++++++ 3 files changed, 72 insertions(+), 29 deletions(-) create mode 100644 app/src/main/java/com/google/samples/apps/nowinandroid/MainActivityViewModel.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index f7d561dbc..6d3a8e6b5 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -106,6 +106,7 @@ dependencies { implementation(libs.androidx.core.ktx) implementation(libs.androidx.core.splashscreen) implementation(libs.androidx.compose.runtime) + implementation(libs.androidx.lifecycle.runtimeCompose) implementation(libs.androidx.compose.runtime.tracing) implementation(libs.androidx.compose.material3.windowSizeClass) implementation(libs.androidx.hilt.navigation.compose) diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt index 3f9af2a4d..09ea0f2ff 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt @@ -19,6 +19,7 @@ package com.google.samples.apps.nowinandroid import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent +import androidx.activity.viewModels import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass @@ -34,13 +35,11 @@ import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.metrics.performance.JankStats import com.google.accompanist.systemuicontroller.rememberSystemUiController -import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository +import com.google.samples.apps.nowinandroid.MainActivityUiState.Loading +import com.google.samples.apps.nowinandroid.MainActivityUiState.Success import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand -import com.google.samples.apps.nowinandroid.core.model.data.UserData -import com.google.samples.apps.nowinandroid.core.result.Result -import com.google.samples.apps.nowinandroid.core.result.asResult import com.google.samples.apps.nowinandroid.ui.NiaApp import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @@ -58,25 +57,20 @@ class MainActivity : ComponentActivity() { @Inject lateinit var lazyStats: dagger.Lazy - @Inject - lateinit var userDataRepository: UserDataRepository + val viewModel: MainActivityViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { val splashScreen = installSplashScreen() super.onCreate(savedInstanceState) - /** - * The current user data, updated here to drive the UI theme - */ - var userDataResult: Result by mutableStateOf(Result.Loading) + var uiState: MainActivityUiState by mutableStateOf(Loading) - // Update the user data + // Update the uiState lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { - userDataRepository.userDataStream - .asResult() + viewModel.uiState .onEach { - userDataResult = it + uiState = it } .collect() } @@ -84,9 +78,9 @@ class MainActivity : ComponentActivity() { // Keep the splash screen on-screen until the user data is loaded splashScreen.setKeepOnScreenCondition { - when (userDataResult) { - Result.Loading -> true - is Result.Success, is Result.Error -> false + when (uiState) { + Loading -> true + is Success -> false } } @@ -96,7 +90,7 @@ class MainActivity : ComponentActivity() { setContent { val systemUiController = rememberSystemUiController() - val darkTheme = shouldUseDarkTheme(userDataResult) + val darkTheme = shouldUseDarkTheme(uiState) // Update the dark content of the system bars to match the theme DisposableEffect(systemUiController, darkTheme) { @@ -106,7 +100,7 @@ class MainActivity : ComponentActivity() { NiaTheme( darkTheme = darkTheme, - androidTheme = shouldUseAndroidTheme(userDataResult) + androidTheme = shouldUseAndroidTheme(uiState) ) { NiaApp( windowSizeClass = calculateWindowSizeClass(this), @@ -127,29 +121,29 @@ class MainActivity : ComponentActivity() { } /** - * Returns `true` if the Android theme should be used, as a function of the [userDataResult]. + * Returns `true` if the Android theme should be used, as a function of the [uiState]. */ @Composable fun shouldUseAndroidTheme( - userDataResult: Result, -): Boolean = when (userDataResult) { - Result.Loading, is Result.Error -> false - is Result.Success -> when (userDataResult.data.themeBrand) { + uiState: MainActivityUiState, +): Boolean = when (uiState) { + Loading -> false + is Success -> when (uiState.userData.themeBrand) { ThemeBrand.DEFAULT -> false ThemeBrand.ANDROID -> true } } /** - * Returns `true` if dark theme should be used, as a function of the [userDataResult] and the + * Returns `true` if dark theme should be used, as a function of the [uiState] and the * current system context. */ @Composable fun shouldUseDarkTheme( - userDataResult: Result, -): Boolean = when (userDataResult) { - Result.Loading, is Result.Error -> isSystemInDarkTheme() - is Result.Success -> when (userDataResult.data.darkThemeConfig) { + uiState: MainActivityUiState, +): Boolean = when (uiState) { + Loading -> isSystemInDarkTheme() + is Success -> when (uiState.userData.darkThemeConfig) { DarkThemeConfig.FOLLOW_SYSTEM -> isSystemInDarkTheme() DarkThemeConfig.LIGHT -> false DarkThemeConfig.DARK -> true diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivityViewModel.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivityViewModel.kt new file mode 100644 index 000000000..885fb6c3d --- /dev/null +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivityViewModel.kt @@ -0,0 +1,48 @@ +/* + * Copyright 2022 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.google.samples.apps.nowinandroid + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.google.samples.apps.nowinandroid.MainActivityUiState.Loading +import com.google.samples.apps.nowinandroid.MainActivityUiState.Success +import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository +import com.google.samples.apps.nowinandroid.core.model.data.UserData +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn + +@HiltViewModel +class MainActivityViewModel @Inject constructor( + userDataRepository: UserDataRepository +) : ViewModel() { + val uiState: StateFlow = userDataRepository.userDataStream.map { + Success(it) + }.stateIn( + scope = viewModelScope, + initialValue = Loading, + started = SharingStarted.WhileSubscribed(5_000) + ) +} + +sealed interface MainActivityUiState { + object Loading : MainActivityUiState + data class Success(val userData: UserData) : MainActivityUiState +} From f59da72383bf60526a6b55afee523bdc3fc9c4fd Mon Sep 17 00:00:00 2001 From: Don Turner Date: Thu, 20 Oct 2022 12:48:24 +0100 Subject: [PATCH 11/22] Add comment about splashScreen.setKeepOnScreenCondition --- .../java/com/google/samples/apps/nowinandroid/MainActivity.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt index 09ea0f2ff..2f69cdc37 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt @@ -76,7 +76,9 @@ class MainActivity : ComponentActivity() { } } - // Keep the splash screen on-screen until the user data is loaded + // Keep the splash screen on-screen until the UI state is loaded. This condition is + // evaluated each time the app needs to be redrawn so it should be fast to avoid blocking + // the UI. splashScreen.setKeepOnScreenCondition { when (uiState) { Loading -> true From 3a106534e7cc50654fcc5d4d0f25f72012339b19 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Thu, 20 Oct 2022 13:10:41 +0100 Subject: [PATCH 12/22] Remove Scaffold from BookmarksScreen --- .../feature/bookmarks/BookmarksScreen.kt | 63 +++++++++---------- 1 file changed, 28 insertions(+), 35 deletions(-) diff --git a/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt b/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt index b7618dbb2..672213492 100644 --- a/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt +++ b/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt @@ -70,44 +70,37 @@ fun BookmarksScreen( removeFromBookmarks: (String) -> Unit, modifier: Modifier = Modifier ) { - Scaffold( - containerColor = Color.Transparent, - contentWindowInsets = WindowInsets(0, 0, 0, 0) - ) { innerPadding -> - val scrollableState = rememberLazyGridState() - TrackScrollJank(scrollableState = scrollableState, stateName = "bookmarks:grid") - LazyVerticalGrid( - columns = Adaptive(300.dp), - contentPadding = PaddingValues(16.dp), - horizontalArrangement = Arrangement.spacedBy(32.dp), - verticalArrangement = Arrangement.spacedBy(24.dp), - state = scrollableState, - modifier = modifier - .fillMaxSize() - .testTag("bookmarks:feed") - .padding(innerPadding) - .consumedWindowInsets(innerPadding) - ) { - if (feedState is NewsFeedUiState.Loading) { - item(span = { GridItemSpan(maxLineSpan) }) { - NiaLoadingWheel( - modifier = Modifier - .fillMaxWidth() - .wrapContentSize() - .testTag("forYou:loading"), - contentDesc = stringResource(id = R.string.saved_loading), - ) - } + val scrollableState = rememberLazyGridState() + TrackScrollJank(scrollableState = scrollableState, stateName = "bookmarks:grid") + LazyVerticalGrid( + columns = Adaptive(300.dp), + contentPadding = PaddingValues(16.dp), + horizontalArrangement = Arrangement.spacedBy(32.dp), + verticalArrangement = Arrangement.spacedBy(24.dp), + state = scrollableState, + modifier = modifier + .fillMaxSize() + .testTag("bookmarks:feed") + ) { + if (feedState is NewsFeedUiState.Loading) { + item(span = { GridItemSpan(maxLineSpan) }) { + NiaLoadingWheel( + modifier = Modifier + .fillMaxWidth() + .wrapContentSize() + .testTag("forYou:loading"), + contentDesc = stringResource(id = R.string.saved_loading), + ) } + } - newsFeed( - feedState = feedState, - onNewsResourcesCheckedChanged = { id, _ -> removeFromBookmarks(id) }, - ) + newsFeed( + feedState = feedState, + onNewsResourcesCheckedChanged = { id, _ -> removeFromBookmarks(id) }, + ) - item(span = { GridItemSpan(maxLineSpan) }) { - Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing)) - } + item(span = { GridItemSpan(maxLineSpan) }) { + Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing)) } } } From 828242dbaddf6078c08f13b74ebc0dd736c27a61 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 00:13:28 +0100 Subject: [PATCH 13/22] Remove Scaffold from top level screens --- .../apps/nowinandroid/ui/NavigationTest.kt | 13 +- .../apps/nowinandroid/ui/NiaAppStateTest.kt | 89 +++++++-- .../samples/apps/nowinandroid/MainActivity.kt | 5 + .../samples/apps/nowinandroid/ui/NiaApp.kt | 52 +++++- .../apps/nowinandroid/ui/NiaAppState.kt | 39 +++- .../feature/bookmarks/BookmarksScreen.kt | 4 - .../feature/foryou/ForYouScreen.kt | 172 +++++++----------- .../feature/foryou/ForYouViewModel.kt | 8 - .../feature/foryou/ForYouViewModelTest.kt | 15 -- .../feature/settings/SettingsDialog.kt | 8 +- .../feature/settings/SettingsViewModel.kt | 7 +- 11 files changed, 246 insertions(+), 166 deletions(-) diff --git a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt index d7d092a26..dfc45f280 100644 --- a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt +++ b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt @@ -21,6 +21,7 @@ import androidx.compose.ui.test.assertIsOn import androidx.compose.ui.test.assertIsSelected import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onLast import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick @@ -168,13 +169,13 @@ class NavigationTest { // Verify that the top bar contains the app name on the first screen. onNodeWithText(appName).assertExists() - // Go to the bookmarks tab, verify that the top bar contains the app name. + // Go to the saved tab, verify that the top bar contains "saved". This means + // we'll have 2 elements with the text "saved" on screen. One in the top bar, and + // one in the bottom navigation. onNodeWithText(saved).performClick() - onNodeWithText(appName).assertExists() + onAllNodesWithText(saved).assertCountEquals(2) - // Go to the interests tab, verify that the top bar contains "Interests". This means - // we'll have 2 elements with the text "Interests" on screen. One in the top bar, and - // one in the bottom navigation. + // As above but for the interests tab. onNodeWithText(interests).performClick() onAllNodesWithText(interests).assertCountEquals(2) } @@ -214,7 +215,7 @@ class NavigationTest { onNodeWithText(ok).performClick() // Check that the saved screen is still visible and selected. - onNodeWithText(saved).assertIsSelected() + onAllNodesWithText(saved).onLast().assertIsSelected() } } diff --git a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt index f6361d844..ce8f1aa00 100644 --- a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt +++ b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt @@ -30,9 +30,19 @@ import androidx.navigation.compose.ComposeNavigator import androidx.navigation.compose.composable import androidx.navigation.createGraph import androidx.navigation.testing.TestNavHostController +import com.google.samples.apps.nowinandroid.core.testing.util.MainDispatcherRule +import com.google.samples.apps.nowinandroid.core.testing.util.TestNetworkMonitor +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue +import org.junit.Before import org.junit.Rule import org.junit.Test @@ -45,13 +55,33 @@ import org.junit.Test @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) class NiaAppStateTest { + @get:Rule + val mainDispatcherRule = MainDispatcherRule() + @get:Rule val composeTestRule = createComposeRule() + // Create the test dependencies. + private lateinit var testScope: TestScope + private val networkMonitor = TestNetworkMonitor() + + // Subject under test. private lateinit var state: NiaAppState + @Before + fun setup() { + // We use the Unconfined dispatcher to ensure that coroutines are executed sequentially in + // tests. + testScope = TestScope(UnconfinedTestDispatcher()) + } + + @After + fun cleanup() { + testScope.cancel() + } + @Test - fun niaAppState_currentDestination() { + fun niaAppState_currentDestination() = runTest { var currentDestination: String? = null composeTestRule.setContent { @@ -59,7 +89,9 @@ class NiaAppStateTest { state = remember(navController) { NiaAppState( windowSizeClass = getCompactWindowClass(), - navController = navController + navController = navController, + networkMonitor = networkMonitor, + coroutineScope = testScope ) } @@ -76,9 +108,12 @@ class NiaAppStateTest { } @Test - fun niaAppState_destinations() { + fun niaAppState_destinations() = runTest { composeTestRule.setContent { - state = rememberNiaAppState(getCompactWindowClass()) + state = rememberNiaAppState( + windowSizeClass = getCompactWindowClass(), + networkMonitor = networkMonitor + ) } assertEquals(3, state.topLevelDestinations.size) @@ -93,7 +128,8 @@ class NiaAppStateTest { val navController = rememberTestNavController() state = rememberNiaAppState( windowSizeClass = getCompactWindowClass(), - navController = navController + navController = navController, + networkMonitor = networkMonitor ) // Do nothing - we should already be @@ -101,11 +137,13 @@ class NiaAppStateTest { } @Test - fun niaAppState_showBottomBar_compact() { + fun niaAppState_showBottomBar_compact() = runTest { composeTestRule.setContent { state = NiaAppState( windowSizeClass = getCompactWindowClass(), - navController = NavHostController(LocalContext.current) + navController = NavHostController(LocalContext.current), + networkMonitor = networkMonitor, + coroutineScope = testScope ) } @@ -114,11 +152,13 @@ class NiaAppStateTest { } @Test - fun niaAppState_showNavRail_medium() { + fun niaAppState_showNavRail_medium() = runTest { composeTestRule.setContent { state = NiaAppState( windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(800.dp, 800.dp)), - navController = NavHostController(LocalContext.current) + navController = NavHostController(LocalContext.current), + networkMonitor = networkMonitor, + coroutineScope = testScope ) } @@ -127,11 +167,14 @@ class NiaAppStateTest { } @Test - fun niaAppState_showNavRail_large() { + fun niaAppState_showNavRail_large() = runTest { + composeTestRule.setContent { state = NiaAppState( windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(900.dp, 1200.dp)), - navController = NavHostController(LocalContext.current) + navController = NavHostController(LocalContext.current), + networkMonitor = networkMonitor, + coroutineScope = testScope ) } @@ -139,6 +182,30 @@ class NiaAppStateTest { assertFalse(state.shouldShowBottomBar) } + @Test + fun stateIsOfflineWhenNetworkMonitorIsOffline() = runTest { + + composeTestRule.setContent { + state = NiaAppState( + windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(900.dp, 1200.dp)), + navController = NavHostController(LocalContext.current), + networkMonitor = networkMonitor, + coroutineScope = testScope + ) + } + + val collectJob = testScope.launch { state.isOffline.collect() } + + networkMonitor.setConnected(false) + + assertEquals( + true, + state.isOffline.value + ) + + collectJob.cancel() + } + private fun getCompactWindowClass() = WindowSizeClass.calculateFromSize(DpSize(500.dp, 300.dp)) } diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt index 2f69cdc37..60a865fbb 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/MainActivity.kt @@ -37,6 +37,7 @@ import androidx.metrics.performance.JankStats import com.google.accompanist.systemuicontroller.rememberSystemUiController import com.google.samples.apps.nowinandroid.MainActivityUiState.Loading import com.google.samples.apps.nowinandroid.MainActivityUiState.Success +import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand @@ -57,6 +58,9 @@ class MainActivity : ComponentActivity() { @Inject lateinit var lazyStats: dagger.Lazy + @Inject + lateinit var networkMonitor: NetworkMonitor + val viewModel: MainActivityViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { @@ -105,6 +109,7 @@ class MainActivity : ComponentActivity() { androidTheme = shouldUseAndroidTheme(uiState) ) { NiaApp( + networkMonitor = networkMonitor, windowSizeClass = calculateWindowSizeClass(this), ) } diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt index f28824c5a..ef545c70b 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt @@ -31,10 +31,16 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarDuration.Indefinite +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @@ -42,8 +48,11 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavDestination import androidx.navigation.NavDestination.Companion.hierarchy +import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaBackground import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaGradientBackground import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBar @@ -61,12 +70,16 @@ import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination @OptIn( ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class, - ExperimentalComposeUiApi::class + ExperimentalComposeUiApi::class, ExperimentalLifecycleComposeApi::class ) @Composable fun NiaApp( windowSizeClass: WindowSizeClass, - appState: NiaAppState = rememberNiaAppState(windowSizeClass) + networkMonitor: NetworkMonitor, + appState: NiaAppState = rememberNiaAppState( + networkMonitor = networkMonitor, + windowSizeClass = windowSizeClass + ), ) { val background: @Composable (@Composable () -> Unit) -> Unit = when (appState.currentDestination?.route) { @@ -75,6 +88,9 @@ fun NiaApp( } background { + + val snackbarHostState = remember { SnackbarHostState() } + Scaffold( modifier = Modifier.semantics { testTagsAsResourceId = true @@ -82,11 +98,14 @@ fun NiaApp( containerColor = Color.Transparent, contentColor = MaterialTheme.colorScheme.onBackground, contentWindowInsets = WindowInsets(0, 0, 0, 0), + snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { - val destination = appState.topLevelDestinations[appState.currentDestination?.route] - if (appState.shouldShowTopBar && destination != null) { + // Show the top app bar on top level destinations. + val topLevelDestination = + appState.topLevelDestinations[appState.currentDestination?.route] + if (topLevelDestination != null) { NiaTopAppBar( - titleRes = destination.titleTextId, + titleRes = topLevelDestination.titleTextId, actionIcon = NiaIcons.Settings, actionIconContentDescription = stringResource( id = settingsR.string.top_app_bar_action_icon_description @@ -94,7 +113,7 @@ fun NiaApp( colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = Color.Transparent ), - onActionClick = { /*openAccountDialog = true*/ } + onActionClick = { appState.toggleSettingsDialog(true) } ) } }, @@ -108,6 +127,24 @@ fun NiaApp( } } ) { padding -> + + val isOffline by appState.isOffline.collectAsStateWithLifecycle() + + // If user is not connected to the internet show a snack bar to inform them. + val notConnected = stringResource(R.string.for_you_not_connected) + LaunchedEffect(isOffline) { + if (isOffline) snackbarHostState.showSnackbar( + message = notConnected, + duration = Indefinite + ) + } + + if (appState.shouldShowSettingsDialog) { + SettingsDialog( + onDismiss = { appState.toggleSettingsDialog(false) } + ) + } + Row( Modifier .fillMaxSize() @@ -134,6 +171,9 @@ fun NiaApp( .padding(padding) .consumedWindowInsets(padding) ) + + // TODO: We may want to add padding or spacer when the snackbar is shown so that + // content doesn't display behind it. } } } diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt index 250bdf5d1..19bc5366d 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt @@ -21,7 +21,11 @@ import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue import androidx.navigation.NavController import androidx.navigation.NavDestination import androidx.navigation.NavGraph.Companion.findStartDestination @@ -30,6 +34,11 @@ import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navOptions import androidx.tracing.trace +import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor +import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.DrawableResourceIcon +import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.ImageVectorIcon +import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons +import com.google.samples.apps.nowinandroid.core.navigation.NiaNavigationDestination import com.google.samples.apps.nowinandroid.core.ui.TrackDisposableJank import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.navigateToBookmarks import com.google.samples.apps.nowinandroid.feature.foryou.navigation.navigateToForYou @@ -38,29 +47,37 @@ import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination.BOOKMARKS import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination.FOR_YOU import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination.INTERESTS +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn @Composable fun rememberNiaAppState( windowSizeClass: WindowSizeClass, + networkMonitor: NetworkMonitor, + coroutineScope: CoroutineScope = rememberCoroutineScope(), navController: NavHostController = rememberNavController() ): NiaAppState { NavigationTrackingSideEffect(navController) - return remember(navController, windowSizeClass) { - NiaAppState(navController, windowSizeClass) + return remember(navController, coroutineScope, windowSizeClass, networkMonitor) { + NiaAppState(navController, coroutineScope, windowSizeClass, networkMonitor) } } @Stable class NiaAppState( val navController: NavHostController, - val windowSizeClass: WindowSizeClass + val coroutineScope: CoroutineScope, + val windowSizeClass: WindowSizeClass, + networkMonitor: NetworkMonitor, ) { val currentDestination: NavDestination? @Composable get() = navController .currentBackStackEntryAsState().value?.destination - val shouldShowTopBar: Boolean - @Composable get() = (currentDestination?.route in topLevelDestinations) + private var _shouldShowSettingsDialog by mutableStateOf(false) + val shouldShowSettingsDialog = _shouldShowSettingsDialog val shouldShowBottomBar: Boolean get() = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact || @@ -69,6 +86,14 @@ class NiaAppState( val shouldShowNavRail: Boolean get() = !shouldShowBottomBar + val isOffline = networkMonitor.isOnline + .map(Boolean::not) + .stateIn( + scope = coroutineScope, + started = SharingStarted.WhileSubscribed(5_000), + initialValue = false + ) + /** * Map of top level destinations to be used in the TopBar, BottomBar and NavRail. The key is the * route. @@ -109,6 +134,10 @@ class NiaAppState( fun onBackClick() { navController.popBackStack() } + + fun toggleSettingsDialog(shouldShow: Boolean) { + _shouldShowSettingsDialog = shouldShow + } } /** diff --git a/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt b/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt index 672213492..6c45c4314 100644 --- a/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt +++ b/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt @@ -21,10 +21,8 @@ import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.consumedWindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.layout.wrapContentSize @@ -33,11 +31,9 @@ import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt index c15263d3b..75320caea 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt @@ -22,21 +22,14 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.consumedWindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridCells.Adaptive @@ -51,19 +44,13 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarDuration.Indefinite -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalView @@ -104,11 +91,9 @@ internal fun ForYouRoute( ) { val interestsSelectionState by viewModel.interestsSelectionUiState.collectAsStateWithLifecycle() val feedState by viewModel.feedState.collectAsStateWithLifecycle() - val isOffline by viewModel.isOffline.collectAsStateWithLifecycle() val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle() ForYouScreen( - isOffline = isOffline, isSyncing = isSyncing, interestsSelectionState = interestsSelectionState, feedState = feedState, @@ -120,7 +105,6 @@ internal fun ForYouRoute( ) } -@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable internal fun ForYouScreen( isOffline: Boolean, @@ -133,107 +117,88 @@ internal fun ForYouScreen( onNewsResourcesCheckedChanged: (String, Boolean) -> Unit, modifier: Modifier = Modifier, ) { - val snackbarHostState = remember { SnackbarHostState() } - Scaffold( - snackbarHost = { SnackbarHost(snackbarHostState) }, - containerColor = Color.Transparent, - contentWindowInsets = WindowInsets(0, 0, 0, 0) - ) { innerPadding -> - // Workaround to call Activity.reportFullyDrawn from Jetpack Compose. - // This code should be called when the UI is ready for use - // and relates to Time To Full Display. - val interestsLoaded = - interestsSelectionState !is ForYouInterestsSelectionUiState.Loading - val feedLoaded = feedState !is NewsFeedUiState.Loading + // Workaround to call Activity.reportFullyDrawn from Jetpack Compose. + // This code should be called when the UI is ready for use + // and relates to Time To Full Display. + val interestsLoaded = + interestsSelectionState !is ForYouInterestsSelectionUiState.Loading + val feedLoaded = feedState !is NewsFeedUiState.Loading - if (interestsLoaded && feedLoaded) { - val localView = LocalView.current - // We use Unit to call reportFullyDrawn only on the first recomposition, - // however it will be called again if this composable goes out of scope. - // Activity.reportFullyDrawn() has its own check for this - // and is safe to call multiple times though. - LaunchedEffect(Unit) { - // We're leveraging the fact, that the current view is directly set as content of Activity. - val activity = localView.context as? Activity ?: return@LaunchedEffect - // To be sure not to call in the middle of a frame draw. - localView.doOnPreDraw { activity.reportFullyDrawn() } - } + if (interestsLoaded && feedLoaded) { + val localView = LocalView.current + // We use Unit to call reportFullyDrawn only on the first recomposition, + // however it will be called again if this composable goes out of scope. + // Activity.reportFullyDrawn() has its own check for this + // and is safe to call multiple times though. + LaunchedEffect(Unit) { + // We're leveraging the fact, that the current view is directly set as content of Activity. + val activity = localView.context as? Activity ?: return@LaunchedEffect + // To be sure not to call in the middle of a frame draw. + localView.doOnPreDraw { activity.reportFullyDrawn() } } + } - val state = rememberLazyGridState() - TrackScrollJank(scrollableState = state, stateName = "forYou:feed") - - val notConnected = stringResource(R.string.for_you_not_connected) - LaunchedEffect(isOffline) { - if (isOffline) snackbarHostState.showSnackbar( - message = notConnected, - duration = Indefinite - ) - } + val state = rememberLazyGridState() + TrackScrollJank(scrollableState = state, stateName = "forYou:feed") - LazyVerticalGrid( - columns = Adaptive(300.dp), - contentPadding = PaddingValues(16.dp), - horizontalArrangement = Arrangement.spacedBy(16.dp), - verticalArrangement = Arrangement.spacedBy(24.dp), - modifier = modifier - .padding(innerPadding) - .consumedWindowInsets(innerPadding) - .fillMaxSize() - .testTag("forYou:feed"), - state = state - ) { - interestsSelection( - interestsSelectionState = interestsSelectionState, - onAuthorCheckedChanged = onAuthorCheckedChanged, - onTopicCheckedChanged = onTopicCheckedChanged, - saveFollowedTopics = saveFollowedTopics, - // Custom LayoutModifier to remove the enforced parent 16.dp contentPadding - // from the LazyVerticalGrid and enable edge-to-edge scrolling for this section - interestsItemModifier = Modifier.layout { measurable, constraints -> - val placeable = measurable.measure( - constraints.copy( - maxWidth = constraints.maxWidth + 32.dp.roundToPx() - ) + LazyVerticalGrid( + columns = Adaptive(300.dp), + contentPadding = PaddingValues(16.dp), + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalArrangement = Arrangement.spacedBy(24.dp), + modifier = modifier + .fillMaxSize() + .testTag("forYou:feed"), + state = state + ) { + interestsSelection( + interestsSelectionState = interestsSelectionState, + onAuthorCheckedChanged = onAuthorCheckedChanged, + onTopicCheckedChanged = onTopicCheckedChanged, + saveFollowedTopics = saveFollowedTopics, + // Custom LayoutModifier to remove the enforced parent 16.dp contentPadding + // from the LazyVerticalGrid and enable edge-to-edge scrolling for this section + interestsItemModifier = Modifier.layout { measurable, constraints -> + val placeable = measurable.measure( + constraints.copy( + maxWidth = constraints.maxWidth + 32.dp.roundToPx() ) - layout(placeable.width, placeable.height) { - placeable.place(0, 0) - } + ) + layout(placeable.width, placeable.height) { + placeable.place(0, 0) } - ) + } + ) - newsFeed( - feedState = feedState, - onNewsResourcesCheckedChanged = onNewsResourcesCheckedChanged, - ) + newsFeed( + feedState = feedState, + onNewsResourcesCheckedChanged = onNewsResourcesCheckedChanged, + ) - item(span = { GridItemSpan(maxLineSpan) }) { + /*item(span = { GridItemSpan(maxLineSpan) }) { Column { Spacer(modifier = Modifier.height(8.dp)) // Add space for the content to clear the "offline" snackbar. + // TODO: Check that the Scaffold handles this correctly in NiaApp if (isOffline) Spacer(modifier = Modifier.height(48.dp)) Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing)) } - } - } - AnimatedVisibility( - visible = isSyncing || - feedState is NewsFeedUiState.Loading || - interestsSelectionState is ForYouInterestsSelectionUiState.Loading + }*/ + } + AnimatedVisibility( + visible = isSyncing || + feedState is NewsFeedUiState.Loading || + interestsSelectionState is ForYouInterestsSelectionUiState.Loading + ) { + val loadingContentDescription = stringResource(id = R.string.for_you_loading) + Box( + modifier = Modifier.fillMaxWidth() ) { - val loadingContentDescription = stringResource(id = R.string.for_you_loading) - Box( - modifier = Modifier - .padding(innerPadding) - .consumedWindowInsets(innerPadding) - .fillMaxWidth() - ) { - NiaOverlayLoadingWheel( - modifier = Modifier.align(Alignment.Center), - contentDesc = loadingContentDescription - ) - } + NiaOverlayLoadingWheel( + modifier = Modifier.align(Alignment.Center), + contentDesc = loadingContentDescription + ) } } } @@ -426,7 +391,6 @@ fun ForYouScreenPopulatedFeed() { BoxWithConstraints { NiaTheme { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.NoInterestsSelection, feedState = NewsFeedUiState.Success( @@ -449,7 +413,6 @@ fun ForYouScreenOfflinePopulatedFeed() { BoxWithConstraints { NiaTheme { ForYouScreen( - isOffline = true, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.NoInterestsSelection, feedState = NewsFeedUiState.Success( @@ -472,7 +435,6 @@ fun ForYouScreenTopicSelection() { BoxWithConstraints { NiaTheme { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.WithInterestsSelection( topics = previewTopics.map { FollowableTopic(it, false) }, @@ -498,7 +460,6 @@ fun ForYouScreenLoading() { BoxWithConstraints { NiaTheme { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.Loading, feedState = NewsFeedUiState.Loading, @@ -517,7 +478,6 @@ fun ForYouScreenPopulatedAndLoading() { BoxWithConstraints { NiaTheme { ForYouScreen( - isOffline = false, isSyncing = true, interestsSelectionState = ForYouInterestsSelectionUiState.Loading, feedState = NewsFeedUiState.Success( diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt index 8cbf39c31..8eedf40f0 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt @@ -94,14 +94,6 @@ class ForYouViewModel @Inject constructor( mutableStateOf>(emptySet()) } - val isOffline = networkMonitor.isOnline - .map(Boolean::not) - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000), - initialValue = false - ) - val isSyncing = syncStatusMonitor.isSyncing .stateIn( scope = viewModelScope, diff --git a/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt b/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt index 7919dda9e..9549ecb90 100644 --- a/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt +++ b/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt @@ -1404,21 +1404,6 @@ class ForYouViewModelTest { collectJob1.cancel() collectJob2.cancel() } - - @Test - fun stateIsOfflineWhenNetworkMonitorIsOffline() = runTest { - val collectJob = - launch(UnconfinedTestDispatcher()) { viewModel.isOffline.collect() } - - networkMonitor.setConnected(false) - - assertEquals( - true, - viewModel.isOffline.value - ) - - collectJob.cancel() - } } private val sampleAuthors = listOf( diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt index b51c5b6e7..11297d5c5 100644 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsDialog.kt @@ -61,9 +61,9 @@ import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Suc @ExperimentalLifecycleComposeApi @Composable -internal fun SettingsDialog( - viewModel: SettingsViewModel = hiltViewModel(), - onDismiss: () -> Unit +fun SettingsDialog( + onDismiss: () -> Unit, + viewModel: SettingsViewModel = hiltViewModel() ) { val settingsUiState by viewModel.settingsUiState.collectAsStateWithLifecycle() SettingsDialog( @@ -132,7 +132,7 @@ private fun SettingsPanel( onChangeDarkThemeConfig: (darkThemeConfig: DarkThemeConfig) -> Unit ) { SettingsDialogSectionTitle(text = stringResource(R.string.theme)) - Column { + Column(Modifier.selectableGroup()) { SettingsDialogThemeChooserRow( text = stringResource(R.string.brand_default), selected = settings.brand == DEFAULT, diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt index be2927546..da72f8beb 100644 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt @@ -47,7 +47,12 @@ class SettingsViewModel @Inject constructor( } .stateIn( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000), + // Starting eagerly means the user data is ready when the SettingsDialog is laid out + // for the first time. Without this the layout is done using the "Loading" text, + // then replaced with the user editable fields once loaded, however, the layout + // height doesn't change meaning all the fields are squashed into a small + // scrollable column. + started = SharingStarted.Eagerly, initialValue = Loading ) From 0d5dd944eabcb377d815c46761592bae4e5631a2 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 00:22:51 +0100 Subject: [PATCH 14/22] Fix getter for settings dialog state --- .../com/google/samples/apps/nowinandroid/ui/NiaAppState.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt index 19bc5366d..018e4cf8a 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt @@ -77,7 +77,8 @@ class NiaAppState( .currentBackStackEntryAsState().value?.destination private var _shouldShowSettingsDialog by mutableStateOf(false) - val shouldShowSettingsDialog = _shouldShowSettingsDialog + val shouldShowSettingsDialog + get() = _shouldShowSettingsDialog val shouldShowBottomBar: Boolean get() = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact || From 76daa393b1f98c0d90e32999d96eedd054296332 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 16:46:23 +0100 Subject: [PATCH 15/22] Address review feedback from Manu --- .../apps/nowinandroid/ui/NavigationTest.kt | 1 - .../apps/nowinandroid/ui/NiaAppStateTest.kt | 53 +++---------------- .../samples/apps/nowinandroid/ui/NiaApp.kt | 14 ++--- .../apps/nowinandroid/ui/NiaAppState.kt | 12 +++-- .../core/designsystem/component/TopAppBar.kt | 2 - .../src/main/res/values/strings.xml | 1 - .../feature/settings/SettingsViewModel.kt | 2 +- 7 files changed, 22 insertions(+), 63 deletions(-) diff --git a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt index dfc45f280..59f567ca2 100644 --- a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt +++ b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NavigationTest.kt @@ -206,7 +206,6 @@ class NavigationTest { @Test fun whenSettingsDialogDismissed_previousScreenIsDisplayed() { - composeTestRule.apply { // Navigate to the saved screen, open the settings dialog, then close it. diff --git a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt index ce8f1aa00..cfda9c0d9 100644 --- a/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt +++ b/app/src/androidTest/java/com/google/samples/apps/nowinandroid/ui/NiaAppStateTest.kt @@ -30,19 +30,14 @@ import androidx.navigation.compose.ComposeNavigator import androidx.navigation.compose.composable import androidx.navigation.createGraph import androidx.navigation.testing.TestNavHostController -import com.google.samples.apps.nowinandroid.core.testing.util.MainDispatcherRule import com.google.samples.apps.nowinandroid.core.testing.util.TestNetworkMonitor -import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch -import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest -import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue -import org.junit.Before import org.junit.Rule import org.junit.Test @@ -55,31 +50,15 @@ import org.junit.Test @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) class NiaAppStateTest { - @get:Rule - val mainDispatcherRule = MainDispatcherRule() - @get:Rule val composeTestRule = createComposeRule() // Create the test dependencies. - private lateinit var testScope: TestScope private val networkMonitor = TestNetworkMonitor() // Subject under test. private lateinit var state: NiaAppState - @Before - fun setup() { - // We use the Unconfined dispatcher to ensure that coroutines are executed sequentially in - // tests. - testScope = TestScope(UnconfinedTestDispatcher()) - } - - @After - fun cleanup() { - testScope.cancel() - } - @Test fun niaAppState_currentDestination() = runTest { var currentDestination: String? = null @@ -91,7 +70,7 @@ class NiaAppStateTest { windowSizeClass = getCompactWindowClass(), navController = navController, networkMonitor = networkMonitor, - coroutineScope = testScope + coroutineScope = backgroundScope ) } @@ -122,20 +101,6 @@ class NiaAppStateTest { assertTrue(state.topLevelDestinations[2].name.contains("interests", true)) } - @Test - fun niaAppState_showTopBarForTopLevelDestinations() { - composeTestRule.setContent { - val navController = rememberTestNavController() - state = rememberNiaAppState( - windowSizeClass = getCompactWindowClass(), - navController = navController, - networkMonitor = networkMonitor - ) - - // Do nothing - we should already be - } - } - @Test fun niaAppState_showBottomBar_compact() = runTest { composeTestRule.setContent { @@ -143,7 +108,7 @@ class NiaAppStateTest { windowSizeClass = getCompactWindowClass(), navController = NavHostController(LocalContext.current), networkMonitor = networkMonitor, - coroutineScope = testScope + coroutineScope = backgroundScope ) } @@ -158,7 +123,7 @@ class NiaAppStateTest { windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(800.dp, 800.dp)), navController = NavHostController(LocalContext.current), networkMonitor = networkMonitor, - coroutineScope = testScope + coroutineScope = backgroundScope ) } @@ -174,7 +139,7 @@ class NiaAppStateTest { windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(900.dp, 1200.dp)), navController = NavHostController(LocalContext.current), networkMonitor = networkMonitor, - coroutineScope = testScope + coroutineScope = backgroundScope ) } @@ -183,27 +148,23 @@ class NiaAppStateTest { } @Test - fun stateIsOfflineWhenNetworkMonitorIsOffline() = runTest { + fun stateIsOfflineWhenNetworkMonitorIsOffline() = runTest(UnconfinedTestDispatcher()) { composeTestRule.setContent { state = NiaAppState( windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(900.dp, 1200.dp)), navController = NavHostController(LocalContext.current), networkMonitor = networkMonitor, - coroutineScope = testScope + coroutineScope = backgroundScope ) } - val collectJob = testScope.launch { state.isOffline.collect() } - + backgroundScope.launch { state.isOffline.collect() } networkMonitor.setConnected(false) - assertEquals( true, state.isOffline.value ) - - collectJob.cancel() } private fun getCompactWindowClass() = WindowSizeClass.calculateFromSize(DpSize(500.dp, 300.dp)) diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt index ef545c70b..ec2f38551 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt @@ -70,7 +70,8 @@ import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination @OptIn( ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class, - ExperimentalComposeUiApi::class, ExperimentalLifecycleComposeApi::class + ExperimentalComposeUiApi::class, + ExperimentalLifecycleComposeApi::class ) @Composable fun NiaApp( @@ -101,11 +102,10 @@ fun NiaApp( snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { // Show the top app bar on top level destinations. - val topLevelDestination = - appState.topLevelDestinations[appState.currentDestination?.route] - if (topLevelDestination != null) { + val destination = appState.currentTopLevelDestination + if (destination != null) { NiaTopAppBar( - titleRes = topLevelDestination.titleTextId, + titleRes = destination.titleTextId, actionIcon = NiaIcons.Settings, actionIconContentDescription = stringResource( id = settingsR.string.top_app_bar_action_icon_description @@ -113,7 +113,7 @@ fun NiaApp( colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = Color.Transparent ), - onActionClick = { appState.toggleSettingsDialog(true) } + onActionClick = { appState.setShowSettingsDialog(true) } ) } }, @@ -141,7 +141,7 @@ fun NiaApp( if (appState.shouldShowSettingsDialog) { SettingsDialog( - onDismiss = { appState.toggleSettingsDialog(false) } + onDismiss = { appState.setShowSettingsDialog(false) } ) } diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt index 018e4cf8a..c2687d738 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt @@ -76,9 +76,11 @@ class NiaAppState( @Composable get() = navController .currentBackStackEntryAsState().value?.destination - private var _shouldShowSettingsDialog by mutableStateOf(false) - val shouldShowSettingsDialog - get() = _shouldShowSettingsDialog + val currentTopLevelDestination: TopLevelDestination? + @Composable get() = topLevelDestinations[currentDestination?.route] + + var shouldShowSettingsDialog by mutableStateOf(false) + private set val shouldShowBottomBar: Boolean get() = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact || @@ -136,8 +138,8 @@ class NiaAppState( navController.popBackStack() } - fun toggleSettingsDialog(shouldShow: Boolean) { - _shouldShowSettingsDialog = shouldShow + fun setShowSettingsDialog(shouldShow: Boolean) { + shouldShowSettingsDialog = shouldShow } } diff --git a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/TopAppBar.kt b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/TopAppBar.kt index 20cc5c06b..c3290035a 100644 --- a/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/TopAppBar.kt +++ b/core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/TopAppBar.kt @@ -32,9 +32,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.tooling.preview.Preview -import com.google.samples.apps.nowinandroid.core.designsystem.R @OptIn(ExperimentalMaterial3Api::class) @Composable diff --git a/core/designsystem/src/main/res/values/strings.xml b/core/designsystem/src/main/res/values/strings.xml index 3cc19c6ef..5d1158888 100644 --- a/core/designsystem/src/main/res/values/strings.xml +++ b/core/designsystem/src/main/res/values/strings.xml @@ -18,5 +18,4 @@ Follow Unfollow Browse topic - Screen title diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt index da72f8beb..7990a96c0 100644 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt @@ -33,7 +33,7 @@ import kotlinx.coroutines.launch @HiltViewModel class SettingsViewModel @Inject constructor( - private val userDataRepository: UserDataRepository + private val userDataRepository: UserDataRepository, ) : ViewModel() { val settingsUiState: StateFlow = userDataRepository.userDataStream From e5183e21e0804e7cbaff7e0cd62ecefa8e286b55 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 21:15:24 +0100 Subject: [PATCH 16/22] Resolve conflict with navigation changes from main --- .../samples/apps/nowinandroid/ui/NiaApp.kt | 4 ++- .../apps/nowinandroid/ui/NiaAppState.kt | 14 +++++--- app/src/main/res/values/strings.xml | 1 + .../navigation/BookmarksNavigation.kt | 2 +- .../feature/foryou/ForYouScreen.kt | 1 - .../feature/foryou/ForYouViewModel.kt | 1 - .../foryou/src/main/res/values/strings.xml | 1 - .../feature/foryou/ForYouViewModelTest.kt | 1 - .../navigation/InterestsNavigation.kt | 2 +- .../navigation/SettingsDestination.kt | 35 ------------------- 10 files changed, 15 insertions(+), 47 deletions(-) delete mode 100644 feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt index ec2f38551..be9713f61 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt @@ -66,6 +66,8 @@ import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.feature.settings.R as settingsR import com.google.samples.apps.nowinandroid.navigation.NiaNavHost import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination +import com.google.samples.apps.nowinandroid.R +import com.google.samples.apps.nowinandroid.feature.settings.SettingsDialog @OptIn( ExperimentalMaterial3Api::class, @@ -131,7 +133,7 @@ fun NiaApp( val isOffline by appState.isOffline.collectAsStateWithLifecycle() // If user is not connected to the internet show a snack bar to inform them. - val notConnected = stringResource(R.string.for_you_not_connected) + val notConnected = stringResource(R.string.not_connected) LaunchedEffect(isOffline) { if (isOffline) snackbarHostState.showSnackbar( message = notConnected, diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt index c2687d738..a1638e416 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt @@ -35,13 +35,12 @@ import androidx.navigation.compose.rememberNavController import androidx.navigation.navOptions import androidx.tracing.trace import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor -import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.DrawableResourceIcon -import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.ImageVectorIcon -import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons -import com.google.samples.apps.nowinandroid.core.navigation.NiaNavigationDestination import com.google.samples.apps.nowinandroid.core.ui.TrackDisposableJank +import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.bookmarksRoute import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.navigateToBookmarks +import com.google.samples.apps.nowinandroid.feature.foryou.navigation.forYouNavigationRoute import com.google.samples.apps.nowinandroid.feature.foryou.navigation.navigateToForYou +import com.google.samples.apps.nowinandroid.feature.interests.navigation.interestsRoute import com.google.samples.apps.nowinandroid.feature.interests.navigation.navigateToInterestsGraph import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination.BOOKMARKS @@ -77,7 +76,12 @@ class NiaAppState( .currentBackStackEntryAsState().value?.destination val currentTopLevelDestination: TopLevelDestination? - @Composable get() = topLevelDestinations[currentDestination?.route] + @Composable get() = when(currentDestination?.route){ + forYouNavigationRoute -> FOR_YOU + bookmarksRoute -> BOOKMARKS + interestsRoute -> INTERESTS + else -> null + } var shouldShowSettingsDialog by mutableStateOf(false) private set diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 6d5202b99..cd92f3977 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -16,4 +16,5 @@ --> Now in Android + ⚠️ You aren’t connected to the internet diff --git a/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/navigation/BookmarksNavigation.kt b/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/navigation/BookmarksNavigation.kt index 0d530019d..188c948e4 100644 --- a/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/navigation/BookmarksNavigation.kt +++ b/feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/navigation/BookmarksNavigation.kt @@ -22,7 +22,7 @@ import androidx.navigation.NavOptions import androidx.navigation.compose.composable import com.google.samples.apps.nowinandroid.feature.bookmarks.BookmarksRoute -private const val bookmarksRoute = "bookmarks_route" +const val bookmarksRoute = "bookmarks_route" fun NavController.navigateToBookmarks(navOptions: NavOptions? = null) { this.navigate(bookmarksRoute, navOptions) diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt index 75320caea..19d3c1e6b 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt @@ -107,7 +107,6 @@ internal fun ForYouRoute( @Composable internal fun ForYouScreen( - isOffline: Boolean, isSyncing: Boolean, interestsSelectionState: ForYouInterestsSelectionUiState, feedState: NewsFeedUiState, diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt index 8eedf40f0..f88cd9d39 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt @@ -51,7 +51,6 @@ import kotlinx.coroutines.launch @OptIn(SavedStateHandleSaveableApi::class) @HiltViewModel class ForYouViewModel @Inject constructor( - networkMonitor: NetworkMonitor, syncStatusMonitor: SyncStatusMonitor, private val userDataRepository: UserDataRepository, private val getSaveableNewsResourcesStream: GetSaveableNewsResourcesStreamUseCase, diff --git a/feature/foryou/src/main/res/values/strings.xml b/feature/foryou/src/main/res/values/strings.xml index 5a66a0645..8f109ef69 100644 --- a/feature/foryou/src/main/res/values/strings.xml +++ b/feature/foryou/src/main/res/values/strings.xml @@ -23,7 +23,6 @@ Updates from topics you follow will appear here. Follow some things to get started. Now in Android Search - ⚠️ You aren’t connected to the internet You are following diff --git a/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt b/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt index 9549ecb90..4a6ce9c12 100644 --- a/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt +++ b/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt @@ -76,7 +76,6 @@ class ForYouViewModelTest { @Before fun setup() { viewModel = ForYouViewModel( - networkMonitor = networkMonitor, syncStatusMonitor = syncStatusMonitor, userDataRepository = userDataRepository, getSaveableNewsResourcesStream = getSaveableNewsResourcesStreamUseCase, diff --git a/feature/interests/src/main/java/com/google/samples/apps/nowinandroid/feature/interests/navigation/InterestsNavigation.kt b/feature/interests/src/main/java/com/google/samples/apps/nowinandroid/feature/interests/navigation/InterestsNavigation.kt index 19e04b8b5..f0604e46f 100644 --- a/feature/interests/src/main/java/com/google/samples/apps/nowinandroid/feature/interests/navigation/InterestsNavigation.kt +++ b/feature/interests/src/main/java/com/google/samples/apps/nowinandroid/feature/interests/navigation/InterestsNavigation.kt @@ -24,7 +24,7 @@ import androidx.navigation.navigation import com.google.samples.apps.nowinandroid.feature.interests.InterestsRoute private const val interestsGraphRoutePattern = "interests_graph" -private const val interestsRoute = "interests_route" +const val interestsRoute = "interests_route" fun NavController.navigateToInterestsGraph(navOptions: NavOptions? = null) { this.navigate(interestsGraphRoutePattern, navOptions) diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt deleted file mode 100644 index 3eb9a6c92..000000000 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/navigation/SettingsDestination.kt +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2022 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.google.samples.apps.nowinandroid.feature.settings.navigation - -import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi -import androidx.navigation.NavGraphBuilder -import androidx.navigation.compose.dialog -import com.google.samples.apps.nowinandroid.core.navigation.NiaNavigationDestination -import com.google.samples.apps.nowinandroid.feature.settings.SettingsDialog - -object SettingsDestination : NiaNavigationDestination { - override val route = "settings_route" - override val destinationId = "settings_destination" -} - -@OptIn(ExperimentalLifecycleComposeApi::class) -fun NavGraphBuilder.settingsDialog(onDismiss: () -> Unit) { - dialog(route = SettingsDestination.route) { - SettingsDialog(onDismiss = onDismiss) - } -} From dbff140b64da33e9802206102ce3dcfd1ef15dcb Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 21:20:28 +0100 Subject: [PATCH 17/22] Fix minor issues --- .../apps/nowinandroid/navigation/TopLevelDestination.kt | 2 +- .../com/google/samples/apps/nowinandroid/ui/NiaApp.kt | 9 ++++++--- .../google/samples/apps/nowinandroid/ui/NiaAppState.kt | 2 +- .../core/navigation/NiaNavigationDestination.kt | 0 .../apps/nowinandroid/feature/foryou/ForYouViewModel.kt | 1 - 5 files changed, 8 insertions(+), 6 deletions(-) delete mode 100644 core/navigation/src/main/java/com/google/samples/apps/nowinandroid/core/navigation/NiaNavigationDestination.kt diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/navigation/TopLevelDestination.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/navigation/TopLevelDestination.kt index 247b2934b..956037f29 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/navigation/TopLevelDestination.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/navigation/TopLevelDestination.kt @@ -16,6 +16,7 @@ package com.google.samples.apps.nowinandroid.navigation +import com.google.samples.apps.nowinandroid.R import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.DrawableResourceIcon import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.ImageVectorIcon @@ -23,7 +24,6 @@ import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.feature.bookmarks.R as bookmarksR import com.google.samples.apps.nowinandroid.feature.foryou.R as forYouR import com.google.samples.apps.nowinandroid.feature.interests.R as interestsR -import com.google.samples.apps.nowinandroid.R /** * Type for the top level destinations in the application. Each of these destinations diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt index be9713f61..7556213d5 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt @@ -52,6 +52,7 @@ import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavDestination import androidx.navigation.NavDestination.Companion.hierarchy +import com.google.samples.apps.nowinandroid.R import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaBackground import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaGradientBackground @@ -64,10 +65,9 @@ import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.Drawable import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.ImageVectorIcon import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.feature.settings.R as settingsR +import com.google.samples.apps.nowinandroid.feature.settings.SettingsDialog import com.google.samples.apps.nowinandroid.navigation.NiaNavHost import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination -import com.google.samples.apps.nowinandroid.R -import com.google.samples.apps.nowinandroid.feature.settings.SettingsDialog @OptIn( ExperimentalMaterial3Api::class, @@ -86,7 +86,10 @@ fun NiaApp( ) { val background: @Composable (@Composable () -> Unit) -> Unit = when (appState.currentDestination?.route) { - TopLevelDestination.FOR_YOU.name -> { content -> NiaGradientBackground(content = content) } + TopLevelDestination.FOR_YOU.name -> { + content -> + NiaGradientBackground(content = content) + } else -> { content -> NiaBackground(content = content) } } diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt index a1638e416..bc5724c02 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt @@ -76,7 +76,7 @@ class NiaAppState( .currentBackStackEntryAsState().value?.destination val currentTopLevelDestination: TopLevelDestination? - @Composable get() = when(currentDestination?.route){ + @Composable get() = when (currentDestination?.route) { forYouNavigationRoute -> FOR_YOU bookmarksRoute -> BOOKMARKS interestsRoute -> INTERESTS diff --git a/core/navigation/src/main/java/com/google/samples/apps/nowinandroid/core/navigation/NiaNavigationDestination.kt b/core/navigation/src/main/java/com/google/samples/apps/nowinandroid/core/navigation/NiaNavigationDestination.kt deleted file mode 100644 index e69de29bb..000000000 diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt index f88cd9d39..548e786fe 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt @@ -25,7 +25,6 @@ import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.compose.SavedStateHandleSaveableApi import androidx.lifecycle.viewmodel.compose.saveable import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository -import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor import com.google.samples.apps.nowinandroid.core.data.util.SyncStatusMonitor import com.google.samples.apps.nowinandroid.core.domain.GetFollowableTopicsStreamUseCase import com.google.samples.apps.nowinandroid.core.domain.GetSaveableNewsResourcesStreamUseCase From 501d29be59b6fd3d5757bef978e948d0a3735d06 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 21:39:57 +0100 Subject: [PATCH 18/22] Add back spacer for navigation bar --- .../feature/foryou/ForYouScreen.kt | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt index 19d3c1e6b..bcff09fae 100644 --- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt +++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt @@ -24,12 +24,17 @@ import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridCells.Adaptive @@ -175,15 +180,15 @@ internal fun ForYouScreen( onNewsResourcesCheckedChanged = onNewsResourcesCheckedChanged, ) - /*item(span = { GridItemSpan(maxLineSpan) }) { - Column { - Spacer(modifier = Modifier.height(8.dp)) - // Add space for the content to clear the "offline" snackbar. - // TODO: Check that the Scaffold handles this correctly in NiaApp - if (isOffline) Spacer(modifier = Modifier.height(48.dp)) - Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing)) - } - }*/ + item(span = { GridItemSpan(maxLineSpan) }) { + Column { + Spacer(modifier = Modifier.height(8.dp)) + // Add space for the content to clear the "offline" snackbar. + // TODO: Check that the Scaffold handles this correctly in NiaApp + // if (isOffline) Spacer(modifier = Modifier.height(48.dp)) + Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing)) + } + } } AnimatedVisibility( visible = isSyncing || From 756e45eb82c168a48e500d9935bf8cac68dbfad3 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 21:52:43 +0100 Subject: [PATCH 19/22] Add note about b/221643630 --- .../nowinandroid/feature/settings/SettingsViewModel.kt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt index 7990a96c0..fa159b555 100644 --- a/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt +++ b/feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt @@ -48,10 +48,11 @@ class SettingsViewModel @Inject constructor( .stateIn( scope = viewModelScope, // Starting eagerly means the user data is ready when the SettingsDialog is laid out - // for the first time. Without this the layout is done using the "Loading" text, - // then replaced with the user editable fields once loaded, however, the layout - // height doesn't change meaning all the fields are squashed into a small + // for the first time. Without this, due to b/221643630 the layout is done using the + // "Loading" text, then replaced with the user editable fields once loaded, however, + // the layout height doesn't change meaning all the fields are squashed into a small // scrollable column. + // TODO: Change to SharingStarted.WhileSubscribed(5_000) when b/221643630 is fixed started = SharingStarted.Eagerly, initialValue = Loading ) From 1c6c812b76d334238d396b287ff3530cc72dfed2 Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 22:02:51 +0100 Subject: [PATCH 20/22] Update app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt Co-authored-by: Alex Vanyo --- .../java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt index 7556213d5..b7f6f633e 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt @@ -85,8 +85,8 @@ fun NiaApp( ), ) { val background: @Composable (@Composable () -> Unit) -> Unit = - when (appState.currentDestination?.route) { - TopLevelDestination.FOR_YOU.name -> { + when (appState.currentTopLevelDestination) { + TopLevelDestination.FOR_YOU -> { content -> NiaGradientBackground(content = content) } From 505187482b05e597deafd16e49ccf5523e99feec Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 22:11:11 +0100 Subject: [PATCH 21/22] Add workaround for top app bar overlapping nav rail --- .../java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt index b7f6f633e..30acd84cf 100644 --- a/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt +++ b/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaApp.kt @@ -48,6 +48,7 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.compose.ui.zIndex import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavDestination @@ -110,6 +111,11 @@ fun NiaApp( val destination = appState.currentTopLevelDestination if (destination != null) { NiaTopAppBar( + // When the nav rail is displayed, the top app bar will, by default + // overlap it. This means that the top most item in the nav rail + // won't be tappable. A workaround is to position the top app bar + // behind the nav rail using zIndex. + modifier = Modifier.zIndex(-1F), titleRes = destination.titleTextId, actionIcon = NiaIcons.Settings, actionIconContentDescription = stringResource( From b9156f681286d69fd4a45a9995a9ab4e1ebbab7f Mon Sep 17 00:00:00 2001 From: Don Turner Date: Fri, 21 Oct 2022 23:36:50 +0100 Subject: [PATCH 22/22] Fix UI tests --- .../apps/nowinandroid/feature/foryou/ForYouScreenTest.kt | 8 -------- 1 file changed, 8 deletions(-) diff --git a/feature/foryou/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreenTest.kt b/feature/foryou/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreenTest.kt index e06981709..af5f07372 100644 --- a/feature/foryou/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreenTest.kt +++ b/feature/foryou/src/androidTest/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreenTest.kt @@ -53,7 +53,6 @@ class ForYouScreenTest { composeTestRule.setContent { BoxWithConstraints { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.Loading, feedState = NewsFeedUiState.Loading, @@ -77,7 +76,6 @@ class ForYouScreenTest { composeTestRule.setContent { BoxWithConstraints { ForYouScreen( - isOffline = false, isSyncing = true, interestsSelectionState = ForYouInterestsSelectionUiState.NoInterestsSelection, feedState = NewsFeedUiState.Success(emptyList()), @@ -101,7 +99,6 @@ class ForYouScreenTest { composeTestRule.setContent { BoxWithConstraints { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.WithInterestsSelection( @@ -151,7 +148,6 @@ class ForYouScreenTest { composeTestRule.setContent { BoxWithConstraints { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.WithInterestsSelection( @@ -204,7 +200,6 @@ class ForYouScreenTest { composeTestRule.setContent { BoxWithConstraints { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.WithInterestsSelection( @@ -257,7 +252,6 @@ class ForYouScreenTest { composeTestRule.setContent { BoxWithConstraints { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.WithInterestsSelection( @@ -285,7 +279,6 @@ class ForYouScreenTest { composeTestRule.setContent { BoxWithConstraints { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.NoInterestsSelection, feedState = NewsFeedUiState.Loading, @@ -308,7 +301,6 @@ class ForYouScreenTest { fun feed_whenNoInterestsSelectionAndLoaded_showsFeed() { composeTestRule.setContent { ForYouScreen( - isOffline = false, isSyncing = false, interestsSelectionState = ForYouInterestsSelectionUiState.NoInterestsSelection, feedState = NewsFeedUiState.Success(