Added backup rules for user preferences and no test needed

backup-and-restore-a12-changes
Niharika Arora 3 years ago
commit 1d3cad8dc9

@ -0,0 +1,16 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base", "group:all", ":dependencyDashboard", "schedule:daily"
],
"packageRules": [
{
"matchPackageNames": ["org.objenesis:objenesis"],
"allowedVersions": "<=2.6"
},
{
"matchPackageNames": ["com.google.protobuf"],
"allowedVersions": "<=0.8.19"
}
]
}

@ -34,16 +34,16 @@ jobs:
uses: gradle/gradle-build-action@v2 uses: gradle/gradle-build-action@v2
- name: Check spotless - name: Check spotless
run: ./gradlew spotlessCheck --init-script gradle/init.gradle.kts --no-configuration-cache --stacktrace run: ./gradlew spotlessCheck --init-script gradle/init.gradle.kts --no-configuration-cache
- name: Check lint - name: Check lint
run: ./gradlew lintDemoDebug --stacktrace run: ./gradlew lintDemoDebug
- name: Build all build type and flavor permutations - name: Build all build type and flavor permutations
run: ./gradlew assemble --stacktrace run: ./gradlew assemble
- name: Run local tests - name: Run local tests
run: ./gradlew testDemoDebug testProdDebug --stacktrace run: ./gradlew testDemoDebug testProdDebug
- name: Upload build outputs (APKs) - name: Upload build outputs (APKs)
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v3
@ -64,7 +64,7 @@ jobs:
timeout-minutes: 55 timeout-minutes: 55
strategy: strategy:
matrix: matrix:
api-level: [23, 26, 30] api-level: [26, 30]
steps: steps:
- name: Checkout - name: Checkout
@ -88,9 +88,9 @@ jobs:
api-level: ${{ matrix.api-level }} api-level: ${{ matrix.api-level }}
arch: x86_64 arch: x86_64
disable-animations: true disable-animations: true
disk-size: 2000M disk-size: 6000M
heap-size: 600M heap-size: 600M
script: ./gradlew connectedProdDebugAndroidTest -x :benchmark:connectedProdBenchmarkAndroidTest --stacktrace script: ./gradlew connectedProdDebugAndroidTest -x :benchmark:connectedProdBenchmarkAndroidTest
- name: Upload test reports - name: Upload test reports
if: always() if: always()

@ -18,10 +18,31 @@
# End users may safely ignore this file. It has no relevance to other systems. # End users may safely ignore this file. It has no relevance to other systems.
--- ---
status: PUBLISHED status: PUBLISHED
technologies: [Android] technologies: [Android, JetpackCompose, Coroutines]
categories: [Architecture] categories:
- AndroidTesting
- AndroidArchitecture
- AndroidArchitectureUILayer
- AndroidArchitectureDomainLayer
- AndroidArchitectureDataLayer
- AndroidArchitectureStateProduction
- AndroidArchitectureStateHolder
- JetpackComposeTesting
- JetpackComposeA11y
- JetpackComposeArchitectureAndState
- JetpackComposeDesignSystems
- JetpackComposeNavigation
- JetpackComposeAnimation
solutions:
- Mobile
- Flow
- JetpackHilt
- JetpackDataStore
- JetpackRoom
- JetpackNavigation
- JetpackWorkManager
- JetpackLifecycle
languages: [Kotlin] languages: [Kotlin]
solutions: [Mobile]
github: android/nowinandroid github: android/nowinandroid
level: ADVANCED level: ADVANCED
license: apache2 license: apache2

@ -28,9 +28,6 @@
<option name="JD_PRESERVE_LINE_FEEDS" value="true" /> <option name="JD_PRESERVE_LINE_FEEDS" value="true" />
</JavaCodeStyleSettings> </JavaCodeStyleSettings>
<JetCodeStyleSettings> <JetCodeStyleSettings>
<option name="PACKAGES_TO_USE_STAR_IMPORTS">
<value />
</option>
<option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="99" /> <option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="99" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="99" /> <option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="99" />
<option name="IMPORT_NESTED_CLASSES" value="true" /> <option name="IMPORT_NESTED_CLASSES" value="true" />

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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
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.
-->
<component name="ProjectRunConfigurationManager">
<!--
Baseline Profiles improve code execution speed by around 30% from the first launch by avoiding
interpretation and just-in-time (JIT) compilation steps for included code paths.
More information at http://d.android.com/baseline-profiles.
In this run configuration we leverage rerun parameter that always reruns the requested task regardless of cache.
We also leverage enable-display parameter to be able to verify the generator works as intended.
-->
<configuration default="false" name="Generate Demo Baseline Profile" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="-Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=BaselineProfile" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value=":benchmark:pixel6Api31DemoBenchmarkAndroidTest" />
<option value="--rerun" />
<option value="--enable-display" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<method v="2" />
</configuration>
</component>

