├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── ic_launcher-playstore.png
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ ├── ic_launcher_round.webp
│ │ │ │ └── ic_launcher_foreground.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ ├── ic_launcher_round.webp
│ │ │ │ └── ic_launcher_foreground.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ ├── ic_launcher_round.webp
│ │ │ │ └── ic_launcher_foreground.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ ├── ic_launcher_round.webp
│ │ │ │ └── ic_launcher_foreground.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ ├── ic_launcher_round.webp
│ │ │ │ └── ic_launcher_foreground.webp
│ │ │ ├── values
│ │ │ │ ├── ic_launcher_background.xml
│ │ │ │ ├── themes.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── strings.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── drawable
│ │ │ │ ├── ic_refresh.xml
│ │ │ │ ├── ic_arrow_back.xml
│ │ │ │ └── ic_arrow_forward.xml
│ │ │ └── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── hadiyarajesh
│ │ │ │ └── composetemplate
│ │ │ │ ├── utility
│ │ │ │ ├── Constants.kt
│ │ │ │ ├── ImageUtility.kt
│ │ │ │ └── ParcelableType.kt
│ │ │ │ ├── MyApplication.kt
│ │ │ │ ├── ui
│ │ │ │ ├── theme
│ │ │ │ │ ├── Color.kt
│ │ │ │ │ ├── Type.kt
│ │ │ │ │ └── Theme.kt
│ │ │ │ ├── home
│ │ │ │ │ ├── HomeScreenUiState.kt
│ │ │ │ │ ├── HomeViewModel.kt
│ │ │ │ │ └── HomeScreen.kt
│ │ │ │ ├── ComposeApp.kt
│ │ │ │ ├── components
│ │ │ │ │ ├── AnimationComponents.kt
│ │ │ │ │ ├── TextWithIcon.kt
│ │ │ │ │ └── Components.kt
│ │ │ │ └── detail
│ │ │ │ │ └── DetailScreen.kt
│ │ │ │ ├── data
│ │ │ │ ├── database
│ │ │ │ │ ├── AppDatabase.kt
│ │ │ │ │ ├── entity
│ │ │ │ │ │ └── Image.kt
│ │ │ │ │ ├── dao
│ │ │ │ │ │ └── ImageDao.kt
│ │ │ │ │ └── DatabaseInitializer.kt
│ │ │ │ └── repository
│ │ │ │ │ └── HomeRepository.kt
│ │ │ │ ├── navigation
│ │ │ │ ├── NavDestination.kt
│ │ │ │ └── AppNavigation.kt
│ │ │ │ ├── MainActivity.kt
│ │ │ │ └── di
│ │ │ │ ├── RepositoryModule.kt
│ │ │ │ ├── DatabaseModule.kt
│ │ │ │ └── NetworkModule.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── hadiyarajesh
│ │ │ └── composetemplate
│ │ │ ├── data
│ │ │ ├── TestDataGenerator.kt
│ │ │ └── repository
│ │ │ │ └── TestHomeRepository.kt
│ │ │ └── ui
│ │ │ └── home
│ │ │ └── HomeViewModelTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── hadiyarajesh
│ │ └── composetemplate
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── .gitignore
├── .github
├── pull_request_template.md
└── workflows
│ ├── merge-build-and-test-workflow.yml
│ └── pr-build-and-test-workflow.yml
├── settings.gradle.kts
├── LICENSE
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/ic_launcher-playstore.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/ic_launcher-playstore.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hadiyarajesh/compose-template/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/values/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #244E6A
4 |
5 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 | app/schemas
12 | .kotlin
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/utility/Constants.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.utility
2 |
3 | object Constants {
4 | const val API_BASE_URL = "API_BASE_URL"
5 | }
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/MyApplication.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate
2 |
3 | import android.app.Application
4 | import dagger.hilt.android.HiltAndroidApp
5 |
6 | @HiltAndroidApp
7 | class MyApplication: Application()
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Jun 17 21:00:00 IST 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple80 = Color(0xFFD0BCFF)
6 | val PurpleGrey80 = Color(0xFFCCC2DC)
7 | val Pink80 = Color(0xFFEFB8C8)
8 |
9 | val Purple40 = Color(0xFF6650a4)
10 | val PurpleGrey40 = Color(0xFF625b71)
11 | val Pink40 = Color(0xFF7D5260)
12 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ### What's Changing?
2 |
3 | **Description:**
4 |
5 |
6 | ### Checklist
7 |
8 | - [ ] I have run the code locally and it's working well
9 | - [ ] I have performed a self-review of my code
10 | - [ ] I have added thorough tests (if applicable)
11 | - [ ] I have added all screenshots (if applicable)
12 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/data/database/AppDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.data.database
2 |
3 | import androidx.room.Database
4 | import androidx.room.RoomDatabase
5 | import com.hadiyarajesh.composetemplate.data.database.dao.ImageDao
6 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
7 |
8 | @Database(
9 | version = 1,
10 | entities = [Image::class],
11 | exportSchema = true
12 | )
13 | abstract class AppDatabase : RoomDatabase() {
14 | abstract fun imageDao(): ImageDao
15 | }
16 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_refresh.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/data/database/entity/Image.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.data.database.entity
2 |
3 | import android.os.Parcelable
4 | import androidx.room.Entity
5 | import androidx.room.PrimaryKey
6 | import kotlinx.parcelize.Parcelize
7 | import kotlinx.serialization.Serializable
8 |
9 | @Serializable
10 | @Parcelize
11 | @Entity
12 | data class Image(
13 | @PrimaryKey(autoGenerate = true)
14 | val imageId: Long = 0,
15 | val url: String,
16 | val description: String,
17 | val altText: String
18 | ) : Parcelable
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/navigation/NavDestination.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.navigation
2 |
3 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
4 | import kotlinx.serialization.Serializable
5 |
6 | /**
7 | * Defines all top-level navigation destinations in the app.
8 | * Each destination represents a distinct screen or route.
9 | */
10 | sealed interface NavDestination {
11 | @Serializable
12 | data object Home : NavDestination
13 |
14 | @Serializable
15 | data class Detail(val image: Image) : NavDestination
16 | }
17 |
--------------------------------------------------------------------------------
/app/src/test/java/com/hadiyarajesh/composetemplate/data/TestDataGenerator.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.data
2 |
3 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
4 | import kotlin.random.Random
5 |
6 | object TestDataGenerator {
7 | fun getRandomImage(): Image {
8 | val randomId = Random.nextLong(0, 100)
9 |
10 | return Image(
11 | imageId = randomId,
12 | url = "https://example.com",
13 | "Image $randomId description",
14 | altText = "Image $randomId Alt text"
15 | )
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google {
4 | content {
5 | includeGroupByRegex("com\\.android.*")
6 | includeGroupByRegex("com\\.google.*")
7 | includeGroupByRegex("androidx.*")
8 | }
9 | }
10 | mavenCentral()
11 | gradlePluginPortal()
12 | }
13 | }
14 | dependencyResolutionManagement {
15 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
16 | repositories {
17 | google()
18 | mavenCentral()
19 | }
20 | }
21 |
22 | rootProject.name = "ComposeTemplate"
23 | include(":app")
24 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
20 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate
2 |
3 | import android.os.Bundle
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.compose.setContent
6 | import androidx.activity.enableEdgeToEdge
7 | import com.hadiyarajesh.composetemplate.ui.ComposeApp
8 | import dagger.hilt.android.AndroidEntryPoint
9 |
10 | @AndroidEntryPoint
11 | class MainActivity : ComponentActivity() {
12 | override fun onCreate(savedInstanceState: Bundle?) {
13 | super.onCreate(savedInstanceState)
14 |
15 | enableEdgeToEdge()
16 | setContent {
17 | ComposeApp()
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/home/HomeScreenUiState.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.home
2 |
3 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
4 |
5 | /**
6 | * Represents all possible UI states for the [HomeScreenContent].
7 | *
8 | * This sealed interface helps the UI layer react to state changes
9 | * in a type-safe and declarative manner.
10 | */
11 | internal sealed interface HomeScreenUiState {
12 | data object Initial : HomeScreenUiState
13 |
14 | data object Loading : HomeScreenUiState
15 |
16 | data class Success(val data: Image) : HomeScreenUiState
17 |
18 | data class Error(val msg: String) : HomeScreenUiState
19 | }
20 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/utility/ImageUtility.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.utility
2 |
3 | import kotlin.random.Random
4 |
5 | /**
6 | * Utility object for generating random image URLs from the [picsum.photos](https://picsum.photos) service.
7 | */
8 | object ImageUtility {
9 | private const val IMAGE_WIDTH = "720"
10 | private const val IMAGE_HEIGHT = "720"
11 |
12 | /**
13 | * Returns a random image ID between 1 and 200 (inclusive).
14 | */
15 | private val randomImageId: Int
16 | get() = Random.nextInt(1, 201)
17 |
18 | fun getRandomImageUrl(): String {
19 | return "https://picsum.photos/id/${randomImageId}/${IMAGE_WIDTH}/${IMAGE_HEIGHT}"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_arrow_back.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_arrow_forward.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/data/database/dao/ImageDao.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.data.database.dao
2 |
3 | import androidx.room.Dao
4 | import androidx.room.Query
5 | import androidx.room.Upsert
6 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
7 | import kotlinx.coroutines.flow.Flow
8 |
9 | @Dao
10 | interface ImageDao {
11 | @Upsert
12 | suspend fun insertOrUpdateImage(image: Image): Long
13 |
14 | /**
15 | * As we're using Kotlin CodeGen for Room, we need to mark [Image] as nullable.
16 | * Refer @link https://developer.android.com/jetpack/androidx/releases/room#2.6.0 for more info.
17 | */
18 | @Query("SELECT * FROM Image LIMIT 1")
19 | fun getImages(): Flow
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/test/java/com/hadiyarajesh/composetemplate/data/repository/TestHomeRepository.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.data.repository
2 |
3 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
4 | import kotlinx.coroutines.flow.Flow
5 | import kotlinx.coroutines.flow.flow
6 |
7 | internal class TestHomeRepository : HomeRepository {
8 | var throwError: Boolean = false
9 | var imagesToEmit: List = emptyList()
10 |
11 | override fun loadData(): Flow = flow {
12 | if (throwError) {
13 | throw RuntimeException("Test Exception!!!")
14 | }
15 |
16 | imagesToEmit.forEach { emit(it) }
17 | }
18 |
19 | override suspend fun changeImage(image: Image) {
20 | // no-op
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Compose Template
3 | Welcome to Compose Template
4 | Go back
5 | Home
6 | Detail
7 | %1$s Screen
8 | You are coming from: %1$s
9 | Go to %1$s Screen
10 | Change Image
11 | Description
12 | URL
13 | Failed to load image
14 | Failed to open URL
15 |
16 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/ComposeApp.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui
2 |
3 | import androidx.compose.foundation.layout.padding
4 | import androidx.compose.material3.Scaffold
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.ui.Modifier
7 | import androidx.navigation.compose.rememberNavController
8 | import com.hadiyarajesh.composetemplate.navigation.AppNavigation
9 | import com.hadiyarajesh.composetemplate.ui.theme.AppTheme
10 |
11 | @Composable
12 | fun ComposeApp() {
13 | AppTheme {
14 | val navController = rememberNavController()
15 |
16 | Scaffold { innerPadding ->
17 | AppNavigation(
18 | modifier = Modifier.padding(innerPadding),
19 | navController = navController
20 | )
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/hadiyarajesh/composetemplate/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.hadiyarajesh.composetemplate", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/di/RepositoryModule.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.di
2 |
3 | import com.hadiyarajesh.composetemplate.data.repository.HomeRepository
4 | import com.hadiyarajesh.composetemplate.data.repository.HomeRepositoryImpl
5 | import dagger.Binds
6 | import dagger.Module
7 | import dagger.hilt.InstallIn
8 | import dagger.hilt.android.components.ViewModelComponent
9 |
10 | /**
11 | * Dagger-Hilt module that provides repository bindings scoped to ViewModel lifecycle.
12 | *
13 | * This module includes:
14 | * - A binding from [HomeRepositoryImpl] to [HomeRepository] using [@Binds].
15 | *
16 | * Annotated with [@InstallIn(ViewModelComponent::class)] to ensure the bound instance
17 | * is scoped to the ViewModel's lifecycle.
18 | */
19 | @Module
20 | @InstallIn(ViewModelComponent::class)
21 | abstract class RepositoryModule {
22 | @Binds
23 | abstract fun bindHomeRepository(homeRepositoryImpl: HomeRepositoryImpl): HomeRepository
24 | }
25 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2025 Rajesh Hadiya
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
18 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/.github/workflows/merge-build-and-test-workflow.yml:
--------------------------------------------------------------------------------
1 | # Builds the app and runs unit tests on push
2 | name: Build and test
3 |
4 | on:
5 | push:
6 | branches: [ "master" ]
7 |
8 | jobs:
9 | build:
10 | # Run this job only if the pull request is not a draft
11 | if: github.event.pull_request.draft == false
12 | name: Build app and execute unit tests on Push
13 | runs-on: ubuntu-latest
14 |
15 | steps:
16 | - uses: actions/checkout@v4.2.2
17 | - name: Set up JDK 21
18 | uses: actions/setup-java@v4
19 | with:
20 | java-version: "21"
21 | distribution: "temurin"
22 | cache: gradle # Enables Gradle caching for faster builds
23 |
24 | - name: Print project directory content
25 | run: |
26 | echo "Current directory is: ${GITHUB_WORKSPACE}"
27 |
28 | - name: Setup Gradle
29 | uses: gradle/actions/setup-gradle@v4
30 |
31 | - name: Grant permission to Gradle
32 | run: chmod +x ./gradlew
33 |
34 | - name: Run unit tests
35 | run: ./gradlew test
36 |
37 | # Upload test reports only if the test step fails
38 | - name: Archive test reports
39 | uses: actions/upload-artifact@v4
40 | if: failure()
41 | with:
42 | name: test-reports
43 | path: |
44 | ./**/build/reports/
45 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp
17 | )
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 |
34 | headlineSmall = TextStyle(
35 | letterSpacing = 1.sp,
36 | fontWeight = FontWeight.Normal,
37 | fontSize = 16.sp,
38 | lineHeight = 24.sp,
39 | )*/
40 | )
41 |
--------------------------------------------------------------------------------
/.github/workflows/pr-build-and-test-workflow.yml:
--------------------------------------------------------------------------------
1 | # Builds the app and runs unit tests on pull requests.
2 | name: Build and test
3 |
4 | on:
5 | pull_request:
6 | branches: [ "master" ]
7 | types: [ "opened", "reopened", "synchronize", "ready_for_review" ]
8 |
9 | jobs:
10 | build:
11 | # Run this job only if the pull request is not a draft
12 | if: github.event.pull_request.draft == false
13 | name: Build app and execute unit tests on PR
14 | runs-on: ubuntu-latest
15 |
16 | steps:
17 | - uses: actions/checkout@v4.2.2
18 | - name: Set up JDK 21
19 | uses: actions/setup-java@v4
20 | with:
21 | java-version: "21"
22 | distribution: "temurin"
23 | cache: gradle # Enables Gradle caching for faster builds
24 |
25 | - name: Print project directory content
26 | run: |
27 | echo "Current directory is: ${GITHUB_WORKSPACE}"
28 |
29 | - name: Setup Gradle
30 | uses: gradle/actions/setup-gradle@v4
31 |
32 | - name: Grant permission to Gradle
33 | run: chmod +x ./gradlew
34 |
35 | - name: Run unit tests
36 | run: ./gradlew test
37 |
38 | # Upload test reports only if the test step fails
39 | - name: Archive test reports
40 | uses: actions/upload-artifact@v4
41 | if: failure()
42 | with:
43 | name: test-reports
44 | path: |
45 | ./**/build/reports/
46 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/data/repository/HomeRepository.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.data.repository
2 |
3 | import com.hadiyarajesh.composetemplate.data.database.dao.ImageDao
4 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
5 | import kotlinx.coroutines.flow.Flow
6 | import javax.inject.Inject
7 | import javax.inject.Singleton
8 |
9 | /**
10 | * Repository interface for handling home screen data operations.
11 | *
12 | * Designed to abstract data access for the home UI, such as fetching and updating
13 | * the current [Image]. Implementation may interact with local database, network,
14 | * or both depending on the app's architecture.
15 | */
16 | interface HomeRepository {
17 | /**
18 | * Returns a [Flow] that emits the current [Image], if available.
19 | *
20 | * This can be collected to observe changes to the image data.
21 | */
22 | fun loadData(): Flow
23 |
24 | /**
25 | * Updates or replaces the current [Image].
26 | */
27 | suspend fun changeImage(image: Image)
28 | }
29 |
30 | @Singleton
31 | class HomeRepositoryImpl @Inject constructor(
32 | private val imageDao: ImageDao
33 | ) : HomeRepository {
34 | override fun loadData(): Flow {
35 | return imageDao.getImages()
36 | }
37 |
38 | override suspend fun changeImage(image: Image) {
39 | imageDao.insertOrUpdateImage(image)
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/components/AnimationComponents.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.components
2 |
3 | import androidx.compose.animation.AnimatedContentTransitionScope
4 | import androidx.compose.animation.AnimatedContentTransitionScope.SlideDirection
5 | import androidx.compose.animation.core.EaseIn
6 | import androidx.compose.animation.core.EaseOut
7 | import androidx.compose.animation.core.tween
8 | import androidx.navigation.NavBackStackEntry
9 |
10 | const val NAVIGATION_ANIMATION_DURATION = 200
11 |
12 | fun AnimatedContentTransitionScope.slideIntoContainerAnimation(
13 | towards: SlideDirection = SlideDirection.End
14 | ) = slideIntoContainer(
15 | animationSpec = tween(
16 | durationMillis = NAVIGATION_ANIMATION_DURATION,
17 | easing = EaseIn
18 | ),
19 | towards = towards
20 | )
21 |
22 | fun AnimatedContentTransitionScope.slideOutOfContainerAnimation(
23 | towards: SlideDirection = SlideDirection.Start
24 | ) = slideOutOfContainer(
25 | animationSpec = tween(
26 | durationMillis = NAVIGATION_ANIMATION_DURATION,
27 | easing = EaseOut
28 | ),
29 | towards = towards
30 | )
31 |
32 | fun AnimatedContentTransitionScope.reverseSlideIntoContainerAnimation() =
33 | slideIntoContainerAnimation(towards = SlideDirection.Start)
34 |
35 | fun AnimatedContentTransitionScope.reverseSlideOutOfContainerAnimation() =
36 | slideOutOfContainerAnimation(towards = SlideDirection.End)
37 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 | org.gradle.caching=true
25 | org.gradle.unsafe.configuration-cache=true
26 | android.defaults.buildfeatures.buildconfig=true
27 | android.nonFinalResIds=false
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/data/database/DatabaseInitializer.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.data.database
2 |
3 | import android.content.Context
4 | import androidx.room.RoomDatabase
5 | import androidx.sqlite.db.SupportSQLiteDatabase
6 | import com.hadiyarajesh.composetemplate.R
7 | import com.hadiyarajesh.composetemplate.data.database.dao.ImageDao
8 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
9 | import com.hadiyarajesh.composetemplate.utility.ImageUtility
10 | import kotlinx.coroutines.CoroutineScope
11 | import kotlinx.coroutines.Dispatchers
12 | import kotlinx.coroutines.SupervisorJob
13 | import kotlinx.coroutines.launch
14 | import javax.inject.Provider
15 |
16 | /**
17 | * A custom [RoomDatabase.Callback] used to initialize the Room database
18 | * when it's created for the first time.
19 | *
20 | * This implementation overrides [RoomDatabase.Callback.onCreate] to pre-populate
21 | * the database with initial data.
22 | *
23 | * A [Provider] of [ImageDao] is used to break the circular dependency between
24 | * the database and its DAO.
25 | */
26 | class DatabaseInitializer(
27 | private val context: Context,
28 | private val imageDaoProvider: Provider
29 | ) : RoomDatabase.Callback() {
30 | private val applicationScope = CoroutineScope(SupervisorJob())
31 |
32 | override fun onCreate(db: SupportSQLiteDatabase) {
33 | super.onCreate(db)
34 | applicationScope.launch(Dispatchers.IO) {
35 | populateDatabase()
36 | }
37 | }
38 |
39 | private suspend fun populateDatabase() {
40 | imageDaoProvider.get().insertOrUpdateImage(
41 | Image(
42 | url = ImageUtility.getRandomImageUrl(),
43 | description = context.getString(R.string.welcome_message),
44 | altText = context.getString(R.string.failed_to_load_image)
45 | )
46 | )
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/di/DatabaseModule.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.di
2 |
3 | import android.content.Context
4 | import androidx.room.Room
5 | import com.hadiyarajesh.composetemplate.R
6 | import com.hadiyarajesh.composetemplate.data.database.AppDatabase
7 | import com.hadiyarajesh.composetemplate.data.database.DatabaseInitializer
8 | import com.hadiyarajesh.composetemplate.data.database.dao.ImageDao
9 | import dagger.Module
10 | import dagger.Provides
11 | import dagger.hilt.InstallIn
12 | import dagger.hilt.android.qualifiers.ApplicationContext
13 | import dagger.hilt.components.SingletonComponent
14 | import javax.inject.Provider
15 | import javax.inject.Singleton
16 |
17 | /**
18 | * Dagger-Hilt module that provides dependencies related to the Room database.
19 | *
20 | * This module includes:
21 | * - A singleton instance of [AppDatabase]
22 | * - A singleton instance of [ImageDao], retrieved from the database.
23 | *
24 | * Annotated with [@InstallIn(SingletonComponent::class)] to ensure the
25 | * provided instances live as long as the application.
26 | */
27 | @Module
28 | @InstallIn(SingletonComponent::class)
29 | object DatabaseModule {
30 | @Singleton
31 | @Provides
32 | fun provideAppDatabase(
33 | @ApplicationContext context: Context,
34 | imageDaoProvider: Provider
35 | ): AppDatabase {
36 | return Room.databaseBuilder(
37 | context.applicationContext, AppDatabase::class.java, context.getString(
38 | R.string.app_name
39 | )
40 | ).addCallback(
41 | /**
42 | * Attach [DatabaseInitializer] as callback to the database
43 | */
44 | DatabaseInitializer(context = context, imageDaoProvider = imageDaoProvider)
45 | )
46 | .build()
47 | }
48 |
49 | @Singleton
50 | @Provides
51 | fun provideMessageDao(appDatabase: AppDatabase): ImageDao = appDatabase.imageDao()
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/navigation/AppNavigation.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.navigation
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.ui.Modifier
5 | import androidx.navigation.NavHostController
6 | import androidx.navigation.compose.NavHost
7 | import androidx.navigation.compose.composable
8 | import androidx.navigation.toRoute
9 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
10 | import com.hadiyarajesh.composetemplate.ui.components.reverseSlideIntoContainerAnimation
11 | import com.hadiyarajesh.composetemplate.ui.components.reverseSlideOutOfContainerAnimation
12 | import com.hadiyarajesh.composetemplate.ui.components.slideIntoContainerAnimation
13 | import com.hadiyarajesh.composetemplate.ui.components.slideOutOfContainerAnimation
14 | import com.hadiyarajesh.composetemplate.ui.detail.DetailScreenRoute
15 | import com.hadiyarajesh.composetemplate.ui.home.HomeScreenRoute
16 | import com.hadiyarajesh.composetemplate.utility.parcelableType
17 | import kotlin.reflect.typeOf
18 |
19 | @Composable
20 | fun AppNavigation(
21 | modifier: Modifier = Modifier,
22 | navController: NavHostController,
23 | ) {
24 | NavHost(
25 | modifier = modifier,
26 | navController = navController,
27 | startDestination = NavDestination.Home
28 | ) {
29 | composable(
30 | enterTransition = { slideIntoContainerAnimation() },
31 | exitTransition = { slideOutOfContainerAnimation() }
32 | ) {
33 | HomeScreenRoute(navController = navController)
34 | }
35 |
36 | composable(
37 | typeMap = mapOf(typeOf() to parcelableType()),
38 | enterTransition = { reverseSlideIntoContainerAnimation() },
39 | exitTransition = { reverseSlideOutOfContainerAnimation() }
40 | ) { backStackEntry ->
41 | val detail = backStackEntry.toRoute()
42 |
43 | DetailScreenRoute(
44 | navController = navController,
45 | image = detail.image
46 | )
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/home/HomeViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.home
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.viewModelScope
5 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
6 | import com.hadiyarajesh.composetemplate.data.repository.HomeRepository
7 | import com.hadiyarajesh.composetemplate.utility.ImageUtility
8 | import dagger.hilt.android.lifecycle.HiltViewModel
9 | import kotlinx.coroutines.flow.MutableStateFlow
10 | import kotlinx.coroutines.flow.StateFlow
11 | import kotlinx.coroutines.flow.asStateFlow
12 | import kotlinx.coroutines.launch
13 | import javax.inject.Inject
14 |
15 | @HiltViewModel
16 | internal class HomeViewModel @Inject constructor(
17 | private val homeRepository: HomeRepository
18 | ) : ViewModel() {
19 | private val _uiState = MutableStateFlow(HomeScreenUiState.Initial)
20 | val uiState: StateFlow get() = _uiState.asStateFlow()
21 |
22 | fun loadData() {
23 | viewModelScope.launch {
24 | _uiState.value = HomeScreenUiState.Loading
25 |
26 | try {
27 | /**
28 | * [Image] object is explicitly marked as nullable because when we launch the app for the first time,
29 | * the database will be empty and Flow will return null value.
30 | * Once the [com.hadiyarajesh.composetemplate.data.database.DatabaseInitializer] populate local database, the Flow will emit updated value.
31 | */
32 | homeRepository
33 | .loadData()
34 | .collect { image: Image? ->
35 | image?.let { msg ->
36 | _uiState.value = HomeScreenUiState.Success(data = msg)
37 | }
38 | }
39 | } catch (e: Exception) {
40 | _uiState.value = HomeScreenUiState.Error(msg = e.message ?: "Something went wrong")
41 | }
42 | }
43 | }
44 |
45 | fun changeImage(image: Image) {
46 | viewModelScope.launch {
47 | val newImage = image.copy(url = ImageUtility.getRandomImageUrl())
48 | homeRepository.changeImage(newImage)
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/utility/ParcelableType.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.utility
2 |
3 | import android.net.Uri
4 | import android.os.Build
5 | import android.os.Bundle
6 | import android.os.Parcelable
7 | import androidx.navigation.NavType
8 | import kotlinx.serialization.KSerializer
9 | import kotlinx.serialization.json.Json
10 | import kotlinx.serialization.serializer
11 |
12 | /**
13 | * Creates a custom [NavType] for a [Parcelable] and [@Serializable] type `T`.
14 | *
15 | * This allows you to pass complex data objects through navigation in a type-safe way
16 | * by serializing/deserializing the object as a JSON string.
17 | *
18 | * The type `T` must be both `@Parcelize` and `@Serializable`.
19 | *
20 | * ### Example:
21 | * ```kotlin
22 | * @Parcelize
23 | * @Serializable
24 | * data class Image(val id: Long, val url: String) : Parcelable
25 | *
26 | * val imageNavType = parcelableType()
27 | * ```
28 | *
29 | * You can then use this in `NavGraphBuilder.composable()` when defining your route.
30 | *
31 | * @param isNullableAllowed Whether the value can be null.
32 | * @param json The [Json] instance to use for (de)serialization.
33 | * @return A [NavType] that supports storing and retrieving type `T` using a Bundle and JSON.
34 | */
35 | inline fun parcelableType(
36 | isNullableAllowed: Boolean = false,
37 | json: Json = Json
38 | ): NavType {
39 | val kSerializer: KSerializer = serializer()
40 |
41 | return object : NavType(isNullableAllowed) {
42 | override fun get(bundle: Bundle, key: String): T? {
43 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
44 | bundle.getParcelable(key, T::class.java)
45 | } else {
46 | @Suppress("DEPRECATION")
47 | bundle.getParcelable(key)
48 | }
49 | }
50 |
51 | override fun parseValue(value: String): T {
52 | return json.decodeFromString(kSerializer, value)
53 | }
54 |
55 | override fun serializeAsValue(value: T): String {
56 | return Uri.encode(json.encodeToString(kSerializer, value))
57 | }
58 |
59 | override fun put(bundle: Bundle, key: String, value: T) {
60 | bundle.putParcelable(key, value)
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/di/NetworkModule.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.di
2 |
3 | import com.hadiyarajesh.composetemplate.BuildConfig
4 | import com.hadiyarajesh.composetemplate.utility.Constants
5 | import com.squareup.moshi.Moshi
6 | import dagger.Module
7 | import dagger.Provides
8 | import dagger.hilt.InstallIn
9 | import dagger.hilt.components.SingletonComponent
10 | import okhttp3.OkHttpClient
11 | import okhttp3.logging.HttpLoggingInterceptor
12 | import retrofit2.Retrofit
13 | import retrofit2.converter.moshi.MoshiConverterFactory
14 | import javax.inject.Singleton
15 |
16 | /**
17 | * Dagger-Hilt module that provides network-related dependencies.
18 | *
19 | * This module includes:
20 | * - A singleton instance of [OkHttpClient] with conditional logging in debug builds.
21 | * - A singleton instance of [Moshi] for JSON parsing.
22 | * - A singleton instance of [Retrofit] configured with [OkHttpClient] and [Moshi].
23 | *
24 | * Annotated with [@InstallIn(SingletonComponent::class)] to ensure the
25 | * provided instances live as long as the application.
26 | */
27 | @Module
28 | @InstallIn(SingletonComponent::class)
29 | object NetworkModule {
30 | private fun getLoggingInterceptor(): HttpLoggingInterceptor {
31 | return HttpLoggingInterceptor().apply {
32 | level = HttpLoggingInterceptor.Level.BODY
33 | }
34 | }
35 |
36 | @Singleton
37 | @Provides
38 | fun provideMoshi(): Moshi {
39 | return Moshi.Builder().build()
40 | }
41 |
42 | @Singleton
43 | @Provides
44 | fun provideOkHttpClient(): OkHttpClient {
45 | return OkHttpClient.Builder()
46 | .retryOnConnectionFailure(true)
47 | .also { okHttpClient ->
48 | /**
49 | * Only add [HttpLoggingInterceptor] on debug build
50 | */
51 | if (BuildConfig.DEBUG) {
52 | okHttpClient.addInterceptor(getLoggingInterceptor())
53 | }
54 | }
55 | .build()
56 | }
57 |
58 | @Singleton
59 | @Provides
60 | fun provideRetrofit(
61 | okHttpClient: OkHttpClient,
62 | moshi: Moshi
63 | ): Retrofit {
64 | return Retrofit.Builder()
65 | .baseUrl(Constants.API_BASE_URL)
66 | .client(okHttpClient)
67 | .addConverterFactory(MoshiConverterFactory.create(moshi))
68 | .build()
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.theme
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import androidx.compose.foundation.isSystemInDarkTheme
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.darkColorScheme
8 | import androidx.compose.material3.dynamicDarkColorScheme
9 | import androidx.compose.material3.dynamicLightColorScheme
10 | import androidx.compose.material3.lightColorScheme
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.SideEffect
13 | import androidx.compose.ui.graphics.toArgb
14 | import androidx.compose.ui.platform.LocalContext
15 | import androidx.compose.ui.platform.LocalView
16 | import androidx.core.view.WindowCompat
17 |
18 | private val DarkColorScheme = darkColorScheme(
19 | primary = Purple80,
20 | secondary = PurpleGrey80,
21 | tertiary = Pink80
22 | )
23 |
24 | private val LightColorScheme = lightColorScheme(
25 | primary = Purple40,
26 | secondary = PurpleGrey40,
27 | tertiary = Pink40
28 |
29 | /* Other default colors to override
30 | background = Color(0xFFFFFBFE),
31 | surface = Color(0xFFFFFBFE),
32 | onPrimary = Color.White,
33 | onSecondary = Color.White,
34 | onTertiary = Color.White,
35 | onBackground = Color(0xFF1C1B1F),
36 | onSurface = Color(0xFF1C1B1F),
37 | */
38 | )
39 |
40 | @Composable
41 | fun AppTheme(
42 | darkTheme: Boolean = isSystemInDarkTheme(),
43 | // Dynamic color is available on Android 12+
44 | dynamicColor: Boolean = true,
45 | content: @Composable () -> Unit
46 | ) {
47 | val colorScheme = when {
48 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
49 | val context = LocalContext.current
50 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
51 | }
52 |
53 | darkTheme -> DarkColorScheme
54 | else -> LightColorScheme
55 | }
56 | val view = LocalView.current
57 | if (!view.isInEditMode) {
58 | SideEffect {
59 | val window = (view.context as Activity).window
60 | window.statusBarColor = colorScheme.primary.toArgb()
61 | WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
62 | }
63 | }
64 |
65 | MaterialTheme(
66 | colorScheme = colorScheme,
67 | typography = Typography,
68 | content = content
69 | )
70 | }
71 |
--------------------------------------------------------------------------------
/app/src/test/java/com/hadiyarajesh/composetemplate/ui/home/HomeViewModelTest.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.home
2 |
3 | import app.cash.turbine.test
4 | import com.hadiyarajesh.composetemplate.data.TestDataGenerator
5 | import com.hadiyarajesh.composetemplate.data.repository.TestHomeRepository
6 | import kotlinx.coroutines.test.runTest
7 | import org.junit.jupiter.api.Assertions
8 | import org.junit.jupiter.api.BeforeEach
9 | import org.junit.jupiter.api.Test
10 |
11 | internal class HomeViewModelTest {
12 | private lateinit var homeRepository: TestHomeRepository
13 |
14 | @BeforeEach
15 | fun setup() {
16 | homeRepository = TestHomeRepository()
17 | }
18 |
19 | @Test
20 | fun `verify-initial-state`() {
21 | runTest {
22 | val viewModel = newViewModel()
23 | viewModel.uiState.test {
24 | Assertions.assertTrue(awaitItem() is HomeScreenUiState.Initial)
25 | }
26 | }
27 | }
28 |
29 | @Test
30 | fun `verify-success-state`() {
31 | val randomImage = TestDataGenerator.getRandomImage()
32 |
33 | homeRepository.imagesToEmit = buildList {
34 | add(randomImage)
35 | }
36 |
37 | runTest {
38 | val viewModel = newViewModel()
39 | viewModel.uiState.test {
40 | viewModel.loadData()
41 |
42 | skipItems(1) // Initial state
43 | Assertions.assertTrue(awaitItem() is HomeScreenUiState.Loading)
44 |
45 | val successState = awaitItem()
46 | Assertions.assertTrue(successState is HomeScreenUiState.Success)
47 |
48 | val retrievedImage = (successState as HomeScreenUiState.Success).data
49 | Assertions.assertEquals(randomImage, retrievedImage)
50 | }
51 | }
52 | }
53 |
54 | @Test
55 | fun `verify-error-state`() {
56 | homeRepository.throwError = true
57 |
58 | runTest {
59 | val viewModel = newViewModel()
60 | viewModel.uiState.test {
61 | viewModel.loadData()
62 |
63 | skipItems(1) // Initial state
64 | Assertions.assertTrue(awaitItem() is HomeScreenUiState.Loading)
65 | val errorState = awaitItem()
66 | Assertions.assertTrue(errorState is HomeScreenUiState.Error)
67 | }
68 | }
69 | }
70 |
71 | private fun newViewModel(): HomeViewModel {
72 | return HomeViewModel(homeRepository)
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/components/TextWithIcon.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.components
2 |
3 | import androidx.compose.foundation.text.InlineTextContent
4 | import androidx.compose.foundation.text.appendInlineContent
5 | import androidx.compose.material3.Icon
6 | import androidx.compose.material3.Text
7 | import androidx.compose.runtime.Composable
8 | import androidx.compose.ui.Modifier
9 | import androidx.compose.ui.graphics.painter.Painter
10 | import androidx.compose.ui.graphics.vector.ImageVector
11 | import androidx.compose.ui.text.Placeholder
12 | import androidx.compose.ui.text.PlaceholderVerticalAlign
13 | import androidx.compose.ui.text.buildAnnotatedString
14 | import androidx.compose.ui.unit.sp
15 |
16 | /**
17 | * A composable function that displays a [text] with an [icon], either at the leading
18 | * or trailing position.
19 | *
20 | * Useful for showing UI elements like labels, buttons, or clickable rows with icons
21 | * aligned next to the text in a seamless way using inline content.
22 | *
23 | * @param modifier Modifier to be applied to the icon.
24 | * @param text The text to display alongside the icon.
25 | * @param icon The [ImageVector] representing the icon to show.
26 | * @param position Controls whether the icon appears before or after the text.
27 | */
28 | @Composable
29 | internal fun TextWithIcon(
30 | modifier: Modifier = Modifier,
31 | text: String,
32 | icon: Painter,
33 | position: IconPositionInText = IconPositionInText.Trailing
34 | ) {
35 | val iconId = "arrow_icon"
36 |
37 | val annotatedText = buildAnnotatedString {
38 | when (position) {
39 | IconPositionInText.Leading -> {
40 | appendInlineContent(iconId, iconId)
41 | append(" ")
42 | append(text)
43 | }
44 |
45 | IconPositionInText.Trailing -> {
46 | append(text)
47 | append(" ")
48 | appendInlineContent(iconId, iconId)
49 | }
50 | }
51 | }
52 |
53 | val inlineContent = mapOf(
54 | iconId to InlineTextContent(
55 | Placeholder(
56 | width = 16.sp,
57 | height = 16.sp,
58 | placeholderVerticalAlign = PlaceholderVerticalAlign.Center
59 | )
60 | ) {
61 | Icon(
62 | modifier = modifier,
63 | painter = icon,
64 | contentDescription = iconId
65 | )
66 | }
67 | )
68 |
69 | Text(
70 | text = annotatedText,
71 | inlineContent = inlineContent
72 | )
73 | }
74 |
75 | internal enum class IconPositionInText {
76 | Leading,
77 | Trailing
78 | }
79 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Compose Template
2 |
3 | This template repository provides a quick start for creating new Android apps using [Jetpack Compose](https://developer.android.com/jetpack/compose) as the UI framework and following the [MVVM architecture pattern](https://developer.android.com/topic/architecture).
4 |
5 | It includes the following popular libraries:
6 |
7 | - [Hilt](https://dagger.dev/hilt) - Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project.
8 | - [Room](https://developer.android.com/training/data-storage/room) - Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
9 | - [Retrofit](https://github.com/square/retrofit) - A type-safe HTTP client for Android and the JVM.
10 | - [Moshi](https://github.com/square/moshi) - A modern JSON library for Kotlin and Java.
11 | - [Coil](https://github.com/coil-kt/coil) - Image loading for Android backed by Kotlin Coroutines.
12 |
13 | ## How to use
14 | To use this template, simply click on the **Use this template** button at the top (or fork the repository) and start building your app on top of it.
15 | Make sure to update the package name and other app-specific details before building and deploying your app.
16 |
17 | ## CI/CD
18 |
19 | This project includes built-in support for [GitHub Actions](https://github.com/features/actions) to
20 | automate builds, run unit tests, and ensure code quality.
21 | CI/CD workflows can be found in the `.github/workflows/` directory and can be customized based on
22 | your needs.
23 |
24 | ## Unit Testing
25 |
26 | This project supports unit testing with the following features:
27 |
28 | - Kotlin and Android unit tests with JUnit5
29 | - Coroutine and Flow testing utilities
30 | - `StateFlow` testing support via the [Turbine](https://github.com/cashapp/turbine) library, for
31 | testing UI state streams in a reactive manner.
32 |
33 | ## Annotation Processing
34 | This project uses [Kotlin Symbol Processing (KSP)](https://kotlinlang.org/docs/ksp-overview.html) for annotation processing, which provides faster build times compared to [KAPT](https://kotlinlang.org/docs/kapt.html).
35 |
36 | ## Build and Configuration Caching
37 | This project also takes advantage of Gradle's [Build Cache](https://docs.gradle.org/current/userguide/build_cache.html) and [Configuration Cache](https://docs.gradle.org/current/userguide/configuration_cache.html) features to speed up builds and reduce build times.
38 | Note that these features may not always provide significant improvements in build times depending on the project structure and build complexity.
39 |
40 | ## Contribution
41 | Contributions to this project are welcome! If you encounter any problems or have suggestions for improvement, feel free to submit a pull request or open an issue.
42 |
43 | ## License
44 | This project is licensed under the [MIT License](https://github.com/hadiyarajesh/compose-template/blob/master/LICENSE).
45 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget
2 |
3 | plugins {
4 | alias(libs.plugins.android.application)
5 | alias(libs.plugins.kotlin.android)
6 | alias(libs.plugins.kotlin.compose)
7 | alias(libs.plugins.kotlin.serialization)
8 | alias(libs.plugins.kotlin.parcelize)
9 | alias(libs.plugins.ksp)
10 | alias(libs.plugins.hilt.android)
11 | alias(libs.plugins.room)
12 | }
13 |
14 | android {
15 | namespace = "com.hadiyarajesh.composetemplate"
16 | compileSdk = 36
17 |
18 | defaultConfig {
19 | applicationId = "com.hadiyarajesh.composetemplate"
20 | minSdk = 23
21 | targetSdk = 36
22 | versionCode = 1
23 | versionName = "1.0"
24 |
25 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
26 | }
27 |
28 | buildTypes {
29 | debug {
30 | applicationIdSuffix = ".debug"
31 | versionNameSuffix = "-debug"
32 | }
33 |
34 | release {
35 | isMinifyEnabled = true
36 | isShrinkResources = true
37 | proguardFiles(
38 | getDefaultProguardFile("proguard-android-optimize.txt"),
39 | "proguard-rules.pro"
40 | )
41 | // Use debug signing for release (only if testing locally)
42 | signingConfig = signingConfigs.getByName("debug")
43 | }
44 | }
45 |
46 | compileOptions {
47 | sourceCompatibility = JavaVersion.VERSION_21
48 | targetCompatibility = JavaVersion.VERSION_21
49 | }
50 |
51 | buildFeatures {
52 | compose = true
53 | }
54 |
55 | kotlin {
56 | compilerOptions {
57 | jvmTarget = JvmTarget.JVM_21
58 | }
59 | }
60 |
61 | room {
62 | schemaDirectory("$projectDir/schemas")
63 | }
64 | }
65 |
66 | dependencies {
67 | implementation(libs.androidx.core.ktx)
68 | implementation(libs.activity.compose)
69 | implementation(libs.bundles.lifecycle)
70 | implementation(platform(libs.compose.bom))
71 | implementation(libs.bundles.compose.ui.impl)
72 | implementation(libs.material3)
73 | implementation(libs.navigation.compose)
74 |
75 | implementation(libs.hilt.android)
76 | implementation(libs.hilt.navigation.compose)
77 | ksp(libs.hilt.android.compiler)
78 |
79 | implementation(libs.bundles.room)
80 | ksp(libs.room.compiler)
81 |
82 | implementation(libs.bundles.retrofit)
83 | implementation(libs.okhttp.interceptor.logging)
84 |
85 | implementation(libs.kotlinx.serialization.json)
86 | implementation(libs.moshi)
87 | ksp(libs.moshi.kotlin.codegen)
88 |
89 | implementation(libs.bundles.coil)
90 |
91 | testImplementation(platform(libs.junit5.bom))
92 | testImplementation(libs.junit5)
93 | testRuntimeOnly(libs.junit5.platform.launcher)
94 | testImplementation(libs.kotlin.coroutines.test)
95 | testImplementation(libs.turbine)
96 |
97 | androidTestImplementation(libs.androidx.junit)
98 | androidTestImplementation(libs.espresso.core)
99 | androidTestImplementation(platform(libs.compose.bom))
100 | androidTestImplementation(libs.ui.test.junit4)
101 | debugImplementation(libs.bundles.compose.ui.debug)
102 | }
103 |
104 | // Use the JUnit5 Platform for running tests
105 | tasks.withType().configureEach {
106 | useJUnitPlatform()
107 | }
108 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | agp = "8.13.1"
3 | kotlin = "2.2.21"
4 | ksp = "2.3.3"
5 | coreKtx = "1.17.0"
6 | junit5 = "6.0.1"
7 | junitPlatformLauncher = "6.0.1"
8 | androidXJunitVersion = "1.3.0"
9 | espressoCore = "3.7.0"
10 | lifecycleRuntimeKtx = "2.10.0"
11 | activityCompose = "1.12.0"
12 | composeBom = "2025.11.01"
13 | hilt = "2.57.2"
14 | hiltNavigationCompose = "1.3.0"
15 | navigationCompose = "2.9.6"
16 | room = "2.8.4"
17 | retrofit = "3.0.0"
18 | okhttpLoggingInterceptor = "5.3.2"
19 | moshi = "1.15.2"
20 | coil = "3.3.0"
21 | kotlinxSerializationJson = "1.9.0"
22 | coroutinesTest = "1.10.2"
23 | turbine = "1.2.1"
24 |
25 | [libraries]
26 | androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
27 | junit5-bom = { module = "org.junit:junit-bom", version.ref = "junit5" }
28 | junit5 = { group = "org.junit.jupiter", name = "junit-jupiter" }
29 | junit5-platform-launcher = { module = "org.junit.platform:junit-platform-launcher", version.ref = "junitPlatformLauncher" }
30 | androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidXJunitVersion" }
31 | espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
32 | lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
33 | lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycleRuntimeKtx" }
34 | activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
35 | compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
36 | ui = { group = "androidx.compose.ui", name = "ui" }
37 | ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
38 | ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
39 | ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
40 | ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
41 | ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
42 | material3 = { group = "androidx.compose.material3", name = "material3" }
43 | navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
44 | hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }
45 | hilt-android-compiler = { group = "com.google.dagger", name = "hilt-android-compiler", version.ref = "hilt" }
46 | hilt-navigation-compose = { group = "androidx.hilt", name = "hilt-navigation-compose", version.ref = "hiltNavigationCompose" }
47 | room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
48 | room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
49 | room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
50 | retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
51 | retrofit-converter-moshi = { group = "com.squareup.retrofit2", name = "converter-moshi", version.ref = "retrofit" }
52 | okhttp-interceptor-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttpLoggingInterceptor" }
53 | moshi = { group = "com.squareup.moshi", name = "moshi", version.ref = "moshi" }
54 | moshi-kotlin-codegen = { group = "com.squareup.moshi", name = "moshi-kotlin-codegen", version.ref = "moshi" }
55 | coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }
56 | coil-network-okhttp = { module = "io.coil-kt.coil3:coil-network-okhttp", version.ref = "coil" }
57 | kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" }
58 | kotlin-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutinesTest" }
59 | turbine = { group = "app.cash.turbine", name = "turbine", version.ref = "turbine" }
60 |
61 | [plugins]
62 | android-application = { id = "com.android.application", version.ref = "agp" }
63 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
64 | kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
65 | ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
66 | hilt-android = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }
67 | kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
68 | kotlin-parcelize = { id = "kotlin-parcelize" }
69 | room = { id = "androidx.room", version.ref = "room" }
70 |
71 | [bundles]
72 | lifecycle = ["lifecycle-runtime-ktx", "lifecycle-runtime-compose"]
73 | compose-ui-impl = ["ui", "ui-graphics", "ui-tooling-preview"]
74 | compose-ui-debug = ["ui-tooling", "ui-test-manifest"]
75 | room = ["room-runtime", "room-ktx"]
76 | retrofit = ["retrofit", "retrofit-converter-moshi"]
77 | coil = ["coil-compose", "coil-network-okhttp"]
78 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/detail/DetailScreen.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.detail
2 |
3 | import android.widget.Toast
4 | import androidx.compose.foundation.layout.Arrangement
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.layout.fillMaxSize
7 | import androidx.compose.foundation.layout.padding
8 | import androidx.compose.material3.MaterialTheme
9 | import androidx.compose.material3.Scaffold
10 | import androidx.compose.material3.Text
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.ui.Alignment
13 | import androidx.compose.ui.Modifier
14 | import androidx.compose.ui.platform.LocalContext
15 | import androidx.compose.ui.platform.LocalUriHandler
16 | import androidx.compose.ui.res.stringResource
17 | import androidx.compose.ui.text.SpanStyle
18 | import androidx.compose.ui.text.buildAnnotatedString
19 | import androidx.compose.ui.text.font.FontWeight
20 | import androidx.compose.ui.text.withStyle
21 | import androidx.compose.ui.tooling.preview.Preview
22 | import androidx.compose.ui.unit.dp
23 | import androidx.navigation.NavController
24 | import com.hadiyarajesh.composetemplate.R
25 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
26 | import com.hadiyarajesh.composetemplate.ui.components.ClickableUrlText
27 | import com.hadiyarajesh.composetemplate.ui.components.ImageBox
28 | import com.hadiyarajesh.composetemplate.ui.components.TopBarWithBackButton
29 | import com.hadiyarajesh.composetemplate.ui.components.VerticalSpacer
30 | import com.hadiyarajesh.composetemplate.utility.ImageUtility
31 |
32 | /**
33 | * Entry-point composable for the Detail screen, intended to be invoked from
34 | * [com.hadiyarajesh.composetemplate.navigation.AppNavigation].
35 | *
36 | * It handles navigation and business logic by interacting with the ViewModel,
37 | * and delegates the actual UI rendering to [DetailScreenContent], making it easier
38 | * to separate concerns and enable previewing of the UI independently.
39 | */
40 | @Composable
41 | internal fun DetailScreenRoute(
42 | navController: NavController,
43 | image: Image
44 | ) {
45 | DetailScreenContent(
46 | image = image,
47 | onBackClick = { navController.popBackStack() }
48 | )
49 | }
50 |
51 | /**
52 | * Stateless, preview-friendly composable that renders the Detail screen UI.
53 | *
54 | * It does not require any ViewModel or navigation controller, making it
55 | * suitable for @Preview usage and reusable in different contexts. All actions
56 | * and data are passed in via parameters to promote testability and separation
57 | * of concerns.
58 | */
59 | @Composable
60 | private fun DetailScreenContent(
61 | image: Image,
62 | onBackClick: () -> Unit
63 | ) {
64 | val context = LocalContext.current
65 | val uriHandler = LocalUriHandler.current
66 |
67 | Scaffold(
68 | topBar = {
69 | TopBarWithBackButton(
70 | title = stringResource(
71 | R.string.screen_name,
72 | stringResource(R.string.detail)
73 | ),
74 | onBackClick = onBackClick
75 | )
76 | }
77 | ) { innerPadding ->
78 | Column(
79 | modifier = Modifier
80 | .fillMaxSize()
81 | .padding(innerPadding),
82 | verticalArrangement = Arrangement.Center,
83 | horizontalAlignment = Alignment.CenterHorizontally
84 | ) {
85 | ImageDetailView(
86 | modifier = Modifier.padding(16.dp),
87 | image = image,
88 | onImageUrlClick = { url ->
89 | try {
90 | uriHandler.openUri(url)
91 | } catch (e: IllegalArgumentException) {
92 | Toast.makeText(
93 | context,
94 | context.getString(R.string.failed_to_open_url),
95 | Toast.LENGTH_SHORT
96 | ).show()
97 | e.printStackTrace()
98 | }
99 | }
100 | )
101 | }
102 | }
103 | }
104 |
105 | @Composable
106 | private fun ImageDetailView(
107 | modifier: Modifier = Modifier,
108 | image: Image,
109 | onImageUrlClick: (String) -> Unit
110 | ) {
111 | Column(
112 | modifier = modifier,
113 | verticalArrangement = Arrangement.Center,
114 | horizontalAlignment = Alignment.CenterHorizontally
115 | ) {
116 | ImageBox(image = image)
117 |
118 | VerticalSpacer(size = 24)
119 |
120 | Text(
121 | text = buildAnnotatedString {
122 | withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
123 | append("${stringResource(R.string.description)}: ")
124 | }
125 | append(image.description)
126 | },
127 | style = MaterialTheme.typography.bodyLarge
128 | )
129 |
130 | VerticalSpacer(size = 16)
131 |
132 | ClickableUrlText(
133 | url = image.url,
134 | onClick = { url -> onImageUrlClick(url) }
135 | )
136 | }
137 | }
138 |
139 | @Preview(showSystemUi = true)
140 | @Composable
141 | fun DetailScreenPreview() {
142 | DetailScreenContent(
143 | image = Image(
144 | url = ImageUtility.getRandomImageUrl(),
145 | description = stringResource(id = R.string.welcome_message),
146 | altText = stringResource(id = R.string.failed_to_load_image)
147 | ),
148 | onBackClick = {}
149 | )
150 | }
151 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/components/Components.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.components
2 |
3 | import androidx.compose.foundation.border
4 | import androidx.compose.foundation.layout.Box
5 | import androidx.compose.foundation.layout.ColumnScope
6 | import androidx.compose.foundation.layout.RowScope
7 | import androidx.compose.foundation.layout.Spacer
8 | import androidx.compose.foundation.layout.fillMaxSize
9 | import androidx.compose.foundation.layout.height
10 | import androidx.compose.foundation.layout.size
11 | import androidx.compose.foundation.layout.width
12 | import androidx.compose.foundation.shape.RoundedCornerShape
13 | import androidx.compose.material3.CircularProgressIndicator
14 | import androidx.compose.material3.ExperimentalMaterial3Api
15 | import androidx.compose.material3.Icon
16 | import androidx.compose.material3.IconButton
17 | import androidx.compose.material3.MaterialTheme
18 | import androidx.compose.material3.Text
19 | import androidx.compose.material3.TopAppBar
20 | import androidx.compose.runtime.Composable
21 | import androidx.compose.ui.Alignment
22 | import androidx.compose.ui.Modifier
23 | import androidx.compose.ui.draw.clip
24 | import androidx.compose.ui.graphics.Color
25 | import androidx.compose.ui.res.painterResource
26 | import androidx.compose.ui.res.stringResource
27 | import androidx.compose.ui.text.LinkAnnotation
28 | import androidx.compose.ui.text.SpanStyle
29 | import androidx.compose.ui.text.TextLinkStyles
30 | import androidx.compose.ui.text.buildAnnotatedString
31 | import androidx.compose.ui.text.font.FontWeight
32 | import androidx.compose.ui.text.style.TextDecoration
33 | import androidx.compose.ui.text.withLink
34 | import androidx.compose.ui.text.withStyle
35 | import androidx.compose.ui.unit.Dp
36 | import androidx.compose.ui.unit.dp
37 | import coil3.compose.SubcomposeAsyncImage
38 | import com.hadiyarajesh.composetemplate.R
39 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
40 |
41 | /**
42 | * Create a [Spacer] of given width in [dp]
43 | */
44 | @Composable
45 | internal fun RowScope.HorizontalSpacer(size: Int) = Spacer(modifier = Modifier.width(size.dp))
46 |
47 | /**
48 | * Create a [Spacer] of given height in [dp]
49 | */
50 | @Composable
51 | internal fun ColumnScope.VerticalSpacer(size: Int) = Spacer(modifier = Modifier.height(size.dp))
52 |
53 | /**
54 | * Create a center aligned [CircularProgressIndicator] wrapped in a [Box]
55 | */
56 | @Composable
57 | internal fun LoadingIndicator(
58 | modifier: Modifier = Modifier,
59 | size: Dp = 40.dp,
60 | color: Color = MaterialTheme.colorScheme.primary,
61 | strokeWidth: Dp = 4.dp
62 | ) {
63 | Box(modifier = modifier) {
64 | CircularProgressIndicator(
65 | modifier = Modifier
66 | .size(size)
67 | .align(Alignment.Center),
68 | color = color,
69 | strokeWidth = strokeWidth
70 | )
71 | }
72 | }
73 |
74 | @Composable
75 | internal fun ErrorItem(
76 | text: String,
77 | modifier: Modifier = Modifier,
78 | color: Color = MaterialTheme.colorScheme.error
79 | ) {
80 | Box(modifier = modifier) {
81 | Text(
82 | modifier = Modifier.align(Alignment.Center),
83 | text = text,
84 | color = color
85 | )
86 | }
87 | }
88 |
89 | @OptIn(ExperimentalMaterial3Api::class)
90 | @Composable
91 | internal fun TopBarWithBackButton(
92 | modifier: Modifier = Modifier,
93 | title: String,
94 | onBackClick: () -> Unit
95 | ) {
96 | TopAppBar(
97 | modifier = modifier,
98 | navigationIcon = {
99 | IconButton(onClick = onBackClick) {
100 | Icon(
101 | painter = painterResource(R.drawable.ic_arrow_back),
102 | contentDescription = stringResource(R.string.go_back)
103 | )
104 | }
105 | },
106 | title = { Text(text = title) }
107 | )
108 | }
109 |
110 | @Composable
111 | internal fun ImageBox(
112 | modifier: Modifier = Modifier,
113 | image: Image
114 | ) {
115 | val imageShape = RoundedCornerShape(16.dp)
116 |
117 | Box(
118 | modifier = modifier
119 | .size(300.dp)
120 | .clip(imageShape)
121 | .border(1.dp, Color.LightGray, imageShape)
122 | ) {
123 | SubcomposeAsyncImage(
124 | modifier = Modifier.fillMaxSize(),
125 | model = image.url,
126 | contentDescription = image.description,
127 | loading = { LoadingIndicator(strokeWidth = 2.dp) },
128 | error = { ErrorItem(text = image.altText) }
129 | )
130 | }
131 | }
132 |
133 | @Composable
134 | internal fun ClickableUrlText(
135 | modifier: Modifier = Modifier,
136 | url: String,
137 | onClick: (String) -> Unit
138 | ) {
139 | val annotatedString = buildAnnotatedString {
140 | withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
141 | append("${stringResource(R.string.url)}: ")
142 | }
143 |
144 | withLink(
145 | LinkAnnotation.Url(
146 | url,
147 | TextLinkStyles(
148 | style = SpanStyle(
149 | color = Color.Blue,
150 | textDecoration = TextDecoration.Underline
151 | )
152 | )
153 | ) { onClick(url) }
154 | ) {
155 | append(url)
156 | }
157 | }
158 |
159 | Text(
160 | modifier = modifier,
161 | text = annotatedString,
162 | style = MaterialTheme.typography.bodyMedium
163 | )
164 | }
165 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hadiyarajesh/composetemplate/ui/home/HomeScreen.kt:
--------------------------------------------------------------------------------
1 | package com.hadiyarajesh.composetemplate.ui.home
2 |
3 | import androidx.compose.foundation.layout.Arrangement
4 | import androidx.compose.foundation.layout.Column
5 | import androidx.compose.foundation.layout.fillMaxSize
6 | import androidx.compose.foundation.layout.padding
7 | import androidx.compose.material3.ExperimentalMaterial3Api
8 | import androidx.compose.material3.MaterialTheme
9 | import androidx.compose.material3.OutlinedButton
10 | import androidx.compose.material3.Scaffold
11 | import androidx.compose.material3.Text
12 | import androidx.compose.material3.TopAppBar
13 | import androidx.compose.runtime.Composable
14 | import androidx.compose.runtime.LaunchedEffect
15 | import androidx.compose.runtime.getValue
16 | import androidx.compose.runtime.remember
17 | import androidx.compose.ui.Alignment
18 | import androidx.compose.ui.Modifier
19 | import androidx.compose.ui.res.painterResource
20 | import androidx.compose.ui.res.stringResource
21 | import androidx.compose.ui.tooling.preview.Preview
22 | import androidx.compose.ui.unit.dp
23 | import androidx.hilt.navigation.compose.hiltViewModel
24 | import androidx.lifecycle.compose.collectAsStateWithLifecycle
25 | import androidx.navigation.NavController
26 | import com.hadiyarajesh.composetemplate.R
27 | import com.hadiyarajesh.composetemplate.data.database.entity.Image
28 | import com.hadiyarajesh.composetemplate.navigation.NavDestination
29 | import com.hadiyarajesh.composetemplate.ui.components.ErrorItem
30 | import com.hadiyarajesh.composetemplate.ui.components.ImageBox
31 | import com.hadiyarajesh.composetemplate.ui.components.LoadingIndicator
32 | import com.hadiyarajesh.composetemplate.ui.components.TextWithIcon
33 | import com.hadiyarajesh.composetemplate.ui.components.VerticalSpacer
34 | import com.hadiyarajesh.composetemplate.utility.ImageUtility
35 |
36 | /**
37 | * Entry-point composable for the Home screen, intended to be invoked from
38 | * [com.hadiyarajesh.composetemplate.navigation.AppNavigation].
39 | *
40 | * It handles navigation and business logic by interacting with the ViewModel,
41 | * and delegates the actual UI rendering to [HomeScreenContent], making it easier
42 | * to separate concerns and enable previewing of the UI independently.
43 | */
44 | @Composable
45 | internal fun HomeScreenRoute(
46 | navController: NavController,
47 | viewModel: HomeViewModel = hiltViewModel()
48 | ) {
49 | val homeScreenUiState by remember { viewModel.uiState }.collectAsStateWithLifecycle()
50 |
51 | HomeScreenContent(
52 | uiState = homeScreenUiState,
53 | loadData = { viewModel.loadData() },
54 | onNavigateClick = { image -> navController.navigate(NavDestination.Detail(image)) },
55 | onChangeImageClick = { image ->
56 | viewModel.changeImage(image)
57 | }
58 | )
59 | }
60 |
61 | /**
62 | * Stateless, preview-friendly composable that renders the Home screen UI.
63 | *
64 | * It does not require any ViewModel or navigation controller, making it
65 | * suitable for @Preview usage and reusable in different contexts. All actions
66 | * and data are passed in via parameters to promote testability and separation
67 | * of concerns.
68 | */
69 | @OptIn(ExperimentalMaterial3Api::class)
70 | @Composable
71 | private fun HomeScreenContent(
72 | uiState: HomeScreenUiState,
73 | loadData: () -> Unit,
74 | onNavigateClick: (Image) -> Unit,
75 | onChangeImageClick: (Image) -> Unit
76 | ) {
77 | LaunchedEffect(Unit) {
78 | loadData()
79 | }
80 |
81 | Scaffold(
82 | topBar = {
83 | TopAppBar(
84 | title = { Text(text = stringResource(id = R.string.app_name)) }
85 | )
86 | }
87 | ) { innerPadding ->
88 | Column(
89 | modifier = Modifier
90 | .padding(innerPadding)
91 | .fillMaxSize()
92 | ) {
93 | when (uiState) {
94 | is HomeScreenUiState.Initial -> {}
95 |
96 | is HomeScreenUiState.Loading -> {
97 | LoadingIndicator(modifier = Modifier.fillMaxSize())
98 | }
99 |
100 | is HomeScreenUiState.Success -> {
101 | ImageAndButtonView(
102 | modifier = Modifier.fillMaxSize(),
103 | image = uiState.data,
104 | onNavigateClick = onNavigateClick,
105 | onChangeImageClick = onChangeImageClick
106 | )
107 | }
108 |
109 | is HomeScreenUiState.Error -> {
110 | ErrorItem(
111 | modifier = Modifier
112 | .padding(16.dp)
113 | .fillMaxSize(),
114 | text = uiState.msg
115 | )
116 | }
117 | }
118 | }
119 | }
120 | }
121 |
122 | @Composable
123 | private fun ImageAndButtonView(
124 | modifier: Modifier = Modifier,
125 | image: Image,
126 | onNavigateClick: (Image) -> Unit,
127 | onChangeImageClick: (Image) -> Unit
128 | ) {
129 | Column(
130 | modifier = modifier,
131 | verticalArrangement = Arrangement.Center,
132 | horizontalAlignment = Alignment.CenterHorizontally
133 | ) {
134 | ImageBox(image = image)
135 |
136 | VerticalSpacer(size = 16)
137 |
138 | Text(
139 | text = image.description,
140 | style = MaterialTheme.typography.titleSmall
141 | )
142 |
143 | VerticalSpacer(size = 16)
144 |
145 | OutlinedButton(onClick = { onChangeImageClick(image) }) {
146 | TextWithIcon(
147 | text = stringResource(R.string.change_image),
148 | icon = painterResource(R.drawable.ic_refresh)
149 | )
150 | }
151 |
152 | VerticalSpacer(size = 8)
153 |
154 | OutlinedButton(onClick = { onNavigateClick(image) }) {
155 | TextWithIcon(
156 | text = stringResource(
157 | R.string.go_to_screen,
158 | stringResource(id = R.string.detail)
159 | ),
160 | icon = painterResource(R.drawable.ic_arrow_forward)
161 | )
162 | }
163 | }
164 | }
165 |
166 | @Preview(showSystemUi = true)
167 | @Composable
168 | private fun HomeScreenPreview() {
169 | HomeScreenContent(
170 | uiState = HomeScreenUiState.Success(
171 | data = Image(
172 | description = stringResource(id = R.string.welcome_message),
173 | altText = stringResource(id = R.string.failed_to_load_image),
174 | url = ImageUtility.getRandomImageUrl()
175 | )
176 | ),
177 | loadData = {},
178 | onNavigateClick = {},
179 | onChangeImageClick = {}
180 | )
181 | }
182 |
--------------------------------------------------------------------------------