path
stringlengths
4
242
contentHash
stringlengths
1
10
content
stringlengths
0
3.9M
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidLibraryJacocoConventionPlugin.kt
1313954241
import com.android.build.api.variant.LibraryAndroidComponentsExtension import com.mshdabiola.app.configureJacoco import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType class AndroidLibraryJacocoConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("org.gradle.jacoco") apply("com.android.library") } val extension = extensions.getByType<LibraryAndroidComponentsExtension>() configureJacoco(extension) } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/JvmLibraryConventionPlugin.kt
2323621727
/* * Copyright 2023 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.mshdabiola.app.configureKotlinJvm import org.gradle.api.Plugin import org.gradle.api.Project class JvmLibraryConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("org.jetbrains.kotlin.jvm") apply("mshdabiola.android.lint") } configureKotlinJvm() } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidLibraryConventionPlugin.kt
2110349312
/* * 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.android.build.api.variant.LibraryAndroidComponentsExtension import com.android.build.gradle.LibraryExtension import com.mshdabiola.app.configureGradleManagedDevices import com.mshdabiola.app.configureKotlinAndroid import com.mshdabiola.app.configurePrintApksTask import com.mshdabiola.app.disableUnnecessaryAndroidTests import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.kotlin class AndroidLibraryConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.android.library") apply("org.jetbrains.kotlin.android") apply("mshdabiola.android.lint") } extensions.configure<LibraryExtension> { configureKotlinAndroid(this) defaultConfig.targetSdk = 34 //configureFlavors(this) configureGradleManagedDevices(this) // The resource prefix is derived from the module name, // so resources inside ":core:module1" must be prefixed with "core_module1_" resourcePrefix = path.split("""\W""".toRegex()).drop(1).distinct().joinToString(separator = "_") .lowercase() + "_" } extensions.configure<LibraryAndroidComponentsExtension> { configurePrintApksTask(this) disableUnnecessaryAndroidTests(target) } dependencies { add("testImplementation", kotlin("test")) } } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidApplicationFirebaseConventionPlugin.kt
1792661672
/* * 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.android.build.api.variant.ApplicationAndroidComponentsExtension import com.google.firebase.crashlytics.buildtools.gradle.CrashlyticsExtension import com.mshdabiola.app.libs import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.dependencies class AndroidApplicationFirebaseConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.google.gms.google-services") apply("com.google.firebase.firebase-perf") apply("com.google.firebase.crashlytics") } dependencies { val bom = libs.findLibrary("firebase-bom").get() add("implementation", platform(bom)) "implementation"(libs.findLibrary("firebase.analytics").get()) "implementation"(libs.findLibrary("firebase.performance").get()) "implementation"(libs.findLibrary("firebase.crashlytics").get()) "implementation"(libs.findLibrary("firebase.cloud.messaging").get()) "implementation"(libs.findLibrary("firebase.remoteconfig").get()) "implementation"(libs.findLibrary("firebase.message").get()) "implementation"(libs.findLibrary("firebase.auth").get()) "implementation"(libs.findLibrary("play.game").get()) "implementation"(libs.findLibrary("play.update").get()) "implementation"(libs.findLibrary("play.update.kts").get()) // "implementation"(libs.findLibrary("admob.service").get()) "implementation"(libs.findLibrary("play.review").get()) "implementation"(libs.findLibrary("play.review.kts").get()) //"implementation"(libs.findLibrary("play.billing.kts").get()) // "implementation"(libs.findLibrary("play.coroutine").get()) } extensions.configure<ApplicationAndroidComponentsExtension> { finalizeDsl { it.buildTypes.forEach { buildType -> // Disable the Crashlytics mapping file upload. This feature should only be // enabled if a Firebase backend is available and configured in // google-services.json. buildType.configure<CrashlyticsExtension> { mappingFileUploadEnabled = !buildType.isDebuggable } } } } } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidApplicationFlavorsConventionPlugin.kt
4011905028
/* * Copyright 2023 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.android.build.api.dsl.ApplicationExtension import com.mshdabiola.app.configureFlavors import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure class AndroidApplicationFlavorsConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { extensions.configure<ApplicationExtension> { configureFlavors(this) } } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidLibraryComposeConventionPlugin.kt
964828968
/* * 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.android.build.gradle.LibraryExtension import com.mshdabiola.app.configureAndroidCompose import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType class AndroidLibraryComposeConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { pluginManager.apply("com.android.library") val extension = extensions.getByType<LibraryExtension>() configureAndroidCompose(extension) } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/GradleManagedDevices.kt
3517397720
/* * Copyright 2023 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.mshdabiola.app import com.android.build.api.dsl.CommonExtension import com.android.build.api.dsl.ManagedVirtualDevice import org.gradle.kotlin.dsl.get import org.gradle.kotlin.dsl.invoke /** * Configure project for Gradle managed devices */ //./gradlew pixel4api30aospatdDemoDebugAndroidTest /** * Configure project for Gradle managed devices */ internal fun configureGradleManagedDevices( commonExtension: CommonExtension<*, *, *, *, *,*>, ) { val pixel4 = DeviceConfig("Pixel 4", 30, "aosp-atd") val pixel6 = DeviceConfig("Pixel 6", 31, "aosp") val pixelC = DeviceConfig("Pixel C", 30, "aosp-atd") val allDevices = listOf(pixel4, pixel6, pixelC) val ciDevices = listOf(pixel4, pixelC) commonExtension.testOptions { managedDevices { devices { allDevices.forEach { deviceConfig -> maybeCreate(deviceConfig.taskName, ManagedVirtualDevice::class.java).apply { device = deviceConfig.device apiLevel = deviceConfig.apiLevel systemImageSource = deviceConfig.systemImageSource } } } groups { maybeCreate("ci").apply { ciDevices.forEach { deviceConfig -> targetDevices.add(devices[deviceConfig.taskName]) } } } } } } private data class DeviceConfig( val device: String, val apiLevel: Int, val systemImageSource: String, ) { val taskName = buildString { append(device.lowercase().replace(" ", "")) append("api") append(apiLevel.toString()) append(systemImageSource.replace("-", "")) } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/PrintTestApks.kt
1173015622
/* * 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.mshdabiola.app import com.android.build.api.artifact.SingleArtifact import com.android.build.api.variant.AndroidComponentsExtension import com.android.build.api.variant.BuiltArtifactsLoader import com.android.build.api.variant.HasAndroidTest import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.file.Directory import org.gradle.api.file.DirectoryProperty import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.work.DisableCachingByDefault import java.io.File internal fun Project.configurePrintApksTask(extension: AndroidComponentsExtension<*, *, *>) { extension.onVariants { variant -> if (variant is HasAndroidTest) { val loader = variant.artifacts.getBuiltArtifactsLoader() val artifact = variant.androidTest?.artifacts?.get(SingleArtifact.APK) val javaSources = variant.androidTest?.sources?.java?.all val kotlinSources = variant.androidTest?.sources?.kotlin?.all val testSources = if (javaSources != null && kotlinSources != null) { javaSources.zip(kotlinSources) { javaDirs, kotlinDirs -> javaDirs + kotlinDirs } } else javaSources ?: kotlinSources if (artifact != null && testSources != null) { tasks.register( "${variant.name}PrintTestApk", PrintApkLocationTask::class.java ) { apkFolder.set(artifact) builtArtifactsLoader.set(loader) variantName.set(variant.name) sources.set(testSources) } } } } } @DisableCachingByDefault(because = "Prints output") internal abstract class PrintApkLocationTask : DefaultTask() { @get:PathSensitive(PathSensitivity.RELATIVE) @get:InputDirectory abstract val apkFolder: DirectoryProperty @get:PathSensitive(PathSensitivity.RELATIVE) @get:InputFiles abstract val sources: ListProperty<Directory> @get:Internal abstract val builtArtifactsLoader: Property<BuiltArtifactsLoader> @get:Input abstract val variantName: Property<String> @TaskAction fun taskAction() { val hasFiles = sources.orNull?.any { directory -> directory.asFileTree.files.any { it.isFile && "build${File.separator}generated" !in it.parentFile.path } } ?: throw RuntimeException("Cannot check androidTest sources") // Don't print APK location if there are no androidTest source files if (!hasFiles) return val builtArtifacts = builtArtifactsLoader.get().load(apkFolder.get()) ?: throw RuntimeException("Cannot load APKs") if (builtArtifacts.elements.size != 1) throw RuntimeException("Expected one APK !") val apk = File(builtArtifacts.elements.single().outputFile).toPath() println(apk) } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/AndroidCompose.kt
3238983735
/* * 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.mshdabiola.app import com.android.build.api.dsl.CommonExtension import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.withType import org.jetbrains.kotlin.gradle.tasks.KotlinCompile /** * Configure Compose-specific options */ internal fun Project.configureAndroidCompose( commonExtension: CommonExtension<*, *, *, *, *,*>, ) { commonExtension.apply { buildFeatures { compose = true } composeOptions { kotlinCompilerExtensionVersion = libs.findVersion("androidxComposeCompiler").get().toString() } dependencies { val bom = libs.findLibrary("androidx-compose-bom").get() add("implementation", platform(bom)) add("androidTestImplementation", platform(bom)) } testOptions { unitTests { // For Robolectric isIncludeAndroidResources = true } } } tasks.withType<KotlinCompile>().configureEach { kotlinOptions { freeCompilerArgs = freeCompilerArgs + buildComposeMetricsParameters() } } } private fun Project.buildComposeMetricsParameters(): List<String> { val metricParameters = mutableListOf<String>() val enableMetricsProvider = project.providers.gradleProperty("enableComposeCompilerMetrics") val relativePath = projectDir.relativeTo(rootDir) val buildDir = layout.buildDirectory.get().asFile val enableMetrics = (enableMetricsProvider.orNull == "true") if (enableMetrics) { val metricsFolder = buildDir.resolve("compose-metrics").resolve(relativePath) metricParameters.add("-P") metricParameters.add( "plugin:androidx.compose.compiler.plugins.kotlin:metricsDestination=" + metricsFolder.absolutePath ) } val enableReportsProvider = project.providers.gradleProperty("enableComposeCompilerReports") val enableReports = (enableReportsProvider.orNull == "true") if (enableReports) { val reportsFolder = buildDir.resolve("compose-reports").resolve(relativePath) metricParameters.add("-P") metricParameters.add( "plugin:androidx.compose.compiler.plugins.kotlin:reportsDestination=" + reportsFolder.absolutePath ) } return metricParameters.toList() }
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/Badging.kt
3277946654
/* * Copyright 2023 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.mshdabiola.app import com.android.SdkConstants import com.android.build.api.artifact.SingleArtifact import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.android.build.gradle.BaseExtension import com.google.common.truth.Truth.assertWithMessage import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Copy import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.configurationcache.extensions.capitalized import org.gradle.kotlin.dsl.register import org.gradle.language.base.plugins.LifecycleBasePlugin import org.gradle.process.ExecOperations import java.io.File import javax.inject.Inject @CacheableTask abstract class GenerateBadgingTask : DefaultTask() { @get:OutputFile abstract val badging: RegularFileProperty @get:PathSensitive(PathSensitivity.NONE) @get:InputFile abstract val apk: RegularFileProperty @get:PathSensitive(PathSensitivity.NONE) @get:InputFile abstract val aapt2Executable: RegularFileProperty @get:Inject abstract val execOperations: ExecOperations @TaskAction fun taskAction() { execOperations.exec { commandLine( aapt2Executable.get().asFile.absolutePath, "dump", "badging", apk.get().asFile.absolutePath, ) standardOutput = badging.asFile.get().outputStream() } } } @CacheableTask abstract class CheckBadgingTask : DefaultTask() { // In order for the task to be up-to-date when the inputs have not changed, // the task must declare an output, even if it's not used. Tasks with no // output are always run regardless of whether the inputs changed @get:OutputDirectory abstract val output: DirectoryProperty @get:PathSensitive(PathSensitivity.NONE) @get:InputFile abstract val goldenBadging: RegularFileProperty @get:PathSensitive(PathSensitivity.NONE) @get:InputFile abstract val generatedBadging: RegularFileProperty @get:Input abstract val updateBadgingTaskName: Property<String> override fun getGroup(): String = LifecycleBasePlugin.VERIFICATION_GROUP @TaskAction fun taskAction() { assertWithMessage( "Generated badging is different from golden badging! " + "If this change is intended, run ./gradlew ${updateBadgingTaskName.get()}", ) .that(generatedBadging.get().asFile.readText()) .isEqualTo(goldenBadging.get().asFile.readText()) } } fun Project.configureBadgingTasks( baseExtension: BaseExtension, componentsExtension: ApplicationAndroidComponentsExtension, ) { // Registers a callback to be called, when a new variant is configured componentsExtension.onVariants { variant -> // Registers a new task to verify the app bundle. val capitalizedVariantName = variant.name.capitalized() val generateBadgingTaskName = "generate${capitalizedVariantName}Badging" val generateBadging = tasks.register<GenerateBadgingTask>(generateBadgingTaskName) { apk.set( variant.artifacts.get(SingleArtifact.APK_FROM_BUNDLE), ) aapt2Executable.set( File( baseExtension.sdkDirectory, "${SdkConstants.FD_BUILD_TOOLS}/" + "${baseExtension.buildToolsVersion}/" + SdkConstants.FN_AAPT2, ), ) badging.set( project.layout.buildDirectory.file( "outputs/apk_from_bundle/${variant.name}/${variant.name}-badging.txt", ), ) } val updateBadgingTaskName = "update${capitalizedVariantName}Badging" tasks.register<Copy>(updateBadgingTaskName) { from(generateBadging.get().badging) into(project.layout.projectDirectory) } val checkBadgingTaskName = "check${capitalizedVariantName}Badging" tasks.register<CheckBadgingTask>(checkBadgingTaskName) { goldenBadging.set( project.layout.projectDirectory.file("${variant.name}-badging.txt"), ) generatedBadging.set( generateBadging.get().badging, ) this.updateBadgingTaskName.set(updateBadgingTaskName) output.set( project.layout.buildDirectory.dir("intermediates/$checkBadgingTaskName"), ) } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/ProjectExtensions.kt
3359858273
/* * Copyright 2023 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.mshdabiola.app import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalog import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.kotlin.dsl.getByType val Project.libs get(): VersionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/Flavor.kt
2712609068
package com.mshdabiola.app import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.dsl.ApplicationProductFlavor import com.android.build.api.dsl.CommonExtension import com.android.build.api.dsl.ProductFlavor import org.gradle.api.Project @Suppress("EnumEntryName") enum class FlavorDimension { contentType } // 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. // These two product flavors reflect this behaviour. @Suppress("EnumEntryName") enum class Flavor( val dimension: FlavorDimension, val applicationIdSuffix: String? = null, val versionNameSuffix: String? = null ) { demo(FlavorDimension.contentType, applicationIdSuffix = ".demo", "-demo"), prod(FlavorDimension.contentType) } fun Project.configureFlavors( commonExtension: CommonExtension<*, *, *, *, *,*>, flavorConfigurationBlock: ProductFlavor.(flavor: Flavor) -> Unit = {} ) { commonExtension.apply { flavorDimensions += FlavorDimension.contentType.name productFlavors { Flavor.values().forEach { create(it.name) { dimension = it.dimension.name flavorConfigurationBlock(this, it) if (this@apply is ApplicationExtension && this is ApplicationProductFlavor) { if (it.applicationIdSuffix != null) { this.applicationIdSuffix = it.applicationIdSuffix } if (it.versionNameSuffix != null) { this.versionNameSuffix = it.versionNameSuffix } } } } } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/KotlinAndroid.kt
760372159
/* * 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.mshdabiola.app import com.android.build.api.dsl.CommonExtension import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.api.plugins.JavaPluginExtension import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.provideDelegate import org.gradle.kotlin.dsl.withType import org.jetbrains.kotlin.gradle.tasks.KotlinCompile /** * Configure base Kotlin with Android options */ internal fun Project.configureKotlinAndroid( commonExtension: CommonExtension<*, *, *, *, *,*>, ) { commonExtension.apply { compileSdk = 34 defaultConfig { minSdk = 24 //24 } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 // isCoreLibraryDesugaringEnabled = true } configureKotlin() // packaging { // resources { // excludes += "/META-INF/{AL2.0,LGPL2.1}" // } // } } // val libs = extensions.getByType<VersionCatalogsExtension>().named("libs") dependencies { // add("coreLibraryDesugaring", libs.findLibrary("android.desugarJdkLibs").get()) } } /** * Configure base Kotlin options for JVM (non-Android) */ internal fun Project.configureKotlinJvm() { extensions.configure<JavaPluginExtension> { // Up to Java 11 APIs are available through desugaring // https://developer.android.com/studio/write/java11-minimal-support-table sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } configureKotlin() } /** * Configure base Kotlin options */ private fun Project.configureKotlin() { // Use withType to workaround https://youtrack.jetbrains.com/issue/KT-55947 tasks.withType<KotlinCompile>().configureEach { kotlinOptions { // Set JVM target to 11 jvmTarget = JavaVersion.VERSION_1_8.toString() // Treat all Kotlin warnings as errors (disabled by default) // Override by setting warningsAsErrors=true in your ~/.gradle/gradle.properties val warningsAsErrors: String? by project allWarningsAsErrors = warningsAsErrors.toBoolean() freeCompilerArgs = freeCompilerArgs + listOf( // Enable experimental coroutines APIs, including Flow "-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi", ) } } } // //fun CommonExtension<*, *, *, *, *>.kotlinOptions(block: KotlinJvmOptions.() -> Unit) { // (this as ExtensionAware).extensions.configure("kotlinOptions", block) //}
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/AndroidInstrumentedTests.kt
3372934006
/* * Copyright 2023 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.mshdabiola.app import com.android.build.api.variant.LibraryAndroidComponentsExtension import org.gradle.api.Project /** * Disable unnecessary Android instrumented tests for the [project] if there is no `androidTest` folder. * Otherwise, these projects would be compiled, packaged, installed and ran only to end-up with the following message: * * > Starting 0 tests on AVD * * Note: this could be improved by checking other potential sourceSets based on buildTypes and flavors. */ internal fun LibraryAndroidComponentsExtension.disableUnnecessaryAndroidTests( project: Project, ) = beforeVariants { it.enableAndroidTest = it.enableAndroidTest && project.projectDir.resolve("src/androidTest").exists() }
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/BuildType.kt
1976495365
package com.mshdabiola.app @Suppress("unused") enum class BuildType(val applicationIdSuffix: String? = null, val versionNameSuffix: String = "") { DEBUG(".debug", "-debug"), RELEASE, BENCHMARK(".benchmark", "-benchmark") }
SkeletonAndroid/build-logic/convention/src/main/kotlin/com/mshdabiola/app/Jacoco.kt
475191334
package com.mshdabiola.app import com.android.build.api.variant.AndroidComponentsExtension import org.gradle.api.Project import org.gradle.api.tasks.testing.Test import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.register import org.gradle.kotlin.dsl.withType import org.gradle.testing.jacoco.plugins.JacocoPluginExtension import org.gradle.testing.jacoco.plugins.JacocoTaskExtension import org.gradle.testing.jacoco.tasks.JacocoReport import java.util.Locale private val coverageExclusions = listOf( // Android "**/R.class", "**/R\$*.class", "**/BuildConfig.*", "**/Manifest*.*" ) private fun String.capitalize() = replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } internal fun Project.configureJacoco( androidComponentsExtension: AndroidComponentsExtension<*, *, *>, ) { configure<JacocoPluginExtension> { toolVersion = libs.findVersion("jacoco").get().toString() } val jacocoTestReport = tasks.create("jacocoTestReport") androidComponentsExtension.onVariants { variant -> val testTaskName = "test${variant.name.capitalize()}UnitTest" val buildDir = layout.buildDirectory.get().asFile val reportTask = tasks.register("jacoco${testTaskName.capitalize()}Report", JacocoReport::class) { dependsOn(testTaskName) reports { xml.required.set(true) html.required.set(true) } classDirectories.setFrom( fileTree("$buildDir/tmp/kotlin-classes/${variant.name}") { exclude(coverageExclusions) } ) sourceDirectories.setFrom( files( "$projectDir/src/main/java", "$projectDir/src/main/kotlin" ) ) executionData.setFrom(file("$buildDir/jacoco/$testTaskName.exec")) } jacocoTestReport.dependsOn(reportTask) } tasks.withType<Test>().configureEach { configure<JacocoTaskExtension> { // Required for JaCoCo + Robolectric // https://github.com/robolectric/robolectric/issues/2230 // TODO: Consider removing if not we don't add Robolectric isIncludeNoLocationClasses = true // Required for JDK 11 with the above // https://github.com/gradle/gradle/issues/5184#issuecomment-391982009 excludes = listOf("jdk.internal.*") } } }
SkeletonAndroid/benchmarks/src/main/kotlin/androidx/test/uiautomator/UiAutomatorHelpers.kt
76049632
/* *abiola 2022 */ 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> = object : UiObject2Condition<Boolean>() { override fun apply(element: UiObject2): Boolean = when (op) { AT_LEAST -> element.childCount >= childCount EXACTLY -> element.childCount == childCount AT_MOST -> element.childCount <= childCount } } enum class HasChildrenOp { AT_LEAST, EXACTLY, AT_MOST, }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/baselineprofile/GenerateBaselineProfile.kt
4126949707
/* *abiola 2022 */ package com.mshdabiola.benchmarks.baselineprofile import androidx.benchmark.macro.junit4.BaselineProfileRule import androidx.test.uiautomator.By import com.mshdabiola.benchmarks.PACKAGE_NAME import com.mshdabiola.benchmarks.startActivity import com.mshdabiola.benchmarks.waitAndFindObject import org.junit.Rule import org.junit.Test class GenerateBaselineProfile { @get:Rule val baselineProfileRule = BaselineProfileRule() @Test fun generate() = baselineProfileRule.collect(PACKAGE_NAME) { startActivity() device.waitAndFindObject(By.res("add"), 1000) .click() } }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/baselineprofile/StartupBaselineProfile.kt
2049966632
/* *abiola 2022 */ package com.mshdabiola.benchmarks.baselineprofile import androidx.benchmark.macro.MacrobenchmarkScope import androidx.benchmark.macro.junit4.BaselineProfileRule import com.mshdabiola.benchmarks.PACKAGE_NAME import com.mshdabiola.benchmarks.startActivity import org.junit.Rule import org.junit.Test /** * Baseline Profile for app startup. This profile also enables using [Dex Layout Optimizations](https://developer.android.com/topic/performance/baselineprofiles/dex-layout-optimizations) * via the `includeInStartupProfile` parameter. */ class StartupBaselineProfile { @get:Rule val baselineProfileRule = BaselineProfileRule() @Test fun generate() = baselineProfileRule.collect( PACKAGE_NAME, includeInStartupProfile = true, profileBlock = MacrobenchmarkScope::startActivity, ) }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/Utils.kt
1189744675
/* *abiola 2022 */ package com.mshdabiola.benchmarks import androidx.test.uiautomator.BySelector import androidx.test.uiautomator.Direction import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiObject2 import androidx.test.uiautomator.Until import java.io.ByteArrayOutputStream /** * Convenience parameter to use proper package name with regards to build type and build flavor. */ val PACKAGE_NAME = buildString { append("com.mshdabiola.skeletonandroid") // 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) } /** * Waits until an object with [selector] if visible on screen and returns the object. * If the element is not available in [timeout], throws [AssertionError] */ fun UiDevice.waitAndFindObject(selector: BySelector, timeout: Long): UiObject2 { if (!wait(Until.hasObject(selector), timeout)) { throw AssertionError("Element not found on screen in ${timeout}ms (selector=$selector)") } return findObject(selector) } /** * Helper to dump window hierarchy into a string. */ fun UiDevice.dumpWindowHierarchy(): String { val buffer = ByteArrayOutputStream() dumpWindowHierarchy(buffer) return buffer.toString() }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/foryou/ScrollForYouFeedBenchmark.kt
2186302336
/* *abiola 2022 */ package com.mshdabiola.benchmarks.foryou import androidx.benchmark.macro.CompilationMode import androidx.benchmark.macro.FrameTimingMetric import androidx.benchmark.macro.StartupMode import androidx.benchmark.macro.junit4.MacrobenchmarkRule import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner import com.mshdabiola.benchmarks.PACKAGE_NAME import com.mshdabiola.benchmarks.startActivityAndAllowNotifications import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4ClassRunner::class) class ScrollForYouFeedBenchmark { @get:Rule val benchmarkRule = MacrobenchmarkRule() @Test fun scrollFeedCompilationNone() = scrollFeed(CompilationMode.None()) @Test fun scrollFeedCompilationBaselineProfile() = scrollFeed(CompilationMode.Partial()) private fun scrollFeed(compilationMode: CompilationMode) = benchmarkRule.measureRepeated( packageName = PACKAGE_NAME, metrics = listOf(FrameTimingMetric()), compilationMode = compilationMode, iterations = 10, startupMode = StartupMode.WARM, setupBlock = { // Start the app pressHome() startActivityAndAllowNotifications() }, ) { forYouWaitForContent() forYouSelectTopics() forYouScrollFeedDownUp() } }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/foryou/ForYouActions.kt
3002783591
/* *abiola 2022 */ package com.mshdabiola.benchmarks.foryou import androidx.benchmark.macro.MacrobenchmarkScope import androidx.test.uiautomator.By import com.mshdabiola.benchmarks.flingElementDownUp import org.junit.Assert.fail fun MacrobenchmarkScope.forYouWaitForContent() { // Wait until content is loaded by checking if topics are loaded // device.wait(Until.gone(By.res("loadingWheel")), 5_000) // Sometimes, the loading wheel is gone, but the content is not loaded yet // So we'll wait here for topics to be sure // val obj = device.waitAndFindObject(By.res("forYou:topicSelection"), 10_000) // Timeout here is quite big, because sometimes data loading takes a long time! // obj.wait(untilHasChildren(), 60_000) } /** * Selects some topics, which will show the feed content for them. * [recheckTopicsIfChecked] Topics may be already checked from the previous iteration. */ fun MacrobenchmarkScope.forYouSelectTopics(recheckTopicsIfChecked: Boolean = false) { val topics = device.findObject(By.res("forYou:topicSelection")) // Set gesture margin from sides not to trigger system gesture navigation val horizontalMargin = 10 * topics.visibleBounds.width() / 100 topics.setGestureMargins(horizontalMargin, 0, horizontalMargin, 0) // Select some topics to show some feed content var index = 0 var visited = 0 while (visited < 3) { if (topics.childCount == 0) { fail("No topics found, can't generate profile for ForYou page.") } // Selecting some topics, which will populate items in the feed. val topic = topics.children[index % topics.childCount] // Find the checkable element to figure out whether it's checked or not val topicCheckIcon = topic.findObject(By.checkable(true)) // Topic icon may not be visible if it's out of the screen boundaries // If that's the case, let's try another index if (topicCheckIcon == null) { index++ continue } when { // Topic wasn't checked, so just do that !topicCheckIcon.isChecked -> { topic.click() device.waitForIdle() } // Topic was checked already and we want to recheck it, so just do it twice recheckTopicsIfChecked -> { repeat(2) { topic.click() device.waitForIdle() } } else -> { // Topic is checked, but we don't recheck it } } index++ visited++ } } fun MacrobenchmarkScope.forYouScrollFeedDownUp() { val feedList = device.findObject(By.res("forYou:feed")) device.flingElementDownUp(feedList) } fun MacrobenchmarkScope.setAppTheme(isDark: Boolean) { when (isDark) { true -> device.findObject(By.text("Dark")).click() false -> device.findObject(By.text("Light")).click() } device.waitForIdle() device.findObject(By.text("OK")).click() }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/GeneralActions.kt
3760253681
/* *abiola 2023 */ package com.mshdabiola.benchmarks import android.Manifest.permission import android.os.Build.VERSION.SDK_INT import android.os.Build.VERSION_CODES.TIRAMISU import androidx.benchmark.macro.MacrobenchmarkScope /** * Because the app under test is different from the one running the instrumentation test, * the permission has to be granted manually by either: * * - tapping the Allow button * ```kotlin * val obj = By.text("Allow") * val dialog = device.wait(Until.findObject(obj), TIMEOUT) * dialog?.let { * it.click() * device.wait(Until.gone(obj), 5_000) * } * ``` * - or (preferred) executing the grant command on the target package. */ fun MacrobenchmarkScope.allowNotifications() { if (SDK_INT >= TIRAMISU) { val command = "pm grant $packageName ${permission.POST_NOTIFICATIONS}" device.executeShellCommand(command) } } /** * Wraps starting the default activity, waiting for it to start and then allowing notifications in * one convenient call. */ fun MacrobenchmarkScope.startActivityAndAllowNotifications() { startActivityAndWait() allowNotifications() } fun MacrobenchmarkScope.startActivity() { startActivityAndWait() }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/bookmarks/BookmarksActions.kt
2476347451
/* *abiola 2022 */ package com.mshdabiola.benchmarks.bookmarks import androidx.benchmark.macro.MacrobenchmarkScope import androidx.test.uiautomator.By fun MacrobenchmarkScope.goToBookmarksScreen() { val savedSelector = By.text("Saved") val savedButton = device.findObject(savedSelector) savedButton.click() device.waitForIdle() // Wait until saved title are shown on screen }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/startup/StartupBenchmark.kt
2708473760
/* *abiola 2022 */ package com.mshdabiola.benchmarks.startup import androidx.benchmark.macro.BaselineProfileMode.Disable import androidx.benchmark.macro.BaselineProfileMode.Require import androidx.benchmark.macro.CompilationMode import androidx.benchmark.macro.StartupMode.COLD import androidx.benchmark.macro.StartupTimingMetric import androidx.benchmark.macro.junit4.MacrobenchmarkRule import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner import com.mshdabiola.benchmarks.PACKAGE_NAME import com.mshdabiola.benchmarks.foryou.forYouWaitForContent import com.mshdabiola.benchmarks.startActivity import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Enables app startups from various states of baseline profile or [CompilationMode]s. * Run this benchmark from Studio to see startup measurements, and captured system traces * for investigating your app's performance from a cold state. */ @RunWith(AndroidJUnit4ClassRunner::class) class StartupBenchmark { @get:Rule val benchmarkRule = MacrobenchmarkRule() @Test fun startupWithoutPreCompilation() = startup(CompilationMode.None()) @Test fun startupWithPartialCompilationAndDisabledBaselineProfile() = startup( CompilationMode.Partial(baselineProfileMode = Disable, warmupIterations = 1), ) @Test fun startupPrecompiledWithBaselineProfile() = startup(CompilationMode.Partial(baselineProfileMode = Require)) @Test fun startupFullyPrecompiled() = startup(CompilationMode.Full()) private fun startup(compilationMode: CompilationMode) = benchmarkRule.measureRepeated( packageName = PACKAGE_NAME, metrics = listOf(StartupTimingMetric()), compilationMode = compilationMode, // More iterations result in higher statistical significance. iterations = 20, startupMode = COLD, setupBlock = { pressHome() // allowNotifications() }, ) { startActivity() // Waits until the content is ready to capture Time To Full Display forYouWaitForContent() } }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/interests/InterestsActions.kt
339685600
/* *abiola 2022 */ package com.mshdabiola.benchmarks.interests import androidx.benchmark.macro.MacrobenchmarkScope import androidx.test.uiautomator.By import androidx.test.uiautomator.Until import com.mshdabiola.benchmarks.flingElementDownUp fun MacrobenchmarkScope.goToInterestsScreen() { device.findObject(By.text("Interests")).click() device.waitForIdle() // Wait until interests are shown on screen // Wait until content is loaded by checking if interests are loaded device.wait(Until.gone(By.res("loadingWheel")), 5_000) } fun MacrobenchmarkScope.interestsScrollTopicsDownUp() { device.wait(Until.hasObject(By.res("interests:topics")), 5_000) val topicsList = device.findObject(By.res("interests:topics")) device.flingElementDownUp(topicsList) } 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() }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/interests/ScrollTopicListPowerMetricsBenchmark.kt
656857661
/* *abiola 2023 */ package com.mshdabiola.benchmarks.interests import android.os.Build.VERSION_CODES import androidx.annotation.RequiresApi import androidx.benchmark.macro.CompilationMode import androidx.benchmark.macro.ExperimentalMetricApi import androidx.benchmark.macro.FrameTimingMetric import androidx.benchmark.macro.PowerCategory import androidx.benchmark.macro.PowerCategoryDisplayLevel import androidx.benchmark.macro.PowerMetric 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.mshdabiola.benchmarks.PACKAGE_NAME import com.mshdabiola.benchmarks.allowNotifications import com.mshdabiola.benchmarks.foryou.forYouScrollFeedDownUp import com.mshdabiola.benchmarks.foryou.forYouSelectTopics import com.mshdabiola.benchmarks.foryou.forYouWaitForContent import com.mshdabiola.benchmarks.foryou.setAppTheme import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalMetricApi::class) @RequiresApi(VERSION_CODES.Q) @RunWith(AndroidJUnit4::class) class ScrollTopicListPowerMetricsBenchmark { @get:Rule val benchmarkRule = MacrobenchmarkRule() private val categories = PowerCategory.entries .associateWith { PowerCategoryDisplayLevel.TOTAL } @Test fun benchmarkStateChangeCompilationLight() = benchmarkStateChangeWithTheme(CompilationMode.Partial(), false) @Test fun benchmarkStateChangeCompilationDark() = benchmarkStateChangeWithTheme(CompilationMode.Partial(), true) private fun benchmarkStateChangeWithTheme(compilationMode: CompilationMode, isDark: Boolean) = benchmarkRule.measureRepeated( packageName = PACKAGE_NAME, metrics = listOf(FrameTimingMetric(), PowerMetric(PowerMetric.Energy(categories))), compilationMode = compilationMode, iterations = 2, startupMode = StartupMode.WARM, setupBlock = { // Start the app pressHome() startActivityAndWait() allowNotifications() // Navigate to Settings device.findObject(By.desc("Settings")).click() device.waitForIdle() setAppTheme(isDark) }, ) { forYouWaitForContent() forYouSelectTopics() repeat(3) { forYouScrollFeedDownUp() } } }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/interests/ScrollTopicListBenchmark.kt
525499308
/* *abiola 2023 */ package com.mshdabiola.benchmarks.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.mshdabiola.benchmarks.PACKAGE_NAME import com.mshdabiola.benchmarks.startActivityAndAllowNotifications import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ScrollTopicListBenchmark { @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() startActivityAndAllowNotifications() // Navigate to interests screen device.findObject(By.text("Interests")).click() device.waitForIdle() }, ) { interestsWaitForTopics() repeat(3) { interestsScrollTopicsDownUp() } } }
SkeletonAndroid/benchmarks/src/main/kotlin/com/mshdabiola/benchmarks/interests/TopicsScreenRecompositionBenchmark.kt
3363281581
/* *abiola 2022 */ package com.mshdabiola.benchmarks.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.mshdabiola.benchmarks.PACKAGE_NAME import com.mshdabiola.benchmarks.startActivityAndAllowNotifications 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() startActivityAndAllowNotifications() // Navigate to interests screen device.findObject(By.text("Interests")).click() device.waitForIdle() }, ) { interestsWaitForTopics() repeat(3) { interestsToggleBookmarked() } } }
SkeletonAndroid/modules/ui/src/androidTest/kotlin/com/mshdabiola/ui/NewsResourceCardTest.kt
1102647969
/* *abiola 2024 */ package com.mshdabiola.ui import androidx.activity.ComponentActivity import androidx.compose.ui.test.junit4.createAndroidComposeRule import org.junit.Rule import org.junit.Test class NewsResourceCardTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun testMetaDataDisplay_withCodelabResource() { // composeTestRule.setContent { // } // // composeTestRule // .onNodeWithText( // "", // ) // .assertExists() } }
SkeletonAndroid/modules/ui/src/main/kotlin/com/mshdabiola/ui/DevicePreviews.kt
3460879350
/* *abiola 2024 */ package com.mshdabiola.ui import androidx.compose.ui.tooling.preview.Preview /** * Multipreview annotation that represents various device sizes. Add this annotation to a composable * to render various devices. */ @Preview(name = "phone", device = "spec:shape=Normal,width=360,height=640,unit=dp,dpi=480") @Preview(name = "landscape", device = "spec:shape=Normal,width=640,height=360,unit=dp,dpi=480") @Preview(name = "foldable", device = "spec:shape=Normal,width=673,height=841,unit=dp,dpi=480") @Preview(name = "tablet", device = "spec:shape=Normal,width=1280,height=800,unit=dp,dpi=480") annotation class DevicePreviews
SkeletonAndroid/modules/ui/src/main/kotlin/com/mshdabiola/ui/TimeZoneBroadcastReceiver.kt
2561224461
/* *abiola 2024 */ package com.mshdabiola.ui import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter class TimeZoneBroadcastReceiver( val onTimeZoneChanged: () -> Unit, ) : BroadcastReceiver() { private var registered = false override fun onReceive(context: Context, intent: Intent) { if (intent.action == Intent.ACTION_TIMEZONE_CHANGED) { onTimeZoneChanged() } } fun register(context: Context) { if (!registered) { val filter = IntentFilter() filter.addAction(Intent.ACTION_TIMEZONE_CHANGED) context.registerReceiver(this, filter) registered = true } } fun unregister(context: Context) { if (registered) { context.unregisterReceiver(this) registered = false } } }
SkeletonAndroid/modules/ui/src/main/kotlin/com/mshdabiola/ui/Notes.kt
1278602720
/* *abiola 2022 */ package com.mshdabiola.ui import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.staggeredgrid.items import androidx.compose.material3.ListItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.mshdabiola.analytics.LocalAnalyticsHelper import com.mshdabiola.designsystem.theme.SkTheme @OptIn(ExperimentalFoundationApi::class) fun LazyListScope.noteItem( feedMainState: MainState, onClick: (Long) -> Unit = {}, ) { when (feedMainState) { MainState.Loading -> Unit is MainState.Success -> { items( items = feedMainState.noteUiStates, key = { it.id }, contentType = { "newsFeedItem" }, ) { note -> val analyticsHelper = LocalAnalyticsHelper.current NoteUi( noteUiState = note, onClick = { analyticsHelper.logNoteOpened( newsResourceId = note.id.toString(), ) onClick(note.id) // launchCustomChromeTab(context, Uri.parse(""), backgroundColor) }, modifier = Modifier .padding(horizontal = 8.dp) .animateItemPlacement(), ) } } } } @Composable fun NoteUi( modifier: Modifier, noteUiState: NoteUiState, onClick: (Long) -> Unit, ) { ListItem( modifier = modifier.clickable { onClick(noteUiState.id) }, headlineContent = { Text(text = noteUiState.title) }, supportingContent = { Text(text = noteUiState.description) }, ) } sealed interface MainState { data object Loading : MainState data class Success( val noteUiStates: List<NoteUiState>, ) : MainState } data class NoteUiState( val id: Long, val title: String, val description: String, ) @Preview @Composable private fun NoteUiPreview() { SkTheme { LazyColumn { noteItem( feedMainState = MainState.Loading, ) } } }
SkeletonAndroid/modules/ui/src/main/kotlin/com/mshdabiola/ui/AnalyticsExtensions.kt
2588512741
/* *abiola 2024 */ package com.mshdabiola.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import com.mshdabiola.analytics.AnalyticsEvent import com.mshdabiola.analytics.AnalyticsEvent.Param import com.mshdabiola.analytics.AnalyticsEvent.ParamKeys import com.mshdabiola.analytics.AnalyticsEvent.Types import com.mshdabiola.analytics.AnalyticsHelper import com.mshdabiola.analytics.LocalAnalyticsHelper /** * Classes and functions associated with analytics events for the UI. */ fun AnalyticsHelper.logScreenView(screenName: String) { logEvent( AnalyticsEvent( type = Types.SCREEN_VIEW, extras = listOf( Param(ParamKeys.SCREEN_NAME, screenName), ), ), ) } fun AnalyticsHelper.logNoteOpened(newsResourceId: String) { logEvent( event = AnalyticsEvent( type = "open_opened", extras = listOf( Param("open_opened", newsResourceId), ), ), ) } /** * A side-effect which records a screen view event. */ @Composable fun TrackScreenViewEvent( screenName: String, analyticsHelper: AnalyticsHelper = LocalAnalyticsHelper.current, ) = DisposableEffect(Unit) { analyticsHelper.logScreenView(screenName) onDispose {} }
SkeletonAndroid/modules/ui/src/main/kotlin/com/mshdabiola/ui/JankStatsExtensions.kt
1538956032
/* *abiola 2024 */ package com.mshdabiola.ui import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.DisposableEffectResult import androidx.compose.runtime.DisposableEffectScope import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.platform.LocalView import androidx.metrics.performance.PerformanceMetricsState import androidx.metrics.performance.PerformanceMetricsState.Holder import kotlinx.coroutines.CoroutineScope /** * Retrieves [PerformanceMetricsState.Holder] from current [LocalView] and * remembers it until the View changes. * @see PerformanceMetricsState.getHolderForHierarchy */ @Composable fun rememberMetricsStateHolder(): Holder { val localView = LocalView.current return remember(localView) { PerformanceMetricsState.getHolderForHierarchy(localView) } } /** * Convenience function to work with [PerformanceMetricsState] state. The side effect is * re-launched if any of the [keys] value is not equal to the previous composition. * @see TrackDisposableJank if you need to work with DisposableEffect to cleanup added state. */ @Composable fun TrackJank( vararg keys: Any, reportMetric: suspend CoroutineScope.(state: Holder) -> Unit, ) { val metrics = rememberMetricsStateHolder() LaunchedEffect(metrics, *keys) { reportMetric(metrics) } } /** * Convenience function to work with [PerformanceMetricsState] state that needs to be cleaned up. * The side effect is re-launched if any of the [keys] value is not equal to the previous composition. */ @Composable fun TrackDisposableJank( vararg keys: Any, reportMetric: DisposableEffectScope.(state: Holder) -> DisposableEffectResult, ) { val metrics = rememberMetricsStateHolder() DisposableEffect(metrics, *keys) { reportMetric(this, metrics) } } /** * Track jank while scrolling anything that's scrollable. */ @Composable fun TrackScrollJank(scrollableState: ScrollableState, stateName: String) { TrackJank(scrollableState) { metricsHolder -> snapshotFlow { scrollableState.isScrollInProgress }.collect { isScrollInProgress -> metricsHolder.state?.apply { if (isScrollInProgress) { putState(stateName, "Scrolling=true") } else { removeState(stateName) } } } } }
SkeletonAndroid/modules/database/src/androidTest/java/com/mshdabiola/database/NoteDaoTest.kt
530007263
/* *abiola 2024 */ package com.mshdabiola.database import android.content.Context import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.mshdabiola.database.dao.NoteDao import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class NoteDaoTest { private lateinit var noteDao: NoteDao private lateinit var db: SkeletonDatabase @Before fun createDb() { val content = ApplicationProvider.getApplicationContext<Context>() db = Room.inMemoryDatabaseBuilder(content, SkeletonDatabase::class.java).build() noteDao = db.getNoteDao() } @Test fun upsertTest() = runTest { } @Test fun deleteTest() = runTest { } @Test fun deleteByIdTest() = runTest { } }
SkeletonAndroid/modules/database/src/test/java/com/mshdabiola/database/ExampleUnitTest.kt
638018253
/* *abiola 2024 */ package com.mshdabiola.database import org.junit.Assert.assertEquals import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
SkeletonAndroid/modules/database/src/main/java/com/mshdabiola/database/dao/NoteDao.kt
3968116016
/* *abiola 2024 */ package com.mshdabiola.database.dao import androidx.room.Dao import androidx.room.Query import androidx.room.Upsert import com.mshdabiola.database.model.NoteEntity import kotlinx.coroutines.flow.Flow @Dao interface NoteDao { @Upsert suspend fun upsert(noteEntity: NoteEntity): Long @Query("SELECT * FROM note_table") fun getAll(): Flow<List<NoteEntity>> @Query("SELECT * FROM note_table WHERE id = :id") fun getOne(id: Long): Flow<NoteEntity?> @Query("DELETE FROM NOTE_TABLE WHERE id = :id") suspend fun delete(id: Long) }
SkeletonAndroid/modules/database/src/main/java/com/mshdabiola/database/DaosModule.kt
3026618865
/* *abiola 2024 */ package com.mshdabiola.database import com.mshdabiola.database.dao.NoteDao import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) object DaosModule { @Provides fun noteDaoProvider(db: SkeletonDatabase): NoteDao { return db.getNoteDao() } }
SkeletonAndroid/modules/database/src/main/java/com/mshdabiola/database/model/NoteEntity.kt
1994784706
/* *abiola 2024 */ package com.mshdabiola.database.model import androidx.room.Entity import androidx.room.PrimaryKey import com.mshdabiola.model.Note @Entity(tableName = "note_table") data class NoteEntity( @PrimaryKey(true) val id: Long?, val title: String, val content: String, ) fun NoteEntity.asExternalNote() = Note(id, title, content)
SkeletonAndroid/modules/database/src/main/java/com/mshdabiola/database/DatabaseMigrations.kt
1435206370
/* *abiola 2024 */ package com.mshdabiola.database import androidx.room.DeleteColumn import androidx.room.DeleteTable import androidx.room.RenameColumn import androidx.room.migration.AutoMigrationSpec /** * Automatic schema migrations sometimes require extra instructions to perform the migration, for * example, when a column is renamed. These extra instructions are placed here by creating a class * using the following naming convention `SchemaXtoY` where X is the schema version you're migrating * from and Y is the schema version you're migrating to. The class should implement * `AutoMigrationSpec`. */ object DatabaseMigrations { @RenameColumn( tableName = "topics", fromColumnName = "description", toColumnName = "shortDescription", ) class Schema2to3 : AutoMigrationSpec @DeleteColumn( tableName = "news_resources", columnName = "episode_id", ) @DeleteTable.Entries( DeleteTable( tableName = "episodes_authors", ), DeleteTable( tableName = "episodes", ), ) class Schema10to11 : AutoMigrationSpec @DeleteTable.Entries( DeleteTable( tableName = "news_resources_authors", ), DeleteTable( tableName = "authors", ), ) class Schema11to12 : AutoMigrationSpec }
SkeletonAndroid/modules/database/src/main/java/com/mshdabiola/database/DatabaseModule.kt
3976609723
/* *abiola 2024 */ package com.mshdabiola.database import android.content.Context import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun databaseProvider( @ApplicationContext context: Context, ): SkeletonDatabase { return Room.databaseBuilder(context, SkeletonDatabase::class.java, "skeletonDb.db") .build() // return Room.inMemoryDatabaseBuilder(context,LudoDatabase::class.java,) // .build() } }
SkeletonAndroid/modules/database/src/main/java/com/mshdabiola/database/SkeletonDatabase.kt
1385583330
/* *abiola 2024 */ package com.mshdabiola.database import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.mshdabiola.database.dao.NoteDao import com.mshdabiola.database.model.NoteEntity @Database( entities = [NoteEntity::class], version = 1, // autoMigrations = [ // //AutoMigration(from = 2, to = 3, spec = DatabaseMigrations.Schema2to3::class), // // ] // , exportSchema = true, ) @TypeConverters() abstract class SkeletonDatabase : RoomDatabase() { abstract fun getNoteDao(): NoteDao // // abstract fun getPlayerDao(): PlayerDao // // abstract fun getPawnDao(): PawnDao }
SkeletonAndroid/modules/designsystem/src/androidTest/kotlin/com/mshdabiola/designsystem/ThemeTest.kt
1363523794
/* *abiola 2024 */ package com.mshdabiola.designsystem import android.os.Build.VERSION.SDK_INT import android.os.Build.VERSION_CODES import androidx.compose.material3.ColorScheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.dynamicDarkColorScheme 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.test.junit4.createComposeRule import androidx.compose.ui.unit.dp import com.mshdabiola.designsystem.theme.BackgroundTheme import com.mshdabiola.designsystem.theme.DarkAndroidBackgroundTheme import com.mshdabiola.designsystem.theme.DarkAndroidColorScheme import com.mshdabiola.designsystem.theme.DarkAndroidGradientColors import com.mshdabiola.designsystem.theme.DarkDefaultColorScheme import com.mshdabiola.designsystem.theme.GradientColors import com.mshdabiola.designsystem.theme.LightAndroidBackgroundTheme import com.mshdabiola.designsystem.theme.LightAndroidColorScheme import com.mshdabiola.designsystem.theme.LightAndroidGradientColors import com.mshdabiola.designsystem.theme.LightDefaultColorScheme import com.mshdabiola.designsystem.theme.LocalBackgroundTheme import com.mshdabiola.designsystem.theme.LocalGradientColors import com.mshdabiola.designsystem.theme.LocalTintTheme import com.mshdabiola.designsystem.theme.SkTheme import com.mshdabiola.designsystem.theme.TintTheme import org.junit.Rule import org.junit.Test import kotlin.test.assertEquals /** * Tests [SkTheme] using different combinations of the theme mode parameters: * darkTheme, disableDynamicTheming, and androidTheme. * * It verifies that the various composition locals — [MaterialTheme], [LocalGradientColors] and * [LocalBackgroundTheme] — have the expected values for a given theme mode, as specified by the * design system. */ class ThemeTest { @get:Rule val composeTestRule = createComposeRule() @Test fun darkThemeFalse_dynamicColorFalse_androidThemeFalse() { composeTestRule.setContent { SkTheme( darkTheme = false, disableDynamicTheming = true, androidTheme = false, ) { val colorScheme = LightDefaultColorScheme assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) val gradientColors = defaultGradientColors(colorScheme) assertEquals(gradientColors, LocalGradientColors.current) val backgroundTheme = defaultBackgroundTheme(colorScheme) assertEquals(backgroundTheme, LocalBackgroundTheme.current) val tintTheme = defaultTintTheme() assertEquals(tintTheme, LocalTintTheme.current) } } } @Test fun darkThemeTrue_dynamicColorFalse_androidThemeFalse() { composeTestRule.setContent { SkTheme( darkTheme = true, disableDynamicTheming = true, androidTheme = false, ) { val colorScheme = DarkDefaultColorScheme assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) val gradientColors = defaultGradientColors(colorScheme) assertEquals(gradientColors, LocalGradientColors.current) val backgroundTheme = defaultBackgroundTheme(colorScheme) assertEquals(backgroundTheme, LocalBackgroundTheme.current) val tintTheme = defaultTintTheme() assertEquals(tintTheme, LocalTintTheme.current) } } } @Test fun darkThemeFalse_dynamicColorTrue_androidThemeFalse() { composeTestRule.setContent { SkTheme( darkTheme = false, disableDynamicTheming = false, androidTheme = false, ) { val colorScheme = dynamicLightColorSchemeWithFallback() assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) val gradientColors = dynamicGradientColorsWithFallback(colorScheme) assertEquals(gradientColors, LocalGradientColors.current) val backgroundTheme = defaultBackgroundTheme(colorScheme) assertEquals(backgroundTheme, LocalBackgroundTheme.current) val tintTheme = dynamicTintThemeWithFallback(colorScheme) assertEquals(tintTheme, LocalTintTheme.current) } } } @Test fun darkThemeTrue_dynamicColorTrue_androidThemeFalse() { composeTestRule.setContent { SkTheme( darkTheme = true, disableDynamicTheming = false, androidTheme = false, ) { val colorScheme = dynamicDarkColorSchemeWithFallback() assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) val gradientColors = dynamicGradientColorsWithFallback(colorScheme) assertEquals(gradientColors, LocalGradientColors.current) val backgroundTheme = defaultBackgroundTheme(colorScheme) assertEquals(backgroundTheme, LocalBackgroundTheme.current) val tintTheme = dynamicTintThemeWithFallback(colorScheme) assertEquals(tintTheme, LocalTintTheme.current) } } } @Test fun darkThemeFalse_dynamicColorFalse_androidThemeTrue() { composeTestRule.setContent { SkTheme( darkTheme = false, disableDynamicTheming = true, androidTheme = true, ) { val colorScheme = LightAndroidColorScheme assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) val gradientColors = LightAndroidGradientColors assertEquals(gradientColors, LocalGradientColors.current) val backgroundTheme = LightAndroidBackgroundTheme assertEquals(backgroundTheme, LocalBackgroundTheme.current) val tintTheme = defaultTintTheme() assertEquals(tintTheme, LocalTintTheme.current) } } } @Test fun darkThemeTrue_dynamicColorFalse_androidThemeTrue() { composeTestRule.setContent { SkTheme( darkTheme = true, disableDynamicTheming = true, androidTheme = true, ) { val colorScheme = DarkAndroidColorScheme assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) val gradientColors = DarkAndroidGradientColors assertEquals(gradientColors, LocalGradientColors.current) val backgroundTheme = DarkAndroidBackgroundTheme assertEquals(backgroundTheme, LocalBackgroundTheme.current) val tintTheme = defaultTintTheme() assertEquals(tintTheme, LocalTintTheme.current) } } } @Test fun darkThemeFalse_dynamicColorTrue_androidThemeTrue() { composeTestRule.setContent { SkTheme( darkTheme = false, disableDynamicTheming = false, androidTheme = true, ) { val colorScheme = LightAndroidColorScheme assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) val gradientColors = LightAndroidGradientColors assertEquals(gradientColors, LocalGradientColors.current) val backgroundTheme = LightAndroidBackgroundTheme assertEquals(backgroundTheme, LocalBackgroundTheme.current) val tintTheme = defaultTintTheme() assertEquals(tintTheme, LocalTintTheme.current) } } } @Test fun darkThemeTrue_dynamicColorTrue_androidThemeTrue() { composeTestRule.setContent { SkTheme( darkTheme = true, disableDynamicTheming = false, androidTheme = true, ) { val colorScheme = DarkAndroidColorScheme assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme) val gradientColors = DarkAndroidGradientColors assertEquals(gradientColors, LocalGradientColors.current) val backgroundTheme = DarkAndroidBackgroundTheme assertEquals(backgroundTheme, LocalBackgroundTheme.current) val tintTheme = defaultTintTheme() assertEquals(tintTheme, LocalTintTheme.current) } } } @Composable private fun dynamicLightColorSchemeWithFallback(): ColorScheme = when { SDK_INT >= VERSION_CODES.S -> dynamicLightColorScheme(LocalContext.current) else -> LightDefaultColorScheme } @Composable private fun dynamicDarkColorSchemeWithFallback(): ColorScheme = when { SDK_INT >= VERSION_CODES.S -> dynamicDarkColorScheme(LocalContext.current) else -> DarkDefaultColorScheme } private fun emptyGradientColors(colorScheme: ColorScheme): GradientColors = GradientColors(container = colorScheme.surfaceColorAtElevation(2.dp)) private fun defaultGradientColors(colorScheme: ColorScheme): GradientColors = GradientColors( top = colorScheme.inverseOnSurface, bottom = colorScheme.primaryContainer, container = colorScheme.surface, ) private fun dynamicGradientColorsWithFallback(colorScheme: ColorScheme): GradientColors = when { SDK_INT >= VERSION_CODES.S -> emptyGradientColors(colorScheme) else -> defaultGradientColors(colorScheme) } private fun defaultBackgroundTheme(colorScheme: ColorScheme): BackgroundTheme = BackgroundTheme( color = colorScheme.surface, tonalElevation = 2.dp, ) private fun defaultTintTheme(): TintTheme = TintTheme() private fun dynamicTintThemeWithFallback(colorScheme: ColorScheme): TintTheme = when { SDK_INT >= VERSION_CODES.S -> TintTheme(colorScheme.primary) else -> TintTheme() } /** * Workaround for the fact that the NiA design system specify all color scheme values. */ private fun assertColorSchemesEqual( expectedColorScheme: ColorScheme, actualColorScheme: ColorScheme, ) { assertEquals(expectedColorScheme.primary, actualColorScheme.primary) assertEquals(expectedColorScheme.onPrimary, actualColorScheme.onPrimary) assertEquals(expectedColorScheme.primaryContainer, actualColorScheme.primaryContainer) assertEquals(expectedColorScheme.onPrimaryContainer, actualColorScheme.onPrimaryContainer) assertEquals(expectedColorScheme.secondary, actualColorScheme.secondary) assertEquals(expectedColorScheme.onSecondary, actualColorScheme.onSecondary) assertEquals(expectedColorScheme.secondaryContainer, actualColorScheme.secondaryContainer) assertEquals( expectedColorScheme.onSecondaryContainer, actualColorScheme.onSecondaryContainer, ) assertEquals(expectedColorScheme.tertiary, actualColorScheme.tertiary) assertEquals(expectedColorScheme.onTertiary, actualColorScheme.onTertiary) assertEquals(expectedColorScheme.tertiaryContainer, actualColorScheme.tertiaryContainer) assertEquals(expectedColorScheme.onTertiaryContainer, actualColorScheme.onTertiaryContainer) assertEquals(expectedColorScheme.error, actualColorScheme.error) assertEquals(expectedColorScheme.onError, actualColorScheme.onError) assertEquals(expectedColorScheme.errorContainer, actualColorScheme.errorContainer) assertEquals(expectedColorScheme.onErrorContainer, actualColorScheme.onErrorContainer) assertEquals(expectedColorScheme.background, actualColorScheme.background) assertEquals(expectedColorScheme.onBackground, actualColorScheme.onBackground) assertEquals(expectedColorScheme.surface, actualColorScheme.surface) assertEquals(expectedColorScheme.onSurface, actualColorScheme.onSurface) assertEquals(expectedColorScheme.surfaceVariant, actualColorScheme.surfaceVariant) assertEquals(expectedColorScheme.onSurfaceVariant, actualColorScheme.onSurfaceVariant) assertEquals(expectedColorScheme.inverseSurface, actualColorScheme.inverseSurface) assertEquals(expectedColorScheme.inverseOnSurface, actualColorScheme.inverseOnSurface) assertEquals(expectedColorScheme.outline, actualColorScheme.outline) } }
SkeletonAndroid/modules/designsystem/src/test/kotlin/com/mshdabiola/designsystem/TopAppBarScreenshotTests.kt
1003364243
/* *abiola 2024 */ package com.mshdabiola.designsystem import androidx.activity.ComponentActivity import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onRoot import com.github.takahirom.roborazzi.captureRoboImage import com.google.accompanist.testharness.TestHarness import com.mshdabiola.designsystem.component.SkTopAppBar import com.mshdabiola.designsystem.icon.SkIcons import com.mshdabiola.designsystem.theme.SkTheme import com.mshdabiola.testing.util.DefaultRoborazziOptions import com.mshdabiola.testing.util.captureMultiTheme import dagger.hilt.android.testing.HiltTestApplication import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.annotation.GraphicsMode import org.robolectric.annotation.LooperMode @OptIn(ExperimentalMaterial3Api::class) @RunWith(RobolectricTestRunner::class) @GraphicsMode(GraphicsMode.Mode.NATIVE) @Config(application = HiltTestApplication::class, qualifiers = "480dpi") @LooperMode(LooperMode.Mode.PAUSED) class TopAppBarScreenshotTests() { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun topAppBar_multipleThemes() { composeTestRule.captureMultiTheme("TopAppBar") { NiaTopAppBarExample() } } @Test fun topAppBar_hugeFont() { composeTestRule.setContent { CompositionLocalProvider( LocalInspectionMode provides true, ) { TestHarness(fontScale = 2f) { SkTheme { NiaTopAppBarExample() } } } } composeTestRule.onRoot() .captureRoboImage( "src/test/screenshots/TopAppBar/TopAppBar_fontScale2.png", roborazziOptions = DefaultRoborazziOptions, ) } @Composable private fun NiaTopAppBarExample() { SkTopAppBar( titleRes = android.R.string.untitled, navigationIcon = SkIcons.Search, navigationIconContentDescription = "Navigation icon", actionIcon = SkIcons.MoreVert, actionIconContentDescription = "Action icon", ) } }
SkeletonAndroid/modules/designsystem/src/test/kotlin/com/mshdabiola/designsystem/ButtonScreenshotTests.kt
779737397
/* *abiola 2024 */ package com.mshdabiola.designsystem import androidx.activity.ComponentActivity import androidx.compose.material3.Icon import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.ui.test.junit4.createAndroidComposeRule import com.mshdabiola.designsystem.component.SkButton import com.mshdabiola.designsystem.icon.SkIcons import com.mshdabiola.testing.util.captureMultiTheme import dagger.hilt.android.testing.HiltTestApplication import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.annotation.GraphicsMode import org.robolectric.annotation.LooperMode @RunWith(RobolectricTestRunner::class) @GraphicsMode(GraphicsMode.Mode.NATIVE) @Config(application = HiltTestApplication::class, qualifiers = "480dpi") @LooperMode(LooperMode.Mode.PAUSED) class ButtonScreenshotTests { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun niaButton_multipleThemes() { composeTestRule.captureMultiTheme("Button") { description -> Surface { SkButton(onClick = {}, text = { Text("$description Button") }) } } } // @Test // fun niaOutlineButton_multipleThemes() { // composeTestRule.captureMultiTheme("Button", "OutlineButton") { description -> // Surface { // NiaOutlinedButton(onClick = {}, text = { Text("$description OutlineButton") }) // } // } // } @Test fun niaButton_leadingIcon_multipleThemes() { composeTestRule.captureMultiTheme( name = "Button", overrideFileName = "ButtonLeadingIcon", shouldCompareAndroidTheme = false, ) { description -> Surface { SkButton( onClick = {}, text = { Text("$description Icon Button") }, leadingIcon = { Icon(imageVector = SkIcons.Add, contentDescription = null) }, ) } } } }
SkeletonAndroid/modules/designsystem/src/test/kotlin/com/mshdabiola/designsystem/BackgroundScreenshotTests.kt
2446901407
/* *abiola 2024 */ package com.mshdabiola.designsystem import androidx.activity.ComponentActivity import androidx.compose.foundation.layout.size import androidx.compose.material3.Text import androidx.compose.ui.Modifier import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.dp import com.mshdabiola.designsystem.component.SkBackground import com.mshdabiola.designsystem.component.SkGradientBackground import com.mshdabiola.testing.util.captureMultiTheme import dagger.hilt.android.testing.HiltTestApplication import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.annotation.GraphicsMode import org.robolectric.annotation.LooperMode @RunWith(RobolectricTestRunner::class) @GraphicsMode(GraphicsMode.Mode.NATIVE) @Config(application = HiltTestApplication::class, qualifiers = "480dpi") @LooperMode(LooperMode.Mode.PAUSED) class BackgroundScreenshotTests { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun niaBackground_multipleThemes() { composeTestRule.captureMultiTheme("Background") { description -> SkBackground(Modifier.size(100.dp)) { Text("$description background") } } } @Test fun niaGradientBackground_multipleThemes() { composeTestRule.captureMultiTheme("Background", "GradientBackground") { description -> SkGradientBackground(Modifier.size(100.dp)) { Text("$description background") } } } }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/component/LoadingWheel.kt
3791068731
/* *abiola 2022 */ package com.mshdabiola.designsystem.component import androidx.compose.animation.animateColor import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.StartOffset import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.keyframes import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import com.mshdabiola.designsystem.theme.SkTheme import kotlinx.coroutines.launch @Composable fun SkLoadingWheel( contentDesc: String, modifier: Modifier = Modifier, ) { val infiniteTransition = rememberInfiniteTransition(label = "wheel transition") // Specifies the float animation for slowly drawing out the lines on entering val startValue = if (LocalInspectionMode.current) 0F else 1F val floatAnimValues = (0 until NUM_OF_LINES).map { remember { Animatable(startValue) } } LaunchedEffect(floatAnimValues) { (0 until NUM_OF_LINES).map { index -> launch { floatAnimValues[index].animateTo( targetValue = 0F, animationSpec = tween( durationMillis = 100, easing = FastOutSlowInEasing, delayMillis = 40 * index, ), ) } } } // Specifies the rotation animation of the entire Canvas composable val rotationAnim by infiniteTransition.animateFloat( initialValue = 0F, targetValue = 360F, animationSpec = infiniteRepeatable( animation = tween(durationMillis = ROTATION_TIME, easing = LinearEasing), ), label = "wheel rotation animation", ) // Specifies the color animation for the base-to-progress line color change val baseLineColor = MaterialTheme.colorScheme.onBackground val progressLineColor = MaterialTheme.colorScheme.inversePrimary val colorAnimValues = (0 until NUM_OF_LINES).map { index -> infiniteTransition.animateColor( initialValue = baseLineColor, targetValue = baseLineColor, animationSpec = infiniteRepeatable( animation = keyframes { durationMillis = ROTATION_TIME / 2 progressLineColor at ROTATION_TIME / NUM_OF_LINES / 2 using LinearEasing baseLineColor at ROTATION_TIME / NUM_OF_LINES using LinearEasing }, repeatMode = RepeatMode.Restart, initialStartOffset = StartOffset(ROTATION_TIME / NUM_OF_LINES / 2 * index), ), label = "wheel color animation", ) } // Draws out the LoadingWheel Canvas composable and sets the animations Canvas( modifier = modifier .size(48.dp) .padding(8.dp) .graphicsLayer { rotationZ = rotationAnim } .semantics { contentDescription = contentDesc } .testTag("loadingWheel"), ) { repeat(NUM_OF_LINES) { index -> rotate(degrees = index * 30f) { drawLine( color = colorAnimValues[index].value, // Animates the initially drawn 1 pixel alpha from 0 to 1 alpha = if (floatAnimValues[index].value < 1f) 1f else 0f, strokeWidth = 4F, cap = StrokeCap.Round, start = Offset(size.width / 2, size.height / 4), end = Offset(size.width / 2, floatAnimValues[index].value * size.height / 4), ) } } } } @Composable fun SkOverlayLoadingWheel( contentDesc: String, modifier: Modifier = Modifier, ) { Surface( shape = RoundedCornerShape(60.dp), shadowElevation = 8.dp, color = MaterialTheme.colorScheme.surface.copy(alpha = 0.83f), modifier = modifier .size(60.dp), ) { SkLoadingWheel( contentDesc = contentDesc, ) } } @ThemePreviews @Composable fun NiaLoadingWheelPreview() { SkTheme { Surface { SkLoadingWheel(contentDesc = "LoadingWheel") } } } @ThemePreviews @Composable fun NiaOverlayLoadingWheelPreview() { SkTheme { Surface { SkOverlayLoadingWheel(contentDesc = "LoadingWheel") } } } private const val ROTATION_TIME = 12000 private const val NUM_OF_LINES = 12
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/component/DynamicAsyncImage.kt
285595099
/* *abiola 2024 */ package com.mshdabiola.designsystem.component import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color.Companion.Unspecified import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.compose.AsyncImagePainter.State.Error import coil.compose.AsyncImagePainter.State.Loading import coil.compose.rememberAsyncImagePainter import com.mshdabiola.designsystem.R import com.mshdabiola.designsystem.theme.LocalTintTheme /** * A wrapper around [AsyncImage] which determines the colorFilter based on the theme */ @Composable fun DynamicAsyncImage( imageUrl: String, contentDescription: String?, modifier: Modifier = Modifier, placeholder: Painter = painterResource(R.drawable.modules_designsystem_ic_placeholder_default), ) { val iconTint = LocalTintTheme.current.iconTint var isLoading by remember { mutableStateOf(true) } var isError by remember { mutableStateOf(false) } val imageLoader = rememberAsyncImagePainter( model = imageUrl, onState = { state -> isLoading = state is Loading isError = state is Error }, ) val isLocalInspection = LocalInspectionMode.current Box( modifier = modifier, contentAlignment = Alignment.Center, ) { if (isLoading && !isLocalInspection) { // Display a progress bar while loading CircularProgressIndicator( modifier = Modifier .align(Alignment.Center) .size(80.dp), color = MaterialTheme.colorScheme.tertiary, ) } Image( contentScale = ContentScale.Crop, painter = if (isError.not() && !isLocalInspection) imageLoader else placeholder, contentDescription = contentDescription, colorFilter = if (iconTint != Unspecified) ColorFilter.tint(iconTint) else null, ) } }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/component/Button.kt
1692525913
/* *abiola 2024 */ package com.mshdabiola.designsystem.component import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.sizeIn import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.mshdabiola.designsystem.icon.SkIcons import com.mshdabiola.designsystem.theme.SkTheme @Composable fun SkButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, contentPadding: PaddingValues = ButtonDefaults.ContentPadding, content: @Composable RowScope.() -> Unit, ) { Button( onClick = onClick, modifier = modifier, enabled = enabled, colors = ButtonDefaults.buttonColors( containerColor = MaterialTheme.colorScheme.onBackground, ), contentPadding = contentPadding, content = content, ) } @Composable fun SkButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, text: @Composable () -> Unit, leadingIcon: @Composable (() -> Unit)? = null, ) { SkButton( onClick = onClick, modifier = modifier, enabled = enabled, contentPadding = if (leadingIcon != null) { ButtonDefaults.ButtonWithIconContentPadding } else { ButtonDefaults.ContentPadding }, ) { SkButtonContent( text = text, leadingIcon = leadingIcon, ) } } @Composable private fun SkButtonContent( text: @Composable () -> Unit, leadingIcon: @Composable (() -> Unit)? = null, ) { if (leadingIcon != null) { Box(Modifier.sizeIn(maxHeight = ButtonDefaults.IconSize)) { leadingIcon() } } Box( Modifier .padding( start = if (leadingIcon != null) { ButtonDefaults.IconSpacing } else { 0.dp }, ), ) { text() } } @ThemePreviews @Composable fun ButtonPreview() { SkTheme { SkBackground(modifier = Modifier.size(150.dp, 50.dp)) { SkButton(onClick = {}, text = { Text("Test button") }) } } } @ThemePreviews @Composable fun ButtonPreview2() { SkTheme { SkBackground(modifier = Modifier.size(150.dp, 50.dp)) { SkButton(onClick = {}, text = { Text("Test button") }) } } } @ThemePreviews @Composable fun ButtonLeadingIconPreview() { SkTheme { SkBackground(modifier = Modifier.size(150.dp, 50.dp)) { SkButton( onClick = {}, text = { Text("Test button") }, leadingIcon = { Icon(imageVector = SkIcons.Add, contentDescription = null) }, ) } } }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/component/TopAppBar.kt
2216297117
/* *abiola 2024 */ @file:OptIn(ExperimentalMaterial3Api::class) package com.mshdabiola.designsystem.component import androidx.annotation.StringRes import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarColors import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.mshdabiola.designsystem.R import com.mshdabiola.designsystem.icon.SkIcons @OptIn(ExperimentalMaterial3Api::class) @Composable fun SkTopAppBar( @StringRes titleRes: Int, navigationIcon: ImageVector, navigationIconContentDescription: String, actionIcon: ImageVector, actionIconContentDescription: String, modifier: Modifier = Modifier, colors: TopAppBarColors = TopAppBarDefaults.centerAlignedTopAppBarColors(), onNavigationClick: () -> Unit = {}, onActionClick: () -> Unit = {}, ) { CenterAlignedTopAppBar( title = { Text(text = stringResource(id = titleRes)) }, navigationIcon = { IconButton(onClick = onNavigationClick) { Icon( imageVector = navigationIcon, contentDescription = navigationIconContentDescription, tint = MaterialTheme.colorScheme.onSurface, ) } }, actions = { IconButton(onClick = onActionClick) { Icon( imageVector = actionIcon, contentDescription = actionIconContentDescription, tint = MaterialTheme.colorScheme.onSurface, ) } }, colors = colors, modifier = modifier.testTag("skTopAppBar"), ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun DetailTopAppBar( modifier: Modifier = Modifier, colors: TopAppBarColors = TopAppBarDefaults.centerAlignedTopAppBarColors(containerColor = MaterialTheme.colorScheme.background), onNavigationClick: () -> Unit = {}, onDeleteClick: () -> Unit = {}, ) { CenterAlignedTopAppBar( title = { Text(text = stringResource(id = R.string.modules_designsystem_note)) }, navigationIcon = { IconButton(onClick = onNavigationClick) { Icon( modifier = Modifier.testTag("back"), imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "back", tint = MaterialTheme.colorScheme.onSurface, ) } }, actions = { IconButton(onClick = onDeleteClick) { Icon( modifier = Modifier.testTag("delete"), imageVector = Icons.Default.Delete, contentDescription = "delete", tint = MaterialTheme.colorScheme.onSurface, ) } }, colors = colors, modifier = modifier.testTag("detailTopAppBar"), ) } @OptIn(ExperimentalMaterial3Api::class) @Preview("Top App Bar") @Composable private fun SkTopAppBarPreview() { SkTopAppBar( titleRes = android.R.string.untitled, navigationIcon = SkIcons.Search, navigationIconContentDescription = "Navigation icon", actionIcon = SkIcons.MoreVert, actionIconContentDescription = "Action icon", ) } @OptIn(ExperimentalMaterial3Api::class) @Preview("Top App Bar") @Composable private fun DetailTopAppBarPreview() { DetailTopAppBar() }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/component/TextField.kt
397367370
/* *abiola 2024 */ package com.mshdabiola.designsystem.component import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.tooling.preview.Preview @Composable fun SkTextField( modifier: Modifier = Modifier, value: String, onValueChange: (String) -> Unit = {}, placeholder: String? = null, imeAction: ImeAction = ImeAction.Done, keyboardAction: () -> Unit = {}, maxNum: Int = Int.MAX_VALUE, ) { TextField( modifier = modifier, // .bringIntoViewRequester(focusRequester2) // .focusRequester(focusRequester) value = value, onValueChange = onValueChange, placeholder = { if (placeholder != null) { Text(text = placeholder) } }, colors = TextFieldDefaults.colors( focusedContainerColor = Color.Transparent, unfocusedContainerColor = Color.Transparent, disabledContainerColor = Color.Transparent, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, ), keyboardOptions = KeyboardOptions.Default.copy( capitalization = KeyboardCapitalization.Sentences, autoCorrect = true, imeAction = imeAction, ), keyboardActions = KeyboardActions { keyboardAction() }, maxLines = maxNum, ) } @Preview @Composable private fun SkTextFieldPreview() { SkTextField(value = "Sk Testing") }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/component/Background.kt
4026382048
/* *abiola 2024 */ package com.mshdabiola.designsystem.component import android.content.res.Configuration import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material3.LocalAbsoluteTonalElevation import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.mshdabiola.designsystem.theme.GradientColors import com.mshdabiola.designsystem.theme.LocalBackgroundTheme import com.mshdabiola.designsystem.theme.LocalGradientColors import com.mshdabiola.designsystem.theme.SkTheme import kotlin.math.tan /** * The main background for the app. * Uses [LocalBackgroundTheme] to set the color and tonal elevation of a [Surface]. * * @param modifier Modifier to be applied to the background. * @param content The background content. */ @Composable fun SkBackground( modifier: Modifier = Modifier, content: @Composable () -> Unit, ) { val color = LocalBackgroundTheme.current.color val tonalElevation = LocalBackgroundTheme.current.tonalElevation Surface( color = if (color == Color.Unspecified) Color.Transparent else color, tonalElevation = if (tonalElevation == Dp.Unspecified) 0.dp else tonalElevation, modifier = modifier.fillMaxSize(), ) { CompositionLocalProvider(LocalAbsoluteTonalElevation provides 0.dp) { content() } } } /** * A gradient background for select screens. Uses [LocalBackgroundTheme] to set the gradient colors * of a [Box] within a [Surface]. * * @param modifier Modifier to be applied to the background. * @param gradientColors The gradient colors to be rendered. * @param content The background content. */ @Composable fun SkGradientBackground( modifier: Modifier = Modifier, gradientColors: GradientColors = LocalGradientColors.current, content: @Composable () -> Unit, ) { val currentTopColor by rememberUpdatedState(gradientColors.top) val currentBottomColor by rememberUpdatedState(gradientColors.bottom) Surface( color = if (gradientColors.container == Color.Unspecified) { Color.Transparent } else { gradientColors.container }, modifier = modifier.fillMaxSize(), ) { Box( Modifier .fillMaxSize() .drawWithCache { // Compute the start and end coordinates such that the gradients are angled 11.06 // degrees off the vertical axis val offset = size.height * tan( Math .toRadians(11.06) .toFloat(), ) val start = Offset(size.width / 2 + offset / 2, 0f) val end = Offset(size.width / 2 - offset / 2, size.height) // Create the top gradient that fades out after the halfway point vertically val topGradient = Brush.linearGradient( 0f to if (currentTopColor == Color.Unspecified) { Color.Transparent } else { currentTopColor }, 0.724f to Color.Transparent, start = start, end = end, ) // Create the bottom gradient that fades in before the halfway point vertically val bottomGradient = Brush.linearGradient( 0.2552f to Color.Transparent, 1f to if (currentBottomColor == Color.Unspecified) { Color.Transparent } else { currentBottomColor }, start = start, end = end, ) onDrawBehind { // There is overlap here, so order is important drawRect(topGradient) drawRect(bottomGradient) } }, ) { content() } } } /** * Multipreview annotation that represents light and dark themes. Add this annotation to a * composable to render the both themes. */ @Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, name = "Light theme") @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark theme") annotation class ThemePreviews @ThemePreviews @Composable fun BackgroundDefault() { SkTheme(disableDynamicTheming = true) { SkBackground(Modifier.size(100.dp), content = {}) } } @ThemePreviews @Composable fun BackgroundDynamic() { SkTheme(disableDynamicTheming = false) { SkBackground(Modifier.size(100.dp), content = {}) } } @ThemePreviews @Composable fun BackgroundAndroid() { SkTheme() { SkBackground(Modifier.size(100.dp), content = {}) } } @ThemePreviews @Composable fun GradientBackgroundDefault() { SkTheme(disableDynamicTheming = true) { SkGradientBackground(Modifier.size(100.dp), content = {}) } } @ThemePreviews @Composable fun GradientBackgroundDynamic() { SkTheme(disableDynamicTheming = false) { SkGradientBackground(Modifier.size(100.dp), content = {}) } } @ThemePreviews @Composable fun GradientBackgroundAndroid() { SkTheme() { SkGradientBackground(Modifier.size(100.dp), content = {}) } }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/theme/Tint.kt
304528648
/* *abiola 2024 */ package com.mshdabiola.designsystem.theme import androidx.compose.runtime.Immutable import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.graphics.Color /** * A class to model background color and tonal elevation values for Now in Android. */ @Immutable data class TintTheme( val iconTint: Color = Color.Unspecified, ) /** * A composition local for [TintTheme]. */ val LocalTintTheme = staticCompositionLocalOf { TintTheme() }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/theme/Color.kt
3364238993
/* *abiola 2024 */ package com.mshdabiola.designsystem.theme import androidx.compose.material3.ColorScheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.mshdabiola.model.Contrast sealed class Theme(val isDark: Boolean,val contrast: Contrast) { abstract fun getColorScheme(): ColorScheme fun getGradientColors():GradientColors{ val colorScheme=getColorScheme() return GradientColors( top = colorScheme.inverseOnSurface, bottom = colorScheme.primaryContainer, container = colorScheme.surface, ) } fun getTintTheme():TintTheme{ return TintTheme() } fun getBackgroundTheme():BackgroundTheme{ val colorScheme=getColorScheme() return BackgroundTheme( color = colorScheme.surface, tonalElevation = 2.dp, ) } class DefaultTheme(isDark: Boolean,contrast: Contrast):Theme(isDark,contrast){ override fun getColorScheme(): ColorScheme { return when{ contrast==Contrast.Normal && !isDark -> { val primaryDark = Color(0xFF9CCBFB) val onPrimaryDark = Color(0xFF003354) val primaryContainerDark = Color(0xFF124A73) val onPrimaryContainerDark = Color(0xFFCFE5FF) val secondaryDark = Color(0xFFB9C8DA) val onSecondaryDark = Color(0xFF243240) val secondaryContainerDark = Color(0xFF3A4857) val onSecondaryContainerDark = Color(0xFFD5E4F7) val tertiaryDark = Color(0xFFD4BEE6) val onTertiaryDark = Color(0xFF392A49) val tertiaryContainerDark = Color(0xFF504060) val onTertiaryContainerDark = Color(0xFFF0DBFF) val errorDark = Color(0xFFFFB4AB) val onErrorDark = Color(0xFF690005) val errorContainerDark = Color(0xFF93000A) val onErrorContainerDark = Color(0xFFFFDAD6) val backgroundDark = Color(0xFF101418) val onBackgroundDark = Color(0xFFE0E2E8) val surfaceDark = Color(0xFF101418) val onSurfaceDark = Color(0xFFE0E2E8) val surfaceVariantDark = Color(0xFF42474E) val onSurfaceVariantDark = Color(0xFFC2C7CF) val outlineDark = Color(0xFF8C9199) val outlineVariantDark = Color(0xFF42474E) val scrimDark = Color(0xFF000000) val inverseSurfaceDark = Color(0xFFE0E2E8) val inverseOnSurfaceDark = Color(0xFF2D3135) val inversePrimaryDark = Color(0xFF31628D) val surfaceDimDark = Color(0xFF101418) val surfaceBrightDark = Color(0xFF36393E) val surfaceContainerLowestDark = Color(0xFF0B0E12) val surfaceContainerLowDark = Color(0xFF181C20) val surfaceContainerDark = Color(0xFF1D2024) val surfaceContainerHighDark = Color(0xFF272A2F) val surfaceContainerHighestDark = Color(0xFF32353A) darkColorScheme( primary = primaryDark, onPrimary = onPrimaryDark, primaryContainer = primaryContainerDark, onPrimaryContainer = onPrimaryContainerDark, secondary = secondaryDark, onSecondary = onSecondaryDark, secondaryContainer = secondaryContainerDark, onSecondaryContainer = onSecondaryContainerDark, tertiary = tertiaryDark, onTertiary = onTertiaryDark, tertiaryContainer = tertiaryContainerDark, onTertiaryContainer = onTertiaryContainerDark, error = errorDark, onError = onErrorDark, errorContainer = errorContainerDark, onErrorContainer = onErrorContainerDark, background = backgroundDark, onBackground = onBackgroundDark, surface = surfaceDark, onSurface = onSurfaceDark, surfaceVariant = surfaceVariantDark, onSurfaceVariant = onSurfaceVariantDark, outline = outlineDark, outlineVariant = outlineVariantDark, scrim = scrimDark, inverseSurface = inverseSurfaceDark, inverseOnSurface = inverseOnSurfaceDark, inversePrimary = inversePrimaryDark, ) } contrast==Contrast.Medium && isDark -> { val primaryDarkMediumContrast = Color(0xFFA1CFFF) val onPrimaryDarkMediumContrast = Color(0xFF00182B) val primaryContainerDarkMediumContrast = Color(0xFF6695C2) val onPrimaryContainerDarkMediumContrast = Color(0xFF000000) val secondaryDarkMediumContrast = Color(0xFFBECCDF) val onSecondaryDarkMediumContrast = Color(0xFF091725) val secondaryContainerDarkMediumContrast = Color(0xFF8492A3) val onSecondaryContainerDarkMediumContrast = Color(0xFF000000) val tertiaryDarkMediumContrast = Color(0xFFD8C3EA) val onTertiaryDarkMediumContrast = Color(0xFF1E0F2D) val tertiaryContainerDarkMediumContrast = Color(0xFF9D89AE) val onTertiaryContainerDarkMediumContrast = Color(0xFF000000) val errorDarkMediumContrast = Color(0xFFFFBAB1) val onErrorDarkMediumContrast = Color(0xFF370001) val errorContainerDarkMediumContrast = Color(0xFFFF5449) val onErrorContainerDarkMediumContrast = Color(0xFF000000) val backgroundDarkMediumContrast = Color(0xFF101418) val onBackgroundDarkMediumContrast = Color(0xFFE0E2E8) val surfaceDarkMediumContrast = Color(0xFF101418) val onSurfaceDarkMediumContrast = Color(0xFFFAFAFF) val surfaceVariantDarkMediumContrast = Color(0xFF42474E) val onSurfaceVariantDarkMediumContrast = Color(0xFFC6CBD3) val outlineDarkMediumContrast = Color(0xFF9EA3AB) val outlineVariantDarkMediumContrast = Color(0xFF7F838B) val scrimDarkMediumContrast = Color(0xFF000000) val inverseSurfaceDarkMediumContrast = Color(0xFFE0E2E8) val inverseOnSurfaceDarkMediumContrast = Color(0xFF272A2F) val inversePrimaryDarkMediumContrast = Color(0xFF144B75) val surfaceDimDarkMediumContrast = Color(0xFF101418) val surfaceBrightDarkMediumContrast = Color(0xFF36393E) val surfaceContainerLowestDarkMediumContrast = Color(0xFF0B0E12) val surfaceContainerLowDarkMediumContrast = Color(0xFF181C20) val surfaceContainerDarkMediumContrast = Color(0xFF1D2024) val surfaceContainerHighDarkMediumContrast = Color(0xFF272A2F) val surfaceContainerHighestDarkMediumContrast = Color(0xFF32353A) darkColorScheme( primary = primaryDarkMediumContrast, onPrimary = onPrimaryDarkMediumContrast, primaryContainer = primaryContainerDarkMediumContrast, onPrimaryContainer = onPrimaryContainerDarkMediumContrast, secondary = secondaryDarkMediumContrast, onSecondary = onSecondaryDarkMediumContrast, secondaryContainer = secondaryContainerDarkMediumContrast, onSecondaryContainer = onSecondaryContainerDarkMediumContrast, tertiary = tertiaryDarkMediumContrast, onTertiary = onTertiaryDarkMediumContrast, tertiaryContainer = tertiaryContainerDarkMediumContrast, onTertiaryContainer = onTertiaryContainerDarkMediumContrast, error = errorDarkMediumContrast, onError = onErrorDarkMediumContrast, errorContainer = errorContainerDarkMediumContrast, onErrorContainer = onErrorContainerDarkMediumContrast, background = backgroundDarkMediumContrast, onBackground = onBackgroundDarkMediumContrast, surface = surfaceDarkMediumContrast, onSurface = onSurfaceDarkMediumContrast, surfaceVariant = surfaceVariantDarkMediumContrast, onSurfaceVariant = onSurfaceVariantDarkMediumContrast, outline = outlineDarkMediumContrast, outlineVariant = outlineVariantDarkMediumContrast, scrim = scrimDarkMediumContrast, inverseSurface = inverseSurfaceDarkMediumContrast, inverseOnSurface = inverseOnSurfaceDarkMediumContrast, inversePrimary = inversePrimaryDarkMediumContrast, ) } contrast==Contrast.Medium && !isDark -> { val primaryLightMediumContrast = Color(0xFF0A466F) val onPrimaryLightMediumContrast = Color(0xFFFFFFFF) val primaryContainerLightMediumContrast = Color(0xFF4978A4) val onPrimaryContainerLightMediumContrast = Color(0xFFFFFFFF) val secondaryLightMediumContrast = Color(0xFF364453) val onSecondaryLightMediumContrast = Color(0xFFFFFFFF) val secondaryContainerLightMediumContrast = Color(0xFF687686) val onSecondaryContainerLightMediumContrast = Color(0xFFFFFFFF) val tertiaryLightMediumContrast = Color(0xFF4C3C5C) val onTertiaryLightMediumContrast = Color(0xFFFFFFFF) val tertiaryContainerLightMediumContrast = Color(0xFF806D91) val onTertiaryContainerLightMediumContrast = Color(0xFFFFFFFF) val errorLightMediumContrast = Color(0xFF8C0009) val onErrorLightMediumContrast = Color(0xFFFFFFFF) val errorContainerLightMediumContrast = Color(0xFFDA342E) val onErrorContainerLightMediumContrast = Color(0xFFFFFFFF) val backgroundLightMediumContrast = Color(0xFFF7F9FF) val onBackgroundLightMediumContrast = Color(0xFF181C20) val surfaceLightMediumContrast = Color(0xFFF7F9FF) val onSurfaceLightMediumContrast = Color(0xFF181C20) val surfaceVariantLightMediumContrast = Color(0xFFDEE3EB) val onSurfaceVariantLightMediumContrast = Color(0xFF3E434A) val outlineLightMediumContrast = Color(0xFF5A5F66) val outlineVariantLightMediumContrast = Color(0xFF767B82) val scrimLightMediumContrast = Color(0xFF000000) val inverseSurfaceLightMediumContrast = Color(0xFF2D3135) val inverseOnSurfaceLightMediumContrast = Color(0xFFEFF1F6) val inversePrimaryLightMediumContrast = Color(0xFF9CCBFB) val surfaceDimLightMediumContrast = Color(0xFFD8DAE0) val surfaceBrightLightMediumContrast = Color(0xFFF7F9FF) val surfaceContainerLowestLightMediumContrast = Color(0xFFFFFFFF) val surfaceContainerLowLightMediumContrast = Color(0xFFF2F3F9) val surfaceContainerLightMediumContrast = Color(0xFFECEEF4) val surfaceContainerHighLightMediumContrast = Color(0xFFE6E8EE) val surfaceContainerHighestLightMediumContrast = Color(0xFFE0E2E8) lightColorScheme( primary = primaryLightMediumContrast, onPrimary = onPrimaryLightMediumContrast, primaryContainer = primaryContainerLightMediumContrast, onPrimaryContainer = onPrimaryContainerLightMediumContrast, secondary = secondaryLightMediumContrast, onSecondary = onSecondaryLightMediumContrast, secondaryContainer = secondaryContainerLightMediumContrast, onSecondaryContainer = onSecondaryContainerLightMediumContrast, tertiary = tertiaryLightMediumContrast, onTertiary = onTertiaryLightMediumContrast, tertiaryContainer = tertiaryContainerLightMediumContrast, onTertiaryContainer = onTertiaryContainerLightMediumContrast, error = errorLightMediumContrast, onError = onErrorLightMediumContrast, errorContainer = errorContainerLightMediumContrast, onErrorContainer = onErrorContainerLightMediumContrast, background = backgroundLightMediumContrast, onBackground = onBackgroundLightMediumContrast, surface = surfaceLightMediumContrast, onSurface = onSurfaceLightMediumContrast, surfaceVariant = surfaceVariantLightMediumContrast, onSurfaceVariant = onSurfaceVariantLightMediumContrast, outline = outlineLightMediumContrast, outlineVariant = outlineVariantLightMediumContrast, scrim = scrimLightMediumContrast, inverseSurface = inverseSurfaceLightMediumContrast, inverseOnSurface = inverseOnSurfaceLightMediumContrast, inversePrimary = inversePrimaryLightMediumContrast, ) } contrast==Contrast.High && isDark -> { val primaryDarkHighContrast = Color(0xFFFAFAFF) val onPrimaryDarkHighContrast = Color(0xFF000000) val primaryContainerDarkHighContrast = Color(0xFFA1CFFF) val onPrimaryContainerDarkHighContrast = Color(0xFF000000) val secondaryDarkHighContrast = Color(0xFFFAFAFF) val onSecondaryDarkHighContrast = Color(0xFF000000) val secondaryContainerDarkHighContrast = Color(0xFFBECCDF) val onSecondaryContainerDarkHighContrast = Color(0xFF000000) val tertiaryDarkHighContrast = Color(0xFFFFF9FC) val onTertiaryDarkHighContrast = Color(0xFF000000) val tertiaryContainerDarkHighContrast = Color(0xFFD8C3EA) val onTertiaryContainerDarkHighContrast = Color(0xFF000000) val errorDarkHighContrast = Color(0xFFFFF9F9) val onErrorDarkHighContrast = Color(0xFF000000) val errorContainerDarkHighContrast = Color(0xFFFFBAB1) val onErrorContainerDarkHighContrast = Color(0xFF000000) val backgroundDarkHighContrast = Color(0xFF101418) val onBackgroundDarkHighContrast = Color(0xFFE0E2E8) val surfaceDarkHighContrast = Color(0xFF101418) val onSurfaceDarkHighContrast = Color(0xFFFFFFFF) val surfaceVariantDarkHighContrast = Color(0xFF42474E) val onSurfaceVariantDarkHighContrast = Color(0xFFFAFAFF) val outlineDarkHighContrast = Color(0xFFC6CBD3) val outlineVariantDarkHighContrast = Color(0xFFC6CBD3) val scrimDarkHighContrast = Color(0xFF000000) val inverseSurfaceDarkHighContrast = Color(0xFFE0E2E8) val inverseOnSurfaceDarkHighContrast = Color(0xFF000000) val inversePrimaryDarkHighContrast = Color(0xFF002C4A) val surfaceDimDarkHighContrast = Color(0xFF101418) val surfaceBrightDarkHighContrast = Color(0xFF36393E) val surfaceContainerLowestDarkHighContrast = Color(0xFF0B0E12) val surfaceContainerLowDarkHighContrast = Color(0xFF181C20) val surfaceContainerDarkHighContrast = Color(0xFF1D2024) val surfaceContainerHighDarkHighContrast = Color(0xFF272A2F) val surfaceContainerHighestDarkHighContrast = Color(0xFF32353A) darkColorScheme( primary = primaryDarkHighContrast, onPrimary = onPrimaryDarkHighContrast, primaryContainer = primaryContainerDarkHighContrast, onPrimaryContainer = onPrimaryContainerDarkHighContrast, secondary = secondaryDarkHighContrast, onSecondary = onSecondaryDarkHighContrast, secondaryContainer = secondaryContainerDarkHighContrast, onSecondaryContainer = onSecondaryContainerDarkHighContrast, tertiary = tertiaryDarkHighContrast, onTertiary = onTertiaryDarkHighContrast, tertiaryContainer = tertiaryContainerDarkHighContrast, onTertiaryContainer = onTertiaryContainerDarkHighContrast, error = errorDarkHighContrast, onError = onErrorDarkHighContrast, errorContainer = errorContainerDarkHighContrast, onErrorContainer = onErrorContainerDarkHighContrast, background = backgroundDarkHighContrast, onBackground = onBackgroundDarkHighContrast, surface = surfaceDarkHighContrast, onSurface = onSurfaceDarkHighContrast, surfaceVariant = surfaceVariantDarkHighContrast, onSurfaceVariant = onSurfaceVariantDarkHighContrast, outline = outlineDarkHighContrast, outlineVariant = outlineVariantDarkHighContrast, scrim = scrimDarkHighContrast, inverseSurface = inverseSurfaceDarkHighContrast, inverseOnSurface = inverseOnSurfaceDarkHighContrast, inversePrimary = inversePrimaryDarkHighContrast, ) } contrast==Contrast.High && !isDark -> { val primaryLightHighContrast = Color(0xFF00243E) val onPrimaryLightHighContrast = Color(0xFFFFFFFF) val primaryContainerLightHighContrast = Color(0xFF0A466F) val onPrimaryContainerLightHighContrast = Color(0xFFFFFFFF) val secondaryLightHighContrast = Color(0xFF152331) val onSecondaryLightHighContrast = Color(0xFFFFFFFF) val secondaryContainerLightHighContrast = Color(0xFF364453) val onSecondaryContainerLightHighContrast = Color(0xFFFFFFFF) val tertiaryLightHighContrast = Color(0xFF2A1C3A) val onTertiaryLightHighContrast = Color(0xFFFFFFFF) val tertiaryContainerLightHighContrast = Color(0xFF4C3C5C) val onTertiaryContainerLightHighContrast = Color(0xFFFFFFFF) val errorLightHighContrast = Color(0xFF4E0002) val onErrorLightHighContrast = Color(0xFFFFFFFF) val errorContainerLightHighContrast = Color(0xFF8C0009) val onErrorContainerLightHighContrast = Color(0xFFFFFFFF) val backgroundLightHighContrast = Color(0xFFF7F9FF) val onBackgroundLightHighContrast = Color(0xFF181C20) val surfaceLightHighContrast = Color(0xFFF7F9FF) val onSurfaceLightHighContrast = Color(0xFF000000) val surfaceVariantLightHighContrast = Color(0xFFDEE3EB) val onSurfaceVariantLightHighContrast = Color(0xFF1F242A) val outlineLightHighContrast = Color(0xFF3E434A) val outlineVariantLightHighContrast = Color(0xFF3E434A) val scrimLightHighContrast = Color(0xFF000000) val inverseSurfaceLightHighContrast = Color(0xFF2D3135) val inverseOnSurfaceLightHighContrast = Color(0xFFFFFFFF) val inversePrimaryLightHighContrast = Color(0xFFE0EDFF) val surfaceDimLightHighContrast = Color(0xFFD8DAE0) val surfaceBrightLightHighContrast = Color(0xFFF7F9FF) val surfaceContainerLowestLightHighContrast = Color(0xFFFFFFFF) val surfaceContainerLowLightHighContrast = Color(0xFFF2F3F9) val surfaceContainerLightHighContrast = Color(0xFFECEEF4) val surfaceContainerHighLightHighContrast = Color(0xFFE6E8EE) val surfaceContainerHighestLightHighContrast = Color(0xFFE0E2E8) lightColorScheme( primary = primaryLightHighContrast, onPrimary = onPrimaryLightHighContrast, primaryContainer = primaryContainerLightHighContrast, onPrimaryContainer = onPrimaryContainerLightHighContrast, secondary = secondaryLightHighContrast, onSecondary = onSecondaryLightHighContrast, secondaryContainer = secondaryContainerLightHighContrast, onSecondaryContainer = onSecondaryContainerLightHighContrast, tertiary = tertiaryLightHighContrast, onTertiary = onTertiaryLightHighContrast, tertiaryContainer = tertiaryContainerLightHighContrast, onTertiaryContainer = onTertiaryContainerLightHighContrast, error = errorLightHighContrast, onError = onErrorLightHighContrast, errorContainer = errorContainerLightHighContrast, onErrorContainer = onErrorContainerLightHighContrast, background = backgroundLightHighContrast, onBackground = onBackgroundLightHighContrast, surface = surfaceLightHighContrast, onSurface = onSurfaceLightHighContrast, surfaceVariant = surfaceVariantLightHighContrast, onSurfaceVariant = onSurfaceVariantLightHighContrast, outline = outlineLightHighContrast, outlineVariant = outlineVariantLightHighContrast, scrim = scrimLightHighContrast, inverseSurface = inverseSurfaceLightHighContrast, inverseOnSurface = inverseOnSurfaceLightHighContrast, inversePrimary = inversePrimaryLightHighContrast, ) } else -> { val primaryLight = Color(0xFF31628D) val onPrimaryLight = Color(0xFFFFFFFF) val primaryContainerLight = Color(0xFFCFE5FF) val onPrimaryContainerLight = Color(0xFF001D33) val secondaryLight = Color(0xFF526070) val onSecondaryLight = Color(0xFFFFFFFF) val secondaryContainerLight = Color(0xFFD5E4F7) val onSecondaryContainerLight = Color(0xFF0E1D2A) val tertiaryLight = Color(0xFF695779) val onTertiaryLight = Color(0xFFFFFFFF) val tertiaryContainerLight = Color(0xFFF0DBFF) val onTertiaryContainerLight = Color(0xFF231533) val errorLight = Color(0xFFBA1A1A) val onErrorLight = Color(0xFFFFFFFF) val errorContainerLight = Color(0xFFFFDAD6) val onErrorContainerLight = Color(0xFF410002) val backgroundLight = Color(0xFFF7F9FF) val onBackgroundLight = Color(0xFF181C20) val surfaceLight = Color(0xFFF7F9FF) val onSurfaceLight = Color(0xFF181C20) val surfaceVariantLight = Color(0xFFDEE3EB) val onSurfaceVariantLight = Color(0xFF42474E) val outlineLight = Color(0xFF72777F) val outlineVariantLight = Color(0xFFC2C7CF) val scrimLight = Color(0xFF000000) val inverseSurfaceLight = Color(0xFF2D3135) val inverseOnSurfaceLight = Color(0xFFEFF1F6) val inversePrimaryLight = Color(0xFF9CCBFB) val surfaceDimLight = Color(0xFFD8DAE0) val surfaceBrightLight = Color(0xFFF7F9FF) val surfaceContainerLowestLight = Color(0xFFFFFFFF) val surfaceContainerLowLight = Color(0xFFF2F3F9) val surfaceContainerLight = Color(0xFFECEEF4) val surfaceContainerHighLight = Color(0xFFE6E8EE) val surfaceContainerHighestLight = Color(0xFFE0E2E8) lightColorScheme( primary = primaryLight, onPrimary = onPrimaryLight, primaryContainer = primaryContainerLight, onPrimaryContainer = onPrimaryContainerLight, secondary = secondaryLight, onSecondary = onSecondaryLight, secondaryContainer = secondaryContainerLight, onSecondaryContainer = onSecondaryContainerLight, tertiary = tertiaryLight, onTertiary = onTertiaryLight, tertiaryContainer = tertiaryContainerLight, onTertiaryContainer = onTertiaryContainerLight, error = errorLight, onError = onErrorLight, errorContainer = errorContainerLight, onErrorContainer = onErrorContainerLight, background = backgroundLight, onBackground = onBackgroundLight, surface = surfaceLight, onSurface = onSurfaceLight, surfaceVariant = surfaceVariantLight, onSurfaceVariant = onSurfaceVariantLight, outline = outlineLight, outlineVariant = outlineVariantLight, scrim = scrimLight, inverseSurface = inverseSurfaceLight, inverseOnSurface = inverseOnSurfaceLight, inversePrimary = inversePrimaryLight, ) } } } } class GreenTheme(isDark: Boolean,contrast: Contrast):Theme(isDark,contrast){ override fun getColorScheme(): ColorScheme { return when{ contrast==Contrast.Normal && !isDark -> { val primaryDark = Color(0xFFB6D085) val onPrimaryDark = Color(0xFF243600) val primaryContainerDark = Color(0xFF394D11) val onPrimaryContainerDark = Color(0xFFD2EC9F) val secondaryDark = Color(0xFFC1CAAB) val onSecondaryDark = Color(0xFF2C331D) val secondaryContainerDark = Color(0xFF424A32) val onSecondaryContainerDark = Color(0xFFDDE6C6) val tertiaryDark = Color(0xFFA0D0C9) val onTertiaryDark = Color(0xFF013733) val tertiaryContainerDark = Color(0xFF1F4E49) val onTertiaryContainerDark = Color(0xFFBCECE5) val errorDark = Color(0xFFFFB4AB) val onErrorDark = Color(0xFF690005) val errorContainerDark = Color(0xFF93000A) val onErrorContainerDark = Color(0xFFFFDAD6) val backgroundDark = Color(0xFF12140D) val onBackgroundDark = Color(0xFFE3E3D8) val surfaceDark = Color(0xFF12140D) val onSurfaceDark = Color(0xFFE3E3D8) val surfaceVariantDark = Color(0xFF45483D) val onSurfaceVariantDark = Color(0xFFC6C8B9) val outlineDark = Color(0xFF8F9284) val outlineVariantDark = Color(0xFF45483D) val scrimDark = Color(0xFF000000) val inverseSurfaceDark = Color(0xFFE3E3D8) val inverseOnSurfaceDark = Color(0xFF2F3129) val inversePrimaryDark = Color(0xFF506528) val surfaceDimDark = Color(0xFF12140D) val surfaceBrightDark = Color(0xFF383A32) val surfaceContainerLowestDark = Color(0xFF0D0F09) val surfaceContainerLowDark = Color(0xFF1A1C15) val surfaceContainerDark = Color(0xFF1E2019) val surfaceContainerHighDark = Color(0xFF292B23) val surfaceContainerHighestDark = Color(0xFF34362E) darkColorScheme( primary = primaryDark, onPrimary = onPrimaryDark, primaryContainer = primaryContainerDark, onPrimaryContainer = onPrimaryContainerDark, secondary = secondaryDark, onSecondary = onSecondaryDark, secondaryContainer = secondaryContainerDark, onSecondaryContainer = onSecondaryContainerDark, tertiary = tertiaryDark, onTertiary = onTertiaryDark, tertiaryContainer = tertiaryContainerDark, onTertiaryContainer = onTertiaryContainerDark, error = errorDark, onError = onErrorDark, errorContainer = errorContainerDark, onErrorContainer = onErrorContainerDark, background = backgroundDark, onBackground = onBackgroundDark, surface = surfaceDark, onSurface = onSurfaceDark, surfaceVariant = surfaceVariantDark, onSurfaceVariant = onSurfaceVariantDark, outline = outlineDark, outlineVariant = outlineVariantDark, scrim = scrimDark, inverseSurface = inverseSurfaceDark, inverseOnSurface = inverseOnSurfaceDark, inversePrimary = inversePrimaryDark, ) } contrast==Contrast.Medium && isDark -> { val primaryDarkMediumContrast = Color(0xFFBAD489) val onPrimaryDarkMediumContrast = Color(0xFF0F1900) val primaryContainerDarkMediumContrast = Color(0xFF819955) val onPrimaryContainerDarkMediumContrast = Color(0xFF000000) val secondaryDarkMediumContrast = Color(0xFFC6CEAF) val onSecondaryDarkMediumContrast = Color(0xFF121906) val secondaryContainerDarkMediumContrast = Color(0xFF8C9478) val onSecondaryContainerDarkMediumContrast = Color(0xFF000000) val tertiaryDarkMediumContrast = Color(0xFFA4D4CD) val onTertiaryDarkMediumContrast = Color(0xFF001A18) val tertiaryContainerDarkMediumContrast = Color(0xFF6B9993) val onTertiaryContainerDarkMediumContrast = Color(0xFF000000) val errorDarkMediumContrast = Color(0xFFFFBAB1) val onErrorDarkMediumContrast = Color(0xFF370001) val errorContainerDarkMediumContrast = Color(0xFFFF5449) val onErrorContainerDarkMediumContrast = Color(0xFF000000) val backgroundDarkMediumContrast = Color(0xFF12140D) val onBackgroundDarkMediumContrast = Color(0xFFE3E3D8) val surfaceDarkMediumContrast = Color(0xFF12140D) val onSurfaceDarkMediumContrast = Color(0xFFFBFBEF) val surfaceVariantDarkMediumContrast = Color(0xFF45483D) val onSurfaceVariantDarkMediumContrast = Color(0xFFCACCBD) val outlineDarkMediumContrast = Color(0xFFA2A496) val outlineVariantDarkMediumContrast = Color(0xFF828477) val scrimDarkMediumContrast = Color(0xFF000000) val inverseSurfaceDarkMediumContrast = Color(0xFFE3E3D8) val inverseOnSurfaceDarkMediumContrast = Color(0xFF292B23) val inversePrimaryDarkMediumContrast = Color(0xFF3A4E13) val surfaceDimDarkMediumContrast = Color(0xFF12140D) val surfaceBrightDarkMediumContrast = Color(0xFF383A32) val surfaceContainerLowestDarkMediumContrast = Color(0xFF0D0F09) val surfaceContainerLowDarkMediumContrast = Color(0xFF1A1C15) val surfaceContainerDarkMediumContrast = Color(0xFF1E2019) val surfaceContainerHighDarkMediumContrast = Color(0xFF292B23) val surfaceContainerHighestDarkMediumContrast = Color(0xFF34362E) darkColorScheme( primary = primaryDarkMediumContrast, onPrimary = onPrimaryDarkMediumContrast, primaryContainer = primaryContainerDarkMediumContrast, onPrimaryContainer = onPrimaryContainerDarkMediumContrast, secondary = secondaryDarkMediumContrast, onSecondary = onSecondaryDarkMediumContrast, secondaryContainer = secondaryContainerDarkMediumContrast, onSecondaryContainer = onSecondaryContainerDarkMediumContrast, tertiary = tertiaryDarkMediumContrast, onTertiary = onTertiaryDarkMediumContrast, tertiaryContainer = tertiaryContainerDarkMediumContrast, onTertiaryContainer = onTertiaryContainerDarkMediumContrast, error = errorDarkMediumContrast, onError = onErrorDarkMediumContrast, errorContainer = errorContainerDarkMediumContrast, onErrorContainer = onErrorContainerDarkMediumContrast, background = backgroundDarkMediumContrast, onBackground = onBackgroundDarkMediumContrast, surface = surfaceDarkMediumContrast, onSurface = onSurfaceDarkMediumContrast, surfaceVariant = surfaceVariantDarkMediumContrast, onSurfaceVariant = onSurfaceVariantDarkMediumContrast, outline = outlineDarkMediumContrast, outlineVariant = outlineVariantDarkMediumContrast, scrim = scrimDarkMediumContrast, inverseSurface = inverseSurfaceDarkMediumContrast, inverseOnSurface = inverseOnSurfaceDarkMediumContrast, inversePrimary = inversePrimaryDarkMediumContrast, ) } contrast==Contrast.Medium && !isDark -> { val primaryLightMediumContrast = Color(0xFF35490D) val onPrimaryLightMediumContrast = Color(0xFFFFFFFF) val primaryContainerLightMediumContrast = Color(0xFF667C3C) val onPrimaryContainerLightMediumContrast = Color(0xFFFFFFFF) val secondaryLightMediumContrast = Color(0xFF3E462E) val onSecondaryLightMediumContrast = Color(0xFFFFFFFF) val secondaryContainerLightMediumContrast = Color(0xFF6F785D) val onSecondaryContainerLightMediumContrast = Color(0xFFFFFFFF) val tertiaryLightMediumContrast = Color(0xFF1B4A45) val onTertiaryLightMediumContrast = Color(0xFFFFFFFF) val tertiaryContainerLightMediumContrast = Color(0xFF4F7D77) val onTertiaryContainerLightMediumContrast = Color(0xFFFFFFFF) val errorLightMediumContrast = Color(0xFF8C0009) val onErrorLightMediumContrast = Color(0xFFFFFFFF) val errorContainerLightMediumContrast = Color(0xFFDA342E) val onErrorContainerLightMediumContrast = Color(0xFFFFFFFF) val backgroundLightMediumContrast = Color(0xFFFAFAEE) val onBackgroundLightMediumContrast = Color(0xFF1A1C15) val surfaceLightMediumContrast = Color(0xFFFAFAEE) val onSurfaceLightMediumContrast = Color(0xFF1A1C15) val surfaceVariantLightMediumContrast = Color(0xFFE2E4D4) val onSurfaceVariantLightMediumContrast = Color(0xFF414439) val outlineLightMediumContrast = Color(0xFF5D6054) val outlineVariantLightMediumContrast = Color(0xFF797C6F) val scrimLightMediumContrast = Color(0xFF000000) val inverseSurfaceLightMediumContrast = Color(0xFF2F3129) val inverseOnSurfaceLightMediumContrast = Color(0xFFF1F1E6) val inversePrimaryLightMediumContrast = Color(0xFFB6D085) val surfaceDimLightMediumContrast = Color(0xFFDADBCF) val surfaceBrightLightMediumContrast = Color(0xFFFAFAEE) val surfaceContainerLowestLightMediumContrast = Color(0xFFFFFFFF) val surfaceContainerLowLightMediumContrast = Color(0xFFF4F4E8) val surfaceContainerLightMediumContrast = Color(0xFFEEEFE3) val surfaceContainerHighLightMediumContrast = Color(0xFFE9E9DD) val surfaceContainerHighestLightMediumContrast = Color(0xFFE3E3D8) lightColorScheme( primary = primaryLightMediumContrast, onPrimary = onPrimaryLightMediumContrast, primaryContainer = primaryContainerLightMediumContrast, onPrimaryContainer = onPrimaryContainerLightMediumContrast, secondary = secondaryLightMediumContrast, onSecondary = onSecondaryLightMediumContrast, secondaryContainer = secondaryContainerLightMediumContrast, onSecondaryContainer = onSecondaryContainerLightMediumContrast, tertiary = tertiaryLightMediumContrast, onTertiary = onTertiaryLightMediumContrast, tertiaryContainer = tertiaryContainerLightMediumContrast, onTertiaryContainer = onTertiaryContainerLightMediumContrast, error = errorLightMediumContrast, onError = onErrorLightMediumContrast, errorContainer = errorContainerLightMediumContrast, onErrorContainer = onErrorContainerLightMediumContrast, background = backgroundLightMediumContrast, onBackground = onBackgroundLightMediumContrast, surface = surfaceLightMediumContrast, onSurface = onSurfaceLightMediumContrast, surfaceVariant = surfaceVariantLightMediumContrast, onSurfaceVariant = onSurfaceVariantLightMediumContrast, outline = outlineLightMediumContrast, outlineVariant = outlineVariantLightMediumContrast, scrim = scrimLightMediumContrast, inverseSurface = inverseSurfaceLightMediumContrast, inverseOnSurface = inverseOnSurfaceLightMediumContrast, inversePrimary = inversePrimaryLightMediumContrast, ) } contrast==Contrast.High && isDark -> { val primaryDarkHighContrast = Color(0xFFF5FFDB) val onPrimaryDarkHighContrast = Color(0xFF000000) val primaryContainerDarkHighContrast = Color(0xFFBAD489) val onPrimaryContainerDarkHighContrast = Color(0xFF000000) val secondaryDarkHighContrast = Color(0xFFF6FFDD) val onSecondaryDarkHighContrast = Color(0xFF000000) val secondaryContainerDarkHighContrast = Color(0xFFC6CEAF) val onSecondaryContainerDarkHighContrast = Color(0xFF000000) val tertiaryDarkHighContrast = Color(0xFFEBFFFB) val onTertiaryDarkHighContrast = Color(0xFF000000) val tertiaryContainerDarkHighContrast = Color(0xFFA4D4CD) val onTertiaryContainerDarkHighContrast = Color(0xFF000000) val errorDarkHighContrast = Color(0xFFFFF9F9) val onErrorDarkHighContrast = Color(0xFF000000) val errorContainerDarkHighContrast = Color(0xFFFFBAB1) val onErrorContainerDarkHighContrast = Color(0xFF000000) val backgroundDarkHighContrast = Color(0xFF12140D) val onBackgroundDarkHighContrast = Color(0xFFE3E3D8) val surfaceDarkHighContrast = Color(0xFF12140D) val onSurfaceDarkHighContrast = Color(0xFFFFFFFF) val surfaceVariantDarkHighContrast = Color(0xFF45483D) val onSurfaceVariantDarkHighContrast = Color(0xFFFAFCEC) val outlineDarkHighContrast = Color(0xFFCACCBD) val outlineVariantDarkHighContrast = Color(0xFFCACCBD) val scrimDarkHighContrast = Color(0xFF000000) val inverseSurfaceDarkHighContrast = Color(0xFFE3E3D8) val inverseOnSurfaceDarkHighContrast = Color(0xFF000000) val inversePrimaryDarkHighContrast = Color(0xFF1F2F00) val surfaceDimDarkHighContrast = Color(0xFF12140D) val surfaceBrightDarkHighContrast = Color(0xFF383A32) val surfaceContainerLowestDarkHighContrast = Color(0xFF0D0F09) val surfaceContainerLowDarkHighContrast = Color(0xFF1A1C15) val surfaceContainerDarkHighContrast = Color(0xFF1E2019) val surfaceContainerHighDarkHighContrast = Color(0xFF292B23) val surfaceContainerHighestDarkHighContrast = Color(0xFF34362E) darkColorScheme( primary = primaryDarkHighContrast, onPrimary = onPrimaryDarkHighContrast, primaryContainer = primaryContainerDarkHighContrast, onPrimaryContainer = onPrimaryContainerDarkHighContrast, secondary = secondaryDarkHighContrast, onSecondary = onSecondaryDarkHighContrast, secondaryContainer = secondaryContainerDarkHighContrast, onSecondaryContainer = onSecondaryContainerDarkHighContrast, tertiary = tertiaryDarkHighContrast, onTertiary = onTertiaryDarkHighContrast, tertiaryContainer = tertiaryContainerDarkHighContrast, onTertiaryContainer = onTertiaryContainerDarkHighContrast, error = errorDarkHighContrast, onError = onErrorDarkHighContrast, errorContainer = errorContainerDarkHighContrast, onErrorContainer = onErrorContainerDarkHighContrast, background = backgroundDarkHighContrast, onBackground = onBackgroundDarkHighContrast, surface = surfaceDarkHighContrast, onSurface = onSurfaceDarkHighContrast, surfaceVariant = surfaceVariantDarkHighContrast, onSurfaceVariant = onSurfaceVariantDarkHighContrast, outline = outlineDarkHighContrast, outlineVariant = outlineVariantDarkHighContrast, scrim = scrimDarkHighContrast, inverseSurface = inverseSurfaceDarkHighContrast, inverseOnSurface = inverseOnSurfaceDarkHighContrast, inversePrimary = inversePrimaryDarkHighContrast, ) } contrast==Contrast.High && !isDark -> { val primaryLightHighContrast = Color(0xFF192600) val onPrimaryLightHighContrast = Color(0xFFFFFFFF) val primaryContainerLightHighContrast = Color(0xFF35490D) val onPrimaryContainerLightHighContrast = Color(0xFFFFFFFF) val secondaryLightHighContrast = Color(0xFF1D2510) val onSecondaryLightHighContrast = Color(0xFFFFFFFF) val secondaryContainerLightHighContrast = Color(0xFF3E462E) val onSecondaryContainerLightHighContrast = Color(0xFFFFFFFF) val tertiaryLightHighContrast = Color(0xFF002724) val onTertiaryLightHighContrast = Color(0xFFFFFFFF) val tertiaryContainerLightHighContrast = Color(0xFF1B4A45) val onTertiaryContainerLightHighContrast = Color(0xFFFFFFFF) val errorLightHighContrast = Color(0xFF4E0002) val onErrorLightHighContrast = Color(0xFFFFFFFF) val errorContainerLightHighContrast = Color(0xFF8C0009) val onErrorContainerLightHighContrast = Color(0xFFFFFFFF) val backgroundLightHighContrast = Color(0xFFFAFAEE) val onBackgroundLightHighContrast = Color(0xFF1A1C15) val surfaceLightHighContrast = Color(0xFFFAFAEE) val onSurfaceLightHighContrast = Color(0xFF000000) val surfaceVariantLightHighContrast = Color(0xFFE2E4D4) val onSurfaceVariantLightHighContrast = Color(0xFF22251B) val outlineLightHighContrast = Color(0xFF414439) val outlineVariantLightHighContrast = Color(0xFF414439) val scrimLightHighContrast = Color(0xFF000000) val inverseSurfaceLightHighContrast = Color(0xFF2F3129) val inverseOnSurfaceLightHighContrast = Color(0xFFFFFFFF) val inversePrimaryLightHighContrast = Color(0xFFDBF6A8) val surfaceDimLightHighContrast = Color(0xFFDADBCF) val surfaceBrightLightHighContrast = Color(0xFFFAFAEE) val surfaceContainerLowestLightHighContrast = Color(0xFFFFFFFF) val surfaceContainerLowLightHighContrast = Color(0xFFF4F4E8) val surfaceContainerLightHighContrast = Color(0xFFEEEFE3) val surfaceContainerHighLightHighContrast = Color(0xFFE9E9DD) val surfaceContainerHighestLightHighContrast = Color(0xFFE3E3D8) lightColorScheme( primary = primaryLightHighContrast, onPrimary = onPrimaryLightHighContrast, primaryContainer = primaryContainerLightHighContrast, onPrimaryContainer = onPrimaryContainerLightHighContrast, secondary = secondaryLightHighContrast, onSecondary = onSecondaryLightHighContrast, secondaryContainer = secondaryContainerLightHighContrast, onSecondaryContainer = onSecondaryContainerLightHighContrast, tertiary = tertiaryLightHighContrast, onTertiary = onTertiaryLightHighContrast, tertiaryContainer = tertiaryContainerLightHighContrast, onTertiaryContainer = onTertiaryContainerLightHighContrast, error = errorLightHighContrast, onError = onErrorLightHighContrast, errorContainer = errorContainerLightHighContrast, onErrorContainer = onErrorContainerLightHighContrast, background = backgroundLightHighContrast, onBackground = onBackgroundLightHighContrast, surface = surfaceLightHighContrast, onSurface = onSurfaceLightHighContrast, surfaceVariant = surfaceVariantLightHighContrast, onSurfaceVariant = onSurfaceVariantLightHighContrast, outline = outlineLightHighContrast, outlineVariant = outlineVariantLightHighContrast, scrim = scrimLightHighContrast, inverseSurface = inverseSurfaceLightHighContrast, inverseOnSurface = inverseOnSurfaceLightHighContrast, inversePrimary = inversePrimaryLightHighContrast, ) } else -> { val primaryLight = Color(0xFF506528) val onPrimaryLight = Color(0xFFFFFFFF) val primaryContainerLight = Color(0xFFD2EC9F) val onPrimaryContainerLight = Color(0xFF131F00) val secondaryLight = Color(0xFF596248) val onSecondaryLight = Color(0xFFFFFFFF) val secondaryContainerLight = Color(0xFFDDE6C6) val onSecondaryContainerLight = Color(0xFF171E0A) val tertiaryLight = Color(0xFF396661) val onTertiaryLight = Color(0xFFFFFFFF) val tertiaryContainerLight = Color(0xFFBCECE5) val onTertiaryContainerLight = Color(0xFF00201D) val errorLight = Color(0xFFBA1A1A) val onErrorLight = Color(0xFFFFFFFF) val errorContainerLight = Color(0xFFFFDAD6) val onErrorContainerLight = Color(0xFF410002) val backgroundLight = Color(0xFFFAFAEE) val onBackgroundLight = Color(0xFF1A1C15) val surfaceLight = Color(0xFFFAFAEE) val onSurfaceLight = Color(0xFF1A1C15) val surfaceVariantLight = Color(0xFFE2E4D4) val onSurfaceVariantLight = Color(0xFF45483D) val outlineLight = Color(0xFF76786B) val outlineVariantLight = Color(0xFFC6C8B9) val scrimLight = Color(0xFF000000) val inverseSurfaceLight = Color(0xFF2F3129) val inverseOnSurfaceLight = Color(0xFFF1F1E6) val inversePrimaryLight = Color(0xFFB6D085) val surfaceDimLight = Color(0xFFDADBCF) val surfaceBrightLight = Color(0xFFFAFAEE) val surfaceContainerLowestLight = Color(0xFFFFFFFF) val surfaceContainerLowLight = Color(0xFFF4F4E8) val surfaceContainerLight = Color(0xFFEEEFE3) val surfaceContainerHighLight = Color(0xFFE9E9DD) val surfaceContainerHighestLight = Color(0xFFE3E3D8) lightColorScheme( primary = primaryLight, onPrimary = onPrimaryLight, primaryContainer = primaryContainerLight, onPrimaryContainer = onPrimaryContainerLight, secondary = secondaryLight, onSecondary = onSecondaryLight, secondaryContainer = secondaryContainerLight, onSecondaryContainer = onSecondaryContainerLight, tertiary = tertiaryLight, onTertiary = onTertiaryLight, tertiaryContainer = tertiaryContainerLight, onTertiaryContainer = onTertiaryContainerLight, error = errorLight, onError = onErrorLight, errorContainer = errorContainerLight, onErrorContainer = onErrorContainerLight, background = backgroundLight, onBackground = onBackgroundLight, surface = surfaceLight, onSurface = onSurfaceLight, surfaceVariant = surfaceVariantLight, onSurfaceVariant = onSurfaceVariantLight, outline = outlineLight, outlineVariant = outlineVariantLight, scrim = scrimLight, inverseSurface = inverseSurfaceLight, inverseOnSurface = inverseOnSurfaceLight, inversePrimary = inversePrimaryLight, ) } } } } }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/theme/Theme.kt
865303112
/* *abiola 2024 */ package com.mshdabiola.designsystem.theme import android.os.Build import androidx.annotation.ChecksSdkIntAtLeast import androidx.annotation.RequiresApi import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.surfaceColorAtElevation import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Immutable import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.mshdabiola.model.Contrast import com.mshdabiola.model.ThemeBrand @Immutable data class ColorFamily( val color: Color, val onColor: Color, val colorContainer: Color, val onColorContainer: Color, ) val unspecified_scheme = ColorFamily( Color.Unspecified, Color.Unspecified, Color.Unspecified, Color.Unspecified, ) @Composable fun SkTheme( darkTheme: Boolean = isSystemInDarkTheme(), themeBrand: ThemeBrand = ThemeBrand.DEFAULT, themeContrast: Contrast = Contrast.Normal, disableDynamicTheming: Boolean = true, content: @Composable () -> Unit, ) { val theme = when (themeBrand) { ThemeBrand.GREEN -> Theme.GreenTheme(darkTheme, themeContrast) else -> Theme.DefaultTheme(darkTheme, themeContrast) } val useDynamicTheme = when { themeBrand != ThemeBrand.DEFAULT -> false !disableDynamicTheming -> true else -> false } val colorScheme = if (useDynamicTheme && supportsDynamicTheming()) { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } else { theme.getColorScheme() } // Composition locals CompositionLocalProvider( LocalGradientColors provides if (useDynamicTheme) GradientColors( container = colorScheme.surfaceColorAtElevation( 2.dp, ), ) else theme.getGradientColors(), LocalBackgroundTheme provides theme.getBackgroundTheme(), LocalTintTheme provides theme.getTintTheme(), ) { MaterialTheme( colorScheme = colorScheme, typography = SkTypography, content = content, ) } } @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S) fun supportsDynamicTheming() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/theme/Background.kt
4074932463
/* *abiola 2024 */ package com.mshdabiola.designsystem.theme import androidx.compose.runtime.Immutable import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp /** * A class to model background color and tonal elevation values for Now in Android. */ @Immutable data class BackgroundTheme( val color: Color = Color.Unspecified, val tonalElevation: Dp = Dp.Unspecified, ) /** * A composition local for [BackgroundTheme]. */ val LocalBackgroundTheme = staticCompositionLocalOf { BackgroundTheme() }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/theme/Type.kt
1997048154
/* *abiola 2024 */ package com.mshdabiola.designsystem.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp /** * Now in Android typography. */ internal val SkTypography = Typography( displayLarge = TextStyle( fontWeight = FontWeight.Normal, fontSize = 57.sp, lineHeight = 64.sp, letterSpacing = (-0.25).sp, ), displayMedium = TextStyle( fontWeight = FontWeight.Normal, fontSize = 45.sp, lineHeight = 52.sp, letterSpacing = 0.sp, ), displaySmall = TextStyle( fontWeight = FontWeight.Normal, fontSize = 36.sp, lineHeight = 44.sp, letterSpacing = 0.sp, ), headlineLarge = TextStyle( fontWeight = FontWeight.Normal, fontSize = 32.sp, lineHeight = 40.sp, letterSpacing = 0.sp, ), headlineMedium = TextStyle( fontWeight = FontWeight.Normal, fontSize = 28.sp, lineHeight = 36.sp, letterSpacing = 0.sp, ), headlineSmall = TextStyle( fontWeight = FontWeight.Normal, fontSize = 24.sp, lineHeight = 32.sp, letterSpacing = 0.sp, ), titleLarge = TextStyle( fontWeight = FontWeight.Bold, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp, ), titleMedium = TextStyle( fontWeight = FontWeight.Bold, fontSize = 18.sp, lineHeight = 24.sp, letterSpacing = 0.1.sp, ), titleSmall = TextStyle( fontWeight = FontWeight.Medium, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp, ), bodyLarge = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp, ), bodyMedium = TextStyle( fontWeight = FontWeight.Normal, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.25.sp, ), bodySmall = TextStyle( fontWeight = FontWeight.Normal, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.4.sp, ), labelLarge = TextStyle( fontWeight = FontWeight.Medium, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp, ), labelMedium = TextStyle( fontWeight = FontWeight.Medium, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp, ), labelSmall = TextStyle( fontWeight = FontWeight.Medium, fontSize = 10.sp, lineHeight = 16.sp, letterSpacing = 0.sp, ), )
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/theme/Gradient.kt
1763383201
/* *abiola 2024 */ package com.mshdabiola.designsystem.theme import androidx.compose.runtime.Immutable import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.graphics.Color /** * A class to model gradient color values for Now in Android. * * @param top The top gradient color to be rendered. * @param bottom The bottom gradient color to be rendered. * @param container The container gradient color over which the gradient will be rendered. */ @Immutable data class GradientColors( val top: Color = Color.Unspecified, val bottom: Color = Color.Unspecified, val container: Color = Color.Unspecified, ) /** * A composition local for [GradientColors]. */ val LocalGradientColors = staticCompositionLocalOf { GradientColors() }
SkeletonAndroid/modules/designsystem/src/main/kotlin/com/mshdabiola/designsystem/icon/SkIcons.kt
1991263924
/* *abiola 2024 */ package com.mshdabiola.designsystem.icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.Search object SkIcons { val Add = Icons.Rounded.Add val MoreVert = Icons.Default.MoreVert val Search = Icons.Rounded.Search }
SkeletonAndroid/modules/network/src/test/java/com/mshdabiola/network/ExampleUnitTest.kt
3318780695
/* *abiola 2024 */ package com.mshdabiola.network import junit.framework.TestCase.assertEquals import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
SkeletonAndroid/modules/network/src/test/java/com/mshdabiola/network/KtorNetworkTest.kt
912671743
/* *abiola 2024 */ package com.mshdabiola.network import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.headersOf import io.ktor.utils.io.ByteReadChannel import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class KtorNetworkTest { private lateinit var ktorNetwork: NetworkSource @Before fun setUp() { val engine = MockEngine { re -> respond( content = ByteReadChannel("""{"id":98,"name":"abiola"}"""), status = HttpStatusCode.OK, headers = headersOf(HttpHeaders.ContentType, "application/json"), ) } val client = Client.get(engine) ktorNetwork = NetworkSource(client) } @After fun close() { } @Test fun get() = runTest { val model = ktorNetwork.get() assertEquals(model.id, 98) } }
SkeletonAndroid/modules/network/src/test/java/com/mshdabiola/network/Client.kt
3909070791
/* *abiola 2024 */ package com.mshdabiola.network import io.ktor.client.HttpClient import io.ktor.client.engine.HttpClientEngine import io.ktor.client.plugins.UserAgent import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.defaultRequest import io.ktor.client.plugins.resources.Resources import io.ktor.serialization.kotlinx.json.json object Client { fun get(httpClientEngine: HttpClientEngine) = HttpClient(httpClientEngine) { install(Resources) install(ContentNegotiation) { json() } defaultRequest { this.url("") } install(UserAgent) { agent = "my app" } } }
SkeletonAndroid/modules/network/src/main/java/JvmUnitTestFakeAssetManager.kt
3287188078
/* *abiola 2022 */ import androidx.annotation.VisibleForTesting import com.mshdabiola.network.fake.FakeAssetManager import java.io.File import java.io.InputStream import java.util.Properties /** * This class helps with loading Android `/assets` files, especially when running JVM unit tests. * It must remain on the root package for an easier [Class.getResource] with relative paths. * @see <a href="https://developer.android.com/reference/tools/gradle-api/7.3/com/android/build/api/dsl/UnitTestOptions">UnitTestOptions</a> */ @VisibleForTesting internal object JvmUnitTestFakeAssetManager : FakeAssetManager { private val config = requireNotNull(javaClass.getResource("com/android/tools/test_config.properties")) { """ Missing Android resources properties file. Did you forget to enable the feature in the gradle build file? android.testOptions.unitTests.isIncludeAndroidResources = true """.trimIndent() } private val properties = Properties().apply { config.openStream().use(::load) } private val assets = File(properties["android_merged_assets"].toString()) override fun open(fileName: String): InputStream = File(assets, fileName).inputStream() }
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/di/NetworkModule.kt
3616894428
/* *abiola 2024 */ package com.mshdabiola.network.di import com.mshdabiola.network.Config import com.mshdabiola.network.INetworkDataSource import com.mshdabiola.network.NetworkDataSource import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import io.ktor.client.HttpClient import io.ktor.client.engine.android.Android import io.ktor.client.plugins.HttpRequestRetry import io.ktor.client.plugins.UserAgent import io.ktor.client.plugins.cache.HttpCache import io.ktor.client.plugins.cache.storage.FileStorage import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.defaultRequest import io.ktor.client.plugins.logging.LogLevel import io.ktor.client.plugins.logging.Logging import io.ktor.client.plugins.logging.SIMPLE import io.ktor.client.plugins.resources.Resources import io.ktor.client.request.headers import io.ktor.http.HttpHeaders import io.ktor.http.URLProtocol import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.json.Json import java.io.File import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module object NetworkModule { @Provides fun clientProvider() = HttpClient(Android) { install(Resources) install(Logging) { logger = io.ktor.client.plugins.logging.Logger.SIMPLE level = LogLevel.ALL } install(ContentNegotiation) { json( Json { this.ignoreUnknownKeys = true }, ) } defaultRequest { headers { this[HttpHeaders.Authorization] = "Bearer ${Config.token}" this[HttpHeaders.Accept] = "application/json" this[HttpHeaders.ContentType] = "application/json" } url { host = "api.spotify.com" protocol = URLProtocol.HTTPS } } install(UserAgent) { agent = "my app" } install(HttpRequestRetry) { retryOnServerErrors(5) exponentialDelay() } install(HttpCache) { val file = File.createTempFile("abiola", "tem") publicStorage(FileStorage(file)) } } } @InstallIn(SingletonComponent::class) @Module interface NetworkBind { @Binds @Singleton fun bindNetworkDataSource(iNetworkDataSource: INetworkDataSource): NetworkDataSource }
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/Engine.kt
632233803
/* *abiola 2024 */ package com.mshdabiola.network import io.ktor.client.engine.HttpClientEngine import javax.inject.Inject class Engine @Inject constructor( private val httpClientEngine: HttpClientEngine, )
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/NetworkSource.kt
1992737100
/* *abiola 2024 */ package com.mshdabiola.network import com.mshdabiola.network.model.Model import com.mshdabiola.network.request.Articles3 import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.plugins.resources.get import javax.inject.Inject class NetworkSource @Inject constructor( private val httpClient: HttpClient, ) { suspend fun get(): Model { return httpClient.get(Articles3.New()).body() } }
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/NetworkDataSource.kt
1278052997
/* *abiola 2024 */ package com.mshdabiola.network interface NetworkDataSource { suspend fun getRecommendation(): List<String> }
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/Config.kt
796421906
/* *abiola 2024 */ package com.mshdabiola.network object Config { var token = "" }
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/model/Model.kt
733470143
/* *abiola 2024 */ package com.mshdabiola.network.model import kotlinx.serialization.Serializable @Serializable data class Model( val id: Long, val name: String, )
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/request/Articles.kt
1676656255
/* *abiola 2024 */ package com.mshdabiola.network.request import io.ktor.resources.Resource @Resource("/article") class Articles() { @Resource("{id}") class Id(val parent: Articles = Articles(), val id: Long) } @Resource("/article") class Articles2(val sort: String? = "news") @Resource("/article") class Articles3() { @Resource("new") class New(val parent: Articles = Articles()) @Resource("{id}") class Id(val parent: Articles = Articles(), val id: Long) { @Resource("edit") class Edit(val parent: Id) } }
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/INetworkDataSource.kt
1772276297
/* *abiola 2024 */ package com.mshdabiola.network import io.ktor.client.HttpClient import javax.inject.Inject class INetworkDataSource @Inject constructor( private val httpClient: HttpClient, ) : NetworkDataSource { override suspend fun getRecommendation(): List<String> { // val response = httpClient.get( // Request.Recommendations( // limit = "10", // market = "NG", // seed_artists = "4NHQUGzhtTLFvgF5SZesLK", // seed_genres = "classical", // seed_tracks = "0c6xIDDpzE81m2q797ordA" // ) // ) // val netWorkTracks: PagingNetWorkTracks = if (response.status == HttpStatusCode.OK) { // response.body() // } else { // val message: Message = response.body() // throw Exception(message.error.message) // } // // // return netWorkTracks.tracks // } TODO() } }
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/fake/FakeNiaNetworkDataSource.kt
1036914355
/* *abiola 2022 */ package com.mshdabiola.network.fake import JvmUnitTestFakeAssetManager import com.mshdabiola.common.network.Dispatcher import com.mshdabiola.common.network.SkDispatchers import kotlinx.coroutines.CoroutineDispatcher import kotlinx.serialization.json.Json import javax.inject.Inject /** * [NiaNetworkDataSource] implementation that provides static news resources to aid development */ class FakeNiaNetworkDataSource @Inject constructor( @Dispatcher(SkDispatchers.IO) private val ioDispatcher: CoroutineDispatcher, private val networkJson: Json, private val assets: FakeAssetManager = JvmUnitTestFakeAssetManager, ) // ) : NiaNetworkDataSource { // // @OptIn(ExperimentalSerializationApi::class) // override suspend fun getTopics(ids: List<String>?): List<NetworkTopic> = // withContext(ioDispatcher) { // assets.open(TOPICS_ASSET).use(networkJson::decodeFromStream) // } // // @OptIn(ExperimentalSerializationApi::class) // override suspend fun getNewsResources(ids: List<String>?): List<NetworkNewsResource> = // withContext(ioDispatcher) { // assets.open(NEWS_ASSET).use(networkJson::decodeFromStream) // } // // override suspend fun getTopicChangeList(after: Int?): List<NetworkChangeList> = // getTopics().mapToChangeList(NetworkTopic::id) // // override suspend fun getNewsResourceChangeList(after: Int?): List<NetworkChangeList> = // getNewsResources().mapToChangeList(NetworkNewsResource::id) // // companion object { // private const val NEWS_ASSET = "news.json" // private const val TOPICS_ASSET = "topics.json" // } // } // // /** // * Converts a list of [T] to change list of all the items in it where [idGetter] defines the // * [NetworkChangeList.id] // */ // private fun <T> List<T>.mapToChangeList( // idGetter: (T) -> String, // ) = mapIndexed { index, item -> // NetworkChangeList( // id = idGetter(item), // changeListVersion = index, // isDelete = false, // ) // }
SkeletonAndroid/modules/network/src/main/java/com/mshdabiola/network/fake/FakeAssetManager.kt
3069425496
/* *abiola 2022 */ package com.mshdabiola.network.fake import java.io.InputStream fun interface FakeAssetManager { fun open(fileName: String): InputStream }
SkeletonAndroid/modules/testing/src/main/java/com/mshdabiola/testing/repository/TestUserDataRepository.kt
826740438
/* *abiola 2022 */ package com.mshdabiola.testing.repository import com.mshdabiola.data.repository.UserDataRepository import com.mshdabiola.model.Contrast import com.mshdabiola.model.DarkThemeConfig import com.mshdabiola.model.ThemeBrand import com.mshdabiola.model.UserData import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.filterNotNull val emptyUserData = UserData( bookmarkedNewsResources = emptySet(), viewedNewsResources = emptySet(), followedTopics = emptySet(), themeBrand = ThemeBrand.DEFAULT, darkThemeConfig = DarkThemeConfig.FOLLOW_SYSTEM, useDynamicColor = false, shouldHideOnboarding = false, contrast = Contrast.Normal ) class TestUserDataRepository : UserDataRepository { /** * The backing hot flow for the list of followed topic ids for testing. */ private val _userData = MutableSharedFlow<UserData>(replay = 1, onBufferOverflow = DROP_OLDEST) private val currentUserData get() = _userData.replayCache.firstOrNull() ?: emptyUserData override val userData: Flow<UserData> = _userData.filterNotNull() override suspend fun setFollowedTopicIds(followedTopicIds: Set<String>) { _userData.tryEmit(currentUserData.copy(followedTopics = followedTopicIds)) } override suspend fun setTopicIdFollowed(followedTopicId: String, followed: Boolean) { currentUserData.let { current -> val followedTopics = if (followed) { current.followedTopics + followedTopicId } else { current.followedTopics - followedTopicId } _userData.tryEmit(current.copy(followedTopics = followedTopics)) } } override suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) { currentUserData.let { current -> val bookmarkedNews = if (bookmarked) { current.bookmarkedNewsResources + newsResourceId } else { current.bookmarkedNewsResources - newsResourceId } _userData.tryEmit(current.copy(bookmarkedNewsResources = bookmarkedNews)) } } override suspend fun setNewsResourceViewed(newsResourceId: String, viewed: Boolean) { currentUserData.let { current -> _userData.tryEmit( current.copy( viewedNewsResources = if (viewed) { current.viewedNewsResources + newsResourceId } else { current.viewedNewsResources - newsResourceId }, ), ) } } override suspend fun setThemeBrand(themeBrand: ThemeBrand) { currentUserData.let { current -> _userData.tryEmit(current.copy(themeBrand = themeBrand)) } } override suspend fun setThemeContrast(contrast: Contrast) { currentUserData.let { current -> _userData.tryEmit(current.copy(contrast = contrast)) } } override suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) { currentUserData.let { current -> _userData.tryEmit(current.copy(darkThemeConfig = darkThemeConfig)) } } override suspend fun setDynamicColorPreference(useDynamicColor: Boolean) { currentUserData.let { current -> _userData.tryEmit(current.copy(useDynamicColor = useDynamicColor)) } } override suspend fun setShouldHideOnboarding(shouldHideOnboarding: Boolean) { currentUserData.let { current -> _userData.tryEmit(current.copy(shouldHideOnboarding = shouldHideOnboarding)) } } /** * A test-only API to allow setting of user data directly. */ fun setUserData(userData: UserData) { _userData.tryEmit(userData) } }
SkeletonAndroid/modules/testing/src/main/java/com/mshdabiola/testing/di/TestDispatcherModule.kt
270633025
/* *abiola 2024 */ package com.mshdabiola.testing.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) internal object TestDispatcherModule { @Provides @Singleton fun providesTestDispatcher(): TestDispatcher = UnconfinedTestDispatcher() }
SkeletonAndroid/modules/testing/src/main/java/com/mshdabiola/testing/util/TestAnalyticsHelper.kt
1562583633
/* *abiola 2024 */ package com.mshdabiola.testing.util import com.mshdabiola.analytics.AnalyticsEvent import com.mshdabiola.analytics.AnalyticsHelper class TestAnalyticsHelper : AnalyticsHelper { private val events = mutableListOf<AnalyticsEvent>() override fun logEvent(event: AnalyticsEvent) { events.add(event) } fun hasLogged(event: AnalyticsEvent) = event in events }
SkeletonAndroid/modules/testing/src/main/java/com/mshdabiola/testing/util/MainDispatcherRule.kt
2851083988
/* *abiola 2024 */ package com.mshdabiola.testing.util import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.rules.TestRule import org.junit.rules.TestWatcher import org.junit.runner.Description /** * A JUnit [TestRule] that sets the Main dispatcher to [testDispatcher] * for the duration of the test. */ class MainDispatcherRule( private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(), ) : TestWatcher() { override fun starting(description: Description) = Dispatchers.setMain(testDispatcher) override fun finished(description: Description) = Dispatchers.resetMain() }
SkeletonAndroid/modules/testing/src/main/java/com/mshdabiola/testing/util/ScreenshotHelper.kt
35176117
/* *abiola 2024 */ package com.mshdabiola.testing.util import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.test.junit4.AndroidComposeTestRule import androidx.compose.ui.test.onRoot import androidx.test.ext.junit.rules.ActivityScenarioRule import com.github.takahirom.roborazzi.RoborazziOptions import com.github.takahirom.roborazzi.RoborazziOptions.CompareOptions import com.github.takahirom.roborazzi.RoborazziOptions.RecordOptions import com.github.takahirom.roborazzi.captureRoboImage import com.google.accompanist.testharness.TestHarness import com.mshdabiola.designsystem.theme.SkTheme import org.robolectric.RuntimeEnvironment val DefaultRoborazziOptions = RoborazziOptions( // Pixel-perfect matching compareOptions = CompareOptions(changeThreshold = 0f), // Reduce the size of the PNGs recordOptions = RecordOptions(resizeScale = 0.5), ) enum class DefaultTestDevices(val description: String, val spec: String) { PHONE("phone", "spec:shape=Normal,width=640,height=360,unit=dp,dpi=480"), FOLDABLE("foldable", "spec:shape=Normal,width=673,height=841,unit=dp,dpi=480"), TABLET("tablet", "spec:shape=Normal,width=1280,height=800,unit=dp,dpi=480"), } fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureMultiDevice( screenshotName: String, body: @Composable () -> Unit, ) { DefaultTestDevices.entries.forEach { this.captureForDevice(it.description, it.spec, screenshotName, body = body) } } fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureForDevice( deviceName: String, deviceSpec: String, screenshotName: String, roborazziOptions: RoborazziOptions = DefaultRoborazziOptions, darkMode: Boolean = false, body: @Composable () -> Unit, ) { val (width, height, dpi) = extractSpecs(deviceSpec) // Set qualifiers from specs RuntimeEnvironment.setQualifiers("w${width}dp-h${height}dp-${dpi}dpi") this.activity.setContent { CompositionLocalProvider( LocalInspectionMode provides true, ) { TestHarness(darkMode = darkMode) { body() } } } this.onRoot() .captureRoboImage( "src/test/screenshots/${screenshotName}_$deviceName.png", roborazziOptions = roborazziOptions, ) } /** * Takes six screenshots combining light/dark and default/Android themes and whether dynamic color * is enabled. */ fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureMultiTheme( name: String, overrideFileName: String? = null, shouldCompareDarkMode: Boolean = true, shouldCompareDynamicColor: Boolean = true, shouldCompareAndroidTheme: Boolean = true, content: @Composable (desc: String) -> Unit, ) { val darkModeValues = if (shouldCompareDarkMode) listOf(true, false) else listOf(false) val dynamicThemingValues = if (shouldCompareDynamicColor) listOf(true, false) else listOf(false) val androidThemeValues = if (shouldCompareAndroidTheme) listOf(true, false) else listOf(false) var darkMode by mutableStateOf(true) var dynamicTheming by mutableStateOf(false) var androidTheme by mutableStateOf(false) this.setContent { CompositionLocalProvider( LocalInspectionMode provides true, ) { SkTheme( androidTheme = androidTheme, darkTheme = darkMode, disableDynamicTheming = !dynamicTheming, ) { // Keying is necessary in some cases (e.g. animations) key(androidTheme, darkMode, dynamicTheming) { val description = generateDescription( shouldCompareDarkMode, darkMode, shouldCompareAndroidTheme, androidTheme, shouldCompareDynamicColor, dynamicTheming, ) content(description) } } } } // Create permutations darkModeValues.forEach { isDarkMode -> darkMode = isDarkMode val darkModeDesc = if (isDarkMode) "dark" else "light" androidThemeValues.forEach { isAndroidTheme -> androidTheme = isAndroidTheme val androidThemeDesc = if (isAndroidTheme) "androidTheme" else "defaultTheme" dynamicThemingValues.forEach dynamicTheme@{ isDynamicTheming -> // Skip tests with both Android Theme and Dynamic color as they're incompatible. if (isAndroidTheme && isDynamicTheming) return@dynamicTheme dynamicTheming = isDynamicTheming val dynamicThemingDesc = if (isDynamicTheming) "dynamic" else "notDynamic" val filename = overrideFileName ?: name this.onRoot() .captureRoboImage( "src/test/screenshots/" + "$name/$filename" + "_$darkModeDesc" + "_$androidThemeDesc" + "_$dynamicThemingDesc" + ".png", roborazziOptions = DefaultRoborazziOptions, ) } } } } @Composable private fun generateDescription( shouldCompareDarkMode: Boolean, darkMode: Boolean, shouldCompareAndroidTheme: Boolean, androidTheme: Boolean, shouldCompareDynamicColor: Boolean, dynamicTheming: Boolean, ): String { val description = "" + if (shouldCompareDarkMode) { if (darkMode) "Dark" else "Light" } else { "" } + if (shouldCompareAndroidTheme) { if (androidTheme) " Android" else " Default" } else { "" } + if (shouldCompareDynamicColor) { if (dynamicTheming) " Dynamic" else "" } else { "" } return description.trim() } /** * Extracts some properties from the spec string. Note that this function is not exhaustive. */ private fun extractSpecs(deviceSpec: String): TestDeviceSpecs { val specs = deviceSpec.substringAfter("spec:") .split(",").map { it.split("=") }.associate { it[0] to it[1] } val width = specs["width"]?.toInt() ?: 640 val height = specs["height"]?.toInt() ?: 480 val dpi = specs["dpi"]?.toInt() ?: 480 return TestDeviceSpecs(width, height, dpi) } data class TestDeviceSpecs(val width: Int, val height: Int, val dpi: Int)
SkeletonAndroid/modules/testing/src/main/java/com/mshdabiola/testing/TestRunner.kt
547443248
/* *abiola 2024 */ package com.mshdabiola.testing import android.app.Application import android.content.Context import androidx.test.runner.AndroidJUnitRunner import dagger.hilt.android.testing.HiltTestApplication /** * A custom runner to set up the instrumented application class for tests. */ class TestRunner : AndroidJUnitRunner() { override fun newApplication(cl: ClassLoader, name: String, context: Context): Application = super.newApplication(cl, HiltTestApplication::class.java.name, context) }
SkeletonAndroid/modules/datastore/src/test/kotlin/com/mshdabiola/datastore/TestDataStoreModule.kt
922540746
/* *abiola 2024 */ package com.mshdabiola.datastore import androidx.datastore.core.DataStore import androidx.datastore.core.DataStoreFactory import com.mshdabiola.common.network.di.ApplicationScope import com.mshdabiola.datastore.di.DataStoreModule import dagger.Module import dagger.Provides import dagger.hilt.components.SingletonComponent import dagger.hilt.testing.TestInstallIn import kotlinx.coroutines.CoroutineScope import org.junit.rules.TemporaryFolder import javax.inject.Singleton @Module @TestInstallIn( components = [SingletonComponent::class], replaces = [DataStoreModule::class], ) internal object TestDataStoreModule { @Provides @Singleton fun providesUserPreferencesDataStore( @ApplicationScope scope: CoroutineScope, userPreferencesSerializer: UserPreferencesSerializer, tmpFolder: TemporaryFolder, ): DataStore<UserPreferences> = tmpFolder.testUserPreferencesDataStore( coroutineScope = scope, userPreferencesSerializer = userPreferencesSerializer, ) } fun TemporaryFolder.testUserPreferencesDataStore( coroutineScope: CoroutineScope, userPreferencesSerializer: UserPreferencesSerializer = UserPreferencesSerializer(), ) = DataStoreFactory.create( serializer = userPreferencesSerializer, scope = coroutineScope, ) { newFile("user_preferences_test.pb") }
SkeletonAndroid/modules/datastore/src/test/kotlin/com/mshdabiola/datastore/UserPreferencesSerializerTest.kt
2986956755
/* *abiola 2024 */ package com.mshdabiola.datastore import androidx.datastore.core.CorruptionException import kotlinx.coroutines.test.runTest import org.junit.Test import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import kotlin.test.assertEquals class UserPreferencesSerializerTest { private val userPreferencesSerializer = UserPreferencesSerializer() @Test fun defaultUserPreferences_isEmpty() { assertEquals( userPreferences { // Default value }, userPreferencesSerializer.defaultValue, ) } @Test fun writingAndReadingUserPreferences_outputsCorrectValue() = runTest { val expectedUserPreferences = userPreferences { followedTopicIds.put("0", true) followedTopicIds.put("1", true) } val outputStream = ByteArrayOutputStream() expectedUserPreferences.writeTo(outputStream) val inputStream = ByteArrayInputStream(outputStream.toByteArray()) val actualUserPreferences = userPreferencesSerializer.readFrom(inputStream) assertEquals( expectedUserPreferences, actualUserPreferences, ) } @Test(expected = CorruptionException::class) fun readingInvalidUserPreferences_throwsCorruptionException() = runTest { userPreferencesSerializer.readFrom(ByteArrayInputStream(byteArrayOf(0))) } }
SkeletonAndroid/modules/datastore/src/test/kotlin/com/mshdabiola/datastore/IntToStringIdsMigrationTest.kt
2861350919
/* *abiola 2024 */ package com.mshdabiola.datastore import kotlinx.coroutines.test.runTest import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue /** * Unit test for [IntToStringIdsMigration] */ class IntToStringIdsMigrationTest { @Test fun IntToStringIdsMigration_should_migrate_topic_ids() = runTest { // Set up existing preferences with topic int ids val preMigrationUserPreferences = userPreferences { deprecatedIntFollowedTopicIds.addAll(listOf(1, 2, 3)) } // Assert that there are no string topic ids yet assertEquals( emptyList<String>(), preMigrationUserPreferences.deprecatedFollowedTopicIdsList, ) // Run the migration val postMigrationUserPreferences = IntToStringIdsMigration.migrate(preMigrationUserPreferences) // Assert the deprecated int topic ids have been migrated to the string topic ids assertEquals( userPreferences { deprecatedFollowedTopicIds.addAll(listOf("1", "2", "3")) hasDoneIntToStringIdMigration = true }, postMigrationUserPreferences, ) // Assert that the migration has been marked complete assertTrue(postMigrationUserPreferences.hasDoneIntToStringIdMigration) } @Test fun IntToStringIdsMigration_should_migrate_author_ids() = runTest { // Set up existing preferences with author int ids val preMigrationUserPreferences = userPreferences { deprecatedIntFollowedAuthorIds.addAll(listOf(4, 5, 6)) } // Assert that there are no string author ids yet assertEquals( emptyList<String>(), preMigrationUserPreferences.deprecatedFollowedAuthorIdsList, ) // Run the migration val postMigrationUserPreferences = IntToStringIdsMigration.migrate(preMigrationUserPreferences) // Assert the deprecated int author ids have been migrated to the string author ids assertEquals( userPreferences { deprecatedFollowedAuthorIds.addAll(listOf("4", "5", "6")) hasDoneIntToStringIdMigration = true }, postMigrationUserPreferences, ) // Assert that the migration has been marked complete assertTrue(postMigrationUserPreferences.hasDoneIntToStringIdMigration) } }
SkeletonAndroid/modules/datastore/src/test/kotlin/com/mshdabiola/datastore/ListToMapMigrationTest.kt
1718114674
/* *abiola 2024 */ package com.mshdabiola.datastore import kotlinx.coroutines.test.runTest import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class ListToMapMigrationTest { @Test fun ListToMapMigration_should_migrate_topic_ids() = runTest { // Set up existing preferences with topic ids val preMigrationUserPreferences = userPreferences { deprecatedFollowedTopicIds.addAll(listOf("1", "2", "3")) } // Assert that there are no topic ids in the map yet assertEquals( emptyMap<String, Boolean>(), preMigrationUserPreferences.followedTopicIdsMap, ) // Run the migration val postMigrationUserPreferences = ListToMapMigration.migrate(preMigrationUserPreferences) // Assert the deprecated topic ids have been migrated to the topic ids map assertEquals( mapOf("1" to true, "2" to true, "3" to true), postMigrationUserPreferences.followedTopicIdsMap, ) // Assert that the migration has been marked complete assertTrue(postMigrationUserPreferences.hasDoneListToMapMigration) } @Test fun ListToMapMigration_should_migrate_author_ids() = runTest { // Set up existing preferences with author ids val preMigrationUserPreferences = userPreferences { deprecatedFollowedAuthorIds.addAll(listOf("4", "5", "6")) } // Assert that there are no author ids in the map yet assertEquals( emptyMap<String, Boolean>(), preMigrationUserPreferences.followedAuthorIdsMap, ) // Run the migration val postMigrationUserPreferences = ListToMapMigration.migrate(preMigrationUserPreferences) // Assert the deprecated author ids have been migrated to the author ids map assertEquals( mapOf("4" to true, "5" to true, "6" to true), postMigrationUserPreferences.followedAuthorIdsMap, ) // Assert that the migration has been marked complete assertTrue(postMigrationUserPreferences.hasDoneListToMapMigration) } @Test fun ListToMapMigration_should_migrate_bookmarks() = runTest { // Set up existing preferences with bookmarks val preMigrationUserPreferences = userPreferences { deprecatedBookmarkedNewsResourceIds.addAll(listOf("7", "8", "9")) } // Assert that there are no bookmarks in the map yet assertEquals( emptyMap<String, Boolean>(), preMigrationUserPreferences.bookmarkedNewsResourceIdsMap, ) // Run the migration val postMigrationUserPreferences = ListToMapMigration.migrate(preMigrationUserPreferences) // Assert the deprecated bookmarks have been migrated to the bookmarks map assertEquals( mapOf("7" to true, "8" to true, "9" to true), postMigrationUserPreferences.bookmarkedNewsResourceIdsMap, ) // Assert that the migration has been marked complete assertTrue(postMigrationUserPreferences.hasDoneListToMapMigration) } }
SkeletonAndroid/modules/datastore/src/test/kotlin/com/mshdabiola/datastore/SkPreferencesDataSourceTest.kt
192596852
/* *abiola 2024 */ package com.mshdabiola.datastore import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import kotlin.test.assertFalse import kotlin.test.assertTrue class SkPreferencesDataSourceTest { private val testScope = TestScope(UnconfinedTestDispatcher()) private lateinit var subject: SkPreferencesDataSource @get:Rule val tmpFolder: TemporaryFolder = TemporaryFolder.builder().assureDeletion().build() @Before fun setup() { subject = SkPreferencesDataSource( tmpFolder.testUserPreferencesDataStore(testScope), ) } @Test fun shouldHideOnboardingIsFalseByDefault() = testScope.runTest { assertFalse(subject.userData.first().shouldHideOnboarding) } @Test fun userShouldHideOnboardingIsTrueWhenSet() = testScope.runTest { subject.setShouldHideOnboarding(true) assertTrue(subject.userData.first().shouldHideOnboarding) } @Test fun userShouldHideOnboarding_unfollowsLastTopic_shouldHideOnboardingIsFalse() = testScope.runTest { // Given: user completes onboarding by selecting a single topic. subject.setTopicIdFollowed("1", true) subject.setShouldHideOnboarding(true) // When: they unfollow that topic. subject.setTopicIdFollowed("1", false) // Then: onboarding should be shown again assertFalse(subject.userData.first().shouldHideOnboarding) } @Test fun userShouldHideOnboarding_unfollowsAllTopics_shouldHideOnboardingIsFalse() = testScope.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) } @Test fun shouldUseDynamicColorFalseByDefault() = testScope.runTest { assertFalse(subject.userData.first().useDynamicColor) } @Test fun userShouldUseDynamicColorIsTrueWhenSet() = testScope.runTest { subject.setDynamicColorPreference(true) assertTrue(subject.userData.first().useDynamicColor) } }
SkeletonAndroid/modules/datastore/src/main/kotlin/com/mshdabiola/datastore/UserPreferencesSerializer.kt
3886906861
/* *abiola 2024 */ package com.mshdabiola.datastore import androidx.datastore.core.CorruptionException import androidx.datastore.core.Serializer import com.google.protobuf.InvalidProtocolBufferException import java.io.InputStream import java.io.OutputStream import javax.inject.Inject /** * An [androidx.datastore.core.Serializer] for the [UserPreferences] proto. */ class UserPreferencesSerializer @Inject constructor() : Serializer<UserPreferences> { override val defaultValue: UserPreferences = UserPreferences.getDefaultInstance() override suspend fun readFrom(input: InputStream): UserPreferences = try { // readFrom is already called on the data store background thread UserPreferences.parseFrom(input) } catch (exception: InvalidProtocolBufferException) { throw CorruptionException("Cannot read proto.", exception) } override suspend fun writeTo(t: UserPreferences, output: OutputStream) { // writeTo is already called on the data store background thread t.writeTo(output) } }
SkeletonAndroid/modules/datastore/src/main/kotlin/com/mshdabiola/datastore/IntToStringIdsMigration.kt
2512802863
/* *abiola 2024 */ package com.mshdabiola.datastore import androidx.datastore.core.DataMigration /** * Migrates saved ids from [Int] to [String] types */ internal object IntToStringIdsMigration : DataMigration<UserPreferences> { override suspend fun cleanUp() = Unit override suspend fun migrate(currentData: UserPreferences): UserPreferences = currentData.copy { // Migrate topic ids } override suspend fun shouldMigrate(currentData: UserPreferences): Boolean = true }
SkeletonAndroid/modules/datastore/src/main/kotlin/com/mshdabiola/datastore/di/TestDataStoreModule.kt
3482563306
/* *abiola 2024 */ package com.mshdabiola.datastore.di import androidx.datastore.core.DataStore import androidx.datastore.core.DataStoreFactory import com.mshdabiola.common.network.di.ApplicationScope import com.mshdabiola.datastore.UserPreferences import com.mshdabiola.datastore.UserPreferencesSerializer import dagger.Module import dagger.Provides import dagger.hilt.components.SingletonComponent import dagger.hilt.testing.TestInstallIn import kotlinx.coroutines.CoroutineScope import org.junit.rules.TemporaryFolder import javax.inject.Singleton @Module @TestInstallIn( components = [SingletonComponent::class], replaces = [DataStoreModule::class], ) internal object TestDataStoreModule { @Provides @Singleton fun providesUserPreferencesDataStore( @ApplicationScope scope: CoroutineScope, userPreferencesSerializer: UserPreferencesSerializer, tmpFolder: TemporaryFolder, ): DataStore<UserPreferences> = tmpFolder.testUserPreferencesDataStore( coroutineScope = scope, userPreferencesSerializer = userPreferencesSerializer, ) } fun TemporaryFolder.testUserPreferencesDataStore( coroutineScope: CoroutineScope, userPreferencesSerializer: UserPreferencesSerializer = UserPreferencesSerializer(), ) = DataStoreFactory.create( serializer = userPreferencesSerializer, scope = coroutineScope, ) { newFile("user_preferences_test.pb") }
SkeletonAndroid/modules/datastore/src/main/kotlin/com/mshdabiola/datastore/di/DataStoreModule.kt
3878133335
/* *abiola 2024 */ package com.mshdabiola.datastore.di import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.core.DataStoreFactory import androidx.datastore.dataStoreFile import com.mshdabiola.common.network.Dispatcher import com.mshdabiola.common.network.SkDispatchers.IO import com.mshdabiola.common.network.di.ApplicationScope import com.mshdabiola.datastore.IntToStringIdsMigration import com.mshdabiola.datastore.UserPreferences import com.mshdabiola.datastore.UserPreferencesSerializer import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DataStoreModule { @Provides @Singleton internal fun providesUserPreferencesDataStore( @ApplicationContext context: Context, @Dispatcher(IO) ioDispatcher: CoroutineDispatcher, @ApplicationScope scope: CoroutineScope, userPreferencesSerializer: UserPreferencesSerializer, ): DataStore<UserPreferences> = DataStoreFactory.create( serializer = userPreferencesSerializer, scope = CoroutineScope(scope.coroutineContext + ioDispatcher), migrations = listOf( IntToStringIdsMigration, ), ) { context.dataStoreFile("user_preferences.pb") } }
SkeletonAndroid/modules/datastore/src/main/kotlin/com/mshdabiola/datastore/SkPreferencesDataSource.kt
3660156959
/* *abiola 2024 */ package com.mshdabiola.datastore import android.util.Log import androidx.datastore.core.DataStore import com.mshdabiola.model.Contrast import com.mshdabiola.model.DarkThemeConfig import com.mshdabiola.model.ThemeBrand import com.mshdabiola.model.UserData import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map import java.io.IOException import javax.inject.Inject class SkPreferencesDataSource @Inject constructor( private val userPreferences: DataStore<UserPreferences>, ) { val userData = userPreferences.data .map { UserData( themeBrand = when (it.themeBrand) { null, ThemeBrandProto.THEME_BRAND_UNSPECIFIED, ThemeBrandProto.UNRECOGNIZED, ThemeBrandProto.THEME_BRAND_DEFAULT, -> ThemeBrand.DEFAULT ThemeBrandProto.THEME_BRAND_GREEN -> ThemeBrand.GREEN }, 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 }, useDynamicColor = it.useDynamicColor, shouldHideOnboarding = it.shouldHideOnboarding, contrast = when (it.contrast) { null, ThemeContrastProto.THEME_CONTRAST_UNSPECIFIED, ThemeContrastProto.UNRECOGNIZED, ThemeContrastProto.THEME_CONTRAST_NORMAL, -> Contrast.Normal ThemeContrastProto.THEME_CONTRAST_HIGH -> Contrast.High ThemeContrastProto.THEME_CONTRAST_MEDIUM -> Contrast.Medium }, ) } suspend fun setThemeBrand(themeBrand: ThemeBrand) { userPreferences.updateData { it.copy { this.themeBrand = when (themeBrand) { ThemeBrand.DEFAULT -> ThemeBrandProto.THEME_BRAND_DEFAULT ThemeBrand.GREEN -> ThemeBrandProto.THEME_BRAND_GREEN } } } } suspend fun setThemeContrast(contrast: Contrast) { userPreferences.updateData { it.copy { this.contrast = when (contrast) { Contrast.Normal-> ThemeContrastProto.THEME_CONTRAST_NORMAL Contrast.High -> ThemeContrastProto.THEME_CONTRAST_HIGH Contrast.Medium -> ThemeContrastProto.THEME_CONTRAST_MEDIUM } } } } suspend fun setDynamicColorPreference(useDynamicColor: Boolean) { userPreferences.updateData { it.copy { this.useDynamicColor = useDynamicColor } } } suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) { userPreferences.updateData { it.copy { this.darkThemeConfig = when (darkThemeConfig) { DarkThemeConfig.FOLLOW_SYSTEM -> DarkThemeConfigProto.DARK_THEME_CONFIG_FOLLOW_SYSTEM DarkThemeConfig.LIGHT -> DarkThemeConfigProto.DARK_THEME_CONFIG_LIGHT DarkThemeConfig.DARK -> DarkThemeConfigProto.DARK_THEME_CONFIG_DARK } } } } suspend fun setShouldHideOnboarding(shouldHideOnboarding: Boolean) { userPreferences.updateData { it.copy { this.shouldHideOnboarding = shouldHideOnboarding } } } }
SkeletonAndroid/modules/datastore/src/main/kotlin/com/mshdabiola/datastore/ChangeListVersions.kt
1414971598
/* *abiola 2024 */ package com.mshdabiola.datastore /** * Class summarizing the local version of each model for sync */ data class ChangeListVersions( val topicVersion: Int = -1, val newsResourceVersion: Int = -1, )
SkeletonAndroid/modules/common/src/test/kotlin/com/mshdabiola/common/ResultKtTest.kt
1874669260
/* *abiola 2024 */ package com.mshdabiola.common import app.cash.turbine.test import com.mshdabiola.common.result.Result import com.mshdabiola.common.result.asResult import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.runTest import org.junit.Test import kotlin.test.assertEquals class ResultKtTest { @Test fun Result_catches_errors() = runTest { flow { emit(1) throw Exception("Test Done") } .asResult() .test { assertEquals(Result.Loading, awaitItem()) assertEquals(Result.Success(1), awaitItem()) when (val errorResult = awaitItem()) { is Result.Error -> assertEquals( "Test Done", errorResult.exception?.message, ) Result.Loading, is Result.Success, -> throw IllegalStateException( "The flow should have emitted an Error Result", ) } awaitComplete() } } }
SkeletonAndroid/modules/common/src/main/kotlin/com/mshdabiola/common/result/Result.kt
2676670700
/* *abiola 2024 */ package com.mshdabiola.common.result import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart sealed interface Result<out T> { data class Success<T>(val data: T) : Result<T> data class Error(val exception: Throwable) : Result<Nothing> data object Loading : Result<Nothing> } fun <T> Flow<T>.asResult(): Flow<Result<T>> = map<T, Result<T>> { Result.Success(it) } .onStart { emit(Result.Loading) } .catch { emit(Result.Error(it)) }
SkeletonAndroid/modules/common/src/main/kotlin/com/mshdabiola/common/network/SkDispatchers.kt
4273290844
/* *abiola 2024 */ package com.mshdabiola.common.network import javax.inject.Qualifier import kotlin.annotation.AnnotationRetention.RUNTIME @Qualifier @Retention(RUNTIME) annotation class Dispatcher(val niaDispatcher: SkDispatchers) enum class SkDispatchers { Default, IO, }
SkeletonAndroid/modules/common/src/main/kotlin/com/mshdabiola/common/network/di/CoroutineScopesModule.kt
106055118
/* *abiola 2024 */ package com.mshdabiola.common.network.di import com.mshdabiola.common.network.Dispatcher import com.mshdabiola.common.network.SkDispatchers.Default import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import javax.inject.Qualifier import javax.inject.Singleton @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class ApplicationScope @Module @InstallIn(SingletonComponent::class) internal object CoroutineScopesModule { @Provides @Singleton @ApplicationScope fun providesCoroutineScope( @Dispatcher(Default) dispatcher: CoroutineDispatcher, ): CoroutineScope = CoroutineScope(SupervisorJob() + dispatcher) }
SkeletonAndroid/modules/common/src/main/kotlin/com/mshdabiola/common/network/di/DispatchersModule.kt
3204527361
/* *abiola 2024 */ package com.mshdabiola.common.network.di import com.mshdabiola.common.network.Dispatcher import com.mshdabiola.common.network.SkDispatchers.Default import com.mshdabiola.common.network.SkDispatchers.IO import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers @Module @InstallIn(SingletonComponent::class) object DispatchersModule { @Provides @Dispatcher(IO) fun providesIODispatcher(): CoroutineDispatcher = Dispatchers.IO @Provides @Dispatcher(Default) fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default }
SkeletonAndroid/modules/model/src/main/java/com/mshdabiola/model/UserData.kt
1395718287
/* *abiola 2024 */ package com.mshdabiola.model /** * Class summarizing user interest data */ data class UserData( val themeBrand: ThemeBrand, val darkThemeConfig: DarkThemeConfig, val useDynamicColor: Boolean, val shouldHideOnboarding: Boolean, val contrast: Contrast )
SkeletonAndroid/modules/model/src/main/java/com/mshdabiola/model/DarkThemeConfig.kt
4045724058
/* *abiola 2024 */ package com.mshdabiola.model enum class DarkThemeConfig { FOLLOW_SYSTEM, LIGHT, DARK, }
SkeletonAndroid/modules/model/src/main/java/com/mshdabiola/model/ThemeBrand.kt
3776385530
/* *abiola 2024 */ package com.mshdabiola.model enum class ThemeBrand { DEFAULT, GREEN }
SkeletonAndroid/modules/model/src/main/java/com/mshdabiola/model/Note.kt
4045941758
/* *abiola 2024 */ package com.mshdabiola.model data class Note( val id: Long? = null, val title: String = "", val content: String = "", )