@ -1,33 +1,32 @@
![Now in Android](docs/images/nia-splash.jpg "Now in Android") ![Now in Android](docs/images/nia-splash.jpg "Now in Android")
Now in Android App [Work in progress 🚧] <a href="https://play.google.com/store/apps/details?id=com.google.samples.apps.nowinandroid"><img src="https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png" height="70"></a>
Now in Android App
================== ==================
**Learn how this app was designed by reading the [architecture](docs/ArchitectureLearningJourney.md) and [modularization](docs/ModularizationLearningJourney.md) learning journeys.** **Learn how this app was designed and built in the [design case study](https://goo.gle/nia-figma), [architecture learning journey](docs/ArchitectureLearningJourney.md) and [modularization learning journey](docs/ModularizationLearningJourney.md).**
This is the repository for the [Now in Android](https://developer.android.com/series/now-in-android) This is the repository for the [Now in Android](https://developer.android.com/series/now-in-android)
app. app. It is a **work in progress** 🚧.
**Now in Android** is a fully functional Android app built entirely with Kotlin and Jetpack Compose. It **Now in Android** is a fully functional Android app built entirely with Kotlin and Jetpack Compose. It
follows Android design and development best practices and is intended to be a useful reference follows Android design and development best practices and is intended to be a useful reference
for developers. As a running app, it's intended to help developers keep up-to-date with the world for developers. As a running app, it's intended to help developers keep up-to-date with the world
of Android development by providing regular news updates. of Android development by providing regular news updates.
The app is currently in early stage development and is not yet available on the Play Store. The app is currently in development. The `demoRelease` variant is [available on the Play Store in open beta](https://play.google.com/store/apps/details?id=com.google.samples.apps.nowinandroid).
# Features # Features
**Now in Android** displays content from the **Now in Android** displays content from the
[Now in Android](https://developer.android.com/series/now-in-android) series. Users can browse for [Now in Android](https://developer.android.com/series/now-in-android) series. Users can browse for
links to recent videos, articles and other content. Users can also follow topics they are interested links to recent videos, articles and other content. Users can also follow topics they are interested
in or follow specific authors. in.
## Screenshots ## Screenshots
![Screenshot showing For You screen](docs/images/screenshot-1-foryou.png "Screenshot showing For You screen") ![Screenshot showing For You screen, Interests screen and Topic detail screen](docs/images/screenshots.png "Screenshot showing For You screen, Interests screen and Topic detail screen")
![Screenshot showing Interests screen](docs/images/screenshot-2-interests.png "Screenshot showing Interests screen")
![Screenshot showing Topic detail screen](docs/images/screenshot-3-topicdetail.png "Screenshot showing Topic detail screen")
# Development Environment # Development Environment
@ -110,9 +109,10 @@ Examples:
checking that specific repository methods were called. checking that specific repository methods were called.
# UI # UI
The app was designed using [Material 3 guidelines](https://m3.material.io/). Learn more about the design process and
obtain the design files in the [Now in Android Material 3 Case Study](https://goo.gle/nia-figma) (design assets [also available as a PDF](docs/Now-In-Android-Design-File.pdf)).
UI components are designed according to [Material 3 guidelines](https://m3.material.io/) and built The Screens and UI elements are built entirely using [Jetpack Compose](https://developer.android.com/jetpack/compose).
entirely using [Jetpack Compose](https://developer.android.com/jetpack/compose).
The app has two themes: The app has two themes:

@ -1,3 +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.
*/
import com.google.samples.apps.nowinandroid.FlavorDimension
import com.google.samples.apps.nowinandroid.NiaFlavor
/* /*
* Copyright 2022 The Android Open Source Project * Copyright 2022 The Android Open Source Project
* *
@ -21,10 +39,12 @@ plugins {
android { android {
defaultConfig { defaultConfig {
applicationId = "com.google.samples.apps.niacatalog" applicationId = "com.google.samples.apps.niacatalog"
versionCode = 1
versionName = "0.0.1" // X.Y.Z; X = Major, Y = minor, Z = Patch level
// The UI catalog does not depend on content from the app, however, it depends on modules // The UI catalog does not depend on content from the app, however, it depends on modules
// which do, so we must specify a default value for the contentType dimension. // which do, so we must specify a default value for the contentType dimension.
missingDimensionStrategy("contentType", "demo") missingDimensionStrategy(FlavorDimension.contentType.name, NiaFlavor.demo.name)
} }
packagingOptions { packagingOptions {
@ -33,6 +53,15 @@ android {
} }
} }
namespace = "com.google.samples.apps.niacatalog" namespace = "com.google.samples.apps.niacatalog"
buildTypes {
val release by getting {
// To publish on the Play store a private signing key is required, but to allow anyone
// who clones the code to sign and run the release variant, use the debug signing key.
// TODO: Abstract the signing configuration to a separate file to avoid hardcoding this.
signingConfig = signingConfigs.getByName("debug")
}
}
} }
dependencies { dependencies {

@ -37,16 +37,16 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.google.accompanist.flowlayout.FlowRow import com.google.accompanist.flowlayout.FlowRow
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaDropdownMenuButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaDropdownMenuButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilledButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilterChip import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilterChip
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaIconToggleButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBar import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBar
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBarItem import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBarItem
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaOutlinedButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaOutlinedButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTab 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.NiaTabRow
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTextButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTextButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaToggleButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopicTag import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopicTag
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaViewToggleButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaViewToggleButton
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
@ -77,7 +77,7 @@ fun NiaCatalog() {
item { Text("Buttons", Modifier.padding(top = 16.dp)) } item { Text("Buttons", Modifier.padding(top = 16.dp)) }
item { item {
FlowRow(mainAxisSpacing = 16.dp) { FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(onClick = {}) { NiaButton(onClick = {}) {
Text(text = "Enabled") Text(text = "Enabled")
} }
NiaOutlinedButton(onClick = {}) { NiaOutlinedButton(onClick = {}) {
@ -91,7 +91,7 @@ fun NiaCatalog() {
item { Text("Disabled buttons", Modifier.padding(top = 16.dp)) } item { Text("Disabled buttons", Modifier.padding(top = 16.dp)) }
item { item {
FlowRow(mainAxisSpacing = 16.dp) { FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton( NiaButton(
onClick = {}, onClick = {},
enabled = false enabled = false
) { ) {
@ -114,7 +114,7 @@ fun NiaCatalog() {
item { Text("Buttons with leading icons", Modifier.padding(top = 16.dp)) } item { Text("Buttons with leading icons", Modifier.padding(top = 16.dp)) }
item { item {
FlowRow(mainAxisSpacing = 16.dp) { FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton( NiaButton(
onClick = {}, onClick = {},
text = { Text(text = "Enabled") }, text = { Text(text = "Enabled") },
leadingIcon = { leadingIcon = {
@ -140,7 +140,7 @@ fun NiaCatalog() {
item { Text("Disabled buttons with leading icons", Modifier.padding(top = 16.dp)) } item { Text("Disabled buttons with leading icons", Modifier.padding(top = 16.dp)) }
item { item {
FlowRow(mainAxisSpacing = 16.dp) { FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton( NiaButton(
onClick = {}, onClick = {},
enabled = false, enabled = false,
text = { Text(text = "Disabled") }, text = { Text(text = "Disabled") },
@ -166,251 +166,24 @@ fun NiaCatalog() {
) )
} }
} }
item { Text("Buttons with trailing icons", Modifier.padding(top = 16.dp)) } item { Text("Dropdown menus", Modifier.padding(top = 16.dp)) }
item { item {
FlowRow(mainAxisSpacing = 16.dp) { FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton( NiaDropdownMenuButton(
onClick = {}, text = { Text("Enabled") },
text = { Text(text = "Enabled") }, items = listOf("Item 1", "Item 2", "Item 3"),
trailingIcon = { onItemClick = {},
Icon(imageVector = NiaIcons.Add, contentDescription = null) itemText = { item -> Text(item) }
} )
) NiaDropdownMenuButton(
NiaOutlinedButton( text = { Text("Disabled") },
onClick = {}, items = listOf("Item 1", "Item 2", "Item 3"),
text = { Text(text = "Enabled") }, onItemClick = {},
trailingIcon = { itemText = { item -> Text(item) },
Icon(imageVector = NiaIcons.Add, contentDescription = null) enabled = false
}
)
NiaTextButton(
onClick = {},
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item { Text("Disabled buttons with trailing icons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
enabled = false,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
enabled = false,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item { Text("Small buttons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
small = true
) {
Text(text = "Enabled")
}
NiaOutlinedButton(
onClick = {},
small = true
) {
Text(text = "Enabled")
}
NiaTextButton(
onClick = {},
small = true
) {
Text(text = "Enabled")
}
}
}
item { Text("Disabled small buttons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false,
small = true
) {
Text(text = "Disabled")
}
NiaOutlinedButton(
onClick = {},
enabled = false,
small = true
) {
Text(text = "Disabled")
}
NiaTextButton(
onClick = {},
enabled = false,
small = true
) {
Text(text = "Disabled")
}
}
}
item { Text("Small buttons with leading icons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item {
Text(
"Disabled small buttons with leading icons",
Modifier.padding(top = 16.dp)
)
}
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item { Text("Small buttons with trailing icons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item {
Text(
"Disabled small buttons with trailing icons",
Modifier.padding(top = 16.dp)
)
}
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
) )
} }
} }
item { Text("Dropdown menu", Modifier.padding(top = 16.dp)) }
item {
NiaDropdownMenuButton(
text = { Text("Newest first") },
items = listOf("Item 1", "Item 2", "Item 3"),
onItemClick = {},
itemText = { item -> Text(item) }
)
}
item { Text("Chips", Modifier.padding(top = 16.dp)) } item { Text("Chips", Modifier.padding(top = 16.dp)) }
item { item {
FlowRow(mainAxisSpacing = 16.dp) { FlowRow(mainAxisSpacing = 16.dp) {
@ -418,28 +191,33 @@ fun NiaCatalog() {
NiaFilterChip( NiaFilterChip(
selected = firstChecked, selected = firstChecked,
onSelectedChange = { checked -> firstChecked = checked }, onSelectedChange = { checked -> firstChecked = checked },
label = { Text(text = "Enabled".uppercase()) } label = { Text(text = "Enabled") }
) )
var secondChecked by remember { mutableStateOf(true) } var secondChecked by remember { mutableStateOf(true) }
NiaFilterChip( NiaFilterChip(
selected = secondChecked, selected = secondChecked,
onSelectedChange = { checked -> secondChecked = checked }, onSelectedChange = { checked -> secondChecked = checked },
label = { Text(text = "Enabled".uppercase()) } label = { Text(text = "Enabled") }
) )
var thirdChecked by remember { mutableStateOf(true) }
NiaFilterChip( NiaFilterChip(
selected = thirdChecked, selected = false,
onSelectedChange = { checked -> thirdChecked = checked }, onSelectedChange = {},
enabled = false, enabled = false,
label = { Text(text = "Disabled".uppercase()) } label = { Text(text = "Disabled") }
)
NiaFilterChip(
selected = true,
onSelectedChange = {},
enabled = false,
label = { Text(text = "Disabled") }
) )
} }
} }
item { Text("Toggle buttons", Modifier.padding(top = 16.dp)) } item { Text("Icon buttons", Modifier.padding(top = 16.dp)) }
item { item {
FlowRow(mainAxisSpacing = 16.dp) { FlowRow(mainAxisSpacing = 16.dp) {
var firstChecked by remember { mutableStateOf(false) } var firstChecked by remember { mutableStateOf(false) }
NiaToggleButton( NiaIconToggleButton(
checked = firstChecked, checked = firstChecked,
onCheckedChange = { checked -> firstChecked = checked }, onCheckedChange = { checked -> firstChecked = checked },
icon = { icon = {
@ -456,7 +234,7 @@ fun NiaCatalog() {
} }
) )
var secondChecked by remember { mutableStateOf(true) } var secondChecked by remember { mutableStateOf(true) }
NiaToggleButton( NiaIconToggleButton(
checked = secondChecked, checked = secondChecked,
onCheckedChange = { checked -> secondChecked = checked }, onCheckedChange = { checked -> secondChecked = checked },
icon = { icon = {
@ -472,27 +250,39 @@ fun NiaCatalog() {
) )
} }
) )
var thirdChecked by remember { mutableStateOf(false) } NiaIconToggleButton(
NiaToggleButton( checked = false,
checked = thirdChecked, onCheckedChange = {},
onCheckedChange = { checked -> thirdChecked = checked },
icon = { icon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null) Icon(
painter = painterResource(id = NiaIcons.BookmarkBorder),
contentDescription = null
)
}, },
checkedIcon = { checkedIcon = {
Icon(imageVector = NiaIcons.Check, contentDescription = null) Icon(
} painter = painterResource(id = NiaIcons.Bookmark),
contentDescription = null
)
},
enabled = false
) )
var fourthChecked by remember { mutableStateOf(true) } NiaIconToggleButton(
NiaToggleButton( checked = true,
checked = fourthChecked, onCheckedChange = {},
onCheckedChange = { checked -> fourthChecked = checked },
icon = { icon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null) Icon(
painter = painterResource(id = NiaIcons.BookmarkBorder),
contentDescription = null
)
}, },
checkedIcon = { checkedIcon = {
Icon(imageVector = NiaIcons.Check, contentDescription = null) Icon(
} painter = painterResource(id = NiaIcons.Bookmark),
contentDescription = null
)
},
enabled = false
) )
} }
} }
@ -513,6 +303,13 @@ fun NiaCatalog() {
compactText = { Text(text = "Compact view") }, compactText = { Text(text = "Compact view") },
expandedText = { Text(text = "Expanded view") } expandedText = { Text(text = "Expanded view") }
) )
NiaViewToggleButton(
expanded = false,
onExpandedChange = {},
compactText = { Text(text = "Disabled") },
expandedText = { Text(text = "Disabled") },
enabled = false
)
} }
} }
item { Text("Tags", Modifier.padding(top = 16.dp)) } item { Text("Tags", Modifier.padding(top = 16.dp)) }
@ -524,7 +321,7 @@ fun NiaCatalog() {
NiaTopicTag( NiaTopicTag(
expanded = expandedTopicId == "Topic 1", expanded = expandedTopicId == "Topic 1",
followed = firstFollowed, followed = firstFollowed,
onDropMenuToggle = { show -> onDropdownMenuToggle = { show ->
expandedTopicId = if (show) "Topic 1" else null expandedTopicId = if (show) "Topic 1" else null
}, },
onFollowClick = { firstFollowed = true }, onFollowClick = { firstFollowed = true },
@ -539,7 +336,7 @@ fun NiaCatalog() {
NiaTopicTag( NiaTopicTag(
expanded = expandedTopicId == "Topic 2", expanded = expandedTopicId == "Topic 2",
followed = secondFollowed, followed = secondFollowed,
onDropMenuToggle = { show -> onDropdownMenuToggle = { show ->
expandedTopicId = if (show) "Topic 2" else null expandedTopicId = if (show) "Topic 2" else null
}, },
onFollowClick = { secondFollowed = true }, onFollowClick = { secondFollowed = true },
@ -550,6 +347,16 @@ fun NiaCatalog() {
unFollowText = { Text(text = "Unfollow") }, unFollowText = { Text(text = "Unfollow") },
browseText = { Text(text = "Browse topic") } browseText = { Text(text = "Browse topic") }
) )
NiaTopicTag(
expanded = false,
followed = false,
onDropdownMenuToggle = {},
onFollowClick = {},
onUnfollowClick = {},
onBrowseClick = {},
text = { Text(text = "Disabled".uppercase()) },
enabled = false
)
} }
} }
item { Text("Tabs", Modifier.padding(top = 16.dp)) } item { Text("Tabs", Modifier.padding(top = 16.dp)) }

@ -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.

@ -1,5 +1,5 @@
/* /*
* Copyright 2021 The Android Open Source Project * Copyright 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import com.google.samples.apps.nowinandroid.NiaBuildType
plugins { plugins {
id("nowinandroid.android.application") id("nowinandroid.android.application")
@ -26,8 +27,8 @@ plugins {
android { android {
defaultConfig { defaultConfig {
applicationId = "com.google.samples.apps.nowinandroid" applicationId = "com.google.samples.apps.nowinandroid"
versionCode = 1 versionCode = 3
versionName = "0.0.1" // X.Y.Z; X = Major, Y = minor, Z = Patch level versionName = "0.0.3" // X.Y.Z; X = Major, Y = minor, Z = Patch level
// Custom test runner to set up Hilt dependency graph // Custom test runner to set up Hilt dependency graph
testInstrumentationRunner = "com.google.samples.apps.nowinandroid.core.testing.NiaTestRunner" testInstrumentationRunner = "com.google.samples.apps.nowinandroid.core.testing.NiaTestRunner"
@ -38,10 +39,11 @@ android {
buildTypes { buildTypes {
val debug by getting { val debug by getting {
applicationIdSuffix = ".debug" applicationIdSuffix = NiaBuildType.DEBUG.applicationIdSuffix
} }
val release by getting { val release by getting {
isMinifyEnabled = true isMinifyEnabled = true
applicationIdSuffix = NiaBuildType.RELEASE.applicationIdSuffix
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
// To publish on the Play store a private signing key is required, but to allow anyone // To publish on the Play store a private signing key is required, but to allow anyone
@ -57,9 +59,8 @@ android {
signingConfig = signingConfigs.getByName("debug") signingConfig = signingConfigs.getByName("debug")
// Only use benchmark proguard rules // Only use benchmark proguard rules
proguardFiles("benchmark-rules.pro") proguardFiles("benchmark-rules.pro")
// FIXME enabling minification breaks access to demo backend. isMinifyEnabled = true
isMinifyEnabled = false applicationIdSuffix = NiaBuildType.BENCHMARK.applicationIdSuffix
applicationIdSuffix = ".benchmark"
} }
} }
@ -77,33 +78,41 @@ android {
} }
dependencies { dependencies {
implementation(project(":feature:author"))
implementation(project(":feature:interests")) implementation(project(":feature:interests"))
implementation(project(":feature:foryou")) implementation(project(":feature:foryou"))
implementation(project(":feature:bookmarks")) implementation(project(":feature:bookmarks"))
implementation(project(":feature:topic")) implementation(project(":feature:topic"))
implementation(project(":feature:settings"))
implementation(project(":core:common"))
implementation(project(":core:ui")) implementation(project(":core:ui"))
implementation(project(":core:designsystem")) implementation(project(":core:designsystem"))
implementation(project(":core:navigation")) implementation(project(":core:data"))
implementation(project(":core:model"))
implementation(project(":sync:work")) implementation(project(":sync:work"))
implementation(project(":sync:sync-test"))
androidTestImplementation(project(":core:testing")) androidTestImplementation(project(":core:testing"))
androidTestImplementation(project(":core:datastore-test")) androidTestImplementation(project(":core:datastore-test"))
androidTestImplementation(project(":core:data-test")) androidTestImplementation(project(":core:data-test"))
androidTestImplementation(project(":core:network")) androidTestImplementation(project(":core:network"))
androidTestImplementation(libs.androidx.navigation.testing) androidTestImplementation(libs.androidx.navigation.testing)
androidTestImplementation(libs.accompanist.testharness)
androidTestImplementation(kotlin("test"))
debugImplementation(libs.androidx.compose.ui.testManifest) debugImplementation(libs.androidx.compose.ui.testManifest)
debugImplementation(project(":ui-test-hilt-manifest"))
implementation(libs.accompanist.systemuicontroller)
implementation(libs.androidx.activity.compose) implementation(libs.androidx.activity.compose)
implementation(libs.androidx.appcompat) implementation(libs.androidx.appcompat)
implementation(libs.androidx.core.ktx) implementation(libs.androidx.core.ktx)
implementation(libs.androidx.core.splashscreen) implementation(libs.androidx.core.splashscreen)
implementation(libs.androidx.compose.runtime) implementation(libs.androidx.compose.runtime)
implementation(libs.androidx.lifecycle.runtimeCompose)
implementation(libs.androidx.compose.runtime.tracing) implementation(libs.androidx.compose.runtime.tracing)
implementation(libs.androidx.compose.material3.windowSizeClass) implementation(libs.androidx.compose.material3.windowSizeClass)
implementation(libs.androidx.hilt.navigation.compose)
implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.window.manager) implementation(libs.androidx.window.manager)
implementation(libs.androidx.profileinstaller) implementation(libs.androidx.profileinstaller)

@ -16,17 +16,23 @@
package com.google.samples.apps.nowinandroid.ui package com.google.samples.apps.nowinandroid.ui
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.assertIsOn import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.assertIsSelected import androidx.compose.ui.test.assertIsSelected
import androidx.compose.ui.test.junit4.createAndroidComposeRule 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.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performClick
import androidx.test.espresso.Espresso import androidx.test.espresso.Espresso
import androidx.test.espresso.NoActivityResumedException import androidx.test.espresso.NoActivityResumedException
import com.google.samples.apps.nowinandroid.MainActivity 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.foryou.R as FeatureForyouR
import com.google.samples.apps.nowinandroid.feature.interests.R as FeatureInterestsR 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.BindValue
import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest import dagger.hilt.android.testing.HiltAndroidTest
@ -67,6 +73,11 @@ class NavigationTest {
private lateinit var forYou: String private lateinit var forYou: String
private lateinit var interests: String private lateinit var interests: String
private lateinit var sampleTopic: String private lateinit var sampleTopic: String
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 @Before
fun setup() { fun setup() {
@ -77,6 +88,11 @@ class NavigationTest {
forYou = getString(FeatureForyouR.string.for_you) forYou = getString(FeatureForyouR.string.for_you)
interests = getString(FeatureInterestsR.string.interests) interests = getString(FeatureInterestsR.string.interests)
sampleTopic = "Headlines" sampleTopic = "Headlines"
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)
} }
} }
@ -146,6 +162,62 @@ 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 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()
onAllNodesWithText(saved).assertCountEquals(2)
// As above but for the interests tab.
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()
}
}
@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.
onAllNodesWithText(saved).onLast().assertIsSelected()
}
}
/* /*
* There should always be at most one instance of a top-level destination at the same time. * There should always be at most one instance of a top-level destination at the same time.
*/ */
@ -183,7 +255,8 @@ class NavigationTest {
fun navigationBar_multipleBackStackInterests() { fun navigationBar_multipleBackStackInterests() {
composeTestRule.apply { composeTestRule.apply {
onNodeWithText(interests).performClick() onNodeWithText(interests).performClick()
onNodeWithText("Android Studio").performClick() // TODO: Grab string from fake data // TODO: Grab string from fake data
onNodeWithText("Android Studio & Tools").performClick()
// Switch tab // Switch tab
onNodeWithText(forYou).performClick() onNodeWithText(forYou).performClick()

@ -0,0 +1,243 @@
/*
* 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.ui
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import com.google.accompanist.testharness.TestHarness
import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor
import com.google.samples.apps.nowinandroid.uitesthiltmanifest.HiltComponentActivity
import dagger.hilt.android.testing.BindValue
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import javax.inject.Inject
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
/**
* Tests that the navigation UI is rendered correctly on different screen sizes.
*/
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@HiltAndroidTest
class NavigationUiTest {
/**
* Manages the components' state and is used to perform injection on your test
*/
@get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)
/**
* Create a temporary folder used to create a Data Store file. This guarantees that
* the file is removed in between each test, preventing a crash.
*/
@BindValue @get:Rule(order = 1)
val tmpFolder: TemporaryFolder = TemporaryFolder.builder().assureDeletion().build()
/**
* Use a test activity to set the content on.
*/
@get:Rule(order = 2)
val composeTestRule = createAndroidComposeRule<HiltComponentActivity>()
@Inject
lateinit var networkMonitor: NetworkMonitor
@Before
fun setup() {
hiltRule.inject()
}
@Test
fun compactWidth_compactHeight_showsNavigationBar() {
composeTestRule.setContent {
TestHarness(size = DpSize(400.dp, 400.dp)) {
BoxWithConstraints {
NiaApp(
windowSizeClass = WindowSizeClass.calculateFromSize(
DpSize(maxWidth, maxHeight)
),
networkMonitor = networkMonitor
)
}
}
}
composeTestRule.onNodeWithTag("NiaBottomBar").assertIsDisplayed()
composeTestRule.onNodeWithTag("NiaNavRail").assertDoesNotExist()
}
@Test
fun mediumWidth_compactHeight_showsNavigationBar() {
composeTestRule.setContent {
TestHarness(size = DpSize(610.dp, 400.dp)) {
BoxWithConstraints {
NiaApp(
windowSizeClass = WindowSizeClass.calculateFromSize(
DpSize(maxWidth, maxHeight)
),
networkMonitor = networkMonitor
)
}
}
}
composeTestRule.onNodeWithTag("NiaBottomBar").assertIsDisplayed()
composeTestRule.onNodeWithTag("NiaNavRail").assertDoesNotExist()
}
@Test
fun expandedWidth_compactHeight_showsNavigationBar() {
composeTestRule.setContent {
TestHarness(size = DpSize(900.dp, 400.dp)) {
BoxWithConstraints {
NiaApp(
windowSizeClass = WindowSizeClass.calculateFromSize(
DpSize(maxWidth, maxHeight)
),
networkMonitor = networkMonitor
)
}
}
}
composeTestRule.onNodeWithTag("NiaBottomBar").assertIsDisplayed()
composeTestRule.onNodeWithTag("NiaNavRail").assertDoesNotExist()
}
@Test
fun compcatWidth_mediumHeight_showsNavigationBar() {
composeTestRule.setContent {
TestHarness(size = DpSize(400.dp, 500.dp)) {
BoxWithConstraints {
NiaApp(
windowSizeClass = WindowSizeClass.calculateFromSize(
DpSize(maxWidth, maxHeight)
),
networkMonitor = networkMonitor
)
}
}
}
composeTestRule.onNodeWithTag("NiaBottomBar").assertIsDisplayed()
composeTestRule.onNodeWithTag("NiaNavRail").assertDoesNotExist()
}
@Test
fun mediumWidth_mediumHeight_showsNavigationRail() {
composeTestRule.setContent {
TestHarness(size = DpSize(610.dp, 500.dp)) {
BoxWithConstraints {
NiaApp(
windowSizeClass = WindowSizeClass.calculateFromSize(
DpSize(maxWidth, maxHeight)
),
networkMonitor = networkMonitor
)
}
}
}
composeTestRule.onNodeWithTag("NiaNavRail").assertIsDisplayed()
composeTestRule.onNodeWithTag("NiaBottomBar").assertDoesNotExist()
}
@Test
fun expandedWidth_mediumHeight_showsNavigationRail() {
composeTestRule.setContent {
TestHarness(size = DpSize(900.dp, 500.dp)) {
BoxWithConstraints {
NiaApp(
windowSizeClass = WindowSizeClass.calculateFromSize(
DpSize(maxWidth, maxHeight)
),
networkMonitor = networkMonitor
)
}
}
}
composeTestRule.onNodeWithTag("NiaNavRail").assertIsDisplayed()
composeTestRule.onNodeWithTag("NiaBottomBar").assertDoesNotExist()
}
@Test
fun compactWidth_expandedHeight_showsNavigationBar() {
composeTestRule.setContent {
TestHarness(size = DpSize(400.dp, 1000.dp)) {
BoxWithConstraints {
NiaApp(
windowSizeClass = WindowSizeClass.calculateFromSize(
DpSize(maxWidth, maxHeight)
),
networkMonitor = networkMonitor
)
}
}
}
composeTestRule.onNodeWithTag("NiaBottomBar").assertIsDisplayed()
composeTestRule.onNodeWithTag("NiaNavRail").assertDoesNotExist()
}
@Test
fun mediumWidth_expandedHeight_showsNavigationRail() {
composeTestRule.setContent {
TestHarness(size = DpSize(610.dp, 1000.dp)) {
BoxWithConstraints {
NiaApp(
windowSizeClass = WindowSizeClass.calculateFromSize(
DpSize(maxWidth, maxHeight)
),
networkMonitor = networkMonitor
)
}
}
}
composeTestRule.onNodeWithTag("NiaNavRail").assertIsDisplayed()
composeTestRule.onNodeWithTag("NiaBottomBar").assertDoesNotExist()
}
@Test
fun expandedWidth_expandedHeight_showsNavigationRail() {
composeTestRule.setContent {
TestHarness(size = DpSize(900.dp, 1000.dp)) {
BoxWithConstraints {
NiaApp(
windowSizeClass = WindowSizeClass.calculateFromSize(
DpSize(maxWidth, maxHeight)
),
networkMonitor = networkMonitor
)
}
}
}
composeTestRule.onNodeWithTag("NiaNavRail").assertIsDisplayed()
composeTestRule.onNodeWithTag("NiaBottomBar").assertDoesNotExist()
}
}

@ -30,9 +30,14 @@ import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import androidx.navigation.createGraph import androidx.navigation.createGraph
import androidx.navigation.testing.TestNavHostController import androidx.navigation.testing.TestNavHostController
import org.junit.Assert.assertEquals import com.google.samples.apps.nowinandroid.core.testing.util.TestNetworkMonitor
import org.junit.Assert.assertFalse import kotlin.test.assertEquals
import org.junit.Assert.assertTrue import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
@ -48,10 +53,14 @@ class NiaAppStateTest {
@get:Rule @get:Rule
val composeTestRule = createComposeRule() val composeTestRule = createComposeRule()
// Create the test dependencies.
private val networkMonitor = TestNetworkMonitor()
// Subject under test.
private lateinit var state: NiaAppState private lateinit var state: NiaAppState
@Test @Test
fun niaAppState_currentDestination() { fun niaAppState_currentDestination() = runTest {
var currentDestination: String? = null var currentDestination: String? = null
composeTestRule.setContent { composeTestRule.setContent {
@ -59,7 +68,9 @@ class NiaAppStateTest {
state = remember(navController) { state = remember(navController) {
NiaAppState( NiaAppState(
windowSizeClass = getCompactWindowClass(), windowSizeClass = getCompactWindowClass(),
navController = navController navController = navController,
networkMonitor = networkMonitor,
coroutineScope = backgroundScope
) )
} }
@ -76,23 +87,28 @@ class NiaAppStateTest {
} }
@Test @Test
fun niaAppState_destinations() { fun niaAppState_destinations() = runTest {
composeTestRule.setContent { composeTestRule.setContent {
state = rememberNiaAppState(getCompactWindowClass()) state = rememberNiaAppState(
windowSizeClass = getCompactWindowClass(),
networkMonitor = networkMonitor
)
} }
assertEquals(3, state.topLevelDestinations.size) assertEquals(3, state.topLevelDestinations.size)
assertTrue(state.topLevelDestinations[0].destination.contains("for_you")) assertTrue(state.topLevelDestinations[0].name.contains("for_you", true))
assertTrue(state.topLevelDestinations[1].destination.contains("bookmarks")) assertTrue(state.topLevelDestinations[1].name.contains("bookmarks", true))
assertTrue(state.topLevelDestinations[2].destination.contains("interests")) assertTrue(state.topLevelDestinations[2].name.contains("interests", true))
} }
@Test @Test
fun niaAppState_showBottomBar_compact() { fun niaAppState_showBottomBar_compact() = runTest {
composeTestRule.setContent { composeTestRule.setContent {
state = NiaAppState( state = NiaAppState(
windowSizeClass = getCompactWindowClass(), windowSizeClass = getCompactWindowClass(),
navController = NavHostController(LocalContext.current) navController = NavHostController(LocalContext.current),
networkMonitor = networkMonitor,
coroutineScope = backgroundScope
) )
} }
@ -101,11 +117,13 @@ class NiaAppStateTest {
} }
@Test @Test
fun niaAppState_showNavRail_medium() { fun niaAppState_showNavRail_medium() = runTest {
composeTestRule.setContent { composeTestRule.setContent {
state = NiaAppState( state = NiaAppState(
windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(800.dp, 800.dp)), windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(800.dp, 800.dp)),
navController = NavHostController(LocalContext.current) navController = NavHostController(LocalContext.current),
networkMonitor = networkMonitor,
coroutineScope = backgroundScope
) )
} }
@ -114,11 +132,14 @@ class NiaAppStateTest {
} }
@Test @Test
fun niaAppState_showNavRail_large() { fun niaAppState_showNavRail_large() = runTest {
composeTestRule.setContent { composeTestRule.setContent {
state = NiaAppState( state = NiaAppState(
windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(900.dp, 1200.dp)), windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(900.dp, 1200.dp)),
navController = NavHostController(LocalContext.current) navController = NavHostController(LocalContext.current),
networkMonitor = networkMonitor,
coroutineScope = backgroundScope
) )
} }
@ -126,6 +147,26 @@ class NiaAppStateTest {
assertFalse(state.shouldShowBottomBar) assertFalse(state.shouldShowBottomBar)
} }
@Test
fun stateIsOfflineWhenNetworkMonitorIsOffline() = runTest(UnconfinedTestDispatcher()) {
composeTestRule.setContent {
state = NiaAppState(
windowSizeClass = WindowSizeClass.calculateFromSize(DpSize(900.dp, 1200.dp)),
navController = NavHostController(LocalContext.current),
networkMonitor = networkMonitor,
coroutineScope = backgroundScope
)
}
backgroundScope.launch { state.isOffline.collect() }
networkMonitor.setConnected(false)
assertEquals(
true,
state.isOffline.value
)
}
private fun getCompactWindowClass() = WindowSizeClass.calculateFromSize(DpSize(500.dp, 300.dp)) private fun getCompactWindowClass() = WindowSizeClass.calculateFromSize(DpSize(500.dp, 300.dp))
} }

@ -22,6 +22,7 @@
<application <application
android:name=".NiaApplication" android:name=".NiaApplication"
android:allowBackup="true" android:allowBackup="true"
android:enableOnBackInvokedCallback="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:dataExtractionRules="@xml/backup_rules_12" android:dataExtractionRules="@xml/backup_rules_12"
@ -33,8 +34,7 @@
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true">
android:label="@string/app_name">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />

File diff suppressed because it is too large Load Diff

@ -19,14 +19,34 @@ package com.google.samples.apps.nowinandroid
import android.os.Bundle import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent 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.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass 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.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.metrics.performance.JankStats 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
import com.google.samples.apps.nowinandroid.ui.NiaApp import com.google.samples.apps.nowinandroid.ui.NiaApp
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class) @OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@AndroidEntryPoint @AndroidEntryPoint
@ -38,16 +58,61 @@ class MainActivity : ComponentActivity() {
@Inject @Inject
lateinit var lazyStats: dagger.Lazy<JankStats> lateinit var lazyStats: dagger.Lazy<JankStats>
@Inject
lateinit var networkMonitor: NetworkMonitor
val viewModel: MainActivityViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen() val splashScreen = installSplashScreen()
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
var uiState: MainActivityUiState by mutableStateOf(Loading)
// Update the uiState
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState
.onEach {
uiState = it
}
.collect()
}
}
// 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
is Success -> false
}
}
// Turn off the decor fitting system windows, which allows us to handle insets, // Turn off the decor fitting system windows, which allows us to handle insets,
// including IME animations // including IME animations
WindowCompat.setDecorFitsSystemWindows(window, false) WindowCompat.setDecorFitsSystemWindows(window, false)
setContent { setContent {
NiaApp(calculateWindowSizeClass(this)) val systemUiController = rememberSystemUiController()
val darkTheme = shouldUseDarkTheme(uiState)
// Update the dark content of the system bars to match the theme
DisposableEffect(systemUiController, darkTheme) {
systemUiController.systemBarsDarkContentEnabled = !darkTheme
onDispose {}
}
NiaTheme(
darkTheme = darkTheme,
androidTheme = shouldUseAndroidTheme(uiState)
) {
NiaApp(
networkMonitor = networkMonitor,
windowSizeClass = calculateWindowSizeClass(this),
)
}
} }
} }
@ -61,3 +126,33 @@ class MainActivity : ComponentActivity() {
lazyStats.get().isTrackingEnabled = false lazyStats.get().isTrackingEnabled = false
} }
} }
/**
* Returns `true` if the Android theme should be used, as a function of the [uiState].
*/
@Composable
private fun shouldUseAndroidTheme(
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 [uiState] and the
* current system context.
*/
@Composable
private fun shouldUseDarkTheme(
uiState: MainActivityUiState,
): Boolean = when (uiState) {
Loading -> isSystemInDarkTheme()
is Success -> when (uiState.userData.darkThemeConfig) {
DarkThemeConfig.FOLLOW_SYSTEM -> isSystemInDarkTheme()
DarkThemeConfig.LIGHT -> false
DarkThemeConfig.DARK -> true
}
}

@ -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<MainActivityUiState> = userDataRepository.userData.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
}

@ -20,15 +20,12 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost import androidx.navigation.compose.NavHost
import com.google.samples.apps.nowinandroid.core.navigation.NiaNavigationDestination import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.bookmarksScreen
import com.google.samples.apps.nowinandroid.feature.author.navigation.AuthorDestination import com.google.samples.apps.nowinandroid.feature.foryou.navigation.forYouNavigationRoute
import com.google.samples.apps.nowinandroid.feature.author.navigation.authorGraph import com.google.samples.apps.nowinandroid.feature.foryou.navigation.forYouScreen
import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.bookmarksGraph
import com.google.samples.apps.nowinandroid.feature.foryou.navigation.ForYouDestination
import com.google.samples.apps.nowinandroid.feature.foryou.navigation.forYouGraph
import com.google.samples.apps.nowinandroid.feature.interests.navigation.interestsGraph import com.google.samples.apps.nowinandroid.feature.interests.navigation.interestsGraph
import com.google.samples.apps.nowinandroid.feature.topic.navigation.TopicDestination import com.google.samples.apps.nowinandroid.feature.topic.navigation.navigateToTopic
import com.google.samples.apps.nowinandroid.feature.topic.navigation.topicGraph import com.google.samples.apps.nowinandroid.feature.topic.navigation.topicScreen
/** /**
* Top-level navigation graph. Navigation is organized as explained at * Top-level navigation graph. Navigation is organized as explained at
@ -40,32 +37,23 @@ import com.google.samples.apps.nowinandroid.feature.topic.navigation.topicGraph
@Composable @Composable
fun NiaNavHost( fun NiaNavHost(
navController: NavHostController, navController: NavHostController,
onNavigateToDestination: (NiaNavigationDestination, String) -> Unit,
onBackClick: () -> Unit, onBackClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
startDestination: String = ForYouDestination.route startDestination: String = forYouNavigationRoute
) { ) {
NavHost( NavHost(
navController = navController, navController = navController,
startDestination = startDestination, startDestination = startDestination,
modifier = modifier, modifier = modifier,
) { ) {
forYouGraph() forYouScreen()
bookmarksGraph() bookmarksScreen()
interestsGraph( interestsGraph(
navigateToTopic = { navigateToTopic = { topicId ->
onNavigateToDestination( navController.navigateToTopic(topicId)
TopicDestination, TopicDestination.createNavigationRoute(it)
)
},
navigateToAuthor = {
onNavigateToDestination(
AuthorDestination, AuthorDestination.createNavigationRoute(it)
)
}, },
nestedGraphs = { nestedGraphs = {
topicGraph(onBackClick) topicScreen(onBackClick)
authorGraph(onBackClick)
} }
) )
} }

@ -16,18 +16,42 @@
package com.google.samples.apps.nowinandroid.navigation 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
import com.google.samples.apps.nowinandroid.core.navigation.NiaNavigationDestination 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.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
/** /**
* Type for the top level destinations in the application. Each of these destinations * Type for the top level destinations in the application. Each of these destinations
* can contain one or more screens (based on the window size). Navigation from one screen to the * can contain one or more screens (based on the window size). Navigation from one screen to the
* next within a single destination will be handled directly in composables. * next within a single destination will be handled directly in composables.
*/ */
data class TopLevelDestination( enum class TopLevelDestination(
override val route: String,
override val destination: String,
val selectedIcon: Icon, val selectedIcon: Icon,
val unselectedIcon: Icon, val unselectedIcon: Icon,
val iconTextId: Int val iconTextId: Int,
) : NiaNavigationDestination val titleTextId: Int
) {
FOR_YOU(
selectedIcon = DrawableResourceIcon(NiaIcons.Upcoming),
unselectedIcon = DrawableResourceIcon(NiaIcons.UpcomingBorder),
iconTextId = forYouR.string.for_you,
titleTextId = R.string.app_name
),
BOOKMARKS(
selectedIcon = DrawableResourceIcon(NiaIcons.Bookmarks),
unselectedIcon = DrawableResourceIcon(NiaIcons.BookmarksBorder),
iconTextId = bookmarksR.string.saved,
titleTextId = bookmarksR.string.saved
),
INTERESTS(
selectedIcon = ImageVectorIcon(NiaIcons.Grid3x3),
unselectedIcon = ImageVectorIcon(NiaIcons.Grid3x3),
iconTextId = interestsR.string.interests,
titleTextId = interestsR.string.interests
)
}

@ -16,6 +16,7 @@
package com.google.samples.apps.nowinandroid.ui package com.google.samples.apps.nowinandroid.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsets
@ -31,49 +32,92 @@ import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold 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.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.runtime.Composable 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.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavDestination import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy 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.NiaBackground
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaGradientBackground import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaGradientBackground
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBar import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBar
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBarItem 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.NiaNavigationRail
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationRailItem 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.DrawableResourceIcon
import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.ImageVectorIcon 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.core.designsystem.icon.NiaIcons
import com.google.samples.apps.nowinandroid.feature.foryou.navigation.ForYouDestination import com.google.samples.apps.nowinandroid.core.designsystem.theme.GradientColors
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LocalGradientColors
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.NiaNavHost
import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination
@OptIn( @OptIn(
ExperimentalMaterial3Api::class, ExperimentalMaterial3Api::class,
ExperimentalLayoutApi::class, ExperimentalLayoutApi::class,
ExperimentalComposeUiApi::class ExperimentalComposeUiApi::class,
ExperimentalLifecycleComposeApi::class
) )
@Composable @Composable
fun NiaApp( fun NiaApp(
windowSizeClass: WindowSizeClass, windowSizeClass: WindowSizeClass,
appState: NiaAppState = rememberNiaAppState(windowSizeClass) networkMonitor: NetworkMonitor,
appState: NiaAppState = rememberNiaAppState(
networkMonitor = networkMonitor,
windowSizeClass = windowSizeClass
),
) { ) {
NiaTheme { val shouldShowGradientBackground =
val background: @Composable (@Composable () -> Unit) -> Unit = appState.currentTopLevelDestination == TopLevelDestination.FOR_YOU
when (appState.currentDestination?.route) {
ForYouDestination.route -> { content -> NiaGradientBackground(content = content) } NiaBackground {
else -> { content -> NiaBackground(content = content) } NiaGradientBackground(
gradientColors = if (shouldShowGradientBackground) {
LocalGradientColors.current
} else {
GradientColors()
},
) {
val snackbarHostState = remember { SnackbarHostState() }
val isOffline by appState.isOffline.collectAsStateWithLifecycle()
// If user is not connected to the internet show a snack bar to inform them.
val notConnectedMessage = stringResource(R.string.not_connected)
LaunchedEffect(isOffline) {
if (isOffline) snackbarHostState.showSnackbar(
message = notConnectedMessage,
duration = Indefinite
)
}
if (appState.shouldShowSettingsDialog) {
SettingsDialog(
onDismiss = { appState.setShowSettingsDialog(false) }
)
} }
background {
Scaffold( Scaffold(
modifier = Modifier.semantics { modifier = Modifier.semantics {
testTagsAsResourceId = true testTagsAsResourceId = true
@ -81,12 +125,14 @@ fun NiaApp(
containerColor = Color.Transparent, containerColor = Color.Transparent,
contentColor = MaterialTheme.colorScheme.onBackground, contentColor = MaterialTheme.colorScheme.onBackground,
contentWindowInsets = WindowInsets(0, 0, 0, 0), contentWindowInsets = WindowInsets(0, 0, 0, 0),
snackbarHost = { SnackbarHost(snackbarHostState) },
bottomBar = { bottomBar = {
if (appState.shouldShowBottomBar) { if (appState.shouldShowBottomBar) {
NiaBottomBar( NiaBottomBar(
destinations = appState.topLevelDestinations, destinations = appState.topLevelDestinations,
onNavigateToDestination = appState::navigate, onNavigateToDestination = appState::navigateToTopLevelDestination,
currentDestination = appState.currentDestination currentDestination = appState.currentDestination,
modifier = Modifier.testTag("NiaBottomBar")
) )
} }
} }
@ -94,6 +140,8 @@ fun NiaApp(
Row( Row(
Modifier Modifier
.fillMaxSize() .fillMaxSize()
.padding(padding)
.consumedWindowInsets(padding)
.windowInsetsPadding( .windowInsetsPadding(
WindowInsets.safeDrawing.only( WindowInsets.safeDrawing.only(
WindowInsetsSides.Horizontal WindowInsetsSides.Horizontal
@ -103,20 +151,39 @@ fun NiaApp(
if (appState.shouldShowNavRail) { if (appState.shouldShowNavRail) {
NiaNavRail( NiaNavRail(
destinations = appState.topLevelDestinations, destinations = appState.topLevelDestinations,
onNavigateToDestination = appState::navigate, onNavigateToDestination = appState::navigateToTopLevelDestination,
currentDestination = appState.currentDestination, currentDestination = appState.currentDestination,
modifier = Modifier.safeDrawingPadding() modifier = Modifier
.testTag("NiaNavRail")
.safeDrawingPadding()
)
}
Column(Modifier.fillMaxSize()) {
// Show the top app bar on top level destinations.
val destination = appState.currentTopLevelDestination
if (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 = { appState.setShowSettingsDialog(true) }
)
}
NiaNavHost(
navController = appState.navController,
onBackClick = appState::onBackClick
) )
} }
NiaNavHost( // TODO: We may want to add padding or spacer when the snackbar is shown so that
navController = appState.navController, // content doesn't display behind it.
onBackClick = appState::onBackClick,
onNavigateToDestination = appState::navigate,
modifier = Modifier
.padding(padding)
.consumedWindowInsets(padding)
)
} }
} }
} }
@ -132,8 +199,7 @@ private fun NiaNavRail(
) { ) {
NiaNavigationRail(modifier = modifier) { NiaNavigationRail(modifier = modifier) {
destinations.forEach { destination -> destinations.forEach { destination ->
val selected = val selected = currentDestination.isTopLevelDestinationInHierarchy(destination)
currentDestination?.hierarchy?.any { it.route == destination.route } == true
NiaNavigationRailItem( NiaNavigationRailItem(
selected = selected, selected = selected,
onClick = { onNavigateToDestination(destination) }, onClick = { onNavigateToDestination(destination) },
@ -164,12 +230,14 @@ private fun NiaNavRail(
private fun NiaBottomBar( private fun NiaBottomBar(
destinations: List<TopLevelDestination>, destinations: List<TopLevelDestination>,
onNavigateToDestination: (TopLevelDestination) -> Unit, onNavigateToDestination: (TopLevelDestination) -> Unit,
currentDestination: NavDestination? currentDestination: NavDestination?,
modifier: Modifier = Modifier
) { ) {
NiaNavigationBar { NiaNavigationBar(
modifier = modifier
) {
destinations.forEach { destination -> destinations.forEach { destination ->
val selected = val selected = currentDestination.isTopLevelDestinationInHierarchy(destination)
currentDestination?.hierarchy?.any { it.route == destination.route } == true
NiaNavigationBarItem( NiaNavigationBarItem(
selected = selected, selected = selected,
onClick = { onNavigateToDestination(destination) }, onClick = { onNavigateToDestination(destination) },
@ -184,6 +252,7 @@ private fun NiaBottomBar(
imageVector = icon.imageVector, imageVector = icon.imageVector,
contentDescription = null contentDescription = null
) )
is DrawableResourceIcon -> Icon( is DrawableResourceIcon -> Icon(
painter = painterResource(id = icon.id), painter = painterResource(id = icon.id),
contentDescription = null contentDescription = null
@ -195,3 +264,8 @@ private fun NiaBottomBar(
} }
} }
} }
private fun NavDestination?.isTopLevelDestinationInHierarchy(destination: TopLevelDestination) =
this?.hierarchy?.any {
it.route?.contains(destination.name, true) ?: false
} ?: false

@ -21,47 +21,71 @@ import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.navigation.NavController import androidx.navigation.NavController
import androidx.navigation.NavDestination import androidx.navigation.NavDestination
import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController import androidx.navigation.compose.rememberNavController
import androidx.navigation.navOptions
import androidx.tracing.trace import androidx.tracing.trace
import com.google.samples.apps.nowinandroid.core.designsystem.icon.Icon.DrawableResourceIcon import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor
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.core.ui.TrackDisposableJank
import com.google.samples.apps.nowinandroid.feature.bookmarks.R as bookmarksR import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.bookmarksRoute
import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.BookmarksDestination import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.navigateToBookmarks
import com.google.samples.apps.nowinandroid.feature.foryou.R as forYouR import com.google.samples.apps.nowinandroid.feature.foryou.navigation.forYouNavigationRoute
import com.google.samples.apps.nowinandroid.feature.foryou.navigation.ForYouDestination import com.google.samples.apps.nowinandroid.feature.foryou.navigation.navigateToForYou
import com.google.samples.apps.nowinandroid.feature.interests.R as interestsR import com.google.samples.apps.nowinandroid.feature.interests.navigation.interestsRoute
import com.google.samples.apps.nowinandroid.feature.interests.navigation.InterestsDestination 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
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 @Composable
fun rememberNiaAppState( fun rememberNiaAppState(
windowSizeClass: WindowSizeClass, windowSizeClass: WindowSizeClass,
networkMonitor: NetworkMonitor,
coroutineScope: CoroutineScope = rememberCoroutineScope(),
navController: NavHostController = rememberNavController() navController: NavHostController = rememberNavController()
): NiaAppState { ): NiaAppState {
NavigationTrackingSideEffect(navController) NavigationTrackingSideEffect(navController)
return remember(navController, windowSizeClass) { return remember(navController, coroutineScope, windowSizeClass, networkMonitor) {
NiaAppState(navController, windowSizeClass) NiaAppState(navController, coroutineScope, windowSizeClass, networkMonitor)
} }
} }
@Stable @Stable
class NiaAppState( class NiaAppState(
val navController: NavHostController, val navController: NavHostController,
val windowSizeClass: WindowSizeClass val coroutineScope: CoroutineScope,
val windowSizeClass: WindowSizeClass,
networkMonitor: NetworkMonitor,
) { ) {
val currentDestination: NavDestination? val currentDestination: NavDestination?
@Composable get() = navController @Composable get() = navController
.currentBackStackEntryAsState().value?.destination .currentBackStackEntryAsState().value?.destination
val currentTopLevelDestination: TopLevelDestination?
@Composable get() = when (currentDestination?.route) {
forYouNavigationRoute -> FOR_YOU
bookmarksRoute -> BOOKMARKS
interestsRoute -> INTERESTS
else -> null
}
var shouldShowSettingsDialog by mutableStateOf(false)
private set
val shouldShowBottomBar: Boolean val shouldShowBottomBar: Boolean
get() = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact || get() = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact ||
windowSizeClass.heightSizeClass == WindowHeightSizeClass.Compact windowSizeClass.heightSizeClass == WindowHeightSizeClass.Compact
@ -69,64 +93,47 @@ class NiaAppState(
val shouldShowNavRail: Boolean val shouldShowNavRail: Boolean
get() = !shouldShowBottomBar get() = !shouldShowBottomBar
val isOffline = networkMonitor.isOnline
.map(Boolean::not)
.stateIn(
scope = coroutineScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = false
)
/** /**
* 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> = listOf( val topLevelDestinations: List<TopLevelDestination> = TopLevelDestination.values().asList()
TopLevelDestination(
route = ForYouDestination.route,
destination = ForYouDestination.destination,
selectedIcon = DrawableResourceIcon(NiaIcons.Upcoming),
unselectedIcon = DrawableResourceIcon(NiaIcons.UpcomingBorder),
iconTextId = forYouR.string.for_you
),
TopLevelDestination(
route = BookmarksDestination.route,
destination = BookmarksDestination.destination,
selectedIcon = DrawableResourceIcon(NiaIcons.Bookmarks),
unselectedIcon = DrawableResourceIcon(NiaIcons.BookmarksBorder),
iconTextId = bookmarksR.string.saved
),
TopLevelDestination(
route = InterestsDestination.route,
destination = InterestsDestination.destination,
selectedIcon = ImageVectorIcon(NiaIcons.Grid3x3),
unselectedIcon = ImageVectorIcon(NiaIcons.Grid3x3),
iconTextId = interestsR.string.interests
)
)
/** /**
* UI logic for navigating to a particular destination in the app. The NavigationOptions to * UI logic for navigating to a top level destination in the app. Top level destinations have
* navigate with are based on the type of destination, which could be a top level destination or * only one copy of the destination of the back stack, and save and restore state whenever you
* just a regular destination. * navigate to and from it.
* *
* Top level destinations have only one copy of the destination of the back stack, and save and * @param topLevelDestination: The destination the app needs to navigate to.
* restore state whenever you navigate to and from it.
* Regular destinations can have multiple copies in the back stack and state isn't saved nor
* restored.
*
* @param destination: The [NiaNavigationDestination] the app needs to navigate to.
* @param route: Optional route to navigate to in case the destination contains arguments.
*/ */
fun navigate(destination: NiaNavigationDestination, route: String? = null) { fun navigateToTopLevelDestination(topLevelDestination: TopLevelDestination) {
trace("Navigation: ${destination.route}") { trace("Navigation: ${topLevelDestination.name}") {
if (destination is TopLevelDestination) { val topLevelNavOptions = navOptions {
navController.navigate(route ?: destination.route) { // Pop up to the start destination of the graph to
// Pop up to the start destination of the graph to // avoid building up a large stack of destinations
// avoid building up a large stack of destinations // on the back stack as users select items
// on the back stack as users select items popUpTo(navController.graph.findStartDestination().id) {
popUpTo(navController.graph.findStartDestination().id) { saveState = true
saveState = true
}
// Avoid multiple copies of the same destination when
// reselecting the same item
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = true
} }
} else { // Avoid multiple copies of the same destination when
navController.navigate(route ?: destination.route) // reselecting the same item
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = true
}
when (topLevelDestination) {
FOR_YOU -> navController.navigateToForYou(topLevelNavOptions)
BOOKMARKS -> navController.navigateToBookmarks(topLevelNavOptions)
INTERESTS -> navController.navigateToInterestsGraph(topLevelNavOptions)
} }
} }
} }
@ -134,6 +141,10 @@ class NiaAppState(
fun onBackClick() { fun onBackClick() {
navController.popBackStack() navController.popBackStack()
} }
fun setShowSettingsDialog(shouldShow: Boolean) {
shouldShowSettingsDialog = shouldShow
}
} }
/** /**

@ -15,12 +15,6 @@
limitations under the License. limitations under the License.
--> -->
<resources> <resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<!-- Status bar --> <!-- Status bar -->
<color name="black30">#4D000000</color> <color name="black30">#4D000000</color>
</resources> </resources>

@ -16,4 +16,5 @@
--> -->
<resources> <resources>
<string name="app_name">Now in Android</string> <string name="app_name">Now in Android</string>
<string name="not_connected">⚠️ You arent connected to the internet</string>
</resources> </resources>

@ -13,8 +13,8 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import com.google.samples.apps.nowinandroid.Flavor import com.android.build.api.dsl.ManagedVirtualDevice
import com.google.samples.apps.nowinandroid.FlavorDimension import com.google.samples.apps.nowinandroid.NiaBuildType
import com.google.samples.apps.nowinandroid.configureFlavors import com.google.samples.apps.nowinandroid.configureFlavors
plugins { plugins {
@ -22,11 +22,13 @@ plugins {
} }
android { android {
namespace = "com.google.samples.apps.nowinandroid.benchmark" namespace = "com.google.samples.apps.nowinandroid.benchmarks"
defaultConfig { defaultConfig {
minSdk = 23 minSdk = 23
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
buildConfigField("String", "APP_BUILD_TYPE_SUFFIX", "\"\"")
} }
buildFeatures { buildFeatures {
@ -42,16 +44,39 @@ android {
isDebuggable = true isDebuggable = true
signingConfig = signingConfigs.getByName("debug") signingConfig = signingConfigs.getByName("debug")
matchingFallbacks.add("release") matchingFallbacks.add("release")
buildConfigField(
"String",
"APP_BUILD_TYPE_SUFFIX",
"\"${NiaBuildType.BENCHMARK.applicationIdSuffix ?: ""}\""
)
} }
} }
// Use the same flavor dimensions as the application to allow generating Baseline Profiles on prod, // Use the same flavor dimensions as the application to allow generating Baseline Profiles on prod,
// which is more close to what will be shipped to users (no fake data), but has ability to run the // which is more close to what will be shipped to users (no fake data), but has ability to run the
// benchmarks on demo, so we benchmark on stable data. // benchmarks on demo, so we benchmark on stable data.
configureFlavors(this) configureFlavors(this) { flavor ->
buildConfigField(
"String",
"APP_FLAVOR_SUFFIX",
"\"${flavor.applicationIdSuffix ?: ""}\""
)
}
targetProjectPath = ":app" targetProjectPath = ":app"
experimentalProperties["android.experimental.self-instrumenting"] = true experimentalProperties["android.experimental.self-instrumenting"] = true
testOptions {
managedDevices {
devices {
create<ManagedVirtualDevice>("pixel6Api31") {
device = "Pixel 6"
apiLevel = 31
systemImageSource = "aosp"
}
}
}
}
} }
dependencies { dependencies {
@ -62,7 +87,6 @@ dependencies {
implementation(libs.androidx.test.rules) implementation(libs.androidx.test.rules)
implementation(libs.androidx.test.uiautomator) implementation(libs.androidx.test.uiautomator)
implementation(libs.androidx.benchmark.macro) implementation(libs.androidx.benchmark.macro)
implementation(libs.androidx.profileinstaller)
} }
androidComponents { androidComponents {

@ -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 androidx.test.uiautomator
import androidx.test.uiautomator.HasChildrenOp.AT_LEAST
import androidx.test.uiautomator.HasChildrenOp.AT_MOST
import androidx.test.uiautomator.HasChildrenOp.EXACTLY
// These helpers need to be in the androidx.test.uiautomator package,
// because the abstract class has package local method that needs to be implemented.
/**
* Condition will be satisfied if given element has specified count of children
*/
fun untilHasChildren(
childCount: Int = 1,
op: HasChildrenOp = AT_LEAST
): UiObject2Condition<Boolean> {
return object : UiObject2Condition<Boolean>() {
override fun apply(element: UiObject2): Boolean {
return when (op) {
AT_LEAST -> element.childCount >= childCount
EXACTLY -> element.childCount == childCount
AT_MOST -> element.childCount <= childCount
}
}
}
}
enum class HasChildrenOp {
AT_LEAST,
EXACTLY,
AT_MOST
}

@ -0,0 +1,40 @@
/*
* 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.test.uiautomator.Direction
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.UiObject2
import com.google.samples.apps.nowinandroid.benchmarks.BuildConfig
/**
* Convenience parameter to use proper package name with regards to build type and build flavor.
*/
val PACKAGE_NAME = buildString {
append("com.google.samples.apps.nowinandroid")
append(BuildConfig.APP_FLAVOR_SUFFIX)
append(BuildConfig.APP_BUILD_TYPE_SUFFIX)
}
fun UiDevice.flingElementDownUp(element: UiObject2) {
// Set some margin from the sides to prevent triggering system navigation
element.setGestureMargin(displayWidth / 5)
element.fling(Direction.DOWN)
waitForIdle()
element.fling(Direction.UP)
}

@ -20,9 +20,7 @@ import androidx.benchmark.macro.ExperimentalBaselineProfilesApi
import androidx.benchmark.macro.junit4.BaselineProfileRule import androidx.benchmark.macro.junit4.BaselineProfileRule
import androidx.test.uiautomator.By import androidx.test.uiautomator.By
import com.google.samples.apps.nowinandroid.PACKAGE_NAME import com.google.samples.apps.nowinandroid.PACKAGE_NAME
import com.google.samples.apps.nowinandroid.bookmarks.bookmarksScrollFeedDownUp
import com.google.samples.apps.nowinandroid.foryou.forYouScrollFeedDownUp import com.google.samples.apps.nowinandroid.foryou.forYouScrollFeedDownUp
import com.google.samples.apps.nowinandroid.foryou.forYouSelectAuthors
import com.google.samples.apps.nowinandroid.foryou.forYouWaitForContent import com.google.samples.apps.nowinandroid.foryou.forYouWaitForContent
import com.google.samples.apps.nowinandroid.interests.interestsScrollPeopleDownUp import com.google.samples.apps.nowinandroid.interests.interestsScrollPeopleDownUp
import com.google.samples.apps.nowinandroid.interests.interestsScrollTopicsDownUp import com.google.samples.apps.nowinandroid.interests.interestsScrollTopicsDownUp
@ -48,14 +46,13 @@ class BaselineProfileGenerator {
// Scroll the feed critical user journey // Scroll the feed critical user journey
forYouWaitForContent() forYouWaitForContent()
forYouSelectAuthors()
forYouScrollFeedDownUp() forYouScrollFeedDownUp()
// Navigate to saved screen // Navigate to saved screen
device.findObject(By.text("Saved")).click() device.findObject(By.text("Saved")).click()
device.waitForIdle() device.waitForIdle()
// TODO: we need to implement adding stuff to bookmarks before able to scroll it
bookmarksScrollFeedDownUp() // bookmarksScrollFeedDownUp()
// Navigate to interests screen // Navigate to interests screen
device.findObject(By.text("Interests")).click() device.findObject(By.text("Interests")).click()

@ -18,11 +18,9 @@ package com.google.samples.apps.nowinandroid.bookmarks
import androidx.benchmark.macro.MacrobenchmarkScope import androidx.benchmark.macro.MacrobenchmarkScope
import androidx.test.uiautomator.By import androidx.test.uiautomator.By
import androidx.test.uiautomator.Direction import com.google.samples.apps.nowinandroid.flingElementDownUp
fun MacrobenchmarkScope.bookmarksScrollFeedDownUp() { fun MacrobenchmarkScope.bookmarksScrollFeedDownUp() {
val feedList = device.findObject(By.res("bookmarks:feed")) val feedList = device.findObject(By.res("bookmarks:feed"))
feedList.fling(Direction.DOWN) device.flingElementDownUp(feedList)
device.waitForIdle()
feedList.fling(Direction.UP)
} }

@ -18,27 +18,20 @@ package com.google.samples.apps.nowinandroid.foryou
import androidx.benchmark.macro.MacrobenchmarkScope import androidx.benchmark.macro.MacrobenchmarkScope
import androidx.test.uiautomator.By import androidx.test.uiautomator.By
import androidx.test.uiautomator.Direction
import androidx.test.uiautomator.Until import androidx.test.uiautomator.Until
import androidx.test.uiautomator.untilHasChildren
import com.google.samples.apps.nowinandroid.flingElementDownUp
fun MacrobenchmarkScope.forYouWaitForContent() { fun MacrobenchmarkScope.forYouWaitForContent() {
// Wait until content is loaded // Wait until content is loaded by checking if authors are loaded
device.wait(Until.hasObject(By.text("What are you interested in?")), 30_000) device.wait(Until.gone(By.res("forYou:loadingWheel")), 5_000)
} // Sometimes, the loading wheel is gone, but the content is not loaded yet
// So we'll wait here for authors to be sure
fun MacrobenchmarkScope.forYouSelectAuthors() { val obj = device.findObject(By.res("forYou:authors"))
val authors = device.findObject(By.res("forYou:authors")) obj.wait(untilHasChildren(), 30_000)
// select some authors to show some feed content
repeat(3) { index ->
val author = authors.children[index % authors.childCount]
author.click()
device.waitForIdle()
}
} }
fun MacrobenchmarkScope.forYouScrollFeedDownUp() { fun MacrobenchmarkScope.forYouScrollFeedDownUp() {
val feedList = device.findObject(By.res("forYou:feed")) val feedList = device.findObject(By.res("forYou:feed"))
feedList.fling(Direction.DOWN) device.flingElementDownUp(feedList)
device.waitForIdle()
feedList.fling(Direction.UP)
} }

@ -50,7 +50,6 @@ class ScrollForYouFeedBenchmark {
} }
) { ) {
forYouWaitForContent() forYouWaitForContent()
forYouSelectAuthors()
forYouScrollFeedDownUp() forYouScrollFeedDownUp()
} }
} }

@ -18,18 +18,26 @@ package com.google.samples.apps.nowinandroid.interests
import androidx.benchmark.macro.MacrobenchmarkScope import androidx.benchmark.macro.MacrobenchmarkScope
import androidx.test.uiautomator.By import androidx.test.uiautomator.By
import androidx.test.uiautomator.Direction import androidx.test.uiautomator.Until
import com.google.samples.apps.nowinandroid.flingElementDownUp
fun MacrobenchmarkScope.interestsScrollTopicsDownUp() { fun MacrobenchmarkScope.interestsScrollTopicsDownUp() {
val topicsList = device.findObject(By.res("interests:topics")) val topicsList = device.findObject(By.res("interests:topics"))
topicsList.fling(Direction.DOWN) device.flingElementDownUp(topicsList)
device.waitForIdle()
topicsList.fling(Direction.UP)
} }
fun MacrobenchmarkScope.interestsScrollPeopleDownUp() { fun MacrobenchmarkScope.interestsScrollPeopleDownUp() {
val peopleList = device.findObject(By.res("interests:people")) val peopleList = device.findObject(By.res("interests:people"))
peopleList.fling(Direction.DOWN) device.flingElementDownUp(peopleList)
}
fun MacrobenchmarkScope.interestsWaitForTopics() {
device.wait(Until.hasObject(By.text("Accessibility")), 30_000)
}
fun MacrobenchmarkScope.interestsToggleBookmarked() {
val topicsList = device.findObject(By.res("interests:topics"))
val checkable = topicsList.findObject(By.checkable(true))
checkable.click()
device.waitForIdle() device.waitForIdle()
peopleList.fling(Direction.UP)
} }

@ -0,0 +1,61 @@
/*
* 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.interests
import androidx.benchmark.macro.CompilationMode
import androidx.benchmark.macro.FrameTimingMetric
import androidx.benchmark.macro.StartupMode
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.uiautomator.By
import com.google.samples.apps.nowinandroid.PACKAGE_NAME
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class TopicsScreenRecompositionBenchmark {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
@Test
fun benchmarkStateChangeCompilationBaselineProfile() =
benchmarkStateChange(CompilationMode.Partial())
private fun benchmarkStateChange(compilationMode: CompilationMode) =
benchmarkRule.measureRepeated(
packageName = PACKAGE_NAME,
metrics = listOf(FrameTimingMetric()),
compilationMode = compilationMode,
iterations = 10,
startupMode = StartupMode.WARM,
setupBlock = {
// Start the app
pressHome()
startActivityAndWait()
// Navigate to interests screen
device.findObject(By.text("Interests")).click()
device.waitForIdle()
}
) {
interestsWaitForTopics()
repeat(3) {
interestsToggleBookmarked()
}
}
}

@ -21,6 +21,7 @@ import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.kotlin
class AndroidFeatureConventionPlugin : Plugin<Project> { class AndroidFeatureConventionPlugin : Plugin<Project> {
override fun apply(target: Project) { override fun apply(target: Project) {
@ -44,10 +45,11 @@ class AndroidFeatureConventionPlugin : Plugin<Project> {
add("implementation", project(":core:designsystem")) add("implementation", project(":core:designsystem"))
add("implementation", project(":core:data")) add("implementation", project(":core:data"))
add("implementation", project(":core:common")) add("implementation", project(":core:common"))
add("implementation", project(":core:navigation"))
add("implementation", project(":core:domain")) add("implementation", project(":core:domain"))
add("testImplementation", kotlin("test"))
add("testImplementation", project(":core:testing")) add("testImplementation", project(":core:testing"))
add("androidTestImplementation", kotlin("test"))
add("androidTestImplementation", project(":core:testing")) add("androidTestImplementation", project(":core:testing"))
add("implementation", libs.findLibrary("coil.kt").get()) add("implementation", libs.findLibrary("coil.kt").get())
@ -58,13 +60,6 @@ class AndroidFeatureConventionPlugin : Plugin<Project> {
add("implementation", libs.findLibrary("androidx.lifecycle.viewModelCompose").get()) add("implementation", libs.findLibrary("androidx.lifecycle.viewModelCompose").get())
add("implementation", libs.findLibrary("kotlinx.coroutines.android").get()) add("implementation", libs.findLibrary("kotlinx.coroutines.android").get())
// TODO : Remove this dependency once we upgrade to Android Studio Dolphin b/228889042
// These dependencies are currently necessary to render Compose previews
add(
"debugImplementation",
libs.findLibrary("androidx.customview.poolingcontainer").get()
)
} }
} }
} }

@ -27,8 +27,10 @@ class AndroidHiltConventionPlugin : Plugin<Project> {
override fun apply(target: Project) { override fun apply(target: Project) {
with(target) { with(target) {
with(pluginManager) { with(pluginManager) {
apply("org.jetbrains.kotlin.kapt")
apply("dagger.hilt.android.plugin") apply("dagger.hilt.android.plugin")
// KAPT must go last to avoid build warnings.
// See: https://stackoverflow.com/questions/70550883/warning-the-following-options-were-not-recognized-by-any-processor-dagger-f
apply("org.jetbrains.kotlin.kapt")
} }
val libs = extensions.getByType<VersionCatalogsExtension>().named("libs") val libs = extensions.getByType<VersionCatalogsExtension>().named("libs")

@ -26,6 +26,7 @@ import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.kotlin
class AndroidLibraryConventionPlugin : Plugin<Project> { class AndroidLibraryConventionPlugin : Plugin<Project> {
override fun apply(target: Project) { override fun apply(target: Project) {
@ -51,6 +52,10 @@ class AndroidLibraryConventionPlugin : Plugin<Project> {
force("org.objenesis:objenesis:2.6") force("org.objenesis:objenesis:2.6")
} }
} }
dependencies {
add("androidTestImplementation", kotlin("test"))
add("testImplementation", kotlin("test"))
}
} }
} }
} }

@ -19,6 +19,7 @@ package com.google.samples.apps.nowinandroid
import com.android.build.api.dsl.CommonExtension import com.android.build.api.dsl.CommonExtension
import org.gradle.api.Project import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.getByType
import java.io.File import java.io.File
@ -42,6 +43,12 @@ internal fun Project.configureAndroidCompose(
kotlinOptions { kotlinOptions {
freeCompilerArgs = freeCompilerArgs + buildComposeMetricsParameters() freeCompilerArgs = freeCompilerArgs + buildComposeMetricsParameters()
} }
dependencies {
val bom = libs.findLibrary("androidx-compose-bom").get()
add("implementation", platform(bom))
add("androidTestImplementation", platform(bom))
}
} }
} }

@ -0,0 +1,27 @@
/*
* 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
/**
* This is shared between :app and :benchmarks module to provide configurations type safety.
*/
@Suppress("unused")
enum class NiaBuildType(val applicationIdSuffix: String? = null) {
DEBUG(".debug"),
RELEASE,
BENCHMARK(".benchmark")
}

@ -2,10 +2,11 @@ package com.google.samples.apps.nowinandroid
import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.dsl.ApplicationExtension
import com.android.build.api.dsl.ApplicationProductFlavor import com.android.build.api.dsl.ApplicationProductFlavor
import com.android.build.api.dsl.ApplicationVariantDimension
import com.android.build.api.dsl.CommonExtension import com.android.build.api.dsl.CommonExtension
import com.android.build.api.dsl.ProductFlavor
import org.gradle.api.Project import org.gradle.api.Project
@Suppress("EnumEntryName")
enum class FlavorDimension { enum class FlavorDimension {
contentType contentType
} }
@ -13,20 +14,23 @@ enum class FlavorDimension {
// The content for the app can either come from local static data which is useful for demo // The content for the app can either come from local static data which is useful for demo
// purposes, or from a production backend server which supplies up-to-date, real content. // purposes, or from a production backend server which supplies up-to-date, real content.
// These two product flavors reflect this behaviour. // These two product flavors reflect this behaviour.
enum class Flavor (val dimension : FlavorDimension, val applicationIdSuffix : String? = null) { @Suppress("EnumEntryName")
demo(FlavorDimension.contentType, ".demo"), enum class NiaFlavor(val dimension: FlavorDimension, val applicationIdSuffix: String? = null) {
prod(FlavorDimension.contentType) demo(FlavorDimension.contentType),
prod(FlavorDimension.contentType, ".prod")
} }
fun Project.configureFlavors( fun Project.configureFlavors(
commonExtension: CommonExtension<*, *, *, *> commonExtension: CommonExtension<*, *, *, *>,
flavorConfigurationBlock: ProductFlavor.(flavor: NiaFlavor) -> Unit = {}
) { ) {
commonExtension.apply { commonExtension.apply {
flavorDimensions += FlavorDimension.contentType.name flavorDimensions += FlavorDimension.contentType.name
productFlavors { productFlavors {
Flavor.values().forEach{ NiaFlavor.values().forEach {
create(it.name) { create(it.name) {
dimension = it.dimension.name dimension = it.dimension.name
flavorConfigurationBlock(this, it)
if (this@apply is ApplicationExtension && this is ApplicationProductFlavor) { if (this@apply is ApplicationExtension && this is ApplicationProductFlavor) {
if (it.applicationIdSuffix != null) { if (it.applicationIdSuffix != null) {
this.applicationIdSuffix = it.applicationIdSuffix this.applicationIdSuffix = it.applicationIdSuffix

@ -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.decoder
interface StringDecoder {
fun decodeString(encodedString: String): String
}

@ -14,14 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
package com.google.samples.apps.nowinandroid.core.domain.model package com.google.samples.apps.nowinandroid.core.decoder
import com.google.samples.apps.nowinandroid.core.model.data.Author import android.net.Uri
import javax.inject.Inject
/** class UriDecoder @Inject constructor() : StringDecoder {
* An [author] with the additional information for whether or not it is followed. override fun decodeString(encodedString: String): String = Uri.decode(encodedString)
*/ }
data class FollowableAuthor(
val author: Author,
val isFollowed: Boolean
)

@ -14,20 +14,18 @@
* limitations under the License. * limitations under the License.
*/ */
package com.google.samples.apps.nowinandroid.core.data.repository package com.google.samples.apps.nowinandroid.core.decoder.di
import com.google.samples.apps.nowinandroid.core.data.Syncable import com.google.samples.apps.nowinandroid.core.decoder.StringDecoder
import com.google.samples.apps.nowinandroid.core.model.data.Author import com.google.samples.apps.nowinandroid.core.decoder.UriDecoder
import kotlinx.coroutines.flow.Flow import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
interface AuthorsRepository : Syncable { @Module
/** @InstallIn(SingletonComponent::class)
* Gets the available Authors as a stream abstract class StringDecoderModule {
*/ @Binds
fun getAuthorsStream(): Flow<List<Author>> abstract fun bindStringDecoder(uriDecoder: UriDecoder): StringDecoder
/**
* Gets data for a specific author
*/
fun getAuthorStream(id: String): Flow<Author>
} }

@ -17,9 +17,9 @@
package com.google.samples.apps.nowinandroid.core.result package com.google.samples.apps.nowinandroid.core.result
import app.cash.turbine.test import app.cash.turbine.test
import kotlin.test.assertEquals
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class ResultKtTest { class ResultKtTest {

@ -17,11 +17,9 @@
package com.google.samples.apps.nowinandroid.core.data.test package com.google.samples.apps.nowinandroid.core.data.test
import com.google.samples.apps.nowinandroid.core.data.di.DataModule import com.google.samples.apps.nowinandroid.core.data.di.DataModule
import com.google.samples.apps.nowinandroid.core.data.repository.AuthorsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.NewsRepository import com.google.samples.apps.nowinandroid.core.data.repository.NewsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.TopicsRepository import com.google.samples.apps.nowinandroid.core.data.repository.TopicsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository
import com.google.samples.apps.nowinandroid.core.data.repository.fake.FakeAuthorsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.fake.FakeNewsRepository import com.google.samples.apps.nowinandroid.core.data.repository.fake.FakeNewsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.fake.FakeTopicsRepository import com.google.samples.apps.nowinandroid.core.data.repository.fake.FakeTopicsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.fake.FakeUserDataRepository import com.google.samples.apps.nowinandroid.core.data.repository.fake.FakeUserDataRepository
@ -42,11 +40,6 @@ interface TestDataModule {
fakeTopicsRepository: FakeTopicsRepository fakeTopicsRepository: FakeTopicsRepository
): TopicsRepository ): TopicsRepository
@Binds
fun bindsAuthorRepository(
fakeAuthorsRepository: FakeAuthorsRepository
): AuthorsRepository
@Binds @Binds
fun bindsNewsResourceRepository( fun bindsNewsResourceRepository(
fakeNewsRepository: FakeNewsRepository fakeNewsRepository: FakeNewsRepository

@ -22,6 +22,11 @@ plugins {
android { android {
namespace = "com.google.samples.apps.nowinandroid.core.data" namespace = "com.google.samples.apps.nowinandroid.core.data"
testOptions {
unitTests {
isIncludeAndroidResources = true
}
}
} }
dependencies { dependencies {

@ -16,9 +16,7 @@
package com.google.samples.apps.nowinandroid.core.data.di package com.google.samples.apps.nowinandroid.core.data.di
import com.google.samples.apps.nowinandroid.core.data.repository.AuthorsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.NewsRepository import com.google.samples.apps.nowinandroid.core.data.repository.NewsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.OfflineFirstAuthorsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.OfflineFirstNewsRepository import com.google.samples.apps.nowinandroid.core.data.repository.OfflineFirstNewsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.OfflineFirstTopicsRepository import com.google.samples.apps.nowinandroid.core.data.repository.OfflineFirstTopicsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.OfflineFirstUserDataRepository import com.google.samples.apps.nowinandroid.core.data.repository.OfflineFirstUserDataRepository
@ -40,11 +38,6 @@ interface DataModule {
topicsRepository: OfflineFirstTopicsRepository topicsRepository: OfflineFirstTopicsRepository
): TopicsRepository ): TopicsRepository
@Binds
fun bindsAuthorsRepository(
authorsRepository: OfflineFirstAuthorsRepository
): AuthorsRepository
@Binds @Binds
fun bindsNewsResourceRepository( fun bindsNewsResourceRepository(
newsRepository: OfflineFirstNewsRepository newsRepository: OfflineFirstNewsRepository

@ -16,8 +16,6 @@
package com.google.samples.apps.nowinandroid.core.data.model package com.google.samples.apps.nowinandroid.core.data.model
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceAuthorCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity
@ -44,22 +42,6 @@ fun NetworkNewsResourceExpanded.asEntity() = NewsResourceEntity(
type = type, type = type,
) )
/**
* A shell [AuthorEntity] to fulfill the foreign key constraint when inserting
* a [NewsResourceEntity] into the DB
*/
fun NetworkNewsResource.authorEntityShells() =
authors.map { authorId ->
AuthorEntity(
id = authorId,
name = "",
imageUrl = "",
twitter = "",
mediumPage = "",
bio = "",
)
}
/** /**
* A shell [TopicEntity] to fulfill the foreign key constraint when inserting * A shell [TopicEntity] to fulfill the foreign key constraint when inserting
* a [NewsResourceEntity] into the DB * a [NewsResourceEntity] into the DB
@ -83,11 +65,3 @@ fun NetworkNewsResource.topicCrossReferences(): List<NewsResourceTopicCrossRef>
topicId = topicId topicId = topicId
) )
} }
fun NetworkNewsResource.authorCrossReferences(): List<NewsResourceAuthorCrossRef> =
authors.map { authorId ->
NewsResourceAuthorCrossRef(
newsResourceId = id,
authorId = authorId
)
}

@ -27,13 +27,12 @@ interface NewsRepository : Syncable {
/** /**
* Returns available news resources as a stream. * Returns available news resources as a stream.
*/ */
fun getNewsResourcesStream(): Flow<List<NewsResource>> fun getNewsResources(): Flow<List<NewsResource>>
/** /**
* Returns available news resources as a stream filtered by authors or topics. * Returns available news resources as a stream filtered by topics.
*/ */
fun getNewsResourcesStream( fun getNewsResources(
filterAuthorIds: Set<String> = emptySet(),
filterTopicIds: Set<String> = emptySet(), filterTopicIds: Set<String> = emptySet(),
): Flow<List<NewsResource>> ): Flow<List<NewsResource>>
} }

@ -1,68 +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.core.data.repository
import com.google.samples.apps.nowinandroid.core.data.Synchronizer
import com.google.samples.apps.nowinandroid.core.data.changeListSync
import com.google.samples.apps.nowinandroid.core.data.model.asEntity
import com.google.samples.apps.nowinandroid.core.database.dao.AuthorDao
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.asExternalModel
import com.google.samples.apps.nowinandroid.core.datastore.ChangeListVersions
import com.google.samples.apps.nowinandroid.core.model.data.Author
import com.google.samples.apps.nowinandroid.core.network.NiaNetworkDataSource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
/**
* Disk storage backed implementation of the [AuthorsRepository].
* Reads are exclusively from local storage to support offline access.
*/
class OfflineFirstAuthorsRepository @Inject constructor(
private val authorDao: AuthorDao,
private val network: NiaNetworkDataSource,
) : AuthorsRepository {
override fun getAuthorStream(id: String): Flow<Author> =
authorDao.getAuthorEntityStream(id).map {
it.asExternalModel()
}
override fun getAuthorsStream(): Flow<List<Author>> =
authorDao.getAuthorEntitiesStream()
.map { it.map(AuthorEntity::asExternalModel) }
override suspend fun syncWith(synchronizer: Synchronizer): Boolean =
synchronizer.changeListSync(
versionReader = ChangeListVersions::authorVersion,
changeListFetcher = { currentVersion ->
network.getAuthorChangeList(after = currentVersion)
},
versionUpdater = { latestVersion ->
copy(authorVersion = latestVersion)
},
modelDeleter = authorDao::deleteAuthors,
modelUpdater = { changedIds ->
val networkAuthors = network.getAuthors(ids = changedIds)
authorDao.upsertAuthors(
entities = networkAuthors.map(NetworkAuthor::asEntity)
)
}
)
}

@ -19,14 +19,10 @@ package com.google.samples.apps.nowinandroid.core.data.repository
import com.google.samples.apps.nowinandroid.core.data.Synchronizer import com.google.samples.apps.nowinandroid.core.data.Synchronizer
import com.google.samples.apps.nowinandroid.core.data.changeListSync import com.google.samples.apps.nowinandroid.core.data.changeListSync
import com.google.samples.apps.nowinandroid.core.data.model.asEntity import com.google.samples.apps.nowinandroid.core.data.model.asEntity
import com.google.samples.apps.nowinandroid.core.data.model.authorCrossReferences
import com.google.samples.apps.nowinandroid.core.data.model.authorEntityShells
import com.google.samples.apps.nowinandroid.core.data.model.topicCrossReferences import com.google.samples.apps.nowinandroid.core.data.model.topicCrossReferences
import com.google.samples.apps.nowinandroid.core.data.model.topicEntityShells import com.google.samples.apps.nowinandroid.core.data.model.topicEntityShells
import com.google.samples.apps.nowinandroid.core.database.dao.AuthorDao
import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao
import com.google.samples.apps.nowinandroid.core.database.dao.TopicDao import com.google.samples.apps.nowinandroid.core.database.dao.TopicDao
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource
import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity
import com.google.samples.apps.nowinandroid.core.database.model.asExternalModel import com.google.samples.apps.nowinandroid.core.database.model.asExternalModel
@ -44,20 +40,17 @@ import kotlinx.coroutines.flow.map
*/ */
class OfflineFirstNewsRepository @Inject constructor( class OfflineFirstNewsRepository @Inject constructor(
private val newsResourceDao: NewsResourceDao, private val newsResourceDao: NewsResourceDao,
private val authorDao: AuthorDao,
private val topicDao: TopicDao, private val topicDao: TopicDao,
private val network: NiaNetworkDataSource, private val network: NiaNetworkDataSource,
) : NewsRepository { ) : NewsRepository {
override fun getNewsResourcesStream(): Flow<List<NewsResource>> = override fun getNewsResources(): Flow<List<NewsResource>> =
newsResourceDao.getNewsResourcesStream() newsResourceDao.getNewsResources()
.map { it.map(PopulatedNewsResource::asExternalModel) } .map { it.map(PopulatedNewsResource::asExternalModel) }
override fun getNewsResourcesStream( override fun getNewsResources(
filterAuthorIds: Set<String>,
filterTopicIds: Set<String> filterTopicIds: Set<String>
): Flow<List<NewsResource>> = newsResourceDao.getNewsResourcesStream( ): Flow<List<NewsResource>> = newsResourceDao.getNewsResources(
filterAuthorIds = filterAuthorIds,
filterTopicIds = filterTopicIds filterTopicIds = filterTopicIds
) )
.map { it.map(PopulatedNewsResource::asExternalModel) } .map { it.map(PopulatedNewsResource::asExternalModel) }
@ -83,12 +76,6 @@ class OfflineFirstNewsRepository @Inject constructor(
.flatten() .flatten()
.distinctBy(TopicEntity::id) .distinctBy(TopicEntity::id)
) )
authorDao.insertOrIgnoreAuthors(
authorEntities = networkNewsResources
.map(NetworkNewsResource::authorEntityShells)
.flatten()
.distinctBy(AuthorEntity::id)
)
newsResourceDao.upsertNewsResources( newsResourceDao.upsertNewsResources(
newsResourceEntities = networkNewsResources newsResourceEntities = networkNewsResources
.map(NetworkNewsResource::asEntity) .map(NetworkNewsResource::asEntity)
@ -99,12 +86,6 @@ class OfflineFirstNewsRepository @Inject constructor(
.distinct() .distinct()
.flatten() .flatten()
) )
newsResourceDao.insertOrIgnoreAuthorCrossRefEntities(
newsResourceAuthorCrossReferences = networkNewsResources
.map(NetworkNewsResource::authorCrossReferences)
.distinct()
.flatten()
)
} }
) )
} }

@ -39,8 +39,8 @@ class OfflineFirstTopicsRepository @Inject constructor(
private val network: NiaNetworkDataSource, private val network: NiaNetworkDataSource,
) : TopicsRepository { ) : TopicsRepository {
override fun getTopicsStream(): Flow<List<Topic>> = override fun getTopics(): Flow<List<Topic>> =
topicDao.getTopicEntitiesStream() topicDao.getTopicEntities()
.map { it.map(TopicEntity::asExternalModel) } .map { it.map(TopicEntity::asExternalModel) }
override fun getTopic(id: String): Flow<Topic> = override fun getTopic(id: String): Flow<Topic> =

@ -17,6 +17,8 @@
package com.google.samples.apps.nowinandroid.core.data.repository 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.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 com.google.samples.apps.nowinandroid.core.model.data.UserData
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@ -25,8 +27,8 @@ class OfflineFirstUserDataRepository @Inject constructor(
private val niaPreferencesDataSource: NiaPreferencesDataSource private val niaPreferencesDataSource: NiaPreferencesDataSource
) : UserDataRepository { ) : UserDataRepository {
override val userDataStream: Flow<UserData> = override val userData: Flow<UserData> =
niaPreferencesDataSource.userDataStream niaPreferencesDataSource.userData
override suspend fun setFollowedTopicIds(followedTopicIds: Set<String>) = override suspend fun setFollowedTopicIds(followedTopicIds: Set<String>) =
niaPreferencesDataSource.setFollowedTopicIds(followedTopicIds) niaPreferencesDataSource.setFollowedTopicIds(followedTopicIds)
@ -34,12 +36,15 @@ class OfflineFirstUserDataRepository @Inject constructor(
override suspend fun toggleFollowedTopicId(followedTopicId: String, followed: Boolean) = override suspend fun toggleFollowedTopicId(followedTopicId: String, followed: Boolean) =
niaPreferencesDataSource.toggleFollowedTopicId(followedTopicId, followed) niaPreferencesDataSource.toggleFollowedTopicId(followedTopicId, followed)
override suspend fun setFollowedAuthorIds(followedAuthorIds: Set<String>) =
niaPreferencesDataSource.setFollowedAuthorIds(followedAuthorIds)
override suspend fun toggleFollowedAuthorId(followedAuthorId: String, followed: Boolean) =
niaPreferencesDataSource.toggleFollowedAuthorId(followedAuthorId, followed)
override suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) = override suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) =
niaPreferencesDataSource.toggleNewsResourceBookmark(newsResourceId, bookmarked) niaPreferencesDataSource.toggleNewsResourceBookmark(newsResourceId, bookmarked)
override suspend fun setThemeBrand(themeBrand: ThemeBrand) =
niaPreferencesDataSource.setThemeBrand(themeBrand)
override suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) =
niaPreferencesDataSource.setDarkThemeConfig(darkThemeConfig)
override suspend fun setShouldHideOnboarding(shouldHideOnboarding: Boolean) =
niaPreferencesDataSource.setShouldHideOnboarding(shouldHideOnboarding)
} }

@ -24,7 +24,7 @@ interface TopicsRepository : Syncable {
/** /**
* Gets the available topics as a stream * Gets the available topics as a stream
*/ */
fun getTopicsStream(): Flow<List<Topic>> fun getTopics(): Flow<List<Topic>>
/** /**
* Gets data for a specific topic * Gets data for a specific topic

@ -16,6 +16,8 @@
package com.google.samples.apps.nowinandroid.core.data.repository 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 com.google.samples.apps.nowinandroid.core.model.data.UserData
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@ -24,7 +26,7 @@ interface UserDataRepository {
/** /**
* Stream of [UserData] * Stream of [UserData]
*/ */
val userDataStream: Flow<UserData> val userData: Flow<UserData>
/** /**
* Sets the user's currently followed topics * Sets the user's currently followed topics
@ -37,17 +39,22 @@ interface UserDataRepository {
suspend fun toggleFollowedTopicId(followedTopicId: String, followed: Boolean) suspend fun toggleFollowedTopicId(followedTopicId: String, followed: Boolean)
/** /**
* Sets the user's currently followed authors * Updates the bookmarked status for a news resource
*/ */
suspend fun setFollowedAuthorIds(followedAuthorIds: Set<String>) suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean)
/** /**
* Toggles the user's newly followed/unfollowed author * Sets the desired theme brand.
*/ */
suspend fun toggleFollowedAuthorId(followedAuthorId: String, followed: Boolean) suspend fun setThemeBrand(themeBrand: ThemeBrand)
/** /**
* Updates the bookmarked status for a news resource * Sets the desired dark theme config.
*/ */
suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig)
/**
* Sets whether the user has completed the onboarding process.
*/
suspend fun setShouldHideOnboarding(shouldHideOnboarding: Boolean)
} }

@ -1,67 +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.core.data.repository.fake
import com.google.samples.apps.nowinandroid.core.data.Synchronizer
import com.google.samples.apps.nowinandroid.core.data.repository.AuthorsRepository
import com.google.samples.apps.nowinandroid.core.model.data.Author
import com.google.samples.apps.nowinandroid.core.network.Dispatcher
import com.google.samples.apps.nowinandroid.core.network.NiaDispatchers.IO
import com.google.samples.apps.nowinandroid.core.network.fake.FakeDataSource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
/**
* Fake implementation of the [AuthorsRepository] that returns hardcoded authors.
*
* This allows us to run the app with fake data, without needing an internet connection or working
* backend.
*/
class FakeAuthorsRepository @Inject constructor(
@Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher,
private val networkJson: Json,
) : AuthorsRepository {
override fun getAuthorsStream(): Flow<List<Author>> = flow {
emit(
networkJson.decodeFromString<List<NetworkAuthor>>(FakeDataSource.authors).map {
Author(
id = it.id,
name = it.name,
imageUrl = it.imageUrl,
twitter = it.twitter,
mediumPage = it.mediumPage,
bio = it.bio,
)
}
)
}
.flowOn(ioDispatcher)
override fun getAuthorStream(id: String): Flow<Author> {
return getAuthorsStream().map { it.first { author -> author.id == id } }
}
override suspend fun syncWith(synchronizer: Synchronizer) = true
}

@ -24,15 +24,13 @@ import com.google.samples.apps.nowinandroid.core.database.model.asExternalModel
import com.google.samples.apps.nowinandroid.core.model.data.NewsResource import com.google.samples.apps.nowinandroid.core.model.data.NewsResource
import com.google.samples.apps.nowinandroid.core.network.Dispatcher import com.google.samples.apps.nowinandroid.core.network.Dispatcher
import com.google.samples.apps.nowinandroid.core.network.NiaDispatchers.IO import com.google.samples.apps.nowinandroid.core.network.NiaDispatchers.IO
import com.google.samples.apps.nowinandroid.core.network.fake.FakeDataSource import com.google.samples.apps.nowinandroid.core.network.fake.FakeNiaNetworkDataSource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
/** /**
* Fake implementation of the [NewsRepository] that retrieves the news resources from a JSON String. * Fake implementation of the [NewsRepository] that retrieves the news resources from a JSON String.
@ -42,35 +40,31 @@ import kotlinx.serialization.json.Json
*/ */
class FakeNewsRepository @Inject constructor( class FakeNewsRepository @Inject constructor(
@Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher, @Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher,
private val networkJson: Json private val datasource: FakeNiaNetworkDataSource
) : NewsRepository { ) : NewsRepository {
override fun getNewsResourcesStream(): Flow<List<NewsResource>> = override fun getNewsResources(): Flow<List<NewsResource>> =
flow { flow {
emit( emit(
networkJson.decodeFromString<List<NetworkNewsResource>>(FakeDataSource.data) datasource.getNewsResources()
.map(NetworkNewsResource::asEntity) .map(NetworkNewsResource::asEntity)
.map(NewsResourceEntity::asExternalModel) .map(NewsResourceEntity::asExternalModel)
) )
} }.flowOn(ioDispatcher)
.flowOn(ioDispatcher)
override fun getNewsResourcesStream( override fun getNewsResources(
filterAuthorIds: Set<String>,
filterTopicIds: Set<String>, filterTopicIds: Set<String>,
): Flow<List<NewsResource>> = ): Flow<List<NewsResource>> =
flow { flow {
emit( emit(
networkJson.decodeFromString<List<NetworkNewsResource>>(FakeDataSource.data) datasource
.filter { .getNewsResources()
it.authors.intersect(filterAuthorIds).isNotEmpty() || .filter { it.topics.intersect(filterTopicIds).isNotEmpty() }
it.topics.intersect(filterTopicIds).isNotEmpty()
}
.map(NetworkNewsResource::asEntity) .map(NetworkNewsResource::asEntity)
.map(NewsResourceEntity::asExternalModel) .map(NewsResourceEntity::asExternalModel)
) )
} }.flowOn(ioDispatcher)
.flowOn(ioDispatcher)
override suspend fun syncWith(synchronizer: Synchronizer) = true override suspend fun syncWith(synchronizer: Synchronizer) = true
} }

@ -21,16 +21,13 @@ import com.google.samples.apps.nowinandroid.core.data.repository.TopicsRepositor
import com.google.samples.apps.nowinandroid.core.model.data.Topic import com.google.samples.apps.nowinandroid.core.model.data.Topic
import com.google.samples.apps.nowinandroid.core.network.Dispatcher import com.google.samples.apps.nowinandroid.core.network.Dispatcher
import com.google.samples.apps.nowinandroid.core.network.NiaDispatchers.IO import com.google.samples.apps.nowinandroid.core.network.NiaDispatchers.IO
import com.google.samples.apps.nowinandroid.core.network.fake.FakeDataSource import com.google.samples.apps.nowinandroid.core.network.fake.FakeNiaNetworkDataSource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
/** /**
* Fake implementation of the [TopicsRepository] that retrieves the topics from a JSON String, and * Fake implementation of the [TopicsRepository] that retrieves the topics from a JSON String, and
@ -41,11 +38,11 @@ import kotlinx.serialization.json.Json
*/ */
class FakeTopicsRepository @Inject constructor( class FakeTopicsRepository @Inject constructor(
@Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher, @Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher,
private val networkJson: Json, private val datasource: FakeNiaNetworkDataSource
) : TopicsRepository { ) : TopicsRepository {
override fun getTopicsStream(): Flow<List<Topic>> = flow<List<Topic>> { override fun getTopics(): Flow<List<Topic>> = flow {
emit( emit(
networkJson.decodeFromString<List<NetworkTopic>>(FakeDataSource.topicsData).map { datasource.getTopics().map {
Topic( Topic(
id = it.id, id = it.id,
name = it.name, name = it.name,
@ -56,11 +53,10 @@ class FakeTopicsRepository @Inject constructor(
) )
} }
) )
} }.flowOn(ioDispatcher)
.flowOn(ioDispatcher)
override fun getTopic(id: String): Flow<Topic> { override fun getTopic(id: String): Flow<Topic> {
return getTopicsStream().map { it.first { topic -> topic.id == id } } return getTopics().map { it.first { topic -> topic.id == id } }
} }
override suspend fun syncWith(synchronizer: Synchronizer) = true override suspend fun syncWith(synchronizer: Synchronizer) = true

@ -16,15 +16,16 @@
package com.google.samples.apps.nowinandroid.core.data.repository.fake 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.data.repository.UserDataRepository
import com.google.samples.apps.nowinandroid.core.datastore.NiaPreferencesDataSource 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 com.google.samples.apps.nowinandroid.core.model.data.UserData
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
/** /**
* Fake implementation of the [AuthorsRepository] that returns hardcoded authors. * Fake implementation of the [UserDataRepository] that returns hardcoded user data.
* *
* This allows us to run the app with fake data, without needing an internet connection or working * This allows us to run the app with fake data, without needing an internet connection or working
* backend. * backend.
@ -33,8 +34,8 @@ class FakeUserDataRepository @Inject constructor(
private val niaPreferencesDataSource: NiaPreferencesDataSource, private val niaPreferencesDataSource: NiaPreferencesDataSource,
) : UserDataRepository { ) : UserDataRepository {
override val userDataStream: Flow<UserData> = override val userData: Flow<UserData> =
niaPreferencesDataSource.userDataStream niaPreferencesDataSource.userData
override suspend fun setFollowedTopicIds(followedTopicIds: Set<String>) = override suspend fun setFollowedTopicIds(followedTopicIds: Set<String>) =
niaPreferencesDataSource.setFollowedTopicIds(followedTopicIds) niaPreferencesDataSource.setFollowedTopicIds(followedTopicIds)
@ -42,15 +43,19 @@ class FakeUserDataRepository @Inject constructor(
override suspend fun toggleFollowedTopicId(followedTopicId: String, followed: Boolean) = override suspend fun toggleFollowedTopicId(followedTopicId: String, followed: Boolean) =
niaPreferencesDataSource.toggleFollowedTopicId(followedTopicId, followed) niaPreferencesDataSource.toggleFollowedTopicId(followedTopicId, followed)
override suspend fun setFollowedAuthorIds(followedAuthorIds: Set<String>) { override suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) {
niaPreferencesDataSource.setFollowedAuthorIds(followedAuthorIds) niaPreferencesDataSource.toggleNewsResourceBookmark(newsResourceId, bookmarked)
} }
override suspend fun toggleFollowedAuthorId(followedAuthorId: String, followed: Boolean) { override suspend fun setThemeBrand(themeBrand: ThemeBrand) {
niaPreferencesDataSource.toggleFollowedAuthorId(followedAuthorId, followed) niaPreferencesDataSource.setThemeBrand(themeBrand)
} }
override suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) { override suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) {
niaPreferencesDataSource.toggleNewsResourceBookmark(newsResourceId, bookmarked) niaPreferencesDataSource.setDarkThemeConfig(darkThemeConfig)
}
override suspend fun setShouldHideOnboarding(shouldHideOnboarding: Boolean) {
niaPreferencesDataSource.setShouldHideOnboarding(shouldHideOnboarding)
} }
} }

@ -35,18 +35,30 @@ import kotlinx.coroutines.flow.conflate
class ConnectivityManagerNetworkMonitor @Inject constructor( class ConnectivityManagerNetworkMonitor @Inject constructor(
@ApplicationContext private val context: Context @ApplicationContext private val context: Context
) : NetworkMonitor { ) : NetworkMonitor {
override val isOnline: Flow<Boolean> = callbackFlow<Boolean> { override val isOnline: Flow<Boolean> = callbackFlow {
val connectivityManager = context.getSystemService<ConnectivityManager>()
/**
* The callback's methods are invoked on changes to *any* network, not just the active
* network. So to check for network connectivity, one must query the active network of the
* ConnectivityManager.
*/
val callback = object : NetworkCallback() { val callback = object : NetworkCallback() {
override fun onAvailable(network: Network) { override fun onAvailable(network: Network) {
channel.trySend(true) channel.trySend(connectivityManager.isCurrentlyConnected())
} }
override fun onLost(network: Network) { override fun onLost(network: Network) {
channel.trySend(false) channel.trySend(connectivityManager.isCurrentlyConnected())
} }
}
val connectivityManager = context.getSystemService<ConnectivityManager>() override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
channel.trySend(connectivityManager.isCurrentlyConnected())
}
}
connectivityManager?.registerNetworkCallback( connectivityManager?.registerNetworkCallback(
Builder() Builder()

@ -17,33 +17,15 @@
package com.google.samples.apps.nowinandroid.core.data.model package com.google.samples.apps.nowinandroid.core.data.model
import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Article import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Article
import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor
import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResourceExpanded import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResourceExpanded
import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic
import kotlin.test.assertEquals
import kotlinx.datetime.Instant import kotlinx.datetime.Instant
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class NetworkEntityKtTest { class NetworkEntityKtTest {
@Test
fun network_author_can_be_mapped_to_author_entity() {
val networkModel = NetworkAuthor(
id = "0",
name = "Test",
imageUrl = "something",
twitter = "twitter",
mediumPage = "mediumPage",
bio = "bio",
)
val entity = networkModel.asEntity()
assertEquals("0", entity.id)
assertEquals("Test", entity.name)
assertEquals("something", entity.imageUrl)
}
@Test @Test
fun network_topic_can_be_mapped_to_topic_entity() { fun network_topic_can_be_mapped_to_topic_entity() {
val networkModel = NetworkTopic( val networkModel = NetworkTopic(

@ -1,37 +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.core.data.repository
import com.google.samples.apps.nowinandroid.core.data.repository.fake.FakeNewsRepository
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.serialization.json.Json
import org.junit.Before
class FakeNewsRepositoryTest {
private lateinit var subject: FakeNewsRepository
private val testDispatcher = StandardTestDispatcher()
@Before
fun setup() {
subject = FakeNewsRepository(
ioDispatcher = testDispatcher,
networkJson = Json { ignoreUnknownKeys = true }
)
}
}

@ -1,180 +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.core.data.repository
import com.google.samples.apps.nowinandroid.core.data.Synchronizer
import com.google.samples.apps.nowinandroid.core.data.model.asEntity
import com.google.samples.apps.nowinandroid.core.data.testdoubles.CollectionType
import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestAuthorDao
import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestNiaNetworkDataSource
import com.google.samples.apps.nowinandroid.core.database.dao.AuthorDao
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.asExternalModel
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.Author
import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor
import com.google.samples.apps.nowinandroid.core.network.model.NetworkChangeList
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class OfflineFirstAuthorsRepositoryTest {
private lateinit var subject: OfflineFirstAuthorsRepository
private lateinit var authorDao: AuthorDao
private lateinit var network: TestNiaNetworkDataSource
private lateinit var synchronizer: Synchronizer
@get:Rule
val tmpFolder: TemporaryFolder = TemporaryFolder.builder().assureDeletion().build()
@Before
fun setup() {
authorDao = TestAuthorDao()
network = TestNiaNetworkDataSource()
val niaPreferencesDataSource = NiaPreferencesDataSource(
tmpFolder.testUserPreferencesDataStore()
)
synchronizer = TestSynchronizer(niaPreferencesDataSource)
subject = OfflineFirstAuthorsRepository(
authorDao = authorDao,
network = network,
)
}
@Test
fun offlineFirstAuthorsRepository_Authors_stream_is_backed_by_Authors_dao() =
runTest {
Assert.assertEquals(
authorDao.getAuthorEntitiesStream()
.first()
.map(AuthorEntity::asExternalModel),
subject.getAuthorsStream()
.first()
)
}
@Test
fun offlineFirstAuthorsRepository_sync_pulls_from_network() =
runTest {
subject.syncWith(synchronizer)
val networkAuthors = network.getAuthors()
.map(NetworkAuthor::asEntity)
val dbAuthors = authorDao.getAuthorEntitiesStream()
.first()
Assert.assertEquals(
networkAuthors.map(AuthorEntity::id),
dbAuthors.map(AuthorEntity::id)
)
// After sync version should be updated
Assert.assertEquals(
network.latestChangeListVersion(CollectionType.Authors),
synchronizer.getChangeListVersions().authorVersion
)
}
@Test
fun offlineFirstAuthorsRepository_incremental_sync_pulls_from_network() =
runTest {
// Set author version to 5
synchronizer.updateChangeListVersions {
copy(authorVersion = 5)
}
subject.syncWith(synchronizer)
val changeList = network.changeListsAfter(
CollectionType.Authors,
version = 5
)
val changeListIds = changeList
.map(NetworkChangeList::id)
.toSet()
val network = network.getAuthors()
.map(NetworkAuthor::asEntity)
.filter { it.id in changeListIds }
val db = authorDao.getAuthorEntitiesStream()
.first()
Assert.assertEquals(
network.map(AuthorEntity::id),
db.map(AuthorEntity::id)
)
// After sync version should be updated
Assert.assertEquals(
changeList.last().changeListVersion,
synchronizer.getChangeListVersions().authorVersion
)
}
@Test
fun offlineFirstAuthorsRepository_sync_deletes_items_marked_deleted_on_network() =
runTest {
val networkAuthors = network.getAuthors()
.map(NetworkAuthor::asEntity)
.map(AuthorEntity::asExternalModel)
// Delete half of the items on the network
val deletedItems = networkAuthors
.map(Author::id)
.partition { it.chars().sum() % 2 == 0 }
.first
.toSet()
deletedItems.forEach {
network.editCollection(
collectionType = CollectionType.Authors,
id = it,
isDelete = true
)
}
subject.syncWith(synchronizer)
val dbAuthors = authorDao.getAuthorEntitiesStream()
.first()
.map(AuthorEntity::asExternalModel)
// Assert that items marked deleted on the network have been deleted locally
Assert.assertEquals(
networkAuthors.map(Author::id) - deletedItems,
dbAuthors.map(Author::id)
)
// After sync version should be updated
Assert.assertEquals(
network.latestChangeListVersion(CollectionType.Authors),
synchronizer.getChangeListVersions().authorVersion
)
}
}

@ -18,18 +18,14 @@ package com.google.samples.apps.nowinandroid.core.data.repository
import com.google.samples.apps.nowinandroid.core.data.Synchronizer import com.google.samples.apps.nowinandroid.core.data.Synchronizer
import com.google.samples.apps.nowinandroid.core.data.model.asEntity import com.google.samples.apps.nowinandroid.core.data.model.asEntity
import com.google.samples.apps.nowinandroid.core.data.model.authorCrossReferences
import com.google.samples.apps.nowinandroid.core.data.model.authorEntityShells
import com.google.samples.apps.nowinandroid.core.data.model.topicCrossReferences import com.google.samples.apps.nowinandroid.core.data.model.topicCrossReferences
import com.google.samples.apps.nowinandroid.core.data.model.topicEntityShells import com.google.samples.apps.nowinandroid.core.data.model.topicEntityShells
import com.google.samples.apps.nowinandroid.core.data.testdoubles.CollectionType import com.google.samples.apps.nowinandroid.core.data.testdoubles.CollectionType
import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestAuthorDao
import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestNewsResourceDao import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestNewsResourceDao
import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestNiaNetworkDataSource import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestNiaNetworkDataSource
import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestTopicDao import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestTopicDao
import com.google.samples.apps.nowinandroid.core.data.testdoubles.filteredInterestsIds import com.google.samples.apps.nowinandroid.core.data.testdoubles.filteredInterestsIds
import com.google.samples.apps.nowinandroid.core.data.testdoubles.nonPresentInterestsIds import com.google.samples.apps.nowinandroid.core.data.testdoubles.nonPresentInterestsIds
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity
import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource
import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity
@ -39,9 +35,9 @@ import com.google.samples.apps.nowinandroid.core.datastore.test.testUserPreferen
import com.google.samples.apps.nowinandroid.core.model.data.NewsResource import com.google.samples.apps.nowinandroid.core.model.data.NewsResource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkChangeList import com.google.samples.apps.nowinandroid.core.network.model.NetworkChangeList
import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource
import kotlin.test.assertEquals
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Before import org.junit.Before
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
@ -53,8 +49,6 @@ class OfflineFirstNewsRepositoryTest {
private lateinit var newsResourceDao: TestNewsResourceDao private lateinit var newsResourceDao: TestNewsResourceDao
private lateinit var authorDao: TestAuthorDao
private lateinit var topicDao: TestTopicDao private lateinit var topicDao: TestTopicDao
private lateinit var network: TestNiaNetworkDataSource private lateinit var network: TestNiaNetworkDataSource
@ -67,7 +61,6 @@ class OfflineFirstNewsRepositoryTest {
@Before @Before
fun setup() { fun setup() {
newsResourceDao = TestNewsResourceDao() newsResourceDao = TestNewsResourceDao()
authorDao = TestAuthorDao()
topicDao = TestTopicDao() topicDao = TestTopicDao()
network = TestNiaNetworkDataSource() network = TestNiaNetworkDataSource()
synchronizer = TestSynchronizer( synchronizer = TestSynchronizer(
@ -78,7 +71,6 @@ class OfflineFirstNewsRepositoryTest {
subject = OfflineFirstNewsRepository( subject = OfflineFirstNewsRepository(
newsResourceDao = newsResourceDao, newsResourceDao = newsResourceDao,
authorDao = authorDao,
topicDao = topicDao, topicDao = topicDao,
network = network, network = network,
) )
@ -88,10 +80,10 @@ class OfflineFirstNewsRepositoryTest {
fun offlineFirstNewsRepository_news_resources_stream_is_backed_by_news_resource_dao() = fun offlineFirstNewsRepository_news_resources_stream_is_backed_by_news_resource_dao() =
runTest { runTest {
assertEquals( assertEquals(
newsResourceDao.getNewsResourcesStream() newsResourceDao.getNewsResources()
.first() .first()
.map(PopulatedNewsResource::asExternalModel), .map(PopulatedNewsResource::asExternalModel),
subject.getNewsResourcesStream() subject.getNewsResources()
.first() .first()
) )
} }
@ -100,50 +92,26 @@ class OfflineFirstNewsRepositoryTest {
fun offlineFirstNewsRepository_news_resources_for_topic_is_backed_by_news_resource_dao() = fun offlineFirstNewsRepository_news_resources_for_topic_is_backed_by_news_resource_dao() =
runTest { runTest {
assertEquals( assertEquals(
newsResourceDao.getNewsResourcesStream( newsResourceDao.getNewsResources(
filterTopicIds = filteredInterestsIds, filterTopicIds = filteredInterestsIds,
) )
.first() .first()
.map(PopulatedNewsResource::asExternalModel), .map(PopulatedNewsResource::asExternalModel),
subject.getNewsResourcesStream( subject.getNewsResources(
filterTopicIds = filteredInterestsIds, filterTopicIds = filteredInterestsIds,
) )
.first() .first()
) )
assertEquals( assertEquals(
emptyList<NewsResource>(), emptyList(),
subject.getNewsResourcesStream( subject.getNewsResources(
filterTopicIds = nonPresentInterestsIds, filterTopicIds = nonPresentInterestsIds,
) )
.first() .first()
) )
} }
@Test
fun offlineFirstNewsRepository_news_resources_for_author_is_backed_by_news_resource_dao() =
runTest {
assertEquals(
newsResourceDao.getNewsResourcesStream(
filterAuthorIds = filteredInterestsIds
)
.first()
.map(PopulatedNewsResource::asExternalModel),
subject.getNewsResourcesStream(
filterAuthorIds = filteredInterestsIds
)
.first()
)
assertEquals(
emptyList<NewsResource>(),
subject.getNewsResourcesStream(
filterAuthorIds = nonPresentInterestsIds
)
.first()
)
}
@Test @Test
fun offlineFirstNewsRepository_sync_pulls_from_network() = fun offlineFirstNewsRepository_sync_pulls_from_network() =
runTest { runTest {
@ -153,7 +121,7 @@ class OfflineFirstNewsRepositoryTest {
.map(NetworkNewsResource::asEntity) .map(NetworkNewsResource::asEntity)
.map(NewsResourceEntity::asExternalModel) .map(NewsResourceEntity::asExternalModel)
val newsResourcesFromDb = newsResourceDao.getNewsResourcesStream() val newsResourcesFromDb = newsResourceDao.getNewsResources()
.first() .first()
.map(PopulatedNewsResource::asExternalModel) .map(PopulatedNewsResource::asExternalModel)
@ -193,7 +161,7 @@ class OfflineFirstNewsRepositoryTest {
subject.syncWith(synchronizer) subject.syncWith(synchronizer)
val newsResourcesFromDb = newsResourceDao.getNewsResourcesStream() val newsResourcesFromDb = newsResourceDao.getNewsResources()
.first() .first()
.map(PopulatedNewsResource::asExternalModel) .map(PopulatedNewsResource::asExternalModel)
@ -233,7 +201,7 @@ class OfflineFirstNewsRepositoryTest {
.map(NewsResourceEntity::asExternalModel) .map(NewsResourceEntity::asExternalModel)
.filter { it.id in changeListIds } .filter { it.id in changeListIds }
val newsResourcesFromDb = newsResourceDao.getNewsResourcesStream() val newsResourcesFromDb = newsResourceDao.getNewsResources()
.first() .first()
.map(PopulatedNewsResource::asExternalModel) .map(PopulatedNewsResource::asExternalModel)
@ -259,22 +227,7 @@ class OfflineFirstNewsRepositoryTest {
.map(NetworkNewsResource::topicEntityShells) .map(NetworkNewsResource::topicEntityShells)
.flatten() .flatten()
.distinctBy(TopicEntity::id), .distinctBy(TopicEntity::id),
topicDao.getTopicEntitiesStream() topicDao.getTopicEntities()
.first()
)
}
@Test
fun offlineFirstNewsRepository_sync_saves_shell_author_entities() =
runTest {
subject.syncWith(synchronizer)
assertEquals(
network.getNewsResources()
.map(NetworkNewsResource::authorEntityShells)
.flatten()
.distinctBy(AuthorEntity::id),
authorDao.getAuthorEntitiesStream()
.first() .first()
) )
} }
@ -292,18 +245,4 @@ class OfflineFirstNewsRepositoryTest {
newsResourceDao.topicCrossReferences newsResourceDao.topicCrossReferences
) )
} }
@Test
fun offlineFirstNewsRepository_sync_saves_author_cross_references() =
runTest {
subject.syncWith(synchronizer)
assertEquals(
network.getNewsResources()
.map(NetworkNewsResource::authorCrossReferences)
.distinct()
.flatten(),
newsResourceDao.authorCrossReferences
)
}
} }

@ -28,9 +28,9 @@ import com.google.samples.apps.nowinandroid.core.datastore.NiaPreferencesDataSou
import com.google.samples.apps.nowinandroid.core.datastore.test.testUserPreferencesDataStore import com.google.samples.apps.nowinandroid.core.datastore.test.testUserPreferencesDataStore
import com.google.samples.apps.nowinandroid.core.model.data.Topic import com.google.samples.apps.nowinandroid.core.model.data.Topic
import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic
import kotlin.test.assertEquals
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before import org.junit.Before
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
@ -69,11 +69,11 @@ class OfflineFirstTopicsRepositoryTest {
@Test @Test
fun offlineFirstTopicsRepository_topics_stream_is_backed_by_topics_dao() = fun offlineFirstTopicsRepository_topics_stream_is_backed_by_topics_dao() =
runTest { runTest {
Assert.assertEquals( assertEquals(
topicDao.getTopicEntitiesStream() topicDao.getTopicEntities()
.first() .first()
.map(TopicEntity::asExternalModel), .map(TopicEntity::asExternalModel),
subject.getTopicsStream() subject.getTopics()
.first() .first()
) )
} }
@ -86,16 +86,16 @@ class OfflineFirstTopicsRepositoryTest {
val networkTopics = network.getTopics() val networkTopics = network.getTopics()
.map(NetworkTopic::asEntity) .map(NetworkTopic::asEntity)
val dbTopics = topicDao.getTopicEntitiesStream() val dbTopics = topicDao.getTopicEntities()
.first() .first()
Assert.assertEquals( assertEquals(
networkTopics.map(TopicEntity::id), networkTopics.map(TopicEntity::id),
dbTopics.map(TopicEntity::id) dbTopics.map(TopicEntity::id)
) )
// After sync version should be updated // After sync version should be updated
Assert.assertEquals( assertEquals(
network.latestChangeListVersion(CollectionType.Topics), network.latestChangeListVersion(CollectionType.Topics),
synchronizer.getChangeListVersions().topicVersion synchronizer.getChangeListVersions().topicVersion
) )
@ -116,16 +116,16 @@ class OfflineFirstTopicsRepositoryTest {
// Drop 10 to simulate the first 10 items being unchanged // Drop 10 to simulate the first 10 items being unchanged
.drop(10) .drop(10)
val dbTopics = topicDao.getTopicEntitiesStream() val dbTopics = topicDao.getTopicEntities()
.first() .first()
Assert.assertEquals( assertEquals(
networkTopics.map(TopicEntity::id), networkTopics.map(TopicEntity::id),
dbTopics.map(TopicEntity::id) dbTopics.map(TopicEntity::id)
) )
// After sync version should be updated // After sync version should be updated
Assert.assertEquals( assertEquals(
network.latestChangeListVersion(CollectionType.Topics), network.latestChangeListVersion(CollectionType.Topics),
synchronizer.getChangeListVersions().topicVersion synchronizer.getChangeListVersions().topicVersion
) )
@ -155,18 +155,18 @@ class OfflineFirstTopicsRepositoryTest {
subject.syncWith(synchronizer) subject.syncWith(synchronizer)
val dbTopics = topicDao.getTopicEntitiesStream() val dbTopics = topicDao.getTopicEntities()
.first() .first()
.map(TopicEntity::asExternalModel) .map(TopicEntity::asExternalModel)
// Assert that items marked deleted on the network have been deleted locally // Assert that items marked deleted on the network have been deleted locally
Assert.assertEquals( assertEquals(
networkTopics.map(Topic::id) - deletedItems, networkTopics.map(Topic::id) - deletedItems,
dbTopics.map(Topic::id) dbTopics.map(Topic::id)
) )
// After sync version should be updated // After sync version should be updated
Assert.assertEquals( assertEquals(
network.latestChangeListVersion(CollectionType.Topics), network.latestChangeListVersion(CollectionType.Topics),
synchronizer.getChangeListVersions().topicVersion synchronizer.getChangeListVersions().topicVersion
) )

@ -18,10 +18,15 @@ 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.NiaPreferencesDataSource
import com.google.samples.apps.nowinandroid.core.datastore.test.testUserPreferencesDataStore 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 kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Before import org.junit.Before
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
@ -46,6 +51,21 @@ class OfflineFirstUserDataRepositoryTest {
) )
} }
@Test
fun offlineFirstUserDataRepository_default_user_data_is_correct() =
runTest {
assertEquals(
UserData(
bookmarkedNewsResources = emptySet(),
followedTopics = emptySet(),
themeBrand = ThemeBrand.DEFAULT,
darkThemeConfig = DarkThemeConfig.FOLLOW_SYSTEM,
shouldHideOnboarding = false
),
subject.userData.first()
)
}
@Test @Test
fun offlineFirstUserDataRepository_toggle_followed_topics_logic_delegates_to_nia_preferences() = fun offlineFirstUserDataRepository_toggle_followed_topics_logic_delegates_to_nia_preferences() =
runTest { runTest {
@ -53,7 +73,7 @@ class OfflineFirstUserDataRepositoryTest {
assertEquals( assertEquals(
setOf("0"), setOf("0"),
subject.userDataStream subject.userData
.map { it.followedTopics } .map { it.followedTopics }
.first() .first()
) )
@ -62,16 +82,16 @@ class OfflineFirstUserDataRepositoryTest {
assertEquals( assertEquals(
setOf("0", "1"), setOf("0", "1"),
subject.userDataStream subject.userData
.map { it.followedTopics } .map { it.followedTopics }
.first() .first()
) )
assertEquals( assertEquals(
niaPreferencesDataSource.userDataStream niaPreferencesDataSource.userData
.map { it.followedTopics } .map { it.followedTopics }
.first(), .first(),
subject.userDataStream subject.userData
.map { it.followedTopics } .map { it.followedTopics }
.first() .first()
) )
@ -84,16 +104,16 @@ class OfflineFirstUserDataRepositoryTest {
assertEquals( assertEquals(
setOf("1", "2"), setOf("1", "2"),
subject.userDataStream subject.userData
.map { it.followedTopics } .map { it.followedTopics }
.first() .first()
) )
assertEquals( assertEquals(
niaPreferencesDataSource.userDataStream niaPreferencesDataSource.userData
.map { it.followedTopics } .map { it.followedTopics }
.first(), .first(),
subject.userDataStream subject.userData
.map { it.followedTopics } .map { it.followedTopics }
.first() .first()
) )
@ -106,7 +126,7 @@ class OfflineFirstUserDataRepositoryTest {
assertEquals( assertEquals(
setOf("0"), setOf("0"),
subject.userDataStream subject.userData
.map { it.bookmarkedNewsResources } .map { it.bookmarkedNewsResources }
.first() .first()
) )
@ -115,18 +135,69 @@ class OfflineFirstUserDataRepositoryTest {
assertEquals( assertEquals(
setOf("0", "1"), setOf("0", "1"),
subject.userDataStream subject.userData
.map { it.bookmarkedNewsResources } .map { it.bookmarkedNewsResources }
.first() .first()
) )
assertEquals( assertEquals(
niaPreferencesDataSource.userDataStream niaPreferencesDataSource.userData
.map { it.bookmarkedNewsResources } .map { it.bookmarkedNewsResources }
.first(), .first(),
subject.userDataStream subject.userData
.map { it.bookmarkedNewsResources } .map { it.bookmarkedNewsResources }
.first() .first()
) )
} }
@Test
fun offlineFirstUserDataRepository_set_theme_brand_delegates_to_nia_preferences() =
runTest {
subject.setThemeBrand(ThemeBrand.ANDROID)
assertEquals(
ThemeBrand.ANDROID,
subject.userData
.map { it.themeBrand }
.first()
)
assertEquals(
ThemeBrand.ANDROID,
niaPreferencesDataSource
.userData
.map { it.themeBrand }
.first()
)
}
@Test
fun offlineFirstUserDataRepository_set_dark_theme_config_delegates_to_nia_preferences() =
runTest {
subject.setDarkThemeConfig(DarkThemeConfig.DARK)
assertEquals(
DarkThemeConfig.DARK,
subject.userData
.map { it.darkThemeConfig }
.first()
)
assertEquals(
DarkThemeConfig.DARK,
niaPreferencesDataSource
.userData
.map { it.darkThemeConfig }
.first()
)
}
@Test
fun whenUserCompletesOnboarding_thenRemovesAllInterests_shouldHideOnboardingIsFalse() =
runTest {
subject.setFollowedTopicIds(setOf("1"))
subject.setShouldHideOnboarding(true)
assertTrue(subject.userData.first().shouldHideOnboarding)
subject.setFollowedTopicIds(emptySet())
assertFalse(subject.userData.first().shouldHideOnboarding)
}
} }

@ -1,70 +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.core.data.testdoubles
import com.google.samples.apps.nowinandroid.core.database.dao.AuthorDao
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
/**
* Test double for [AuthorDao]
*/
class TestAuthorDao : AuthorDao {
private var entitiesStateFlow = MutableStateFlow(
listOf(
AuthorEntity(
id = "1",
name = "Topic",
imageUrl = "imageUrl",
twitter = "twitter",
mediumPage = "mediumPage",
bio = "bio",
)
)
)
override fun getAuthorEntitiesStream(): Flow<List<AuthorEntity>> =
entitiesStateFlow
override fun getAuthorEntityStream(authorId: String): Flow<AuthorEntity> {
throw NotImplementedError("Unused in tests")
}
override suspend fun insertOrIgnoreAuthors(authorEntities: List<AuthorEntity>): List<Long> {
entitiesStateFlow.value = authorEntities
// Assume no conflicts on insert
return authorEntities.map { it.id.toLong() }
}
override suspend fun updateAuthors(entities: List<AuthorEntity>) {
throw NotImplementedError("Unused in tests")
}
override suspend fun upsertAuthors(entities: List<AuthorEntity>) {
entitiesStateFlow.value = entities
}
override suspend fun deleteAuthors(ids: List<String>) {
val idSet = ids.toSet()
entitiesStateFlow.update { entities ->
entities.filterNot { idSet.contains(it.id) }
}
}
}

@ -17,8 +17,6 @@
package com.google.samples.apps.nowinandroid.core.data.testdoubles package com.google.samples.apps.nowinandroid.core.data.testdoubles
import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceAuthorCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource
@ -54,22 +52,18 @@ class TestNewsResourceDao : NewsResourceDao {
internal var topicCrossReferences: List<NewsResourceTopicCrossRef> = listOf() internal var topicCrossReferences: List<NewsResourceTopicCrossRef> = listOf()
internal var authorCrossReferences: List<NewsResourceAuthorCrossRef> = listOf() override fun getNewsResources(): Flow<List<PopulatedNewsResource>> =
override fun getNewsResourcesStream(): Flow<List<PopulatedNewsResource>> =
entitiesStateFlow.map { entitiesStateFlow.map {
it.map(NewsResourceEntity::asPopulatedNewsResource) it.map(NewsResourceEntity::asPopulatedNewsResource)
} }
override fun getNewsResourcesStream( override fun getNewsResources(
filterAuthorIds: Set<String>,
filterTopicIds: Set<String> filterTopicIds: Set<String>
): Flow<List<PopulatedNewsResource>> = ): Flow<List<PopulatedNewsResource>> =
getNewsResourcesStream() getNewsResources()
.map { resources -> .map { resources ->
resources.filter { resource -> resources.filter { resource ->
resource.topics.any { it.id in filterTopicIds } || resource.topics.any { it.id in filterTopicIds }
resource.authors.any { it.id in filterAuthorIds }
} }
} }
@ -95,12 +89,6 @@ class TestNewsResourceDao : NewsResourceDao {
topicCrossReferences = newsResourceTopicCrossReferences topicCrossReferences = newsResourceTopicCrossReferences
} }
override suspend fun insertOrIgnoreAuthorCrossRefEntities(
newsResourceAuthorCrossReferences: List<NewsResourceAuthorCrossRef>
) {
authorCrossReferences = newsResourceAuthorCrossReferences
}
override suspend fun deleteNewsResources(ids: List<String>) { override suspend fun deleteNewsResources(ids: List<String>) {
val idSet = ids.toSet() val idSet = ids.toSet()
entitiesStateFlow.update { entities -> entitiesStateFlow.update { entities ->
@ -111,16 +99,6 @@ class TestNewsResourceDao : NewsResourceDao {
private fun NewsResourceEntity.asPopulatedNewsResource() = PopulatedNewsResource( private fun NewsResourceEntity.asPopulatedNewsResource() = PopulatedNewsResource(
entity = this, entity = this,
authors = listOf(
AuthorEntity(
id = "id",
name = "name",
imageUrl = "imageUrl",
twitter = "twitter",
mediumPage = "mediumPage",
bio = "bio",
)
),
topics = listOf( topics = listOf(
TopicEntity( TopicEntity(
id = filteredInterestsIds.random(), id = filteredInterestsIds.random(),

@ -17,17 +17,16 @@
package com.google.samples.apps.nowinandroid.core.data.testdoubles package com.google.samples.apps.nowinandroid.core.data.testdoubles
import com.google.samples.apps.nowinandroid.core.network.NiaNetworkDataSource import com.google.samples.apps.nowinandroid.core.network.NiaNetworkDataSource
import com.google.samples.apps.nowinandroid.core.network.fake.FakeDataSource import com.google.samples.apps.nowinandroid.core.network.fake.FakeNiaNetworkDataSource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor
import com.google.samples.apps.nowinandroid.core.network.model.NetworkChangeList import com.google.samples.apps.nowinandroid.core.network.model.NetworkChangeList
import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic
import kotlinx.serialization.decodeFromString import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
enum class CollectionType { enum class CollectionType {
Topics, Topics,
Authors,
NewsResources NewsResources
} }
@ -36,22 +35,18 @@ enum class CollectionType {
*/ */
class TestNiaNetworkDataSource : NiaNetworkDataSource { class TestNiaNetworkDataSource : NiaNetworkDataSource {
private val networkJson = Json private val source = FakeNiaNetworkDataSource(
UnconfinedTestDispatcher(),
private val allTopics = Json { ignoreUnknownKeys = true }
networkJson.decodeFromString<List<NetworkTopic>>(FakeDataSource.topicsData) )
private val allAuthors = private val allTopics = runBlocking { source.getTopics() }
networkJson.decodeFromString<List<NetworkAuthor>>(FakeDataSource.authors)
private val allNewsResources = private val allNewsResources = runBlocking { source.getNewsResources() }
networkJson.decodeFromString<List<NetworkNewsResource>>(FakeDataSource.data)
private val changeLists: MutableMap<CollectionType, List<NetworkChangeList>> = mutableMapOf( private val changeLists: MutableMap<CollectionType, List<NetworkChangeList>> = mutableMapOf(
CollectionType.Topics to allTopics CollectionType.Topics to allTopics
.mapToChangeList(idGetter = NetworkTopic::id), .mapToChangeList(idGetter = NetworkTopic::id),
CollectionType.Authors to allAuthors
.mapToChangeList(idGetter = NetworkAuthor::id),
CollectionType.NewsResources to allNewsResources CollectionType.NewsResources to allNewsResources
.mapToChangeList(idGetter = NetworkNewsResource::id), .mapToChangeList(idGetter = NetworkNewsResource::id),
) )
@ -62,12 +57,6 @@ class TestNiaNetworkDataSource : NiaNetworkDataSource {
idGetter = NetworkTopic::id idGetter = NetworkTopic::id
) )
override suspend fun getAuthors(ids: List<String>?): List<NetworkAuthor> =
allAuthors.matchIds(
ids = ids,
idGetter = NetworkAuthor::id
)
override suspend fun getNewsResources(ids: List<String>?): List<NetworkNewsResource> = override suspend fun getNewsResources(ids: List<String>?): List<NetworkNewsResource> =
allNewsResources.matchIds( allNewsResources.matchIds(
ids = ids, ids = ids,
@ -77,9 +66,6 @@ class TestNiaNetworkDataSource : NiaNetworkDataSource {
override suspend fun getTopicChangeList(after: Int?): List<NetworkChangeList> = override suspend fun getTopicChangeList(after: Int?): List<NetworkChangeList> =
changeLists.getValue(CollectionType.Topics).after(after) changeLists.getValue(CollectionType.Topics).after(after)
override suspend fun getAuthorChangeList(after: Int?): List<NetworkChangeList> =
changeLists.getValue(CollectionType.Authors).after(after)
override suspend fun getNewsResourceChangeList(after: Int?): List<NetworkChangeList> = override suspend fun getNewsResourceChangeList(after: Int?): List<NetworkChangeList> =
changeLists.getValue(CollectionType.NewsResources).after(after) changeLists.getValue(CollectionType.NewsResources).after(after)

@ -45,11 +45,11 @@ class TestTopicDao : TopicDao {
throw NotImplementedError("Unused in tests") throw NotImplementedError("Unused in tests")
} }
override fun getTopicEntitiesStream(): Flow<List<TopicEntity>> = override fun getTopicEntities(): Flow<List<TopicEntity>> =
entitiesStateFlow entitiesStateFlow
override fun getTopicEntitiesStream(ids: Set<String>): Flow<List<TopicEntity>> = override fun getTopicEntities(ids: Set<String>): Flow<List<TopicEntity>> =
getTopicEntitiesStream() getTopicEntities()
.map { topics -> topics.filter { it.id in ids } } .map { topics -> topics.filter { it.id in ids } }
override suspend fun insertOrIgnoreTopics(topicEntities: List<TopicEntity>): List<Long> { override suspend fun insertOrIgnoreTopics(topicEntities: List<TopicEntity>): List<Long> {

@ -16,12 +16,11 @@
package com.google.samples.apps.nowinandroid.core.database.model package com.google.samples.apps.nowinandroid.core.database.model
import com.google.samples.apps.nowinandroid.core.model.data.Author
import com.google.samples.apps.nowinandroid.core.model.data.NewsResource import com.google.samples.apps.nowinandroid.core.model.data.NewsResource
import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Video import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Video
import com.google.samples.apps.nowinandroid.core.model.data.Topic import com.google.samples.apps.nowinandroid.core.model.data.Topic
import kotlin.test.assertEquals
import kotlinx.datetime.Instant import kotlinx.datetime.Instant
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class PopulatedNewsResourceKtTest { class PopulatedNewsResourceKtTest {
@ -37,16 +36,6 @@ class PopulatedNewsResourceKtTest {
type = Video, type = Video,
publishDate = Instant.fromEpochMilliseconds(1), publishDate = Instant.fromEpochMilliseconds(1),
), ),
authors = listOf(
AuthorEntity(
id = "2",
name = "name",
imageUrl = "imageUrl",
twitter = "twitter",
mediumPage = "mediumPage",
bio = "bio",
)
),
topics = listOf( topics = listOf(
TopicEntity( TopicEntity(
id = "3", id = "3",
@ -69,16 +58,6 @@ class PopulatedNewsResourceKtTest {
headerImageUrl = "headerImageUrl", headerImageUrl = "headerImageUrl",
type = Video, type = Video,
publishDate = Instant.fromEpochMilliseconds(1), publishDate = Instant.fromEpochMilliseconds(1),
authors = listOf(
Author(
id = "2",
name = "name",
imageUrl = "imageUrl",
twitter = "twitter",
mediumPage = "mediumPage",
bio = "bio",
)
),
topics = listOf( topics = listOf(
Topic( Topic(
id = "3", id = "3",

@ -17,7 +17,7 @@
package com.google.samples.apps.nowinandroid.core.database.util package com.google.samples.apps.nowinandroid.core.database.util
import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType
import org.junit.Assert.assertEquals import kotlin.test.assertEquals
import org.junit.Test import org.junit.Test
class NewsResourceTypeConverterTest { class NewsResourceTypeConverterTest {

@ -0,0 +1,192 @@
{
"formatVersion": 1,
"database": {
"version": 12,
"identityHash": "f83b94b22ba0a0ce640922a3475e7c3e",
"entities": [
{
"tableName": "news_resources",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `title` TEXT NOT NULL, `content` TEXT NOT NULL, `url` TEXT NOT NULL, `header_image_url` TEXT, `publish_date` INTEGER NOT NULL, `type` TEXT NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "title",
"columnName": "title",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "content",
"columnName": "content",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "headerImageUrl",
"columnName": "header_image_url",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "publishDate",
"columnName": "publish_date",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "type",
"columnName": "type",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "news_resources_topics",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`news_resource_id` TEXT NOT NULL, `topic_id` TEXT NOT NULL, PRIMARY KEY(`news_resource_id`, `topic_id`), FOREIGN KEY(`news_resource_id`) REFERENCES `news_resources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`topic_id`) REFERENCES `topics`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "newsResourceId",
"columnName": "news_resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "topicId",
"columnName": "topic_id",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"news_resource_id",
"topic_id"
]
},
"indices": [
{
"name": "index_news_resources_topics_news_resource_id",
"unique": false,
"columnNames": [
"news_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_news_resources_topics_news_resource_id` ON `${TABLE_NAME}` (`news_resource_id`)"
},
{
"name": "index_news_resources_topics_topic_id",
"unique": false,
"columnNames": [
"topic_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_news_resources_topics_topic_id` ON `${TABLE_NAME}` (`topic_id`)"
}
],
"foreignKeys": [
{
"table": "news_resources",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"news_resource_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "topics",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"topic_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "topics",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `shortDescription` TEXT NOT NULL, `longDescription` TEXT NOT NULL DEFAULT '', `url` TEXT NOT NULL DEFAULT '', `imageUrl` TEXT NOT NULL DEFAULT '', PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "shortDescription",
"columnName": "shortDescription",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "longDescription",
"columnName": "longDescription",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "imageUrl",
"columnName": "imageUrl",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'f83b94b22ba0a0ce640922a3475e7c3e')"
]
}
}

@ -20,17 +20,15 @@ import android.content.Context
import androidx.room.Room import androidx.room.Room
import androidx.test.core.app.ApplicationProvider import androidx.test.core.app.ApplicationProvider
import com.google.samples.apps.nowinandroid.core.database.NiaDatabase import com.google.samples.apps.nowinandroid.core.database.NiaDatabase
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceAuthorCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity
import com.google.samples.apps.nowinandroid.core.database.model.asExternalModel import com.google.samples.apps.nowinandroid.core.database.model.asExternalModel
import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType
import kotlin.test.assertEquals
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import kotlinx.datetime.Instant import kotlinx.datetime.Instant
import org.junit.Assert.assertEquals
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
@ -38,7 +36,6 @@ class NewsResourceDaoTest {
private lateinit var newsResourceDao: NewsResourceDao private lateinit var newsResourceDao: NewsResourceDao
private lateinit var topicDao: TopicDao private lateinit var topicDao: TopicDao
private lateinit var authorDao: AuthorDao
private lateinit var db: NiaDatabase private lateinit var db: NiaDatabase
@Before @Before
@ -50,7 +47,6 @@ class NewsResourceDaoTest {
).build() ).build()
newsResourceDao = db.newsResourceDao() newsResourceDao = db.newsResourceDao()
topicDao = db.topicDao() topicDao = db.topicDao()
authorDao = db.authorDao()
} }
@Test @Test
@ -77,7 +73,7 @@ class NewsResourceDaoTest {
newsResourceEntities newsResourceEntities
) )
val savedNewsResourceEntities = newsResourceDao.getNewsResourcesStream() val savedNewsResourceEntities = newsResourceDao.getNewsResources()
.first() .first()
assertEquals( assertEquals(
@ -135,7 +131,7 @@ class NewsResourceDaoTest {
newsResourceTopicCrossRefEntities newsResourceTopicCrossRefEntities
) )
val filteredNewsResources = newsResourceDao.getNewsResourcesStream( val filteredNewsResources = newsResourceDao.getNewsResources(
filterTopicIds = topicEntities filterTopicIds = topicEntities
.map(TopicEntity::id) .map(TopicEntity::id)
.toSet(), .toSet(),
@ -147,142 +143,6 @@ class NewsResourceDaoTest {
) )
} }
@Test
fun newsResourceDao_filters_items_by_author_ids_by_descending_publish_date() = runTest {
val authorEntities = listOf(
testAuthorEntity(
id = "1",
name = "1"
),
testAuthorEntity(
id = "2",
name = "2"
),
)
val newsResourceEntities = listOf(
testNewsResource(
id = "0",
millisSinceEpoch = 0,
),
testNewsResource(
id = "1",
millisSinceEpoch = 3,
),
testNewsResource(
id = "2",
millisSinceEpoch = 1,
),
testNewsResource(
id = "3",
millisSinceEpoch = 2,
),
)
val newsResourceAuthorCrossRefEntities = authorEntities.mapIndexed { index, authorEntity ->
NewsResourceAuthorCrossRef(
newsResourceId = index.toString(),
authorId = authorEntity.id
)
}
authorDao.upsertAuthors(authorEntities)
newsResourceDao.upsertNewsResources(newsResourceEntities)
newsResourceDao.insertOrIgnoreAuthorCrossRefEntities(newsResourceAuthorCrossRefEntities)
val filteredNewsResources = newsResourceDao.getNewsResourcesStream(
filterAuthorIds = authorEntities
.map(AuthorEntity::id)
.toSet()
).first()
assertEquals(
listOf("1", "0"),
filteredNewsResources.map { it.entity.id }
)
}
@Test
fun newsResourceDao_filters_items_by_topic_ids_or_author_ids_by_descending_publish_date() =
runTest {
val topicEntities = listOf(
testTopicEntity(
id = "1",
name = "1"
),
testTopicEntity(
id = "2",
name = "2"
),
)
val authorEntities = listOf(
testAuthorEntity(
id = "1",
name = "1"
),
testAuthorEntity(
id = "2",
name = "2"
),
)
val newsResourceEntities = listOf(
testNewsResource(
id = "0",
millisSinceEpoch = 0,
),
testNewsResource(
id = "1",
millisSinceEpoch = 3,
),
testNewsResource(
id = "2",
millisSinceEpoch = 1,
),
testNewsResource(
id = "3",
millisSinceEpoch = 2,
),
// Should be missing as no topics or authors match it
testNewsResource(
id = "4",
millisSinceEpoch = 10,
),
)
val newsResourceTopicCrossRefEntities = topicEntities.mapIndexed { index, topicEntity ->
NewsResourceTopicCrossRef(
newsResourceId = index.toString(),
topicId = topicEntity.id
)
}
val newsResourceAuthorCrossRefEntities =
authorEntities.mapIndexed { index, authorEntity ->
NewsResourceAuthorCrossRef(
// Offset news resources by two
newsResourceId = (index + 2).toString(),
authorId = authorEntity.id
)
}
topicDao.upsertTopics(topicEntities)
authorDao.upsertAuthors(authorEntities)
newsResourceDao.upsertNewsResources(newsResourceEntities)
newsResourceDao.insertOrIgnoreTopicCrossRefEntities(newsResourceTopicCrossRefEntities)
newsResourceDao.insertOrIgnoreAuthorCrossRefEntities(newsResourceAuthorCrossRefEntities)
val filteredNewsResources = newsResourceDao.getNewsResourcesStream(
filterTopicIds = topicEntities
.map(TopicEntity::id)
.toSet(),
filterAuthorIds = authorEntities
.map(AuthorEntity::id)
.toSet()
).first()
assertEquals(
listOf("1", "3", "2", "0"),
filteredNewsResources.map { it.entity.id }
)
}
@Test @Test
fun newsResourceDao_deletes_items_by_ids() = fun newsResourceDao_deletes_items_by_ids() =
runTest { runTest {
@ -315,25 +175,13 @@ class NewsResourceDaoTest {
assertEquals( assertEquals(
toKeep.map(NewsResourceEntity::id) toKeep.map(NewsResourceEntity::id)
.toSet(), .toSet(),
newsResourceDao.getNewsResourcesStream().first() newsResourceDao.getNewsResources().first()
.map { it.entity.id } .map { it.entity.id }
.toSet() .toSet()
) )
} }
} }
private fun testAuthorEntity(
id: String = "0",
name: String
) = AuthorEntity(
id = id,
name = name,
imageUrl = "",
twitter = "",
mediumPage = "",
bio = "",
)
private fun testTopicEntity( private fun testTopicEntity(
id: String = "0", id: String = "0",
name: String name: String

@ -16,7 +16,6 @@
package com.google.samples.apps.nowinandroid.core.database package com.google.samples.apps.nowinandroid.core.database
import com.google.samples.apps.nowinandroid.core.database.dao.AuthorDao
import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao
import com.google.samples.apps.nowinandroid.core.database.dao.TopicDao import com.google.samples.apps.nowinandroid.core.database.dao.TopicDao
import dagger.Module import dagger.Module
@ -27,11 +26,6 @@ import dagger.hilt.components.SingletonComponent
@Module @Module
@InstallIn(SingletonComponent::class) @InstallIn(SingletonComponent::class)
object DaosModule { object DaosModule {
@Provides
fun providesAuthorDao(
database: NiaDatabase,
): AuthorDao = database.authorDao()
@Provides @Provides
fun providesTopicsDao( fun providesTopicsDao(
database: NiaDatabase, database: NiaDatabase,

@ -50,4 +50,14 @@ object DatabaseMigrations {
) )
) )
class Schema10to11 : AutoMigrationSpec class Schema10to11 : AutoMigrationSpec
@DeleteTable.Entries(
DeleteTable(
tableName = "news_resources_authors"
),
DeleteTable(
tableName = "authors"
)
)
class Schema11to12 : AutoMigrationSpec
} }

@ -20,11 +20,8 @@ import androidx.room.AutoMigration
import androidx.room.Database import androidx.room.Database
import androidx.room.RoomDatabase import androidx.room.RoomDatabase
import androidx.room.TypeConverters import androidx.room.TypeConverters
import com.google.samples.apps.nowinandroid.core.database.dao.AuthorDao
import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao
import com.google.samples.apps.nowinandroid.core.database.dao.TopicDao import com.google.samples.apps.nowinandroid.core.database.dao.TopicDao
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceAuthorCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity
@ -33,13 +30,11 @@ import com.google.samples.apps.nowinandroid.core.database.util.NewsResourceTypeC
@Database( @Database(
entities = [ entities = [
AuthorEntity::class,
NewsResourceAuthorCrossRef::class,
NewsResourceEntity::class, NewsResourceEntity::class,
NewsResourceTopicCrossRef::class, NewsResourceTopicCrossRef::class,
TopicEntity::class, TopicEntity::class,
], ],
version = 11, version = 12,
autoMigrations = [ autoMigrations = [
AutoMigration(from = 1, to = 2), AutoMigration(from = 1, to = 2),
AutoMigration(from = 2, to = 3, spec = DatabaseMigrations.Schema2to3::class), AutoMigration(from = 2, to = 3, spec = DatabaseMigrations.Schema2to3::class),
@ -50,7 +45,8 @@ import com.google.samples.apps.nowinandroid.core.database.util.NewsResourceTypeC
AutoMigration(from = 7, to = 8), AutoMigration(from = 7, to = 8),
AutoMigration(from = 8, to = 9), AutoMigration(from = 8, to = 9),
AutoMigration(from = 9, to = 10), AutoMigration(from = 9, to = 10),
AutoMigration(from = 10, to = 11, spec = DatabaseMigrations.Schema10to11::class) AutoMigration(from = 10, to = 11, spec = DatabaseMigrations.Schema10to11::class),
AutoMigration(from = 11, to = 12, spec = DatabaseMigrations.Schema11to12::class)
], ],
exportSchema = true, exportSchema = true,
) )
@ -60,6 +56,5 @@ import com.google.samples.apps.nowinandroid.core.database.util.NewsResourceTypeC
) )
abstract class NiaDatabase : RoomDatabase() { abstract class NiaDatabase : RoomDatabase() {
abstract fun topicDao(): TopicDao abstract fun topicDao(): TopicDao
abstract fun authorDao(): AuthorDao
abstract fun newsResourceDao(): NewsResourceDao abstract fun newsResourceDao(): NewsResourceDao
} }

@ -1,72 +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.core.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import androidx.room.Upsert
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import kotlinx.coroutines.flow.Flow
/**
* DAO for [AuthorEntity] access
*/
@Dao
interface AuthorDao {
@Query(
value = """
SELECT * FROM authors
WHERE id = :authorId
"""
)
fun getAuthorEntityStream(authorId: String): Flow<AuthorEntity>
@Query(value = "SELECT * FROM authors")
fun getAuthorEntitiesStream(): Flow<List<AuthorEntity>>
/**
* Inserts [authorEntities] into the db if they don't exist, and ignores those that do
*/
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertOrIgnoreAuthors(authorEntities: List<AuthorEntity>): List<Long>
/**
* Updates [entities] in the db that match the primary key, and no-ops if they don't
*/
@Update
suspend fun updateAuthors(entities: List<AuthorEntity>)
/**
* Inserts or updates [entities] in the db under the specified primary keys
*/
@Upsert
suspend fun upsertAuthors(entities: List<AuthorEntity>)
/**
* Deletes rows in the db matching the specified [ids]
*/
@Query(
value = """
DELETE FROM authors
WHERE id in (:ids)
"""
)
suspend fun deleteAuthors(ids: List<String>)
}

@ -23,7 +23,6 @@ import androidx.room.Query
import androidx.room.Transaction import androidx.room.Transaction
import androidx.room.Update import androidx.room.Update
import androidx.room.Upsert import androidx.room.Upsert
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceAuthorCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource
@ -42,7 +41,7 @@ interface NewsResourceDao {
ORDER BY publish_date DESC ORDER BY publish_date DESC
""" """
) )
fun getNewsResourcesStream(): Flow<List<PopulatedNewsResource>> fun getNewsResources(): Flow<List<PopulatedNewsResource>>
@Transaction @Transaction
@Query( @Query(
@ -53,16 +52,10 @@ interface NewsResourceDao {
SELECT news_resource_id FROM news_resources_topics SELECT news_resource_id FROM news_resources_topics
WHERE topic_id IN (:filterTopicIds) WHERE topic_id IN (:filterTopicIds)
) )
OR id in
(
SELECT news_resource_id FROM news_resources_authors
WHERE author_id IN (:filterAuthorIds)
)
ORDER BY publish_date DESC ORDER BY publish_date DESC
""" """
) )
fun getNewsResourcesStream( fun getNewsResources(
filterAuthorIds: Set<String> = emptySet(),
filterTopicIds: Set<String> = emptySet(), filterTopicIds: Set<String> = emptySet(),
): Flow<List<PopulatedNewsResource>> ): Flow<List<PopulatedNewsResource>>
@ -89,11 +82,6 @@ interface NewsResourceDao {
newsResourceTopicCrossReferences: List<NewsResourceTopicCrossRef> newsResourceTopicCrossReferences: List<NewsResourceTopicCrossRef>
) )
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertOrIgnoreAuthorCrossRefEntities(
newsResourceAuthorCrossReferences: List<NewsResourceAuthorCrossRef>
)
/** /**
* Deletes rows in the db matching the specified [ids] * Deletes rows in the db matching the specified [ids]
*/ */

@ -39,7 +39,7 @@ interface TopicDao {
fun getTopicEntity(topicId: String): Flow<TopicEntity> fun getTopicEntity(topicId: String): Flow<TopicEntity>
@Query(value = "SELECT * FROM topics") @Query(value = "SELECT * FROM topics")
fun getTopicEntitiesStream(): Flow<List<TopicEntity>> fun getTopicEntities(): Flow<List<TopicEntity>>
@Query( @Query(
value = """ value = """
@ -47,7 +47,7 @@ interface TopicDao {
WHERE id IN (:ids) WHERE id IN (:ids)
""" """
) )
fun getTopicEntitiesStream(ids: Set<String>): Flow<List<TopicEntity>> fun getTopicEntities(ids: Set<String>): Flow<List<TopicEntity>>
/** /**
* Inserts [topicEntities] into the db if they don't exist, and ignores those that do * Inserts [topicEntities] into the db if they don't exist, and ignores those that do

@ -1,52 +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.core.database.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.samples.apps.nowinandroid.core.model.data.Author
/**
* Defines an author for [NewsResourceEntity].
* It has a many to many relationship with both entities
*/
@Entity(
tableName = "authors",
)
data class AuthorEntity(
@PrimaryKey
val id: String,
val name: String,
@ColumnInfo(name = "image_url")
val imageUrl: String,
@ColumnInfo(defaultValue = "")
val twitter: String,
@ColumnInfo(name = "medium_page", defaultValue = "")
val mediumPage: String,
@ColumnInfo(defaultValue = "")
val bio: String,
)
fun AuthorEntity.asExternalModel() = Author(
id = id,
name = name,
imageUrl = imageUrl,
twitter = twitter,
mediumPage = mediumPage,
bio = bio,
)

@ -1,54 +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.core.database.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
/**
* Cross reference for many to many relationship between [NewsResourceEntity] and [AuthorEntity]
*/
@Entity(
tableName = "news_resources_authors",
primaryKeys = ["news_resource_id", "author_id"],
foreignKeys = [
ForeignKey(
entity = NewsResourceEntity::class,
parentColumns = ["id"],
childColumns = ["news_resource_id"],
onDelete = ForeignKey.CASCADE
),
ForeignKey(
entity = AuthorEntity::class,
parentColumns = ["id"],
childColumns = ["author_id"],
onDelete = ForeignKey.CASCADE
),
],
indices = [
Index(value = ["news_resource_id"]),
Index(value = ["author_id"]),
],
)
data class NewsResourceAuthorCrossRef(
@ColumnInfo(name = "news_resource_id")
val newsResourceId: String,
@ColumnInfo(name = "author_id")
val authorId: String,
)

@ -50,6 +50,5 @@ fun NewsResourceEntity.asExternalModel() = NewsResource(
headerImageUrl = headerImageUrl, headerImageUrl = headerImageUrl,
publishDate = publishDate, publishDate = publishDate,
type = type, type = type,
authors = listOf(),
topics = listOf() topics = listOf()
) )

@ -27,16 +27,6 @@ import com.google.samples.apps.nowinandroid.core.model.data.NewsResource
data class PopulatedNewsResource( data class PopulatedNewsResource(
@Embedded @Embedded
val entity: NewsResourceEntity, val entity: NewsResourceEntity,
@Relation(
parentColumn = "id",
entityColumn = "id",
associateBy = Junction(
value = NewsResourceAuthorCrossRef::class,
parentColumn = "news_resource_id",
entityColumn = "author_id",
)
)
val authors: List<AuthorEntity>,
@Relation( @Relation(
parentColumn = "id", parentColumn = "id",
entityColumn = "id", entityColumn = "id",
@ -57,6 +47,5 @@ fun PopulatedNewsResource.asExternalModel() = NewsResource(
headerImageUrl = entity.headerImageUrl, headerImageUrl = entity.headerImageUrl,
publishDate = entity.publishDate, publishDate = entity.publishDate,
type = entity.type, type = entity.type,
authors = authors.map(AuthorEntity::asExternalModel),
topics = topics.map(TopicEntity::asExternalModel) topics = topics.map(TopicEntity::asExternalModel)
) )

@ -59,6 +59,7 @@ dependencies {
implementation(project(":core:model")) implementation(project(":core:model"))
testImplementation(project(":core:testing")) testImplementation(project(":core:testing"))
testImplementation(project(":core:datastore-test"))
implementation(libs.kotlinx.coroutines.android) implementation(libs.kotlinx.coroutines.android)

@ -21,6 +21,5 @@ package com.google.samples.apps.nowinandroid.core.datastore
*/ */
data class ChangeListVersions( data class ChangeListVersions(
val topicVersion: Int = -1, val topicVersion: Int = -1,
val authorVersion: Int = -1,
val newsResourceVersion: Int = -1, val newsResourceVersion: Int = -1,
) )

@ -18,6 +18,8 @@ package com.google.samples.apps.nowinandroid.core.datastore
import android.util.Log import android.util.Log
import androidx.datastore.core.DataStore import androidx.datastore.core.DataStore
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.model.data.UserData
import java.io.IOException import java.io.IOException
import javax.inject.Inject import javax.inject.Inject
@ -28,12 +30,29 @@ class NiaPreferencesDataSource @Inject constructor(
private val userPreferences: DataStore<UserPreferences> private val userPreferences: DataStore<UserPreferences>
) { ) {
val userDataStream = userPreferences.data val userData = userPreferences.data
.map { .map {
UserData( UserData(
bookmarkedNewsResources = it.bookmarkedNewsResourceIdsMap.keys, bookmarkedNewsResources = it.bookmarkedNewsResourceIdsMap.keys,
followedTopics = it.followedTopicIdsMap.keys, followedTopics = it.followedTopicIdsMap.keys,
followedAuthors = it.followedAuthorIdsMap.keys, 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) {
null,
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
},
shouldHideOnboarding = it.shouldHideOnboarding
) )
} }
@ -43,6 +62,7 @@ class NiaPreferencesDataSource @Inject constructor(
it.copy { it.copy {
followedTopicIds.clear() followedTopicIds.clear()
followedTopicIds.putAll(topicIds.associateWith { true }) followedTopicIds.putAll(topicIds.associateWith { true })
updateShouldHideOnboardingIfNecessary()
} }
} }
} catch (ioException: IOException) { } catch (ioException: IOException) {
@ -59,6 +79,7 @@ class NiaPreferencesDataSource @Inject constructor(
} else { } else {
followedTopicIds.remove(topicId) followedTopicIds.remove(topicId)
} }
updateShouldHideOnboardingIfNecessary()
} }
} }
} catch (ioException: IOException) { } catch (ioException: IOException) {
@ -66,32 +87,27 @@ class NiaPreferencesDataSource @Inject constructor(
} }
} }
suspend fun setFollowedAuthorIds(authorIds: Set<String>) { suspend fun setThemeBrand(themeBrand: ThemeBrand) {
try { userPreferences.updateData {
userPreferences.updateData { it.copy {
it.copy { this.themeBrand = when (themeBrand) {
followedAuthorIds.clear() ThemeBrand.DEFAULT -> ThemeBrandProto.THEME_BRAND_DEFAULT
followedAuthorIds.putAll(authorIds.associateWith { true }) ThemeBrand.ANDROID -> ThemeBrandProto.THEME_BRAND_ANDROID
} }
} }
} catch (ioException: IOException) {
Log.e("NiaPreferences", "Failed to update user preferences", ioException)
} }
} }
suspend fun toggleFollowedAuthorId(authorId: String, followed: Boolean) { suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) {
try { userPreferences.updateData {
userPreferences.updateData { it.copy {
it.copy { this.darkThemeConfig = when (darkThemeConfig) {
if (followed) { DarkThemeConfig.FOLLOW_SYSTEM ->
followedAuthorIds.put(authorId, true) DarkThemeConfigProto.DARK_THEME_CONFIG_FOLLOW_SYSTEM
} else { DarkThemeConfig.LIGHT -> DarkThemeConfigProto.DARK_THEME_CONFIG_LIGHT
followedAuthorIds.remove(authorId) DarkThemeConfig.DARK -> DarkThemeConfigProto.DARK_THEME_CONFIG_DARK
}
} }
} }
} catch (ioException: IOException) {
Log.e("NiaPreferences", "Failed to update user preferences", ioException)
} }
} }
@ -115,7 +131,6 @@ class NiaPreferencesDataSource @Inject constructor(
.map { .map {
ChangeListVersions( ChangeListVersions(
topicVersion = it.topicChangeListVersion, topicVersion = it.topicChangeListVersion,
authorVersion = it.authorChangeListVersion,
newsResourceVersion = it.newsResourceChangeListVersion, newsResourceVersion = it.newsResourceChangeListVersion,
) )
} }
@ -130,14 +145,12 @@ class NiaPreferencesDataSource @Inject constructor(
val updatedChangeListVersions = update( val updatedChangeListVersions = update(
ChangeListVersions( ChangeListVersions(
topicVersion = currentPreferences.topicChangeListVersion, topicVersion = currentPreferences.topicChangeListVersion,
authorVersion = currentPreferences.authorChangeListVersion,
newsResourceVersion = currentPreferences.newsResourceChangeListVersion newsResourceVersion = currentPreferences.newsResourceChangeListVersion
) )
) )
currentPreferences.copy { currentPreferences.copy {
topicChangeListVersion = updatedChangeListVersions.topicVersion topicChangeListVersion = updatedChangeListVersions.topicVersion
authorChangeListVersion = updatedChangeListVersions.authorVersion
newsResourceChangeListVersion = updatedChangeListVersions.newsResourceVersion newsResourceChangeListVersion = updatedChangeListVersions.newsResourceVersion
} }
} }
@ -145,4 +158,19 @@ class NiaPreferencesDataSource @Inject constructor(
Log.e("NiaPreferences", "Failed to update user preferences", ioException) Log.e("NiaPreferences", "Failed to update user preferences", ioException)
} }
} }
suspend fun setShouldHideOnboarding(shouldHideOnboarding: Boolean) {
userPreferences.updateData {
it.copy {
this.shouldHideOnboarding = shouldHideOnboarding
}
}
}
}
private fun UserPreferencesKt.Dsl.updateShouldHideOnboardingIfNecessary() {
if (followedTopicIds.isEmpty() && followedAuthorIds.isEmpty()) {
shouldHideOnboarding = false
}
} }

@ -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;
}

@ -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;
}

@ -16,6 +16,9 @@
syntax = "proto3"; 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_package = "com.google.samples.apps.nowinandroid.core.datastore";
option java_multiple_files = true; option java_multiple_files = true;
@ -37,4 +40,9 @@ message UserPreferences {
map<string, bool> followed_topic_ids = 13; map<string, bool> followed_topic_ids = 13;
map<string, bool> followed_author_ids = 14; map<string, bool> followed_author_ids = 14;
map<string, bool> bookmarked_news_resource_ids = 15; map<string, bool> bookmarked_news_resource_ids = 15;
ThemeBrandProto theme_brand = 16;
DarkThemeConfigProto dark_theme_config = 17;
bool should_hide_onboarding = 18;
} }

@ -16,9 +16,9 @@
package com.google.samples.apps.nowinandroid.core.datastore package com.google.samples.apps.nowinandroid.core.datastore
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
/** /**

@ -16,8 +16,9 @@
package com.google.samples.apps.nowinandroid.core.datastore package com.google.samples.apps.nowinandroid.core.datastore
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Test import org.junit.Test
class ListToMapMigrationTest { class ListToMapMigrationTest {
@ -29,7 +30,7 @@ class ListToMapMigrationTest {
deprecatedFollowedTopicIds.addAll(listOf("1", "2", "3")) deprecatedFollowedTopicIds.addAll(listOf("1", "2", "3"))
} }
// Assert that there are no topic ids in the map yet // Assert that there are no topic ids in the map yet
Assert.assertEquals( assertEquals(
emptyMap<String, Boolean>(), emptyMap<String, Boolean>(),
preMigrationUserPreferences.followedTopicIdsMap preMigrationUserPreferences.followedTopicIdsMap
) )
@ -39,13 +40,13 @@ class ListToMapMigrationTest {
ListToMapMigration.migrate(preMigrationUserPreferences) ListToMapMigration.migrate(preMigrationUserPreferences)
// Assert the deprecated topic ids have been migrated to the topic ids map // Assert the deprecated topic ids have been migrated to the topic ids map
Assert.assertEquals( assertEquals(
mapOf("1" to true, "2" to true, "3" to true), mapOf("1" to true, "2" to true, "3" to true),
postMigrationUserPreferences.followedTopicIdsMap postMigrationUserPreferences.followedTopicIdsMap
) )
// Assert that the migration has been marked complete // Assert that the migration has been marked complete
Assert.assertTrue(postMigrationUserPreferences.hasDoneListToMapMigration) assertTrue(postMigrationUserPreferences.hasDoneListToMapMigration)
} }
@Test @Test
@ -55,7 +56,7 @@ class ListToMapMigrationTest {
deprecatedFollowedAuthorIds.addAll(listOf("4", "5", "6")) deprecatedFollowedAuthorIds.addAll(listOf("4", "5", "6"))
} }
// Assert that there are no author ids in the map yet // Assert that there are no author ids in the map yet
Assert.assertEquals( assertEquals(
emptyMap<String, Boolean>(), emptyMap<String, Boolean>(),
preMigrationUserPreferences.followedAuthorIdsMap preMigrationUserPreferences.followedAuthorIdsMap
) )
@ -65,13 +66,13 @@ class ListToMapMigrationTest {
ListToMapMigration.migrate(preMigrationUserPreferences) ListToMapMigration.migrate(preMigrationUserPreferences)
// Assert the deprecated author ids have been migrated to the author ids map // Assert the deprecated author ids have been migrated to the author ids map
Assert.assertEquals( assertEquals(
mapOf("4" to true, "5" to true, "6" to true), mapOf("4" to true, "5" to true, "6" to true),
postMigrationUserPreferences.followedAuthorIdsMap postMigrationUserPreferences.followedAuthorIdsMap
) )
// Assert that the migration has been marked complete // Assert that the migration has been marked complete
Assert.assertTrue(postMigrationUserPreferences.hasDoneListToMapMigration) assertTrue(postMigrationUserPreferences.hasDoneListToMapMigration)
} }
@Test @Test
@ -81,7 +82,7 @@ class ListToMapMigrationTest {
deprecatedBookmarkedNewsResourceIds.addAll(listOf("7", "8", "9")) deprecatedBookmarkedNewsResourceIds.addAll(listOf("7", "8", "9"))
} }
// Assert that there are no bookmarks in the map yet // Assert that there are no bookmarks in the map yet
Assert.assertEquals( assertEquals(
emptyMap<String, Boolean>(), emptyMap<String, Boolean>(),
preMigrationUserPreferences.bookmarkedNewsResourceIdsMap preMigrationUserPreferences.bookmarkedNewsResourceIdsMap
) )
@ -91,12 +92,12 @@ class ListToMapMigrationTest {
ListToMapMigration.migrate(preMigrationUserPreferences) ListToMapMigration.migrate(preMigrationUserPreferences)
// Assert the deprecated bookmarks have been migrated to the bookmarks map // Assert the deprecated bookmarks have been migrated to the bookmarks map
Assert.assertEquals( assertEquals(
mapOf("7" to true, "8" to true, "9" to true), mapOf("7" to true, "8" to true, "9" to true),
postMigrationUserPreferences.bookmarkedNewsResourceIdsMap postMigrationUserPreferences.bookmarkedNewsResourceIdsMap
) )
// Assert that the migration has been marked complete // Assert that the migration has been marked complete
Assert.assertTrue(postMigrationUserPreferences.hasDoneListToMapMigration) assertTrue(postMigrationUserPreferences.hasDoneListToMapMigration)
} }
} }

@ -0,0 +1,80 @@
/*
* 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.datastore
import com.google.samples.apps.nowinandroid.core.datastore.test.testUserPreferencesDataStore
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class NiaPreferencesDataSourceTest {
private lateinit var subject: NiaPreferencesDataSource
@get:Rule
val tmpFolder: TemporaryFolder = TemporaryFolder.builder().assureDeletion().build()
@Before
fun setup() {
subject = NiaPreferencesDataSource(
tmpFolder.testUserPreferencesDataStore()
)
}
@Test
fun shouldHideOnboardingIsFalseByDefault() = runTest {
assertFalse(subject.userData.first().shouldHideOnboarding)
}
@Test
fun userShouldHideOnboardingIsTrueWhenSet() = runTest {
subject.setShouldHideOnboarding(true)
assertTrue(subject.userData.first().shouldHideOnboarding)
}
@Test
fun userShouldHideOnboarding_unfollowsLastTopic_shouldHideOnboardingIsFalse() = runTest {
// Given: user completes onboarding by selecting a single topic.
subject.toggleFollowedTopicId("1", true)
subject.setShouldHideOnboarding(true)
// When: they unfollow that topic.
subject.toggleFollowedTopicId("1", false)
// Then: onboarding should be shown again
assertFalse(subject.userData.first().shouldHideOnboarding)
}
@Test
fun userShouldHideOnboarding_unfollowsAllTopics_shouldHideOnboardingIsFalse() = runTest {
// Given: user completes onboarding by selecting several topics.
subject.setFollowedTopicIds(setOf("1", "2"))
subject.setShouldHideOnboarding(true)
// When: they unfollow those topics.
subject.setFollowedTopicIds(emptySet())
// Then: onboarding should be shown again
assertFalse(subject.userData.first().shouldHideOnboarding)
}
}

@ -19,8 +19,8 @@ package com.google.samples.apps.nowinandroid.core.datastore
import androidx.datastore.core.CorruptionException import androidx.datastore.core.CorruptionException
import java.io.ByteArrayInputStream import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import kotlin.test.assertEquals
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class UserPreferencesSerializerTest { class UserPreferencesSerializerTest {

@ -41,10 +41,4 @@ dependencies {
api(libs.androidx.compose.runtime) api(libs.androidx.compose.runtime)
lintPublish(project(":lint")) lintPublish(project(":lint"))
androidTestImplementation(project(":core:testing")) androidTestImplementation(project(":core:testing"))
// TODO : Remove these dependency once we upgrade to Android Studio Dolphin b/228889042
// These dependencies are currently necessary to render Compose previews
debugImplementation(libs.androidx.customview.poolingcontainer)
debugImplementation(libs.androidx.lifecycle.viewModelCompose)
debugImplementation(libs.androidx.savedstate.ktx)
} }

@ -21,28 +21,31 @@ import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.google.samples.apps.nowinandroid.core.designsystem.theme.BackgroundTheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.BackgroundTheme
import com.google.samples.apps.nowinandroid.core.designsystem.theme.DarkAndroidBackgroundTheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.DarkAndroidBackgroundTheme
import com.google.samples.apps.nowinandroid.core.designsystem.theme.DarkAndroidColorScheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.DarkAndroidColorScheme
import com.google.samples.apps.nowinandroid.core.designsystem.theme.DarkAndroidGradientColors
import com.google.samples.apps.nowinandroid.core.designsystem.theme.DarkDefaultColorScheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.DarkDefaultColorScheme
import com.google.samples.apps.nowinandroid.core.designsystem.theme.GradientColors import com.google.samples.apps.nowinandroid.core.designsystem.theme.GradientColors
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LightAndroidBackgroundTheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.LightAndroidBackgroundTheme
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LightAndroidColorScheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.LightAndroidColorScheme
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LightAndroidGradientColors
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LightDefaultColorScheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.LightDefaultColorScheme
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LightDefaultGradientColors
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LocalBackgroundTheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.LocalBackgroundTheme
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LocalGradientColors import com.google.samples.apps.nowinandroid.core.designsystem.theme.LocalGradientColors
import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme
import org.junit.Assert.assertEquals import kotlin.test.assertEquals
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
/** /**
* Tests [NiaTheme] using different combinations of the theme mode parameters: * Tests [NiaTheme] using different combinations of the theme mode parameters:
* darkTheme, dynamicColor, and androidTheme. * darkTheme, disableDynamicTheming, and androidTheme.
* *
* It verifies that the various composition locals [MaterialTheme], [LocalGradientColors] and * It verifies that the various composition locals [MaterialTheme], [LocalGradientColors] and
* [LocalBackgroundTheme] have the expected values for a given theme mode, as specified by the * [LocalBackgroundTheme] have the expected values for a given theme mode, as specified by the
@ -58,17 +61,14 @@ class ThemeTest {
composeTestRule.setContent { composeTestRule.setContent {
NiaTheme( NiaTheme(
darkTheme = false, darkTheme = false,
dynamicColor = false, disableDynamicTheming = true,
androidTheme = false androidTheme = false
) { ) {
val colorScheme = LightDefaultColorScheme val colorScheme = LightDefaultColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val gradientColors = LightDefaultGradientColors val gradientColors = defaultGradientColors(colorScheme)
assertEquals(gradientColors, LocalGradientColors.current) assertEquals(gradientColors, LocalGradientColors.current)
val backgroundTheme = BackgroundTheme( val backgroundTheme = defaultBackgroundTheme(colorScheme)
color = colorScheme.surface,
tonalElevation = 2.dp
)
assertEquals(backgroundTheme, LocalBackgroundTheme.current) assertEquals(backgroundTheme, LocalBackgroundTheme.current)
} }
} }
@ -79,17 +79,14 @@ class ThemeTest {
composeTestRule.setContent { composeTestRule.setContent {
NiaTheme( NiaTheme(
darkTheme = true, darkTheme = true,
dynamicColor = false, disableDynamicTheming = true,
androidTheme = false androidTheme = false
) { ) {
val colorScheme = DarkDefaultColorScheme val colorScheme = DarkDefaultColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val gradientColors = GradientColors() val gradientColors = defaultGradientColors(colorScheme)
assertEquals(gradientColors, LocalGradientColors.current) assertEquals(gradientColors, LocalGradientColors.current)
val backgroundTheme = BackgroundTheme( val backgroundTheme = defaultBackgroundTheme(colorScheme)
color = colorScheme.surface,
tonalElevation = 2.dp
)
assertEquals(backgroundTheme, LocalBackgroundTheme.current) assertEquals(backgroundTheme, LocalBackgroundTheme.current)
} }
} }
@ -100,25 +97,13 @@ class ThemeTest {
composeTestRule.setContent { composeTestRule.setContent {
NiaTheme( NiaTheme(
darkTheme = false, darkTheme = false,
dynamicColor = true,
androidTheme = false androidTheme = false
) { ) {
val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val colorScheme = dynamicLightColorSchemeWithFallback()
dynamicLightColorScheme(LocalContext.current)
} else {
LightDefaultColorScheme
}
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val gradientColors = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val gradientColors = dynamicGradientColorsWithFallback(colorScheme)
GradientColors()
} else {
LightDefaultGradientColors
}
assertEquals(gradientColors, LocalGradientColors.current) assertEquals(gradientColors, LocalGradientColors.current)
val backgroundTheme = BackgroundTheme( val backgroundTheme = defaultBackgroundTheme(colorScheme)
color = colorScheme.surface,
tonalElevation = 2.dp
)
assertEquals(backgroundTheme, LocalBackgroundTheme.current) assertEquals(backgroundTheme, LocalBackgroundTheme.current)
} }
} }
@ -129,21 +114,13 @@ class ThemeTest {
composeTestRule.setContent { composeTestRule.setContent {
NiaTheme( NiaTheme(
darkTheme = true, darkTheme = true,
dynamicColor = true,
androidTheme = false androidTheme = false
) { ) {
val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val colorScheme = dynamicDarkColorSchemeWithFallback()
dynamicDarkColorScheme(LocalContext.current)
} else {
DarkDefaultColorScheme
}
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val gradientColors = GradientColors() val gradientColors = dynamicGradientColorsWithFallback(colorScheme)
assertEquals(gradientColors, LocalGradientColors.current) assertEquals(gradientColors, LocalGradientColors.current)
val backgroundTheme = BackgroundTheme( val backgroundTheme = defaultBackgroundTheme(colorScheme)
color = colorScheme.surface,
tonalElevation = 2.dp
)
assertEquals(backgroundTheme, LocalBackgroundTheme.current) assertEquals(backgroundTheme, LocalBackgroundTheme.current)
} }
} }
@ -154,12 +131,12 @@ class ThemeTest {
composeTestRule.setContent { composeTestRule.setContent {
NiaTheme( NiaTheme(
darkTheme = false, darkTheme = false,
dynamicColor = false, disableDynamicTheming = true,
androidTheme = true androidTheme = true
) { ) {
val colorScheme = LightAndroidColorScheme val colorScheme = LightAndroidColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val gradientColors = GradientColors() val gradientColors = LightAndroidGradientColors
assertEquals(gradientColors, LocalGradientColors.current) assertEquals(gradientColors, LocalGradientColors.current)
val backgroundTheme = LightAndroidBackgroundTheme val backgroundTheme = LightAndroidBackgroundTheme
assertEquals(backgroundTheme, LocalBackgroundTheme.current) assertEquals(backgroundTheme, LocalBackgroundTheme.current)
@ -172,12 +149,12 @@ class ThemeTest {
composeTestRule.setContent { composeTestRule.setContent {
NiaTheme( NiaTheme(
darkTheme = true, darkTheme = true,
dynamicColor = false, disableDynamicTheming = true,
androidTheme = true androidTheme = true
) { ) {
val colorScheme = DarkAndroidColorScheme val colorScheme = DarkAndroidColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val gradientColors = GradientColors() val gradientColors = DarkAndroidGradientColors
assertEquals(gradientColors, LocalGradientColors.current) assertEquals(gradientColors, LocalGradientColors.current)
val backgroundTheme = DarkAndroidBackgroundTheme val backgroundTheme = DarkAndroidBackgroundTheme
assertEquals(backgroundTheme, LocalBackgroundTheme.current) assertEquals(backgroundTheme, LocalBackgroundTheme.current)
@ -190,25 +167,13 @@ class ThemeTest {
composeTestRule.setContent { composeTestRule.setContent {
NiaTheme( NiaTheme(
darkTheme = false, darkTheme = false,
dynamicColor = true,
androidTheme = true androidTheme = true
) { ) {
val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val colorScheme = LightAndroidColorScheme
dynamicLightColorScheme(LocalContext.current)
} else {
LightDefaultColorScheme
}
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val gradientColors = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val gradientColors = LightAndroidGradientColors
GradientColors()
} else {
LightDefaultGradientColors
}
assertEquals(gradientColors, LocalGradientColors.current) assertEquals(gradientColors, LocalGradientColors.current)
val backgroundTheme = BackgroundTheme( val backgroundTheme = LightAndroidBackgroundTheme
color = colorScheme.surface,
tonalElevation = 2.dp
)
assertEquals(backgroundTheme, LocalBackgroundTheme.current) assertEquals(backgroundTheme, LocalBackgroundTheme.current)
} }
} }
@ -219,26 +184,63 @@ class ThemeTest {
composeTestRule.setContent { composeTestRule.setContent {
NiaTheme( NiaTheme(
darkTheme = true, darkTheme = true,
dynamicColor = true,
androidTheme = true androidTheme = true
) { ) {
val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val colorScheme = DarkAndroidColorScheme
dynamicDarkColorScheme(LocalContext.current)
} else {
DarkDefaultColorScheme
}
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val gradientColors = GradientColors() val gradientColors = DarkAndroidGradientColors
assertEquals(gradientColors, LocalGradientColors.current) assertEquals(gradientColors, LocalGradientColors.current)
val backgroundTheme = BackgroundTheme( val backgroundTheme = DarkAndroidBackgroundTheme
color = colorScheme.surface,
tonalElevation = 2.dp
)
assertEquals(backgroundTheme, LocalBackgroundTheme.current) assertEquals(backgroundTheme, LocalBackgroundTheme.current)
} }
} }
} }
@Composable
private fun dynamicLightColorSchemeWithFallback(): ColorScheme {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
dynamicLightColorScheme(LocalContext.current)
} else {
LightDefaultColorScheme
}
}
@Composable
private fun dynamicDarkColorSchemeWithFallback(): ColorScheme {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
dynamicDarkColorScheme(LocalContext.current)
} else {
DarkDefaultColorScheme
}
}
private fun emptyGradientColors(colorScheme: ColorScheme): GradientColors {
return GradientColors(container = colorScheme.surfaceColorAtElevation(2.dp))
}
private fun defaultGradientColors(colorScheme: ColorScheme): GradientColors {
return GradientColors(
top = colorScheme.inverseOnSurface,
bottom = colorScheme.primaryContainer,
container = colorScheme.surface
)
}
private fun dynamicGradientColorsWithFallback(colorScheme: ColorScheme): GradientColors {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
emptyGradientColors(colorScheme)
} else {
defaultGradientColors(colorScheme)
}
}
private fun defaultBackgroundTheme(colorScheme: ColorScheme): BackgroundTheme {
return BackgroundTheme(
color = colorScheme.surface,
tonalElevation = 2.dp
)
}
/** /**
* Workaround for the fact that the NiA design system specify all color scheme values. * Workaround for the fact that the NiA design system specify all color scheme values.
*/ */
@ -271,6 +273,8 @@ class ThemeTest {
assertEquals(expectedColorScheme.onSurface, actualColorScheme.onSurface) assertEquals(expectedColorScheme.onSurface, actualColorScheme.onSurface)
assertEquals(expectedColorScheme.surfaceVariant, actualColorScheme.surfaceVariant) assertEquals(expectedColorScheme.surfaceVariant, actualColorScheme.surfaceVariant)
assertEquals(expectedColorScheme.onSurfaceVariant, actualColorScheme.onSurfaceVariant) assertEquals(expectedColorScheme.onSurfaceVariant, actualColorScheme.onSurfaceVariant)
assertEquals(expectedColorScheme.inverseSurface, actualColorScheme.inverseSurface)
assertEquals(expectedColorScheme.inverseOnSurface, actualColorScheme.inverseOnSurface)
assertEquals(expectedColorScheme.outline, actualColorScheme.outline) assertEquals(expectedColorScheme.outline, actualColorScheme.outline)
} }
} }

@ -34,6 +34,7 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.google.samples.apps.nowinandroid.core.designsystem.theme.GradientColors
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LocalBackgroundTheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.LocalBackgroundTheme
import com.google.samples.apps.nowinandroid.core.designsystem.theme.LocalGradientColors import com.google.samples.apps.nowinandroid.core.designsystem.theme.LocalGradientColors
import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme
@ -41,7 +42,7 @@ import kotlin.math.tan
/** /**
* The main background for the app. * The main background for the app.
* Uses [LocalBackgroundTheme] to set the color and tonal elevation of a [Box]. * Uses [LocalBackgroundTheme] to set the color and tonal elevation of a [Surface].
* *
* @param modifier Modifier to be applied to the background. * @param modifier Modifier to be applied to the background.
* @param content The background content. * @param content The background content.
@ -66,23 +67,28 @@ fun NiaBackground(
/** /**
* A gradient background for select screens. Uses [LocalBackgroundTheme] to set the gradient colors * A gradient background for select screens. Uses [LocalBackgroundTheme] to set the gradient colors
* of a [Box]. * of a [Box] within a [Surface].
* *
* @param modifier Modifier to be applied to the background. * @param modifier Modifier to be applied to the background.
* @param topColor The top gradient color to be rendered. * @param gradientColors The gradient colors to be rendered.
* @param bottomColor The bottom gradient color to be rendered.
* @param content The background content. * @param content The background content.
*/ */
@Composable @Composable
fun NiaGradientBackground( fun NiaGradientBackground(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
topColor: Color = LocalGradientColors.current.primary, gradientColors: GradientColors = LocalGradientColors.current,
bottomColor: Color = LocalGradientColors.current.secondary,
content: @Composable () -> Unit content: @Composable () -> Unit
) { ) {
val currentTopColor by rememberUpdatedState(topColor) val currentTopColor by rememberUpdatedState(gradientColors.top)
val currentBottomColor by rememberUpdatedState(bottomColor) val currentBottomColor by rememberUpdatedState(gradientColors.bottom)
NiaBackground(modifier) { Surface(
color = if (gradientColors.container == Color.Unspecified) {
Color.Transparent
} else {
gradientColors.container
},
modifier = modifier.fillMaxSize()
) {
Box( Box(
Modifier Modifier
.fillMaxSize() .fillMaxSize()
@ -144,7 +150,7 @@ annotation class ThemePreviews
@ThemePreviews @ThemePreviews
@Composable @Composable
fun BackgroundDefault() { fun BackgroundDefault() {
NiaTheme { NiaTheme(disableDynamicTheming = true) {
NiaBackground(Modifier.size(100.dp), content = {}) NiaBackground(Modifier.size(100.dp), content = {})
} }
} }
@ -152,7 +158,7 @@ fun BackgroundDefault() {
@ThemePreviews @ThemePreviews
@Composable @Composable
fun BackgroundDynamic() { fun BackgroundDynamic() {
NiaTheme(dynamicColor = true) { NiaTheme {
NiaBackground(Modifier.size(100.dp), content = {}) NiaBackground(Modifier.size(100.dp), content = {})
} }
} }
@ -168,7 +174,7 @@ fun BackgroundAndroid() {
@ThemePreviews @ThemePreviews
@Composable @Composable
fun GradientBackgroundDefault() { fun GradientBackgroundDefault() {
NiaTheme { NiaTheme(disableDynamicTheming = true) {
NiaGradientBackground(Modifier.size(100.dp), content = {}) NiaGradientBackground(Modifier.size(100.dp), content = {})
} }
} }
@ -176,7 +182,7 @@ fun GradientBackgroundDefault() {
@ThemePreviews @ThemePreviews
@Composable @Composable
fun GradientBackgroundDynamic() { fun GradientBackgroundDynamic() {
NiaTheme(dynamicColor = true) { NiaTheme {
NiaGradientBackground(Modifier.size(100.dp), content = {}) NiaGradientBackground(Modifier.size(100.dp), content = {})
} }
} }

@ -20,20 +20,15 @@ import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.sizeIn
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
/** /**
@ -43,38 +38,27 @@ import androidx.compose.ui.unit.dp
* @param modifier Modifier to be applied to the button. * @param modifier Modifier to be applied to the button.
* @param enabled Controls the enabled state of the button. When `false`, this button will not be * @param enabled Controls the enabled state of the button. When `false`, this button will not be
* clickable and will appear disabled to accessibility services. * clickable and will appear disabled to accessibility services.
* @param small Whether or not the size of the button should be small or regular.
* @param colors [ButtonColors] that will be used to resolve the container and content color for
* this button in different states. See [NiaButtonDefaults.filledButtonColors].
* @param contentPadding The spacing values to apply internally between the container and the * @param contentPadding The spacing values to apply internally between the container and the
* content. See [NiaButtonDefaults.buttonContentPadding]. * content.
* @param content The button content. * @param content The button content.
*/ */
@Composable @Composable
fun NiaFilledButton( fun NiaButton(
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
enabled: Boolean = true, enabled: Boolean = true,
small: Boolean = false, contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
colors: ButtonColors = NiaButtonDefaults.filledButtonColors(),
contentPadding: PaddingValues = NiaButtonDefaults.buttonContentPadding(small = small),
content: @Composable RowScope.() -> Unit content: @Composable RowScope.() -> Unit
) { ) {
Button( Button(
onClick = onClick, onClick = onClick,
modifier = if (small) { modifier = modifier,
modifier.heightIn(min = NiaButtonDefaults.SmallButtonHeight)
} else {
modifier
},
enabled = enabled, enabled = enabled,
colors = colors, colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.onBackground
),
contentPadding = contentPadding, contentPadding = contentPadding,
content = { content = content
ProvideTextStyle(value = MaterialTheme.typography.labelSmall) {
content()
}
}
) )
} }
@ -85,40 +69,30 @@ fun NiaFilledButton(
* @param modifier Modifier to be applied to the button. * @param modifier Modifier to be applied to the button.
* @param enabled Controls the enabled state of the button. When `false`, this button will not be * @param enabled Controls the enabled state of the button. When `false`, this button will not be
* clickable and will appear disabled to accessibility services. * clickable and will appear disabled to accessibility services.
* @param small Whether or not the size of the button should be small or regular.
* @param colors [ButtonColors] that will be used to resolve the container and content color for
* this button in different states. See [NiaButtonDefaults.filledButtonColors].
* @param text The button text label content. * @param text The button text label content.
* @param leadingIcon The button leading icon content. Pass `null` here for no leading icon. * @param leadingIcon The button leading icon content. Pass `null` here for no leading icon.
* @param trailingIcon The button trailing icon content. Pass `null` here for no trailing icon.
*/ */
@Composable @Composable
fun NiaFilledButton( fun NiaButton(
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
enabled: Boolean = true, enabled: Boolean = true,
small: Boolean = false,
colors: ButtonColors = NiaButtonDefaults.filledButtonColors(),
text: @Composable () -> Unit, text: @Composable () -> Unit,
leadingIcon: @Composable (() -> Unit)? = null, leadingIcon: @Composable (() -> Unit)? = null
trailingIcon: @Composable (() -> Unit)? = null
) { ) {
NiaFilledButton( NiaButton(
onClick = onClick, onClick = onClick,
modifier = modifier, modifier = modifier,
enabled = enabled, enabled = enabled,
small = small, contentPadding = if (leadingIcon != null) {
colors = colors, ButtonDefaults.ButtonWithIconContentPadding
contentPadding = NiaButtonDefaults.buttonContentPadding( } else {
small = small, ButtonDefaults.ContentPadding
leadingIcon = leadingIcon != null, }
trailingIcon = trailingIcon != null
)
) { ) {
NiaButtonContent( NiaButtonContent(
text = text, text = text,
leadingIcon = leadingIcon, leadingIcon = leadingIcon
trailingIcon = trailingIcon
) )
} }
} }
@ -130,12 +104,8 @@ fun NiaFilledButton(
* @param modifier Modifier to be applied to the button. * @param modifier Modifier to be applied to the button.
* @param enabled Controls the enabled state of the button. When `false`, this button will not be * @param enabled Controls the enabled state of the button. When `false`, this button will not be
* clickable and will appear disabled to accessibility services. * clickable and will appear disabled to accessibility services.
* @param small Whether or not the size of the button should be small or regular.
* @param border Border to draw around the button. Pass `null` here for no border.
* @param colors [ButtonColors] that will be used to resolve the container and content color for
* this button in different states. See [NiaButtonDefaults.outlinedButtonColors].
* @param contentPadding The spacing values to apply internally between the container and the * @param contentPadding The spacing values to apply internally between the container and the
* content. See [NiaButtonDefaults.buttonContentPadding]. * content.
* @param content The button content. * @param content The button content.
*/ */
@Composable @Composable
@ -143,28 +113,28 @@ fun NiaOutlinedButton(
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
enabled: Boolean = true, enabled: Boolean = true,
small: Boolean = false, contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
border: BorderStroke? = NiaButtonDefaults.outlinedButtonBorder(enabled = enabled),
colors: ButtonColors = NiaButtonDefaults.outlinedButtonColors(),
contentPadding: PaddingValues = NiaButtonDefaults.buttonContentPadding(small = small),
content: @Composable RowScope.() -> Unit content: @Composable RowScope.() -> Unit
) { ) {
OutlinedButton( OutlinedButton(
onClick = onClick, onClick = onClick,
modifier = if (small) { modifier = modifier,
modifier.heightIn(min = NiaButtonDefaults.SmallButtonHeight)
} else {
modifier
},
enabled = enabled, enabled = enabled,
border = border, colors = ButtonDefaults.outlinedButtonColors(
colors = colors, contentColor = MaterialTheme.colorScheme.onBackground
contentPadding = contentPadding, ),
content = { border = BorderStroke(
ProvideTextStyle(value = MaterialTheme.typography.labelSmall) { width = NiaButtonDefaults.OutlinedButtonBorderWidth,
content() color = if (enabled) {
MaterialTheme.colorScheme.outline
} else {
MaterialTheme.colorScheme.onSurface.copy(
alpha = NiaButtonDefaults.DisabledOutlinedButtonBorderAlpha
)
} }
} ),
contentPadding = contentPadding,
content = content
) )
} }
@ -175,43 +145,30 @@ fun NiaOutlinedButton(
* @param modifier Modifier to be applied to the button. * @param modifier Modifier to be applied to the button.
* @param enabled Controls the enabled state of the button. When `false`, this button will not be * @param enabled Controls the enabled state of the button. When `false`, this button will not be
* clickable and will appear disabled to accessibility services. * clickable and will appear disabled to accessibility services.
* @param small Whether or not the size of the button should be small or regular.
* @param border Border to draw around the button. Pass `null` here for no border.
* @param colors [ButtonColors] that will be used to resolve the container and content color for
* this button in different states. See [NiaButtonDefaults.outlinedButtonColors].
* @param text The button text label content. * @param text The button text label content.
* @param leadingIcon The button leading icon content. Pass `null` here for no leading icon. * @param leadingIcon The button leading icon content. Pass `null` here for no leading icon.
* @param trailingIcon The button trailing icon content. Pass `null` here for no trailing icon.
*/ */
@Composable @Composable
fun NiaOutlinedButton( fun NiaOutlinedButton(
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
enabled: Boolean = true, enabled: Boolean = true,
small: Boolean = false,
border: BorderStroke? = NiaButtonDefaults.outlinedButtonBorder(enabled = enabled),
colors: ButtonColors = NiaButtonDefaults.outlinedButtonColors(),
text: @Composable () -> Unit, text: @Composable () -> Unit,
leadingIcon: @Composable (() -> Unit)? = null, leadingIcon: @Composable (() -> Unit)? = null
trailingIcon: @Composable (() -> Unit)? = null
) { ) {
NiaOutlinedButton( NiaOutlinedButton(
onClick = onClick, onClick = onClick,
modifier = modifier, modifier = modifier,
enabled = enabled, enabled = enabled,
small = small, contentPadding = if (leadingIcon != null) {
border = border, ButtonDefaults.ButtonWithIconContentPadding
colors = colors, } else {
contentPadding = NiaButtonDefaults.buttonContentPadding( ButtonDefaults.ContentPadding
small = small, }
leadingIcon = leadingIcon != null,
trailingIcon = trailingIcon != null
)
) { ) {
NiaButtonContent( NiaButtonContent(
text = text, text = text,
leadingIcon = leadingIcon, leadingIcon = leadingIcon
trailingIcon = trailingIcon
) )
} }
} }
@ -223,11 +180,6 @@ fun NiaOutlinedButton(
* @param modifier Modifier to be applied to the button. * @param modifier Modifier to be applied to the button.
* @param enabled Controls the enabled state of the button. When `false`, this button will not be * @param enabled Controls the enabled state of the button. When `false`, this button will not be
* clickable and will appear disabled to accessibility services. * clickable and will appear disabled to accessibility services.
* @param small Whether or not the size of the button should be small or regular.
* @param colors [ButtonColors] that will be used to resolve the container and content color for
* this button in different states. See [NiaButtonDefaults.textButtonColors].
* @param contentPadding The spacing values to apply internally between the container and the
* content. See [NiaButtonDefaults.buttonContentPadding].
* @param content The button content. * @param content The button content.
*/ */
@Composable @Composable
@ -235,26 +187,16 @@ fun NiaTextButton(
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
enabled: Boolean = true, enabled: Boolean = true,
small: Boolean = false,
colors: ButtonColors = NiaButtonDefaults.textButtonColors(),
contentPadding: PaddingValues = NiaButtonDefaults.buttonContentPadding(small = small),
content: @Composable RowScope.() -> Unit content: @Composable RowScope.() -> Unit
) { ) {
TextButton( TextButton(
onClick = onClick, onClick = onClick,
modifier = if (small) { modifier = modifier,
modifier.heightIn(min = NiaButtonDefaults.SmallButtonHeight)
} else {
modifier
},
enabled = enabled, enabled = enabled,
colors = colors, colors = ButtonDefaults.textButtonColors(
contentPadding = contentPadding, contentColor = MaterialTheme.colorScheme.onBackground
content = { ),
ProvideTextStyle(value = MaterialTheme.typography.labelSmall) { content = content
content()
}
}
) )
} }
@ -265,60 +207,42 @@ fun NiaTextButton(
* @param modifier Modifier to be applied to the button. * @param modifier Modifier to be applied to the button.
* @param enabled Controls the enabled state of the button. When `false`, this button will not be * @param enabled Controls the enabled state of the button. When `false`, this button will not be
* clickable and will appear disabled to accessibility services. * clickable and will appear disabled to accessibility services.
* @param small Whether or not the size of the button should be small or regular.
* @param colors [ButtonColors] that will be used to resolve the container and content color for
* this button in different states. See [NiaButtonDefaults.textButtonColors].
* @param text The button text label content. * @param text The button text label content.
* @param leadingIcon The button leading icon content. Pass `null` here for no leading icon. * @param leadingIcon The button leading icon content. Pass `null` here for no leading icon.
* @param trailingIcon The button trailing icon content. Pass `null` here for no trailing icon.
*/ */
@Composable @Composable
fun NiaTextButton( fun NiaTextButton(
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
enabled: Boolean = true, enabled: Boolean = true,
small: Boolean = false,
colors: ButtonColors = NiaButtonDefaults.textButtonColors(),
text: @Composable () -> Unit, text: @Composable () -> Unit,
leadingIcon: @Composable (() -> Unit)? = null, leadingIcon: @Composable (() -> Unit)? = null
trailingIcon: @Composable (() -> Unit)? = null
) { ) {
NiaTextButton( NiaTextButton(
onClick = onClick, onClick = onClick,
modifier = modifier, modifier = modifier,
enabled = enabled, enabled = enabled
small = small,
colors = colors,
contentPadding = NiaButtonDefaults.buttonContentPadding(
small = small,
leadingIcon = leadingIcon != null,
trailingIcon = trailingIcon != null
)
) { ) {
NiaButtonContent( NiaButtonContent(
text = text, text = text,
leadingIcon = leadingIcon, leadingIcon = leadingIcon
trailingIcon = trailingIcon
) )
} }
} }
/** /**
* Internal Now in Android button content layout for arranging the text label, leading icon and * Internal Now in Android button content layout for arranging the text label and leading icon.
* trailing icon.
* *
* @param text The button text label content. * @param text The button text label content.
* @param leadingIcon The button leading icon content. Pass `null` here for no leading icon. * @param leadingIcon The button leading icon content. Default is `null` for no leading icon.Ï
* @param trailingIcon The button trailing icon content. Pass `null` here for no trailing icon.
*/ */
@Composable @Composable
private fun RowScope.NiaButtonContent( private fun NiaButtonContent(
text: @Composable () -> Unit, text: @Composable () -> Unit,
leadingIcon: @Composable (() -> Unit)?, leadingIcon: @Composable (() -> Unit)? = null
trailingIcon: @Composable (() -> Unit)?
) { ) {
if (leadingIcon != null) { if (leadingIcon != null) {
Box(Modifier.sizeIn(maxHeight = NiaButtonDefaults.ButtonIconSize)) { Box(Modifier.sizeIn(maxHeight = ButtonDefaults.IconSize)) {
leadingIcon() leadingIcon()
} }
} }
@ -326,12 +250,7 @@ private fun RowScope.NiaButtonContent(
Modifier Modifier
.padding( .padding(
start = if (leadingIcon != null) { start = if (leadingIcon != null) {
NiaButtonDefaults.ButtonContentSpacing ButtonDefaults.IconSpacing
} else {
0.dp
},
end = if (trailingIcon != null) {
NiaButtonDefaults.ButtonContentSpacing
} else { } else {
0.dp 0.dp
} }
@ -339,104 +258,16 @@ private fun RowScope.NiaButtonContent(
) { ) {
text() text()
} }
if (trailingIcon != null) {
Box(Modifier.sizeIn(maxHeight = NiaButtonDefaults.ButtonIconSize)) {
trailingIcon()
}
}
} }
/** /**
* Now in Android button default values. * Now in Android button default values.
*/ */
object NiaButtonDefaults { object NiaButtonDefaults {
val SmallButtonHeight = 32.dp // TODO: File bug
const val DisabledButtonContainerAlpha = 0.12f // OutlinedButton border color doesn't respect disabled state by default
const val DisabledButtonContentAlpha = 0.38f const val DisabledOutlinedButtonBorderAlpha = 0.12f
val ButtonHorizontalPadding = 24.dp // TODO: File bug
val ButtonHorizontalIconPadding = 16.dp // OutlinedButton default border width isn't exposed via ButtonDefaults
val ButtonVerticalPadding = 8.dp val OutlinedButtonBorderWidth = 1.dp
val SmallButtonHorizontalPadding = 16.dp
val SmallButtonHorizontalIconPadding = 12.dp
val SmallButtonVerticalPadding = 7.dp
val ButtonContentSpacing = 8.dp
val ButtonIconSize = 18.dp
fun buttonContentPadding(
small: Boolean,
leadingIcon: Boolean = false,
trailingIcon: Boolean = false
): PaddingValues {
return PaddingValues(
start = when {
small && leadingIcon -> SmallButtonHorizontalIconPadding
small -> SmallButtonHorizontalPadding
leadingIcon -> ButtonHorizontalIconPadding
else -> ButtonHorizontalPadding
},
top = if (small) SmallButtonVerticalPadding else ButtonVerticalPadding,
end = when {
small && trailingIcon -> SmallButtonHorizontalIconPadding
small -> SmallButtonHorizontalPadding
trailingIcon -> ButtonHorizontalIconPadding
else -> ButtonHorizontalPadding
},
bottom = if (small) SmallButtonVerticalPadding else ButtonVerticalPadding
)
}
@Composable
fun filledButtonColors(
containerColor: Color = MaterialTheme.colorScheme.onBackground,
contentColor: Color = MaterialTheme.colorScheme.onPrimary,
disabledContainerColor: Color = MaterialTheme.colorScheme.onBackground.copy(
alpha = DisabledButtonContainerAlpha
),
disabledContentColor: Color = MaterialTheme.colorScheme.onBackground.copy(
alpha = DisabledButtonContentAlpha
)
) = ButtonDefaults.buttonColors(
containerColor = containerColor,
contentColor = contentColor,
disabledContainerColor = disabledContainerColor,
disabledContentColor = disabledContentColor
)
@Composable
fun outlinedButtonBorder(
enabled: Boolean,
width: Dp = 1.dp,
color: Color = MaterialTheme.colorScheme.onBackground,
disabledColor: Color = MaterialTheme.colorScheme.onBackground.copy(
alpha = DisabledButtonContainerAlpha
)
): BorderStroke = BorderStroke(
width = width,
color = if (enabled) color else disabledColor
)
@Composable
fun outlinedButtonColors(
containerColor: Color = Color.Transparent,
contentColor: Color = MaterialTheme.colorScheme.onBackground,
disabledContainerColor: Color = Color.Transparent,
disabledContentColor: Color = MaterialTheme.colorScheme.onBackground.copy(
alpha = DisabledButtonContentAlpha
)
) = ButtonDefaults.outlinedButtonColors(
containerColor = containerColor,
contentColor = contentColor,
disabledContainerColor = disabledContainerColor,
disabledContentColor = disabledContentColor
)
@Composable
fun textButtonColors(
containerColor: Color = Color.Transparent,
contentColor: Color = MaterialTheme.colorScheme.onBackground,
disabledContainerColor: Color = Color.Transparent,
disabledContentColor: Color = MaterialTheme.colorScheme.onBackground.copy(
alpha = DisabledButtonContentAlpha
)
) = ButtonDefaults.textButtonColors(
containerColor = containerColor,
contentColor = contentColor,
disabledContainerColor = disabledContainerColor,
disabledContentColor = disabledContentColor
)
} }

@ -58,11 +58,15 @@ fun NiaFilterChip(
}, },
modifier = modifier, modifier = modifier,
enabled = enabled, enabled = enabled,
trailingIcon = { leadingIcon = if (selected) {
Icon( {
imageVector = NiaIcons.Check, Icon(
contentDescription = null imageVector = NiaIcons.Check,
) contentDescription = null
)
}
} else {
null
}, },
shape = CircleShape, shape = CircleShape,
border = FilterChipDefaults.filterChipBorder( border = FilterChipDefaults.filterChipBorder(
@ -74,11 +78,9 @@ fun NiaFilterChip(
disabledSelectedBorderColor = MaterialTheme.colorScheme.onBackground.copy( disabledSelectedBorderColor = MaterialTheme.colorScheme.onBackground.copy(
alpha = NiaChipDefaults.DisabledChipContentAlpha alpha = NiaChipDefaults.DisabledChipContentAlpha
), ),
borderWidth = NiaChipDefaults.ChipBorderWidth,
selectedBorderWidth = NiaChipDefaults.ChipBorderWidth selectedBorderWidth = NiaChipDefaults.ChipBorderWidth
), ),
colors = FilterChipDefaults.filterChipColors( colors = FilterChipDefaults.filterChipColors(
containerColor = Color.Transparent,
labelColor = MaterialTheme.colorScheme.onBackground, labelColor = MaterialTheme.colorScheme.onBackground,
iconColor = MaterialTheme.colorScheme.onBackground, iconColor = MaterialTheme.colorScheme.onBackground,
disabledContainerColor = if (selected) { disabledContainerColor = if (selected) {
@ -105,6 +107,8 @@ fun NiaFilterChip(
* Now in Android chip default values. * Now in Android chip default values.
*/ */
object NiaChipDefaults { object NiaChipDefaults {
// TODO: File bug
// FilterChip default values aren't exposed via FilterChipDefaults
const val DisabledChipContainerAlpha = 0.12f const val DisabledChipContainerAlpha = 0.12f
const val DisabledChipContentAlpha = 0.38f const val DisabledChipContentAlpha = 0.38f
val ChipBorderWidth = 1.dp val ChipBorderWidth = 1.dp

@ -16,16 +16,25 @@
package com.google.samples.apps.nowinandroid.core.designsystem.component package com.google.samples.apps.nowinandroid.core.designsystem.component
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
/** /**
@ -56,17 +65,38 @@ fun <T> NiaDropdownMenuButton(
) { ) {
var expanded by remember { mutableStateOf(false) } var expanded by remember { mutableStateOf(false) }
Box(modifier = modifier) { Box(modifier = modifier) {
NiaOutlinedButton( OutlinedButton(
onClick = { expanded = true }, onClick = { expanded = true },
enabled = enabled, enabled = enabled,
text = text, colors = ButtonDefaults.outlinedButtonColors(
trailingIcon = { contentColor = MaterialTheme.colorScheme.onBackground
Icon( ),
imageVector = if (expanded) NiaIcons.ArrowDropUp else NiaIcons.ArrowDropDown, border = BorderStroke(
contentDescription = null width = NiaDropdownMenuDefaults.DropdownMenuButtonBorderWidth,
) color = if (enabled) {
} MaterialTheme.colorScheme.outline
) } else {
MaterialTheme.colorScheme.onSurface.copy(
alpha = NiaDropdownMenuDefaults.DisabledDropdownMenuButtonBorderAlpha
)
}
),
contentPadding = NiaDropdownMenuDefaults.DropdownMenuButtonContentPadding
) {
NiaDropdownMenuButtonContent(
text = text,
trailingIcon = {
Icon(
imageVector = if (expanded) {
NiaIcons.ArrowDropUp
} else {
NiaIcons.ArrowDropDown
},
contentDescription = null
)
}
)
}
NiaDropdownMenu( NiaDropdownMenu(
expanded = expanded, expanded = expanded,
onDismissRequest = { expanded = false }, onDismissRequest = { expanded = false },
@ -80,6 +110,39 @@ fun <T> NiaDropdownMenuButton(
} }
} }
/**
* Internal Now in Android dropdown menu button content layout for arranging the text label and
* trailing icon.
*
* @param text The button text label content.
* @param trailingIcon The button trailing icon content. Default is `null` for no trailing icon.
*/
@Composable
private fun NiaDropdownMenuButtonContent(
text: @Composable () -> Unit,
trailingIcon: @Composable (() -> Unit)? = null,
) {
Box(
Modifier
.padding(
end = if (trailingIcon != null) {
ButtonDefaults.IconSpacing
} else {
0.dp
}
)
) {
ProvideTextStyle(value = MaterialTheme.typography.labelSmall) {
text()
}
}
if (trailingIcon != null) {
Box(Modifier.sizeIn(maxHeight = ButtonDefaults.IconSize)) {
trailingIcon()
}
}
}
/** /**
* Now in Android dropdown menu with item content slots. Wraps Material 3 [DropdownMenu] and * Now in Android dropdown menu with item content slots. Wraps Material 3 [DropdownMenu] and
* [DropdownMenuItem]. * [DropdownMenuItem].
@ -130,3 +193,24 @@ fun <T> NiaDropdownMenu(
} }
} }
} }
/**
* Now in Android dropdown menu default values.
*/
object NiaDropdownMenuDefaults {
// TODO: File bug
// OutlinedButton border color doesn't respect disabled state by default
const val DisabledDropdownMenuButtonBorderAlpha = 0.12f
// TODO: File bug
// OutlinedButton default border width isn't exposed via ButtonDefaults
val DropdownMenuButtonBorderWidth = 1.dp
// TODO: File bug
// Various default button padding values aren't exposed via ButtonDefaults
val DropdownMenuButtonContentPadding =
PaddingValues(
start = 24.dp,
top = 8.dp,
end = 16.dp,
bottom = 8.dp
)
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save