content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package xyz.androidrey.multimoduletemplate.network import kotlinx.serialization.Serializable @Serializable data class Response<T>( val data: T, val message: String? = null, )
GithubUserList/network/src/main/java/xyz/androidrey/multimoduletemplate/network/Response.kt
72185887
package xyz.androidrey.multimoduletemplate.main import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("xyz.androidrey.multimoduletemplate.main.test", appContext.packageName) } }
GithubUserList/features/main/src/androidTest/java/xyz/androidrey/multimoduletemplate/main/ExampleInstrumentedTest.kt
1135667094
package xyz.androidrey.multimoduletemplate.main import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
GithubUserList/features/main/src/test/java/xyz/androidrey/multimoduletemplate/main/ExampleUnitTest.kt
3969782179
package xyz.androidrey.multimoduletemplate.main.ui.home import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import androidx.paging.cachedIn import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import xyz.androidrey.multimoduletemplate.main.data.repository.DataRepository import xyz.androidrey.multimoduletemplate.main.domain.entity.User import xyz.androidrey.multimoduletemplate.main.data.remote.ThePagingSource import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( pager: Pager<Int, User>, private val repo: DataRepository ) : ViewModel() { private val _uiState = MutableStateFlow<HomeUiState>(HomeUiState.ProfileListLoading) val uiState = _uiState.asStateFlow() val lazyPagingItems: Flow<PagingData<User>> = Pager( config = PagingConfig(pageSize = 10), pagingSourceFactory = { ThePagingSource(repo) } ).flow.cachedIn(viewModelScope) val lazyPagingMediatorItem = pager.flow.cachedIn(viewModelScope) // init { // viewModelScope.launch { // when (val status = repo.getUsers(0)) { // is NetworkResult.Error -> _uiState.value = // HomeUiState.ProfileListLoadingFailed(status.exception.message!!) // // is NetworkResult.Success -> _uiState.value = // HomeUiState.ProfileListLoaded(status.result) // } // } // } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/home/HomeViewModel.kt
3037051452
package xyz.androidrey.multimoduletemplate.main.ui.home import xyz.androidrey.multimoduletemplate.main.domain.entity.User sealed class HomeUiState { data class ProfileListLoaded(val users: List<User>) : HomeUiState() data object ProfileListLoading : HomeUiState() data class ProfileListLoadingFailed(val message: String) : HomeUiState() }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/home/HomeUiState.kt
2269461305
package xyz.androidrey.multimoduletemplate.main.ui.home import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import androidx.paging.LoadState import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import coil.compose.AsyncImage import com.example.compose.AppTheme import xyz.androidrey.multimoduletemplate.main.domain.entity.User import xyz.androidrey.multimoduletemplate.main.ui.MainScreen import xyz.androidrey.multimoduletemplate.theme.components.AppBar import xyz.androidrey.multimoduletemplate.theme.components.ThePreview import xyz.androidrey.multimoduletemplate.theme.utils.toast @Composable fun HomeScreen(viewModel: HomeViewModel, navController: NavController) { val usersPagingItem = viewModel.lazyPagingMediatorItem.collectAsLazyPagingItems() val context = LocalContext.current LaunchedEffect(key1 = usersPagingItem.loadState) { if (usersPagingItem.loadState.refresh is LoadState.Error) { context.toast("Error: " + (usersPagingItem.loadState.refresh as LoadState.Error).error.message) { } } } Column(modifier = Modifier.fillMaxSize()) { AppBar("Users") if (usersPagingItem.loadState.refresh is LoadState.Loading) { LoadingItem() } else { Home(users = usersPagingItem) { navController.navigate("${MainScreen.Profile.route}?name=$it") } } } } @Composable fun Home(users: LazyPagingItems<User>, clickedUserName: (String) -> Unit) { LazyColumn { items(users.itemCount) { index -> val user = users[index] user?.let { UserRow(user = user!!) { clickedUserName(it) } } } if (users.loadState.append is LoadState.Loading) { item { LoadingItem() } // Show loading at the end of the list } if (users.loadState.append is LoadState.Error) { item { ErrorItem { users.retry() // Provide a way to retry failed loads } } } } } @Composable fun UserRow(user: User, clickedUserName: (String) -> Unit) { Card(modifier = Modifier .fillMaxWidth() .wrapContentHeight() .padding(3.dp) .clickable { clickedUserName(user.userLogin) }) { Row( modifier = Modifier.fillMaxSize() ) { AsyncImage( model = user.avatarUrl, contentDescription = "avatar", modifier = Modifier .size(50.dp) .padding(4.dp) ) Column(modifier = Modifier.padding(4.dp)) { Text(text = user.userLogin, color = Color.Black) } } } } @Composable fun LoadingItem() { Box( modifier = Modifier .fillMaxWidth() // Make sure the Box takes the full width .padding(16.dp) ) { // Optional padding CircularProgressIndicator(modifier = Modifier.align(Alignment.Center)) } } @Composable fun ErrorItem(retry: () -> Unit) { Box(modifier = Modifier.fillMaxWidth()) { Button(onClick = retry, modifier = Modifier.align(Alignment.Center)) { Text("Retry") } } } @ThePreview @Composable fun PreviewHome() { AppTheme { Surface(modifier = Modifier.fillMaxSize()) { } } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/home/Home.kt
3969740191
package xyz.androidrey.multimoduletemplate.main.ui.home import androidx.compose.runtime.Composable import xyz.androidrey.multimoduletemplate.main.domain.entity.User import xyz.androidrey.multimoduletemplate.main.ui.composable.ShowError import xyz.androidrey.multimoduletemplate.main.ui.composable.ShowLoading @Composable fun HomeStateHandler( state: HomeUiState, loading: @Composable () -> Unit = { ShowLoading() }, error: @Composable (String) -> Unit = { ShowError(it) }, content: @Composable (List<User>) -> Unit, ) { when (state) { is HomeUiState.ProfileListLoaded -> content(state.users) is HomeUiState.ProfileListLoading -> loading() is HomeUiState.ProfileListLoadingFailed -> error(state.message) } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/home/HomeStateHandler.kt
3854161579
package xyz.androidrey.multimoduletemplate.main.ui.composable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @Composable fun ShowLoading() { Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { CircularProgressIndicator() } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/composable/ShowLoading.kt
1490712823
package xyz.androidrey.multimoduletemplate.main.ui.composable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Warning import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import xyz.androidrey.multimoduletemplate.main.R @Composable fun ShowError(message: String) { Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Column { Icon( imageVector = Icons.Default.Warning, contentDescription = "failed", modifier = Modifier.size(128.dp), // Sets the size of the icon tint = MaterialTheme.colorScheme.error // Optional: sets the icon color ) Text(text = message) } } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/composable/ShowError.kt
4096319969
package xyz.androidrey.multimoduletemplate.main.ui import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navigation import xyz.androidrey.multimoduletemplate.main.ui.home.HomeScreen import xyz.androidrey.multimoduletemplate.main.ui.profile.ProfileScreen const val mainRoute = "main" sealed class MainScreen(val route: String) { data object Home : MainScreen("$mainRoute/home") data object Profile : MainScreen("$mainRoute/profile") } fun NavGraphBuilder.mainNavGraph(navController: NavController) { navigation(startDestination = MainScreen.Home.route, route = mainRoute) { composable(MainScreen.Home.route) { HomeScreen(hiltViewModel(), navController) } composable("${MainScreen.Profile.route}?name={name}", arguments = listOf( navArgument("name") { type = NavType.StringType defaultValue = "Sabbir" } )) { ProfileScreen(it.arguments?.getString("name"), hiltViewModel()) } } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/MainNavGraph.kt
1044157569
package xyz.androidrey.multimoduletemplate.main.ui.profile import xyz.androidrey.multimoduletemplate.main.domain.entity.Profile sealed class ProfileUiState { data class ProfileLoaded(val profile: Profile) : ProfileUiState() data object ProfileLoading : ProfileUiState() data class ProfileLoadingFailed(val message: String) : ProfileUiState() }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/profile/ProfileUiState.kt
2258479711
package xyz.androidrey.multimoduletemplate.main.ui.profile import androidx.compose.runtime.Composable import xyz.androidrey.multimoduletemplate.main.domain.entity.Profile import xyz.androidrey.multimoduletemplate.main.domain.entity.User import xyz.androidrey.multimoduletemplate.main.ui.composable.ShowError import xyz.androidrey.multimoduletemplate.main.ui.composable.ShowLoading @Composable fun ProfileStateHandler( state: ProfileUiState, loading: @Composable () -> Unit = { ShowLoading() }, error: @Composable (String) -> Unit = { ShowError(it) }, content: @Composable (Profile) -> Unit, ) { when (state) { is ProfileUiState.ProfileLoaded -> content(state.profile) is ProfileUiState.ProfileLoading -> loading() is ProfileUiState.ProfileLoadingFailed -> error(state.message) } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/profile/ProfileStateHandler.kt
916484129
package xyz.androidrey.multimoduletemplate.main.ui.profile import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.assisted.AssistedInject import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import xyz.androidrey.multimoduletemplate.main.data.repository.DataRepository import xyz.androidrey.multimoduletemplate.network.NetworkResult import javax.inject.Inject @HiltViewModel class ProfileViewModel @Inject constructor( private val repository: DataRepository ) : ViewModel() { private val _uiState = MutableStateFlow<ProfileUiState>(ProfileUiState.ProfileLoading) val uiState = _uiState.asStateFlow() fun onEvent(uiEvent: ProfileUiEvent) { when (uiEvent) { is ProfileUiEvent.LoadProfile -> { viewModelScope.launch { when (val status = repository.getProfile(uiEvent.name)) { is NetworkResult.Error -> _uiState.value = ProfileUiState.ProfileLoadingFailed(status.exception.message!!) is NetworkResult.Success -> _uiState.value = ProfileUiState.ProfileLoaded(status.result) } } } } } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/profile/ProfileViewModel.kt
342056534
package xyz.androidrey.multimoduletemplate.main.ui.profile import xyz.androidrey.multimoduletemplate.main.domain.entity.Profile sealed class ProfileUiEvent { data class LoadProfile(val name: String) : ProfileUiEvent() }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/profile/ProfileUiEvent.kt
760719301
package xyz.androidrey.multimoduletemplate.main.ui.profile import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.lifecycle.compose.collectAsStateWithLifecycle import xyz.androidrey.multimoduletemplate.theme.components.AppBar @Composable fun ProfileScreen(name: String? = "Sabbir", viewModel: ProfileViewModel) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() LaunchedEffect(Unit) { viewModel.onEvent(ProfileUiEvent.LoadProfile(name!!)) } Column(modifier = Modifier.fillMaxSize()) { AppBar(name!!) ProfileStateHandler(state = uiState) { Profile(it.name!!) } } } @Composable fun Profile(name: String) { Text(text = name) }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/ui/profile/Profile.kt
3490964879
package xyz.androidrey.multimoduletemplate.main.data.repository import xyz.androidrey.multimoduletemplate.main.domain.entity.Profile import xyz.androidrey.multimoduletemplate.main.domain.entity.User import xyz.androidrey.multimoduletemplate.network.NetworkResult interface DataRepository { suspend fun getUsers(lastUserId: Int): NetworkResult<List<User>> suspend fun getProfile(username: String?): NetworkResult<Profile> }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/data/repository/DataRepository.kt
492724911
package xyz.androidrey.multimoduletemplate.main.data.local.dao import androidx.paging.PagingSource import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import xyz.androidrey.multimoduletemplate.main.domain.entity.User @Dao interface UserDao { @Query("select * from User") suspend fun getUsers(): List<User> @Query("SELECT * FROM User") fun getUsersPaging(): PagingSource<Int, User> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(users: List<User>) @Query("DELETE FROM User") suspend fun clearAll() }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/data/local/dao/UserDao.kt
270971959
package xyz.androidrey.multimoduletemplate.main.data.local.dao import androidx.room.Database import androidx.room.RoomDatabase import xyz.androidrey.multimoduletemplate.main.domain.entity.User @Database(entities = [User::class], version = 1) abstract class TheDatabase : RoomDatabase() { abstract val userDao: UserDao }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/data/local/dao/TheDatabase.kt
1481514224
package xyz.androidrey.multimoduletemplate.main.data.remote import androidx.paging.PagingSource import androidx.paging.PagingState import xyz.androidrey.multimoduletemplate.main.data.repository.DataRepository import xyz.androidrey.multimoduletemplate.main.domain.entity.User import xyz.androidrey.multimoduletemplate.network.NetworkResult import javax.inject.Inject class ThePagingSource @Inject constructor(private val repository: DataRepository) : PagingSource<Int, User>() { override fun getRefreshKey(state: PagingState<Int, User>): Int? { return state.anchorPosition?.let { anchorPosition -> state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1) ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1) } } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, User> { var since = params.key ?: 0 val response = repository.getUsers(since) when (response) { is NetworkResult.Error -> return LoadResult.Error(IllegalStateException(response.exception.message)) is NetworkResult.Success -> { val data = response.result val nextKey = if (data.isEmpty()) null else data.last().userId + 1 return LoadResult.Page( data = data, prevKey = null, nextKey = nextKey ) } } } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/data/remote/ThePagingSource.kt
3899472554
package xyz.androidrey.multimoduletemplate.main.data.remote import androidx.paging.ExperimentalPagingApi import androidx.paging.LoadType import androidx.paging.PagingState import androidx.paging.RemoteMediator import androidx.room.withTransaction import xyz.androidrey.multimoduletemplate.main.data.local.dao.TheDatabase import xyz.androidrey.multimoduletemplate.main.domain.entity.User import xyz.androidrey.multimoduletemplate.network.NetworkResult import xyz.androidrey.multimoduletemplate.network.http.RequestHandler import javax.inject.Inject @OptIn(ExperimentalPagingApi::class) class UserRemoteMediator @Inject internal constructor( private val database: TheDatabase, private val requestHandler: RequestHandler ) : RemoteMediator<Int, User>() { override suspend fun load(loadType: LoadType, state: PagingState<Int, User>): MediatorResult { return try { val loadKey = when (loadType) { LoadType.REFRESH -> 0 LoadType.PREPEND -> return MediatorResult.Success( endOfPaginationReached = true ) LoadType.APPEND -> { val lastItem = state.lastItemOrNull() lastItem?.userId ?: 0 } } val users = requestHandler.get<List<User>>( urlPathSegments = listOf("users"), queryParams = mapOf("since" to loadKey, "per_page" to 10) ) when (users) { is NetworkResult.Error -> { MediatorResult.Error(users.exception) } is NetworkResult.Success -> { database.withTransaction { if (loadType == LoadType.REFRESH) { database.userDao.clearAll() } database.userDao.insertAll(users.result) } MediatorResult.Success(endOfPaginationReached = users.result.isEmpty()) } } } catch (e: Exception) { MediatorResult.Error(e) } } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/data/remote/UserRemoteMediator.kt
1952870266
package xyz.androidrey.multimoduletemplate.main.domain.repository import xyz.androidrey.multimoduletemplate.main.data.repository.DataRepository import xyz.androidrey.multimoduletemplate.main.domain.entity.Profile import xyz.androidrey.multimoduletemplate.main.domain.entity.User import xyz.androidrey.multimoduletemplate.network.http.RequestHandler import javax.inject.Inject class DataRepositoryImpl @Inject internal constructor(private val requestHandler: RequestHandler) : DataRepository { override suspend fun getUsers(lastUserId: Int) = requestHandler.get<List<User>>( urlPathSegments = listOf("users"), queryParams = mapOf("since" to lastUserId, "per_page" to 10) ) override suspend fun getProfile(username: String?) = requestHandler.get<Profile>(urlPathSegments = listOf("users", username!!)) }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/domain/repository/DataRepositoryImpl.kt
1783232267
package xyz.androidrey.multimoduletemplate.main.domain.di import android.content.Context import androidx.paging.ExperimentalPagingApi import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import io.ktor.client.HttpClient import io.ktor.http.URLProtocol import xyz.androidrey.multimoduletemplate.main.BuildConfig import xyz.androidrey.multimoduletemplate.main.data.local.dao.TheDatabase import xyz.androidrey.multimoduletemplate.main.data.remote.UserRemoteMediator import xyz.androidrey.multimoduletemplate.main.data.repository.DataRepository import xyz.androidrey.multimoduletemplate.main.domain.entity.User import xyz.androidrey.multimoduletemplate.main.domain.repository.DataRepositoryImpl import xyz.androidrey.multimoduletemplate.network.http.HttpClientBuilder import xyz.androidrey.multimoduletemplate.network.http.RequestHandler import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class NetworkModule { @Provides @Singleton fun provideHttpClient(): HttpClient = HttpClientBuilder().protocol(URLProtocol.HTTPS).host(BuildConfig.base_url).build() @Provides @Singleton fun provideRequestHandler(client: HttpClient) = RequestHandler(client) @Singleton @Provides fun provideDataRepository(dataRepositoryImpl: DataRepositoryImpl): DataRepository { return dataRepositoryImpl } @Singleton @Provides fun provideDatabase(@ApplicationContext context: Context): TheDatabase { return Room.databaseBuilder( context.applicationContext, TheDatabase::class.java, "users.db" ).build() } @OptIn(ExperimentalPagingApi::class) @Provides @Singleton fun provideUserPager(database: TheDatabase, requestHandler: RequestHandler): Pager<Int, User> { return Pager( config = PagingConfig(10), remoteMediator = UserRemoteMediator(database, requestHandler), pagingSourceFactory = { database.userDao.getUsersPaging() } ) } }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/domain/di/NetworkModule.kt
1488577192
package xyz.androidrey.multimoduletemplate.main.domain.util sealed class Status<T>(val data: T? = null, val message: String? = null) { class Success<T>(data: T) : Status<T>(data) class Error<T>(message: String, data: T? = null) : Status<T>(data, message) class Loading<T>(data: T? = null) : Status<T>(data) }
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/domain/util/Status.kt
2035874826
package xyz.androidrey.multimoduletemplate.main.domain.entity import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable @Entity data class User( @SerialName("id") @PrimaryKey val userId: Int, @SerialName("login") val userLogin: String, @SerialName("node_id") val nodeId: String, @SerialName("avatar_url") val avatarUrl: String )
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/domain/entity/User.kt
405312478
package xyz.androidrey.multimoduletemplate.main.domain.entity import kotlinx.serialization.Serializable @Serializable data class Profile( val avatar_url: String? = null, val bio: String? = null, val blog: String? = null, val company: String? = null, val created_at: String? = null, val email: String? = null, val events_url: String? = null, val followers: Int? = null, val followers_url: String? = null, val following: Int? = null, val following_url: String? = null, val gists_url: String? = null, val gravatar_id: String? = null, val hireable: Boolean? = null, val html_url: String? = null, val id: Int? = null, val location: String? = null, val login: String? = null, val name: String? = null, val node_id: String? = null, val organizations_url: String? = null, val public_gists: Int? = null, val public_repos: Int? = null, val received_events_url: String? = null, val repos_url: String? = null, val site_admin: Boolean? = null, val starred_url: String? = null, val subscriptions_url: String? = null, val twitter_username: String? = null, val type: String? = null, val updated_at: String? = null, val url: String? = null )
GithubUserList/features/main/src/main/java/xyz/androidrey/multimoduletemplate/main/domain/entity/Profile.kt
2525352746
package xyz.androidrey.multimoduletemplate.theme.utils import android.content.Context import android.widget.Toast import androidx.annotation.StringRes fun Context.toast(message: String, onToastDisplayChange: (Boolean) -> Unit) { showToast(message, onToastDisplayChange) } fun Context.toast(@StringRes message: Int, onToastDisplayChange: (Boolean) -> Unit) { showToast(getString(message), onToastDisplayChange) } private fun Context.showToast(message: String, onToastDisplayChange: (Boolean) -> Unit) { Toast.makeText(this, message, Toast.LENGTH_SHORT).also { it.addCallback(object : Toast.Callback() { override fun onToastHidden() { super.onToastHidden() onToastDisplayChange(false) } override fun onToastShown() { super.onToastShown() onToastDisplayChange(true) } }) }.show() }
GithubUserList/theme/src/main/java/xyz/androidrey/multimoduletemplate/theme/utils/Toast.kt
1808264652
package com.example.compose import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF6C5E00) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFFCE34D) val md_theme_light_onPrimaryContainer = Color(0xFF211C00) val md_theme_light_secondary = Color(0xFF006C53) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFF79F9CF) val md_theme_light_onSecondaryContainer = Color(0xFF002117) val md_theme_light_tertiary = Color(0xFF426650) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFC3ECD0) val md_theme_light_onTertiaryContainer = Color(0xFF002111) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFFFBFF) val md_theme_light_onBackground = Color(0xFF1D1C16) val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF1D1C16) val md_theme_light_surfaceVariant = Color(0xFFE9E2D0) val md_theme_light_onSurfaceVariant = Color(0xFF4A4739) val md_theme_light_outline = Color(0xFF7B7768) val md_theme_light_inverseOnSurface = Color(0xFFF5F0E7) val md_theme_light_inverseSurface = Color(0xFF32302A) val md_theme_light_inversePrimary = Color(0xFFDFC731) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF6C5E00) val md_theme_light_outlineVariant = Color(0xFFCCC6B5) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFDFC731) val md_theme_dark_onPrimary = Color(0xFF383000) val md_theme_dark_primaryContainer = Color(0xFF514700) val md_theme_dark_onPrimaryContainer = Color(0xFFFCE34D) val md_theme_dark_secondary = Color(0xFF5ADCB4) val md_theme_dark_onSecondary = Color(0xFF00382A) val md_theme_dark_secondaryContainer = Color(0xFF00513E) val md_theme_dark_onSecondaryContainer = Color(0xFF79F9CF) val md_theme_dark_tertiary = Color(0xFFA8D0B5) val md_theme_dark_onTertiary = Color(0xFF123724) val md_theme_dark_tertiaryContainer = Color(0xFF2A4E3A) val md_theme_dark_onTertiaryContainer = Color(0xFFC3ECD0) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF1D1C16) val md_theme_dark_onBackground = Color(0xFFE7E2D9) val md_theme_dark_surface = Color(0xFF1D1C16) val md_theme_dark_onSurface = Color(0xFFE7E2D9) val md_theme_dark_surfaceVariant = Color(0xFF4A4739) val md_theme_dark_onSurfaceVariant = Color(0xFFCCC6B5) val md_theme_dark_outline = Color(0xFF959180) val md_theme_dark_inverseOnSurface = Color(0xFF1D1C16) val md_theme_dark_inverseSurface = Color(0xFFE7E2D9) val md_theme_dark_inversePrimary = Color(0xFF6C5E00) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFDFC731) val md_theme_dark_outlineVariant = Color(0xFF4A4739) val md_theme_dark_scrim = Color(0xFF000000) val seed = Color(0xFFBCA600)
GithubUserList/theme/src/main/java/xyz/androidrey/multimoduletemplate/theme/Color.kt
4188463070
package xyz.androidrey.multimoduletemplate.theme.components import android.content.res.Configuration.UI_MODE_NIGHT_NO import android.content.res.Configuration.UI_MODE_NIGHT_YES import androidx.compose.ui.tooling.preview.Preview @Preview( name = "Preview Day", showBackground = true, uiMode = UI_MODE_NIGHT_NO, ) @Preview( name = "Preview Night", showBackground = true, uiMode = UI_MODE_NIGHT_YES, ) annotation class ThePreview
GithubUserList/theme/src/main/java/xyz/androidrey/multimoduletemplate/theme/components/ThePreview.kt
1772956349
package xyz.androidrey.multimoduletemplate.theme.components import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import com.example.compose.AppTheme @Composable fun TheTextField( value: String, @StringRes label: Int, hint: String = "", onValueChanged: (value: String) -> Unit, isPasswordField: Boolean = false, isClickOnly: Boolean = false, onClick: () -> Unit = {}, leadingIcon: ImageVector? = null, @StringRes error: Int? = null, keyboardType: KeyboardType = KeyboardType.Text, imeAction: ImeAction = ImeAction.Done, onDone: () -> Unit = {}, ) { val focusManager = LocalFocusManager.current Box( modifier = Modifier .fillMaxWidth() .height(90.dp), ) { TextField( modifier = Modifier .fillMaxWidth() .clickable { if (isClickOnly) { onClick() } }, value = value, onValueChange = { onValueChanged(it) }, singleLine = true, isError = error != null, readOnly = isClickOnly, enabled = !isClickOnly, supportingText = { if (error != null) { Text( modifier = Modifier.fillMaxWidth(), text = stringResource(error), color = MaterialTheme.colorScheme.error, ) } }, visualTransformation = if (isPasswordField) PasswordVisualTransformation() else VisualTransformation.None, label = { Text(text = stringResource(label)) }, placeholder = { Text(text = hint) }, leadingIcon = { leadingIcon?.let { Icon(it, hint, tint = MaterialTheme.colorScheme.onSurfaceVariant) } }, trailingIcon = { if (error != null) { Icon(Icons.Filled.Info, "error", tint = MaterialTheme.colorScheme.error) } }, keyboardActions = KeyboardActions( onDone = { focusManager.clearFocus() onDone() }, onNext = { focusManager.moveFocus(FocusDirection.Down) }, ), keyboardOptions = KeyboardOptions( keyboardType = keyboardType, imeAction = imeAction, ), ) } } @ThePreview @Composable fun AppTextFieldPreview() { AppTheme { Surface { TextField( modifier = Modifier .fillMaxWidth() .clickable {}, value = "", onValueChange = { }, singleLine = true, isError = true, // @Update Error State readOnly = false, enabled = true, supportingText = { Text(text = "Error Message or Supporting Message") }, placeholder = { Text(text = "Hint") }, ) } } }
GithubUserList/theme/src/main/java/xyz/androidrey/multimoduletemplate/theme/components/TextFields.kt
2184022204
package xyz.androidrey.multimoduletemplate.theme.components import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.vector.ImageVector @Composable fun AppBar( title: String, navIcon: ImageVector? = null, onNav: () -> Unit = {}, ) { TopAppBar( colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text(text = title) }, navigationIcon = { navIcon?.let { IconButton(onClick = { onNav() }) { Icon(navIcon, contentDescription = "Nav Icon") } } } ) }
GithubUserList/theme/src/main/java/xyz/androidrey/multimoduletemplate/theme/components/AppBar.kt
1229913817
package xyz.androidrey.multimoduletemplate.theme.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.example.compose.AppTheme @Composable fun FullScreenCircularProgressIndicator() { Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center, ) { CircularProgressIndicator() } } @ThePreview @Composable private fun FullScreenCircularProgressIndicatorPreview() { AppTheme { Surface { FullScreenCircularProgressIndicator() } } }
GithubUserList/theme/src/main/java/xyz/androidrey/multimoduletemplate/theme/components/ProgressIndicator.kt
2312964430
package com.example.compose import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable private val LightColors = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColors = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun AppTheme( useDarkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit, ) { val colors = if (!useDarkTheme) { LightColors } else { DarkColors } MaterialTheme( colorScheme = colors, content = content, ) }
GithubUserList/theme/src/main/java/xyz/androidrey/multimoduletemplate/theme/Theme.kt
3619641974
package xyz.androidrey.multimoduletemplate.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.PlatformTextStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.unit.sp private val poppins = FontFamily( Font(R.font.poppins_regular), Font(R.font.poppins_bold), Font(R.font.poppins_extra_bold), Font(R.font.poppins_medium), Font(R.font.poppins_thin), Font(R.font.poppins_italic), Font(R.font.poppins_light), Font(R.font.poppins_black), ) val defaultTextStyle = TextStyle( fontFamily = poppins, platformStyle = PlatformTextStyle( includeFontPadding = false, ), lineHeightStyle = LineHeightStyle( alignment = LineHeightStyle.Alignment.Center, trim = LineHeightStyle.Trim.None, ), ) val appTypography = Typography( displayLarge = defaultTextStyle.copy( fontSize = 57.sp, lineHeight = 64.sp, letterSpacing = (-0.25).sp, ), displayMedium = defaultTextStyle.copy( fontSize = 45.sp, lineHeight = 52.sp, letterSpacing = 0.sp, ), displaySmall = defaultTextStyle.copy( fontSize = 36.sp, lineHeight = 44.sp, letterSpacing = 0.sp, ), headlineLarge = defaultTextStyle.copy( fontSize = 32.sp, lineHeight = 40.sp, letterSpacing = 0.sp, ), headlineMedium = defaultTextStyle.copy( fontSize = 28.sp, lineHeight = 36.sp, letterSpacing = 0.sp, ), headlineSmall = defaultTextStyle.copy( fontSize = 24.sp, lineHeight = 32.sp, letterSpacing = 0.sp, ), titleLarge = defaultTextStyle.copy( fontSize = 28.sp, lineHeight = 28.sp, letterSpacing = 0.sp, ), titleMedium = defaultTextStyle.copy( fontSize = 18.sp, lineHeight = 24.sp, letterSpacing = 0.15.sp, fontWeight = FontWeight.Medium, ), titleSmall = defaultTextStyle.copy( fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp, fontWeight = FontWeight.Medium, ), labelLarge = defaultTextStyle.copy( fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp, fontWeight = FontWeight.Medium, ), labelMedium = defaultTextStyle.copy( fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp, fontWeight = FontWeight.Medium, ), labelSmall = defaultTextStyle.copy( fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp, fontWeight = FontWeight.Medium, ), bodyLarge = defaultTextStyle.copy( fontSize = 20.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp, ), bodyMedium = defaultTextStyle.copy( fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.25.sp, ), bodySmall = defaultTextStyle.copy( fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.4.sp, ), )
GithubUserList/theme/src/main/java/xyz/androidrey/multimoduletemplate/theme/Type.kt
683721225
package io.github.aloussase.calculator import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("io.github.aloussase.calculator", appContext.packageName) } }
android-clean-architecture-calculator/app/src/androidTest/java/io/github/aloussase/calculator/ExampleInstrumentedTest.kt
1556354860
package io.github.aloussase.calculator import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
android-clean-architecture-calculator/app/src/test/java/io/github/aloussase/calculator/ExampleUnitTest.kt
1938345439
package io.github.aloussase.calculator.ui import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.DismissDirection import androidx.compose.material3.DismissValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.material3.SwipeToDismiss import androidx.compose.material3.Text import androidx.compose.material3.rememberDismissState import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import io.github.aloussase.calculator.repository.NullCalculatorRepository import io.github.aloussase.calculator.ui.CalculatorEvent.OnDeleteHistoryItem import io.github.aloussase.calculator.ui.CalculatorEvent.OnHistoryClear import io.github.aloussase.calculator.ui.CalculatorEvent.OnHistoryItemClicked import io.github.aloussase.calculator.ui.theme.CalculatorTheme import kotlinx.coroutines.launch @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun HistoryScreenPreview() { val navController = rememberNavController() val snackbar = remember { SnackbarHostState() } val viewModel = CalculatorViewModel(NullCalculatorRepository()) CalculatorTheme { HistoryScreen( viewModel, navController, snackbar ) } } @Composable fun HistoryScreen( viewModel: CalculatorViewModel, navController: NavController, snackbar: SnackbarHostState, modifier: Modifier = Modifier ) { val scope = rememberCoroutineScope() val state by viewModel.state.collectAsState() Surface( modifier = modifier, color = MaterialTheme.colorScheme.background ) { Box { if (state.history.isNotEmpty()) { FloatingActionButton( shape = RoundedCornerShape(50), containerColor = MaterialTheme.colorScheme.primary, contentColor = MaterialTheme.colorScheme.background, modifier = Modifier .align(Alignment.BottomEnd) .padding(16.dp), onClick = { viewModel.onEvent(OnHistoryClear) scope.launch { snackbar.showSnackbar("History cleared") } }, ) { Icon( Icons.Default.Delete, "Clear history" ) } } Column( modifier = Modifier.fillMaxSize() ) { Text( text = "History", fontSize = 20.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() .padding(10.dp) ) LazyColumn( horizontalAlignment = Alignment.End, ) { items( items = state.history, key = { it.id!! } ) { item -> Box( modifier = Modifier .fillMaxWidth() .clickable { viewModel.onEvent(OnHistoryItemClicked(item.content)) navController.navigate(Screen.Calculator) }, ) { SwipeToDeleteItem( item, onDelete = { viewModel.onEvent(OnDeleteHistoryItem(it.id!!)) scope.launch { snackbar.showSnackbar("Item deleted from history") } } ) { Text( text = it.content, textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.background) .padding(16.dp), ) } } } } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun <T> SwipeToDeleteItem( item: T, onDelete: (T) -> Unit, modifier: Modifier = Modifier, content: @Composable (T) -> Unit ) { val dismissState = rememberDismissState( confirmValueChange = { if (it == DismissValue.DismissedToStart) { onDelete(item) true } else { false } } ) SwipeToDismiss( state = dismissState, modifier = modifier, directions = setOf(DismissDirection.EndToStart), background = { val color = if (dismissState.dismissDirection == DismissDirection.EndToStart) { MaterialTheme.colorScheme.error } else { Color.Transparent } Box( contentAlignment = Alignment.CenterEnd, modifier = Modifier .fillMaxSize() .background(color) .padding(16.dp), ) { Icon( Icons.Default.Delete, "Delete", tint = Color.White, ) } }, dismissContent = { content(item) } ) }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/HistoryScreen.kt
1506824031
package io.github.aloussase.calculator.ui import io.github.aloussase.calculator.data.HistoryItem data class CalculatorState( val input: String = "", val result: Float = 0f, val history: List<HistoryItem> = emptyList(), val hadError: Boolean = false )
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/CalculatorState.kt
3558085636
package io.github.aloussase.calculator.ui import android.content.res.Configuration import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.semantics.Role.Companion.Image import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import io.github.aloussase.calculator.R import io.github.aloussase.calculator.repository.NullCalculatorRepository import io.github.aloussase.calculator.ui.CalculatorEvent.OnClear import io.github.aloussase.calculator.ui.CalculatorEvent.OnClearError import io.github.aloussase.calculator.ui.CalculatorEvent.OnComputeResult import io.github.aloussase.calculator.ui.CalculatorEvent.OnInput import io.github.aloussase.calculator.ui.CalculatorEvent.OnOperation import io.github.aloussase.calculator.ui.CalculatorEvent.OnBackSpace import io.github.aloussase.calculator.ui.theme.CalculatorTheme @Preview( showBackground = true, showSystemUi = true, uiMode = Configuration.UI_MODE_NIGHT_YES ) @Composable fun CalculatorScreenPreview() { val viewModel = CalculatorViewModel(NullCalculatorRepository()) val snackbar = remember { SnackbarHostState() } CalculatorTheme { CalculatorScreen( viewModel, snackbar ) } } @Composable fun CalculatorScreen( viewModel: CalculatorViewModel, snackbar: SnackbarHostState, modifier: Modifier = Modifier ) { val state by viewModel.state.collectAsState() LaunchedEffect(key1 = state.hadError) { if (state.hadError) { snackbar.showSnackbar("There was an error calculating your expression") viewModel.onEvent(OnClearError) } } Surface( modifier = modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column( modifier = Modifier.fillMaxSize() ) { TextField( text = state.input, modifier = Modifier.weight(3f) ) TextField( text = "= " + state.result.toString(), modifier = Modifier.weight(1f) ) Buttons( modifier = Modifier.weight(2f), onNumberPressed = { viewModel.onEvent(OnInput(it)) }, onOperationPressed = { viewModel.onEvent(OnOperation(it)) }, onEqualsPressed = { viewModel.onEvent(OnComputeResult) }, onClearPressed = { viewModel.onEvent(OnClear) }, onBackSpacePressed = { viewModel.onEvent(OnBackSpace) } ) } } } @Composable private fun TextField( modifier: Modifier = Modifier, text: String = "", ) { Box( contentAlignment = Alignment.BottomEnd, modifier = modifier .fillMaxWidth() .padding(16.dp), ) { Text( text = text, fontSize = 26.sp ) } } @Composable private fun Buttons( modifier: Modifier = Modifier, onNumberPressed: (String) -> Unit, onOperationPressed: (String) -> Unit, onEqualsPressed: () -> Unit, onClearPressed: () -> Unit, onBackSpacePressed: () -> Unit = {} ) { Column( modifier = modifier.fillMaxWidth() ) { Row( modifier = Modifier.fillMaxWidth() ) { RectangularButton( text = "C", modifier = Modifier.weight(1f), textColor = MaterialTheme.colorScheme.primary, onClick = { onClearPressed() } ) OperationButton("(", onOperationPressed, Modifier.weight(1f)) OperationButton(")", onOperationPressed, Modifier.weight(1f)) OperationButton("/", onOperationPressed, Modifier.weight(1f)) } Row( modifier = Modifier.fillMaxWidth() ) { NumberButton("7", onNumberPressed, Modifier.weight(1f)) NumberButton("8", onNumberPressed, Modifier.weight(1f)) NumberButton("9", onNumberPressed, Modifier.weight(1f)) OperationButton("*", onOperationPressed, Modifier.weight(1f)) } Row( modifier = Modifier.fillMaxWidth() ) { NumberButton("4", onNumberPressed, Modifier.weight(1f)) NumberButton("5", onNumberPressed, Modifier.weight(1f)) NumberButton("6", onNumberPressed, Modifier.weight(1f)) OperationButton("-", onOperationPressed, Modifier.weight(1f)) } Row( modifier = Modifier.fillMaxWidth(), ) { NumberButton("1", onNumberPressed, Modifier.weight(1f)) NumberButton("2", onNumberPressed, Modifier.weight(1f)) NumberButton("3", onNumberPressed, Modifier.weight(1f)) OperationButton("+", onOperationPressed, Modifier.weight(1f)) } Row( modifier = Modifier.fillMaxWidth() ) { NumberButton("0", onNumberPressed, Modifier.weight(2f)) Image( painter = painterResource(id = R.drawable.back), contentDescription = "Backspace", modifier = Modifier.clickable { onBackSpacePressed() } .weight(1f) .padding(18.dp, 5.dp, 18.dp, 10.dp) ) OperationButton(".", onOperationPressed, Modifier.weight(1f)) RectangularButton( text = "=", modifier = Modifier.weight(1f), backgroundColor = MaterialTheme.colorScheme.primary, onClick = { onEqualsPressed() } ) } } } @Composable private fun NumberButton( number: String, onNumberPressed: (String) -> Unit, modifier: Modifier = Modifier ) { RectangularButton( text = number, onClick = { onNumberPressed(number) }, modifier = modifier, ) } @Composable private fun OperationButton( operation: String, onOperationPressed: (String) -> Unit, modifier: Modifier = Modifier, ) { RectangularButton( text = operation, textColor = MaterialTheme.colorScheme.primary, onClick = { onOperationPressed(operation) }, modifier = modifier, ) }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/CalculatorScreen.kt
72936431
package io.github.aloussase.calculator.ui import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.height import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.tooling.preview.Preview @Composable fun RectangularButton( modifier: Modifier = Modifier, text: String, textColor: Color = MaterialTheme.colorScheme.onBackground, backgroundColor: Color = MaterialTheme.colorScheme.background, onClick: () -> Unit = {} ) { Button( modifier = modifier.height(IntrinsicSize.Max), onClick = onClick, shape = RectangleShape, colors = ButtonDefaults.buttonColors( containerColor = backgroundColor ) ) { Text( text = text, color = textColor, ) } }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/RectangularButton.kt
674406279
package io.github.aloussase.calculator.ui.theme import androidx.compose.ui.graphics.Color val Orange = Color(0xFFF78930)
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/theme/Color.kt
3811405812
package io.github.aloussase.calculator.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable private val DarkColorScheme = darkColorScheme( primary = Orange, ) private val LightColorScheme = lightColorScheme( primary = Orange, ) @Composable fun CalculatorTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colorScheme = if (darkTheme) DarkColorScheme else LightColorScheme MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/theme/Theme.kt
1651461456
package io.github.aloussase.calculator.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/theme/Type.kt
3816565634
package io.github.aloussase.calculator.ui object Screen { const val CalculatorRoutes = "calculator-routes" const val Calculator = "calculator" const val About = "about" const val History = "history" }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/Screen.kt
1116318464
package io.github.aloussase.calculator.ui sealed class CalculatorEvent { data class OnInput(val input: String) : CalculatorEvent() data class OnOperation(val operation: String) : CalculatorEvent() data object OnComputeResult : CalculatorEvent() data object OnClear : CalculatorEvent() data object OnBackSpace : CalculatorEvent() data class OnHistoryItemClicked(val item: String) : CalculatorEvent() data object OnHistoryClear : CalculatorEvent() data class OnDeleteHistoryItem(val itemId: Long) : CalculatorEvent() data object OnClearError : CalculatorEvent() }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/CalculatorEvent.kt
381868898
package io.github.aloussase.calculator.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import io.github.aloussase.calculator.data.HistoryItem import io.github.aloussase.calculator.repository.ICalculatorRepository import io.github.aloussase.calculator.ui.CalculatorEvent.OnClear import io.github.aloussase.calculator.ui.CalculatorEvent.OnClearError import io.github.aloussase.calculator.ui.CalculatorEvent.OnComputeResult import io.github.aloussase.calculator.ui.CalculatorEvent.OnDeleteHistoryItem import io.github.aloussase.calculator.ui.CalculatorEvent.OnHistoryClear import io.github.aloussase.calculator.ui.CalculatorEvent.OnHistoryItemClicked import io.github.aloussase.calculator.ui.CalculatorEvent.OnInput import io.github.aloussase.calculator.ui.CalculatorEvent.OnBackSpace import io.github.aloussase.calculator.ui.CalculatorEvent.OnOperation import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CalculatorViewModel @Inject constructor( private val repository: ICalculatorRepository ) : ViewModel() { private val _state = MutableStateFlow(CalculatorState()) val state: StateFlow<CalculatorState> = _state.asStateFlow() init { viewModelScope.launch { val items = repository.getAllHistoryItems() _state.update { it.copy( history = items ) } } } fun onEvent(evt: CalculatorEvent) { println("Event: $evt") when (evt) { is OnInput -> { _state.update { it.copy( input = it.input + evt.input ) } } is OnOperation -> { _state.update { val currentInput = it.input val lastChar = currentInput.lastOrNull() val result = _state.value.result // if(currentInput.contains('.')){ // it.copy( // input = currentInput + evt.operation // ) // } else if (result != 0f) { it.copy( input = result.toString() + evt.operation, ) } else { val isLastCharOperator = lastChar in listOf('+', '-', '*', '/') val newInput = if (!isLastCharOperator) currentInput + evt.operation else currentInput it.copy(input = newInput) } } } is OnComputeResult -> { viewModelScope.launch { val currentInput = _state.value.input val lastChar = currentInput.lastOrNull() val isLastCharOperator = lastChar in listOf('+', '-', '*', '/') if (!isLastCharOperator) { val result = repository.calculate(_state.value.input) val item = HistoryItem(content = _state.value.input) val id = repository.createHistoryItem(item) _state.update { if (result == null) { it.copy( hadError = true ) } else { it.copy( result = result, history = it.history + item.copy(id = id) ) } } } else { _state.update { it.copy( hadError = true ) } } } } is OnHistoryItemClicked -> { _state.update { it.copy( input = evt.item, result = 0f, ) } } is OnHistoryClear -> { viewModelScope.launch { repository.deleteAllHistoryItems() _state.update { it.copy( history = emptyList() ) } } } is OnDeleteHistoryItem -> { viewModelScope.launch { repository.deleteOneItem(evt.itemId) _state.update { it.copy( history = it.history.filter { item -> item.id != evt.itemId } ) } } } is OnClear -> { _state.update { it.copy( input = "", result = 0f ) } } is OnClearError -> { _state.update { it.copy( hadError = false ) } } is OnBackSpace -> { println("Backspace pressed!") _state.update { val newInput = it.input if (newInput.isNotEmpty()) it.copy( input = it.input.dropLast(1) ) else it.copy( input = it.input ) } } } } }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/CalculatorViewModel.kt
549508470
package io.github.aloussase.calculator.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp @Composable fun AboutScreen( modifier: Modifier = Modifier ) { Surface( modifier = modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { Text( text = "Calculator App", fontSize = 24.sp, fontWeight = FontWeight.Bold ) Text( text = "Version 0.1.0" ) } } }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/ui/AboutScreen.kt
208797519
package io.github.aloussase.calculator.database import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import io.github.aloussase.calculator.data.HistoryItem @Dao interface HistoryItemDao { @Query("SELECT * from history_items") suspend fun findAll(): List<HistoryItem> @Query("DELETE from history_items") suspend fun clear() @Insert suspend fun insertOne(item: HistoryItem): Long @Query("DELETE from history_items WHERE id = :itemId") suspend fun delete(itemId: Long) }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/database/HistoryItemDao.kt
2986923977
package io.github.aloussase.calculator.database import androidx.room.Database import androidx.room.RoomDatabase import io.github.aloussase.calculator.data.HistoryItem @Database( entities = [HistoryItem::class], version = 2 ) abstract class HistoryDatabase : RoomDatabase() { abstract fun historyItemDao(): HistoryItemDao }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/database/HistoryDatabase.kt
58453785
package io.github.aloussase.calculator.repository import io.github.aloussase.calculator.data.HistoryItem final class NullCalculatorRepository : ICalculatorRepository { override suspend fun getAllHistoryItems(): List<HistoryItem> { return listOf( HistoryItem("1+2", 1), HistoryItem("3+3", 2), HistoryItem("4+3", 3) ) } override suspend fun createHistoryItem(item: HistoryItem): Long { return 0 } override suspend fun deleteAllHistoryItems() { } override suspend fun deleteOneItem(itemId: Long) { } override suspend fun calculate(expr: String): Float { return 0f } }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/repository/NullCalculatorRepository.kt
1201331355
package io.github.aloussase.calculator.repository import io.github.aloussase.calculator.data.HistoryItem interface ICalculatorRepository { suspend fun getAllHistoryItems(): List<HistoryItem> suspend fun createHistoryItem(item: HistoryItem): Long suspend fun deleteAllHistoryItems() suspend fun deleteOneItem(itemId: Long) suspend fun calculate(expr: String): Float? }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/repository/ICalculatorRepository.kt
1826553844
package io.github.aloussase.calculator.repository import android.util.Log import io.github.aloussase.calculator.api.MathApi import io.github.aloussase.calculator.api.MathApiRequestBody import io.github.aloussase.calculator.data.HistoryItem import io.github.aloussase.calculator.database.HistoryDatabase class CalculatorRepository( val mathApi: MathApi, val historyDatabase: HistoryDatabase ) : ICalculatorRepository { override suspend fun getAllHistoryItems(): List<HistoryItem> { return historyDatabase.historyItemDao().findAll() } override suspend fun createHistoryItem(item: HistoryItem): Long { return historyDatabase.historyItemDao().insertOne(item) } override suspend fun deleteAllHistoryItems() { historyDatabase.historyItemDao().clear() } override suspend fun deleteOneItem(itemId: Long) { historyDatabase.historyItemDao().delete(itemId) } override suspend fun calculate(expr: String): Float? { Log.d("CalculatorRepository", "Calculating expression: $expr") val result = mathApi.calculateExpr( MathApiRequestBody( expr = expr ) ) if (result.error != null) { return null } return result.result?.toFloatOrNull() } }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/repository/CalculatorRepository.kt
2962820250
package io.github.aloussase.calculator import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class CalculatorApplication : Application()
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/CalculatorApplication.kt
2471938893
package io.github.aloussase.calculator import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.ViewModel import androidx.navigation.NavBackStackEntry import androidx.navigation.NavController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.navigation import androidx.navigation.compose.rememberNavController import dagger.hilt.android.AndroidEntryPoint import io.github.aloussase.calculator.ui.AboutScreen import io.github.aloussase.calculator.ui.CalculatorScreen import io.github.aloussase.calculator.ui.CalculatorViewModel import io.github.aloussase.calculator.ui.HistoryScreen import io.github.aloussase.calculator.ui.Screen import io.github.aloussase.calculator.ui.theme.CalculatorTheme @AndroidEntryPoint class MainActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3Api::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CalculatorTheme { var showOptionsMenu by remember { mutableStateOf(false) } val navController = rememberNavController() val snackbarHostState = remember { SnackbarHostState() } Scaffold( snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, topBar = { TopAppBar( title = {}, actions = { IconButton(onClick = { showOptionsMenu = true }) { Icon( imageVector = Icons.Default.MoreVert, contentDescription = "Options" ) } OptionsMenu( navController, expanded = showOptionsMenu, onDismiss = { showOptionsMenu = false } ) } ) } ) { innerPadding -> NavHost( navController = navController, startDestination = Screen.CalculatorRoutes ) { navigation( startDestination = Screen.Calculator, route = Screen.CalculatorRoutes ) { composable(Screen.Calculator) { entry -> val viewModel = entry.viewModel<CalculatorViewModel>(navController) CalculatorScreen( viewModel, snackbarHostState, modifier = Modifier.padding(innerPadding) ) } composable(Screen.About) { AboutScreen( modifier = Modifier.padding(innerPadding) ) } composable(Screen.History) { entry -> val viewModel = entry.viewModel<CalculatorViewModel>(navController) HistoryScreen( viewModel, navController, snackbarHostState, modifier = Modifier.padding(innerPadding) ) } } } } } } } } @Composable inline fun <reified T : ViewModel> NavBackStackEntry.viewModel(navController: NavController): T { val navGraphRoute = destination.parent?.route ?: return hiltViewModel() val parentEntry = remember(this) { navController.getBackStackEntry(navGraphRoute) } val viewModel = hiltViewModel<T>(parentEntry) return viewModel } @Composable private fun OptionsMenu( navController: NavController, modifier: Modifier = Modifier, expanded: Boolean = false, onDismiss: () -> Unit = {}, ) { DropdownMenu( expanded = expanded, modifier = modifier, onDismissRequest = { onDismiss() } ) { DropdownMenuItem( text = { Text(text = "About") }, onClick = { Log.d("MainActivity", "About clicked") navController.navigate(Screen.About) onDismiss() } ) DropdownMenuItem( text = { Text(text = "History") }, onClick = { Log.d("MainActivity", "History clicked") navController.navigate(Screen.History) onDismiss() } ) } }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/MainActivity.kt
4199600616
package io.github.aloussase.calculator.di import android.app.Application import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import io.github.aloussase.calculator.api.MathApi import io.github.aloussase.calculator.database.HistoryDatabase import io.github.aloussase.calculator.repository.CalculatorRepository import io.github.aloussase.calculator.repository.ICalculatorRepository import retrofit2.Retrofit import retrofit2.converter.jackson.JacksonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object CalculatorModule { @Provides @Singleton fun provideHistoryDatabase( application: Application ): HistoryDatabase { return Room.databaseBuilder( application.applicationContext, HistoryDatabase::class.java, "calculator.db" ) .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun provideMathApi(): MathApi { return Retrofit.Builder() .baseUrl("https://api.mathjs.org/v4/") .addConverterFactory(JacksonConverterFactory.create()) .build() .create(MathApi::class.java) } @Provides @Singleton fun provideCalculatorRepository( mathApi: MathApi, historyDatabase: HistoryDatabase ): ICalculatorRepository { return CalculatorRepository(mathApi, historyDatabase) } }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/di/CalculatorModule.kt
916681381
package io.github.aloussase.calculator.api data class MathApiRequestBody( val expr: String )
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/api/MathApiRequestBody.kt
3417897040
package io.github.aloussase.calculator.api import retrofit2.http.Body import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Url interface MathApi { @POST suspend fun calculateExpr( @Body body: MathApiRequestBody, @Url url: String = "" ): MathApiResult }
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/api/MathApi.kt
1351320559
package io.github.aloussase.calculator.api data class MathApiResult( val result: String? = null, val error: String? = null )
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/api/MathApiResult.kt
3853243106
package io.github.aloussase.calculator.data import androidx.room.Entity import androidx.room.PrimaryKey @Entity( tableName = "history_items" ) data class HistoryItem( val content: String, @PrimaryKey val id: Long? = null, )
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/data/HistoryItem.kt
1987882048
package br.com.alura.orgs import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("br.com.alura.orgs", appContext.packageName) } }
Orgs2.0/app/src/androidTest/java/br/com/alura/orgs/ExampleInstrumentedTest.kt
596631617
package br.com.alura.orgs import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Orgs2.0/app/src/test/java/br/com/alura/orgs/ExampleUnitTest.kt
1470607537
package br.com.alura.orgs.ui.activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import androidx.lifecycle.lifecycleScope import br.com.alura.orgs.R import br.com.alura.orgs.database.AppDatabase import br.com.alura.orgs.databinding.ActivityDetalhesProdutoBinding import br.com.alura.orgs.extensions.formataParaMoedaBrasileira import br.com.alura.orgs.extensions.tentaCarregarImagem import br.com.alura.orgs.model.Produto import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch class DetalhesProdutoActivity : AppCompatActivity() { private var produtoId: Long = 0L private var produto: Produto? = null private val binding by lazy { ActivityDetalhesProdutoBinding.inflate(layoutInflater) } private val produtoDao by lazy { AppDatabase.instancia(this).produtoDao() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) tentaCarregarProduto() } override fun onResume() { super.onResume() buscaProduto() } private fun buscaProduto() { lifecycleScope.launch { produtoDao.buscaPorId(produtoId).collect { produtoEncontrado -> produto = produtoEncontrado produto?.let { preencheCampos(it) } ?: finish() } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_detalhes_produto, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_detalhes_produto_remover -> { produto?.let { lifecycleScope.launch { produtoDao.remove(it) finish() } } } R.id.menu_detalhes_produto_editar -> { Intent(this, FormularioProdutoActivity::class.java).apply { putExtra(CHAVE_PRODUTO_ID, produtoId) startActivity(this) } } } return super.onOptionsItemSelected(item) } private fun tentaCarregarProduto() { produtoId = intent.getLongExtra(CHAVE_PRODUTO_ID, 0L) } private fun preencheCampos(produtoCarregado: Produto) { with(binding) { activityDetalhesProdutoImagem.tentaCarregarImagem(produtoCarregado.imagem) activityDetalhesProdutoNome.text = produtoCarregado.nome activityDetalhesProdutoDescricao.text = produtoCarregado.descricao activityDetalhesProdutoValor.text = produtoCarregado.valor.formataParaMoedaBrasileira() } } }
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/activity/DetalhesProdutoActivity.kt
73715922
package br.com.alura.orgs.ui.activity const val CHAVE_PRODUTO_ID: String = "PRODUTO_ID"
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/activity/ConstantesActivities.kt
2932867855
package br.com.alura.orgs.ui.activity import android.os.Bundle import androidx.lifecycle.lifecycleScope import br.com.alura.orgs.database.AppDatabase import br.com.alura.orgs.database.dao.ProdutoDao import br.com.alura.orgs.databinding.ActivityFormularioProdutoBinding import br.com.alura.orgs.extensions.tentaCarregarImagem import br.com.alura.orgs.model.Produto import br.com.alura.orgs.ui.dialog.FormularioImagemDialog import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.launch import java.math.BigDecimal class FormularioProdutoActivity : UsuarioBaseActivity() { private val binding by lazy { ActivityFormularioProdutoBinding.inflate(layoutInflater) } private var url: String? = null private var produtoId = 0L private val produtoDao: ProdutoDao by lazy { val db = AppDatabase.instancia(this) db.produtoDao() } private val usuarioDao by lazy { AppDatabase.instancia(this).usuarioDao() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) title = "Cadastrar produto" configuraBotaoSalvar() binding.activityFormularioProdutoImagem.setOnClickListener { FormularioImagemDialog(this).mostra(url) { imagem -> url = imagem binding.activityFormularioProdutoImagem.tentaCarregarImagem(url) } } tentaCarregarProduto() } private fun tentaCarregarProduto() { produtoId = intent.getLongExtra(CHAVE_PRODUTO_ID, 0L) } override fun onResume() { super.onResume() tentaBuscarProduto() } private fun tentaBuscarProduto() { lifecycleScope.launch { produtoDao.buscaPorId(produtoId).collect { it?.let { produtoEncontrado -> title = "Alterar produto" preencheCampos(produtoEncontrado) } } } } private fun preencheCampos(produto: Produto) { url = produto.imagem binding.activityFormularioProdutoImagem.tentaCarregarImagem(produto.imagem) binding.activityFormularioProdutoNome.setText(produto.nome) binding.activityFormularioProdutoDescricao.setText(produto.descricao) binding.activityFormularioProdutoValor.setText(produto.valor.toPlainString()) } private fun configuraBotaoSalvar() { val botaoSalvar = binding.activityFormularioProdutoBotaoSalvar botaoSalvar.setOnClickListener { lifecycleScope.launch { usuario.value?.let { usuario -> val produtoNovo = criaProduto(usuario.id) produtoDao.salva(produtoNovo) finish() } } } } private fun criaProduto(usuarioId: String): Produto { val campoNome = binding.activityFormularioProdutoNome val nome = campoNome.text.toString() val campoDescricao = binding.activityFormularioProdutoDescricao val descricao = campoDescricao.text.toString() val campoValor = binding.activityFormularioProdutoValor val valorEmTexto = campoValor.text.toString() val valor = if (valorEmTexto.isBlank()) { BigDecimal.ZERO } else { BigDecimal(valorEmTexto) } return Produto( id = produtoId, nome = nome, descricao = descricao, valor = valor, imagem = url, usuarioId = usuarioId ) } }
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/activity/FormularioProdutoActivity.kt
3186066231
package br.com.alura.orgs.ui.activity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.datastore.preferences.core.edit import androidx.lifecycle.lifecycleScope import br.com.alura.orgs.R import br.com.alura.orgs.database.AppDatabase import br.com.alura.orgs.databinding.ActivityListaProdutosActivityBinding import br.com.alura.orgs.extensions.vaiPara import br.com.alura.orgs.preferences.dataStore import br.com.alura.orgs.preferences.usuarioLogadoPreferences import br.com.alura.orgs.ui.recyclerview.adapter.ListaProdutosAdapter import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.launch class ListaProdutosActivity : UsuarioBaseActivity() { private val adapter = ListaProdutosAdapter(context = this) private val binding by lazy { ActivityListaProdutosActivityBinding.inflate(layoutInflater) } private val produtoDao by lazy { val db = AppDatabase.instancia(this) db.produtoDao() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) configuraRecyclerView() configuraFab() lifecycleScope.launch { launch { usuario .filterNotNull() .collect {usuario -> buscaProdutosUsuario(usuario.id) } } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_lista_produtos, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_lista_produtos_sair_do_app -> { lifecycleScope.launch { deslogaUsuario() } } } return super.onOptionsItemSelected(item) } private suspend fun buscaProdutosUsuario(usuarioId: String) { produtoDao.buscaTodosDoUsuario(usuarioId).collect { produtos -> adapter.atualiza(produtos) } } private fun configuraFab() { val fab = binding.activityListaProdutosFab fab.setOnClickListener { vaiParaFormularioProduto() } } private fun vaiParaFormularioProduto() { val intent = Intent(this, FormularioProdutoActivity::class.java) startActivity(intent) } private fun configuraRecyclerView() { val recyclerView = binding.activityListaProdutosRecyclerView recyclerView.adapter = adapter adapter.quandoClicaNoItem = { val intent = Intent( this, DetalhesProdutoActivity::class.java ).apply { putExtra(CHAVE_PRODUTO_ID, it.id) } startActivity(intent) } } }
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/activity/ListaProdutosActivity.kt
703765688
package br.com.alura.orgs.ui.dialog import android.content.Context import android.view.LayoutInflater import androidx.appcompat.app.AlertDialog import br.com.alura.orgs.databinding.FormularioImagemBinding import br.com.alura.orgs.extensions.tentaCarregarImagem class FormularioImagemDialog(private val context: Context) { fun mostra( urlPadrao: String? = null, quandoImagemCarragada: (imagem: String) -> Unit ) { FormularioImagemBinding .inflate(LayoutInflater.from(context)).apply { urlPadrao?.let { formularioImagemImageview.tentaCarregarImagem(it) formularioImagemUrl.setText(it) } formularioImagemBotaoCarregar.setOnClickListener { val url = formularioImagemUrl.text.toString() formularioImagemImageview.tentaCarregarImagem(url) } AlertDialog.Builder(context) .setView(root) .setPositiveButton("Confirmar") { _, _ -> val url = formularioImagemUrl.text.toString() quandoImagemCarragada(url) } .setNegativeButton("Cancelar") { _, _ -> } .show() } } }
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/dialog/FormularioImagemDialog.kt
946382730
package br.com.alura.orgs.ui.recyclerview.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import br.com.alura.orgs.databinding.ProdutoItemBinding import br.com.alura.orgs.extensions.formataParaMoedaBrasileira import br.com.alura.orgs.extensions.tentaCarregarImagem import br.com.alura.orgs.model.Produto class ListaProdutosAdapter( private val context: Context, produtos: List<Produto> = emptyList(), var quandoClicaNoItem: (produto: Produto) -> Unit = {} ) : RecyclerView.Adapter<ListaProdutosAdapter.ViewHolder>() { private val produtos = produtos.toMutableList() inner class ViewHolder(private val binding: ProdutoItemBinding) : RecyclerView.ViewHolder(binding.root) { private lateinit var produto: Produto init { itemView.setOnClickListener { if (::produto.isInitialized) { quandoClicaNoItem(produto) } } } fun vincula(produto: Produto) { this.produto = produto val nome = binding.produtoItemNome nome.text = produto.nome val descricao = binding.produtoItemDescricao descricao.text = produto.descricao val valor = binding.produtoItemValor val valorEmMoeda: String = produto.valor .formataParaMoedaBrasileira() valor.text = valorEmMoeda val visibilidade = if (produto.imagem != null) { View.VISIBLE } else { View.GONE } binding.imageView.visibility = visibilidade binding.imageView.tentaCarregarImagem(produto.imagem) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(context) val binding = ProdutoItemBinding.inflate(inflater, parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val produto = produtos[position] holder.vincula(produto) } override fun getItemCount(): Int = produtos.size fun atualiza(produtos: List<Produto>) { this.produtos.clear() this.produtos.addAll(produtos) notifyDataSetChanged() } }
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/recyclerview/adapter/ListaProdutosAdapter.kt
3653105942
package br.com.alura.orgs.database import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL(""" CREATE TABLE IF NOT EXISTS `Usuario` ( `id` TEXT NOT NULL, `nome` TEXT NOT NULL, `senha` TEXT NOT NULL, PRIMARY KEY(`id`)) """) } } val MIGRATION_2_3 = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE Produto ADD COLUMN 'usuarioId' TEXT") } }
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/Migrations.kt
2908890328
package br.com.alura.orgs.database.converter import androidx.room.TypeConverter import java.math.BigDecimal class Converters { @TypeConverter fun deDouble(valor: Double?) : BigDecimal { return valor?.let { BigDecimal(valor.toString()) } ?: BigDecimal.ZERO } @TypeConverter fun bigDecimalParaDouble(valor: BigDecimal?) : Double? { return valor?.let { valor.toDouble() } } }
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/converter/Converters.kt
3420313798
package br.com.alura.orgs.database.dao import androidx.room.* import br.com.alura.orgs.model.Produto import kotlinx.coroutines.flow.Flow @Dao interface ProdutoDao { @Query("SELECT * FROM Produto") fun buscaTodos(): Flow<List<Produto>> @Query("SELECT * FROM Produto WHERE usuarioId = :usuarioId") fun buscaTodosDoUsuario(usuarioId: String) : Flow<List<Produto>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun salva(vararg produto: Produto) @Delete suspend fun remove(produto: Produto) @Query("SELECT * FROM Produto WHERE id = :id") fun buscaPorId(id: Long): Flow<Produto?> }
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/dao/ProdutoDao.kt
999944923
package br.com.alura.orgs.database.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import br.com.alura.orgs.model.Usuario import kotlinx.coroutines.flow.Flow @Dao interface UsuarioDao { @Insert suspend fun salva(usuario: Usuario) @Query(""" SELECT * FROM Usuario WHERE id = :usuarioId AND senha = :senha""") suspend fun autentica( usuarioId: String, senha: String ): Usuario? @Query("SELECT * FROM Usuario WHERE id = :usuarioId") fun buscaPorId(usuarioId: String): Flow<Usuario> }
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/dao/UsuarioDao.kt
3008690867
package br.com.alura.orgs.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import br.com.alura.orgs.database.converter.Converters import br.com.alura.orgs.database.dao.ProdutoDao import br.com.alura.orgs.database.dao.UsuarioDao import br.com.alura.orgs.model.Produto import br.com.alura.orgs.model.Usuario @Database( entities = [ Produto::class, Usuario::class ], version = 3, exportSchema = true ) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun produtoDao(): ProdutoDao abstract fun usuarioDao(): UsuarioDao companion object { @Volatile private var db: AppDatabase? = null fun instancia(context: Context): AppDatabase { return db ?: Room.databaseBuilder( context, AppDatabase::class.java, "orgs.db" ).addMigrations( MIGRATION_1_2, MIGRATION_2_3 ) .build().also { db = it } } } }
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/AppDatabase.kt
1903781028
package br.com.alura.orgs.preferences import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "sessao_usuario") val usuarioLogadoPreferences = stringPreferencesKey("usuarioLogado")
Orgs2.0/app/src/main/java/br/com/alura/orgs/preferences/UsuarioPreferences.kt
3272267987
package br.com.alura.orgs.extensions import java.math.BigDecimal import java.text.NumberFormat import java.util.* fun BigDecimal.formataParaMoedaBrasileira(): String { val formatador: NumberFormat = NumberFormat .getCurrencyInstance(Locale("pt", "br")) return formatador.format(this) }
Orgs2.0/app/src/main/java/br/com/alura/orgs/extensions/BigDecimalExtensions.kt
3030808231
package br.com.alura.orgs.extensions import android.widget.ImageView import br.com.alura.orgs.R import coil.load fun ImageView.tentaCarregarImagem( url: String? = null, fallback: Int = R.drawable.imagem_padrao ){ load(url) { fallback(fallback) error(R.drawable.erro) placeholder(R.drawable.placeholder) } }
Orgs2.0/app/src/main/java/br/com/alura/orgs/extensions/ImageViewExtensions.kt
2167883758
package br.com.alura.orgs.model import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize import java.math.BigDecimal @Entity @Parcelize data class Produto( @PrimaryKey(autoGenerate = true) val id: Long = 0L, val nome: String, val descricao: String, val valor: BigDecimal, val imagem: String? = null, val usuarioId: String? = null ) : Parcelable
Orgs2.0/app/src/main/java/br/com/alura/orgs/model/Produto.kt
1760884583
fun main() { oddNumbers() serveDrinks(6) product(50) product(101) println(myNAme(arrayOf("Maureen","Ivy", "Rehema", "Gatweri"))) } fun oddNumbers() { for (num1 in 1 ..100) { if (num1 % 2 != 0) { println(num1) } } } fun serveDrinks(age:Int){ if (age<=6){ println("Serve Milk") } else if (age <= 15 && age>6){ println(" Serve Fanta Orange") } else println("Serve Cocacola") } fun product(num:Int){ for (num in 1..100){ when{ (num%3==0 && num%5 ==0)-> println("FizzBuzz") (num %3 ==0)-> println("Fizz") (num % 5==0)-> println("Buzz") else-> ( println(num)) } } } fun myNAme (name: Array <String>):Int{ return name.count {it.length>5} }
inherita/src/main/kotlin/Main.kt
2584249790
package com.dtks.quickmuseum import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.dtks.quickmuseum", appContext.packageName) } }
QuickMuseum/app/src/androidTest/java/com/dtks/quickmuseum/ExampleInstrumentedTest.kt
1531015177
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtks.quickmuseum.ui import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.rules.TestWatcher import org.junit.runner.Description /** * Sets the main coroutines dispatcher to a [TestDispatcher] for unit testing. * * Declare it as a JUnit Rule: * * ``` * @get:Rule * val mainCoroutineRule = MainCoroutineRule() * ``` * * Then, use `runTest` to execute your tests. */ @ExperimentalCoroutinesApi class MainCoroutineRule( val testDispatcher: TestDispatcher = UnconfinedTestDispatcher() ) : TestWatcher() { override fun starting(description: Description?) { super.starting(description) Dispatchers.setMain(testDispatcher) } override fun finished(description: Description?) { super.finished(description) Dispatchers.resetMain() } }
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/ui/MainCoroutineRule.kt
3199733987
package com.dtks.quickmuseum.ui.details import androidx.lifecycle.SavedStateHandle import com.dtks.quickmuseum.data.model.ArtDetailsRequest import com.dtks.quickmuseum.data.repository.ArtDetailsRepository import com.dtks.quickmuseum.data.repository.defaultArtDetails import com.dtks.quickmuseum.ui.MainCoroutineRule import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import junit.framework.TestCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.Before import org.junit.Rule import org.junit.Test @ExperimentalCoroutinesApi class ArtDetailViewModelTest { @get:Rule val mainCoroutineRule = MainCoroutineRule() private lateinit var artDetailViewModel: ArtDetailViewModel val repository: ArtDetailsRepository = mockk() @Before fun setup() { every { repository.getArtDetailsFlow(any()) } returns flow { emit(defaultArtDetails) } artDetailViewModel = ArtDetailViewModel( repository, SavedStateHandle(mapOf(QuickMuseumDestinationsArgs.ART_ID_ARG to "artId2")) ) } @Test fun testInitialStateIsLoaded() = runTest { Dispatchers.setMain(StandardTestDispatcher()) val uiState = artDetailViewModel.uiState TestCase.assertTrue(uiState.first().isLoading) advanceUntilIdle() TestCase.assertFalse(uiState.first().isLoading) TestCase.assertEquals(uiState.first().artDetails, defaultArtDetails) coVerify { repository.getArtDetailsFlow( ArtDetailsRequest( artObjectNumber = "artId2" ) ) } } }
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/ui/details/ArtDetailViewModelTest.kt
3882703506
package com.dtks.quickmuseum.ui.overview import com.dtks.quickmuseum.data.model.CollectionRequest import com.dtks.quickmuseum.data.repository.OverviewRepository import com.dtks.quickmuseum.data.repository.defaultArtObjectListItems import com.dtks.quickmuseum.data.repository.secondaryArtObjectListItems import com.dtks.quickmuseum.ui.MainCoroutineRule import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertFalse import junit.framework.TestCase.assertTrue import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.Before import org.junit.Rule import org.junit.Test @ExperimentalCoroutinesApi class OverviewViewModelTest { @get:Rule val mainCoroutineRule = MainCoroutineRule() private lateinit var overviewViewModel: OverviewViewModel val repository: OverviewRepository = mockk() @Before fun setup() { every { repository.getCollectionFlow(any()) } returns flow { emit(defaultArtObjectListItems) } andThen flow { emit(secondaryArtObjectListItems) } overviewViewModel = OverviewViewModel( repository ) } @Test fun testInitialStateIsLoaded() = runTest { Dispatchers.setMain(StandardTestDispatcher()) val uiState = overviewViewModel.combinedUiState assertTrue(uiState.first().isLoading) advanceUntilIdle() assertFalse(uiState.first().isLoading) assertEquals(uiState.first().items, defaultArtObjectListItems) } @Test fun testLoadNextPage() = runTest { Dispatchers.setMain(StandardTestDispatcher()) val uiState = overviewViewModel.combinedUiState advanceUntilIdle() overviewViewModel.loadNextPage() assertTrue(uiState.first().isLoading) advanceUntilIdle() assertFalse(uiState.first().isLoading) assertEquals(uiState.first().items, defaultArtObjectListItems+secondaryArtObjectListItems) coVerify { repository.getCollectionFlow( CollectionRequest( page = 2 ) ) } } }
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/ui/overview/OverviewViewModelTest.kt
1858313880
package com.dtks.quickmuseum.data.repository import com.dtks.quickmuseum.data.model.ArtCreator import com.dtks.quickmuseum.data.model.ArtDetailsDao import com.dtks.quickmuseum.data.model.ArtDetailsResponse import com.dtks.quickmuseum.data.model.ArtObjectDao import com.dtks.quickmuseum.data.model.CollectionResponse import com.dtks.quickmuseum.data.model.Dating import com.dtks.quickmuseum.data.model.WebImage import com.dtks.quickmuseum.ui.details.ArtDetails import com.dtks.quickmuseum.ui.details.ArtDetailsImage import com.dtks.quickmuseum.ui.overview.ArtObjectListItem val defaultArtId = "art1" val defaultObjectNumber = "artObject1" val defaultTitle = "Eternal sunshine of the spotless mind" val defaultMaterials = listOf("aluminium", "copper") val defaultTechniques = listOf("acting") val defaultDatingString = "2004" val defaultImageUrl = "imageUrl.com/cool" val defaultCreator = "Charlie Kaufman" val defaultArtDetailsDao = ArtDetailsDao( id = defaultArtId, objectNumber = defaultObjectNumber, title = defaultTitle, principalMakers = listOf( ArtCreator( defaultCreator, "USA", occupation = null, roles = listOf("writer") ) ), materials = defaultMaterials, techniques = defaultTechniques, dating = Dating(defaultDatingString), webImage = WebImage(guid = "id23", width = 100, height = 200, url = defaultImageUrl) ) val defaultArtDetailsResponse = ArtDetailsResponse( artObject = defaultArtDetailsDao ) val defaultArtDetails = ArtDetails( id = defaultArtId, objectNumber = defaultObjectNumber, title = defaultTitle, creators = listOf(defaultCreator), materials = defaultMaterials, techniques = defaultTechniques, dating = defaultDatingString, image = ArtDetailsImage( url = defaultImageUrl, width = 100, height = 200 ) ) val defaultArtObjectListItems = listOf( ArtObjectListItem( id = defaultArtId, objectNumber = defaultObjectNumber, title = defaultTitle, creator = defaultCreator, imageUrl = defaultImageUrl, ) ) val secondaryArtObjectListItems = listOf( ArtObjectListItem( id = "id2", objectNumber = "obj2", title = "Drawing of the office", creator = "Pam Beesly", imageUrl = "http://theoffice.co.uk/pam_drawing.png", ) ) val defaultCollectionResponse = CollectionResponse( count = 1, artObjects = listOf( ArtObjectDao( id = defaultArtId, objectNumber = defaultObjectNumber, title = defaultTitle, hasImage = true, principalOrFirstMaker = defaultCreator, webImage = WebImage( guid = "image2", url = defaultImageUrl, width = 100, height = 100, ) ) ) )
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/data/repository/DefaultTestData.kt
1887867612
package com.dtks.quickmuseum.data.repository import com.dtks.quickmuseum.data.RemoteDataSource import com.dtks.quickmuseum.data.model.CollectionRequest import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.Before import org.junit.Test @ExperimentalCoroutinesApi class OverviewRepositoryTest{ val remoteDataSourceMock = mockk<RemoteDataSource>() private lateinit var repository: OverviewRepository private var testDispatcher = UnconfinedTestDispatcher() private var testScope = TestScope(testDispatcher) @Before fun setup() { repository = OverviewRepository( remoteDataSource = remoteDataSourceMock, dispatcher = testDispatcher ) } @Test fun getOverviewArtObjectsMapsResponseCorrectly()= testScope.runTest{ val expectedArtObjectListItems = defaultArtObjectListItems coEvery { remoteDataSourceMock.getCollection(any())} returns defaultCollectionResponse val artObjects = repository.getOverviewArtObjects( CollectionRequest() ) Assert.assertEquals(expectedArtObjectListItems, artObjects) } }
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/data/repository/OverviewRepositoryTest.kt
407444457
package com.dtks.quickmuseum.data.repository import com.dtks.quickmuseum.data.RemoteDataSource import com.dtks.quickmuseum.data.model.ArtDetailsRequest import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.Before import org.junit.Test @ExperimentalCoroutinesApi class ArtDetailsRepositoryTest{ val remoteDataSourceMock = mockk<RemoteDataSource>() private lateinit var repository: ArtDetailsRepository private var testDispatcher = UnconfinedTestDispatcher() private var testScope = TestScope(testDispatcher) @Before fun setup() { repository = ArtDetailsRepository( remoteDataSource = remoteDataSourceMock, dispatcher = testDispatcher ) } @Test fun getArtDetailsMapsResponseCorrectly()= testScope.runTest{ val expectedArtDetails = defaultArtDetails coEvery { remoteDataSourceMock.getArtDetails(any())} returns defaultArtDetailsResponse val request = ArtDetailsRequest(artObjectNumber = "a") val artDetails = repository.getArtDetails( request ) coVerify { remoteDataSourceMock.getArtDetails(request) } Assert.assertEquals(expectedArtDetails, artDetails) } }
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/data/repository/ArtDetailsRepositoryTest.kt
2174042491
package com.dtks.quickmuseum.ui import androidx.annotation.StringRes import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import com.dtks.quickmuseum.R @Composable fun EmptyContent(@StringRes emptyResultStringResource: Int) { Box(modifier = Modifier.fillMaxSize()) { Text( text = stringResource(id = emptyResultStringResource), style = MaterialTheme.typography.bodyLarge, modifier = Modifier .padding( dimensionResource(id = R.dimen.horizontal_margin) ) .fillMaxSize() .align(Alignment.Center) ) } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/EmptyContent.kt
3891257195
package com.dtks.quickmuseum.ui.loading import androidx.compose.animation.animateColor import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.width import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import com.dtks.quickmuseum.R @Composable fun ImageLoading(modifier: Modifier) { val transition = rememberInfiniteTransition( label = stringResource(id = R.string.image_background_transition) ) val borderColor by transition.animateColor( initialValue = MaterialTheme.colorScheme.primaryContainer, targetValue = MaterialTheme.colorScheme.inversePrimary, animationSpec = infiniteRepeatable( animation = tween(1000), repeatMode = RepeatMode.Reverse ), label = stringResource(id = R.string.image_background_label) ) Box( modifier = modifier.background(color = borderColor) ) { CircularProgressIndicator( modifier = Modifier .align(Alignment.Center) .width(dimensionResource(id = R.dimen.progress_indicator_size)), color = MaterialTheme.colorScheme.secondary, ) } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/loading/ImageLoading.kt
3540192662
package com.dtks.quickmuseum.ui.loading import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.width import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import com.dtks.quickmuseum.R @Composable fun LoadingContent( loading: Boolean, empty: Boolean, emptyContent: @Composable () -> Unit, content: @Composable () -> Unit ) { if (empty && loading) { Box( modifier = Modifier.fillMaxSize() ) { CircularProgressIndicator( modifier = Modifier .align(Alignment.Center) .width(dimensionResource(id = R.dimen.progress_indicator_size)), color = MaterialTheme.colorScheme.secondary, ) } } else if (empty) { emptyContent() } else { content() } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/loading/LoadingContent.kt
1928452846
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtks.quickmuseum.ui.navigation import androidx.navigation.NavHostController import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs.ART_ID_ARG import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs.USER_MESSAGE_ARG import com.dtks.quickmuseum.ui.navigation.QuickMuseumScreens.ARTS_SCREEN import com.dtks.quickmuseum.ui.navigation.QuickMuseumScreens.ART_DETAILS_SCREEN private object QuickMuseumScreens { const val ARTS_SCREEN = "arts" const val ART_DETAILS_SCREEN = "art" } object QuickMuseumDestinationsArgs { const val USER_MESSAGE_ARG = "userMessage" const val ART_ID_ARG = "artId" } object QuickMuseumDestinations { const val ARTS_ROUTE = "$ARTS_SCREEN?$USER_MESSAGE_ARG={$USER_MESSAGE_ARG}" const val ART_DETAILS_ROUTE = "$ART_DETAILS_SCREEN/{$ART_ID_ARG}" } /** * Models the navigation actions in the app. */ class QuickMuseumNavigationActions(private val navController: NavHostController) { fun navigateToArtDetail(artObjectNumber: String) { navController.navigate("$ART_DETAILS_SCREEN/$artObjectNumber") } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/navigation/QuickMuseumNavigation.kt
2963255247
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtks.quickmuseum.ui.navigation import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.dtks.quickmuseum.ui.details.ArtDetailScreen import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs.USER_MESSAGE_ARG import com.dtks.quickmuseum.ui.overview.OverviewScreen import com.dtks.quickmuseum.ui.overview.OverviewViewModel @Composable fun QuickMuseumNavGraph( modifier: Modifier = Modifier, navController: NavHostController = rememberNavController(), startDestination: String = QuickMuseumDestinations.ARTS_ROUTE, navActions: QuickMuseumNavigationActions = remember(navController) { QuickMuseumNavigationActions(navController) }, viewModel: OverviewViewModel = hiltViewModel(), ) { val currentNavBackStackEntry by navController.currentBackStackEntryAsState() NavHost( navController = navController, startDestination = startDestination, modifier = modifier ) { composable( QuickMuseumDestinations.ARTS_ROUTE, arguments = listOf( navArgument(USER_MESSAGE_ARG) { type = NavType.IntType; defaultValue = 0 } ) ) { OverviewScreen( onArtItemClick = { art -> navActions.navigateToArtDetail(art.objectNumber) }, viewModel = viewModel ) } composable(QuickMuseumDestinations.ART_DETAILS_ROUTE) { ArtDetailScreen( onBack = { navController.popBackStack() }, ) } } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/navigation/QuickMuseumNavGraph.kt
1283480676
package com.dtks.quickmuseum.ui.details import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import com.dtks.quickmuseum.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun ArtDetailsTopBar(title: String, onBack: () -> Unit) { TopAppBar( title = { Text(text = title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.Filled.ArrowBack, stringResource(id = R.string.menu_back)) } }, modifier = Modifier.fillMaxWidth() ) }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailsTopBar.kt
410280207
package com.dtks.quickmuseum.ui.details data class ArtDetailsImage( val url : String?, val width: Int, val height: Int, )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailsImage.kt
188553149
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtks.quickmuseum.ui.details import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.dtks.quickmuseum.R import com.dtks.quickmuseum.data.model.ArtDetailsRequest import com.dtks.quickmuseum.data.repository.ArtDetailsRepository import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs import com.dtks.quickmuseum.utils.AsyncResource import com.dtks.quickmuseum.utils.WhileUiSubscribed import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class ArtDetailViewModel @Inject constructor( artDetailsRepository: ArtDetailsRepository, savedStateHandle: SavedStateHandle ) : ViewModel() { private val artObjectNumber: String = savedStateHandle[QuickMuseumDestinationsArgs.ART_ID_ARG]!! private val _userMessage: MutableStateFlow<Int?> = MutableStateFlow(null) private val _isLoading = MutableStateFlow(false) private val _taskAsync = artDetailsRepository.getArtDetailsFlow( ArtDetailsRequest( artObjectNumber = artObjectNumber ) ) .map { handleArtDetails(it) } .catch { emit(AsyncResource.Error(R.string.loading_art_error)) } val uiState: StateFlow<ArtDetailsUiState> = combine( _userMessage, _isLoading, _taskAsync ) { userMessage, isLoading, taskAsync -> when (taskAsync) { AsyncResource.Loading -> { ArtDetailsUiState(isLoading = true) } is AsyncResource.Error -> { ArtDetailsUiState( userMessage = taskAsync.errorMessage, ) } is AsyncResource.Success -> { ArtDetailsUiState( artDetails = taskAsync.data, isLoading = isLoading, userMessage = userMessage, ) } } } .stateIn( scope = viewModelScope, started = WhileUiSubscribed, initialValue = ArtDetailsUiState(isLoading = true) ) fun snackbarMessageShown() { _userMessage.value = null } private fun handleArtDetails(artDetails: ArtDetails?): AsyncResource<ArtDetails?> { if (artDetails == null) { return AsyncResource.Error(R.string.art_details_not_found) } return AsyncResource.Success(artDetails) } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailViewModel.kt
1603520987
package com.dtks.quickmuseum.ui.details data class ArtDetailsUiState( val artDetails: ArtDetails? = null, val isLoading: Boolean = false, val userMessage: Int? = null, val isTaskDeleted: Boolean = false )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailsUiState.kt
29837262
package com.dtks.quickmuseum.ui.details data class ArtDetails( val id: String, val objectNumber: String, val title: String, val creators: List<String>, val materials: List<String>?, val techniques: List<String>?, val dating: String?, val image: ArtDetailsImage? )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetails.kt
3149133229
package com.dtks.quickmuseum.ui.details import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.IntSize import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil.compose.SubcomposeAsyncImage import com.dtks.quickmuseum.R import com.dtks.quickmuseum.ui.EmptyContent import com.dtks.quickmuseum.ui.loading.ImageLoading import com.dtks.quickmuseum.ui.loading.LoadingContent @OptIn(ExperimentalMaterial3Api::class) @Composable fun ArtDetailScreen( onBack: () -> Unit, modifier: Modifier = Modifier, viewModel: ArtDetailViewModel = hiltViewModel(), ) { val snackbarHostState = remember { SnackbarHostState() } val uiState by viewModel.uiState.collectAsStateWithLifecycle() val artDetails = uiState.artDetails Scaffold( snackbarHost = { SnackbarHost(snackbarHostState) }, modifier = modifier.fillMaxSize(), topBar = { ArtDetailsTopBar( title = artDetails?.title ?: "", onBack = onBack, ) }, floatingActionButton = {} ) { paddingValues -> val scrollState = rememberScrollState() var size by remember { mutableStateOf(IntSize.Zero) } Column( modifier = Modifier .padding(paddingValues) .fillMaxHeight() .verticalScroll(state = scrollState) .onSizeChanged { size = it } ) { LoadingContent( empty = artDetails == null, loading = uiState.isLoading, emptyContent = { EmptyContent(R.string.art_details_not_found) } ) { ArtDetailsComposable(artDetails, size) } } uiState.userMessage?.let { userMessage -> val snackbarText = stringResource(userMessage) LaunchedEffect(viewModel, userMessage, snackbarText) { snackbarHostState.showSnackbar(snackbarText) viewModel.snackbarMessageShown() } } } } @Composable private fun ArtDetailsComposable(artDetails: ArtDetails?, size: IntSize) { artDetails?.let { Row { val heightToWidthRatio = artDetails.image?.let { if (it.height != 0 && it.width != 0) { it.height.toFloat() / it.width.toFloat() } else { null } } var imageModifier = Modifier .fillMaxWidth() .wrapContentHeight() heightToWidthRatio?.let { with(LocalDensity.current) { val height = heightToWidthRatio.times(size.width).toDp() imageModifier = imageModifier.height( height ) } } SubcomposeAsyncImage( modifier = imageModifier, model = artDetails.image?.url, loading = { ImageLoading( Modifier .width(dimensionResource(id = R.dimen.list_item_image_width)) .height(dimensionResource(id = R.dimen.list_item_height)), ) }, contentDescription = artDetails.title, contentScale = ContentScale.FillWidth ) } artDetails.dating?.let { Row { Text( text = it, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding( start = dimensionResource(id = R.dimen.horizontal_margin) ) ) } } Row { Text( text = artDetails.title, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding( start = dimensionResource(id = R.dimen.horizontal_margin) ) ) } artDetails.creators.let { Row { Text( text = it.joinToString(), style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding( start = dimensionResource(id = R.dimen.horizontal_margin) ) ) } } artDetails.materials?.let { Row { Text( text = it.joinToString(), style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding( start = dimensionResource(id = R.dimen.horizontal_margin) ) ) } } } ?: EmptyContent(R.string.art_details_not_found) }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailScreen.kt
2218110807
package com.dtks.quickmuseum.ui.overview import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import com.dtks.quickmuseum.R @Composable @OptIn(ExperimentalFoundationApi::class) fun ArtCollectionList( uiState: OverviewUiState, onArtItemClick: (ArtObjectListItem) -> Unit, viewModel: OverviewViewModel ) { val listState = rememberLazyListState() val items = uiState.items LazyColumn( state = listState, modifier = Modifier .background(color = MaterialTheme.colorScheme.background) ) { val groupedItems = items.groupBy { it.creator } groupedItems.forEach { (artist, items) -> stickyHeader { Column( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .background(color = MaterialTheme.colorScheme.primaryContainer) ) { Text( text = artist, style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding( dimensionResource(id = R.dimen.horizontal_margin) ) ) } } items(items, key = { it.id }) { artObject -> ArtItem( modifier = Modifier.animateItemPlacement(), artObject = artObject, onClick = onArtItemClick, ) } } if (!uiState.isEmpty) { item { LoadMoreContent(uiState, viewModel) } } } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/ArtCollectionList.kt
2318899735
package com.dtks.quickmuseum.ui.overview import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.dtks.quickmuseum.R import com.dtks.quickmuseum.ui.EmptyContent import com.dtks.quickmuseum.ui.loading.LoadingContent @OptIn(ExperimentalMaterial3Api::class) @Composable fun OverviewScreen( onArtItemClick: (ArtObjectListItem) -> Unit, modifier: Modifier = Modifier, viewModel: OverviewViewModel = hiltViewModel(), ) { val snackbarHostState = remember { SnackbarHostState() } val uiState by viewModel.combinedUiState.collectAsStateWithLifecycle() Scaffold( snackbarHost = { SnackbarHost(snackbarHostState) }, modifier = modifier.fillMaxSize(), topBar = { OverviewTopBar( title = stringResource(id = R.string.app_name), ) }, floatingActionButton = {} ) { paddingValues -> Column( modifier = modifier .fillMaxSize() .padding(paddingValues) ) { LoadingContent( empty = uiState.isEmpty, loading = uiState.isLoading, emptyContent = { EmptyContent(R.string.no_art_found) } ) { ArtCollectionList(uiState, onArtItemClick, viewModel) } uiState.userMessage?.let { userMessage -> val snackbarText = stringResource(userMessage) LaunchedEffect(viewModel, userMessage, snackbarText) { snackbarHostState.showSnackbar(snackbarText) viewModel.snackbarMessageShown() } } } } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/OverviewScreen.kt
3427053533
package com.dtks.quickmuseum.ui.overview import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import com.dtks.quickmuseum.R @Composable fun LoadMoreContent( uiState: OverviewUiState, viewModel: OverviewViewModel ) { Column(modifier = Modifier .fillMaxWidth() .padding(dimensionResource(id = R.dimen.generic_padding))) { if (!uiState.isLoading) { Button( modifier = Modifier.align(Alignment.CenterHorizontally), onClick = { viewModel.loadNextPage() }) { Text( text = stringResource( id = if (uiState.isLoading) R.string.loading else R.string.load_more ) ) } } else { CircularProgressIndicator( modifier = Modifier .align(Alignment.CenterHorizontally) .width(dimensionResource(id = R.dimen.progress_indicator_size)), color = MaterialTheme.colorScheme.secondary, ) } } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/LoadMoreContent.kt
1607440765
package com.dtks.quickmuseum.ui.overview data class ArtObjectListItem( val id: String, val objectNumber: String, val title: String, val creator: String, val imageUrl: String?= null, )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/ArtObjectListItem.kt
2286780233
package com.dtks.quickmuseum.ui.overview import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.SubcomposeAsyncImage import com.dtks.quickmuseum.R import com.dtks.quickmuseum.ui.loading.ImageLoading @Composable fun ArtItem( modifier: Modifier, artObject: ArtObjectListItem, onClick: (ArtObjectListItem) -> Unit, ) { Card(modifier = modifier .fillMaxWidth() .padding( horizontal = dimensionResource(id = R.dimen.list_item_padding), vertical = dimensionResource(id = R.dimen.list_item_padding), ) .shadow(elevation = 10.dp, shape = RoundedCornerShape(12.dp)) .background(color = MaterialTheme.colorScheme.surface) .clickable { onClick(artObject) }) { Row { Text( text = artObject.title, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.surfaceTint, modifier = Modifier .widthIn(max = dimensionResource(id = R.dimen.list_item_text_width)) .padding( dimensionResource(id = R.dimen.horizontal_margin) ) ) Box( modifier = Modifier .fillMaxWidth() .widthIn(max = dimensionResource(id = R.dimen.list_item_image_width)) .height(dimensionResource(id = R.dimen.list_item_height)) ) { SubcomposeAsyncImage( modifier = Modifier .wrapContentWidth() .align(Alignment.CenterEnd) .height( dimensionResource(id = R.dimen.list_item_height) ), model = artObject.imageUrl, loading = { ImageLoading( Modifier .width(dimensionResource(id = R.dimen.list_item_image_width)) .height(dimensionResource(id = R.dimen.list_item_height)), ) }, contentDescription = artObject.title, contentScale = ContentScale.FillHeight ) } } } } @Preview @Composable fun PreviewArtCard() { ArtItem(modifier = Modifier, artObject = ArtObjectListItem( id = "Jim", objectNumber = "af", title = "Regional manager", creator = "Ricky Gervais", imageUrl = null ), onClick = {}) }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/ArtCard.kt
1381765311
package com.dtks.quickmuseum.ui.overview import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.dtks.quickmuseum.R import com.dtks.quickmuseum.data.model.CollectionRequest import com.dtks.quickmuseum.data.repository.OverviewRepository import com.dtks.quickmuseum.utils.AsyncResource import com.dtks.quickmuseum.utils.WhileUiSubscribed import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class OverviewViewModel @Inject constructor( private val overviewRepository: OverviewRepository ) : ViewModel() { private val currentPage = MutableStateFlow(1) private val initialState = overviewRepository.getCollectionFlow(CollectionRequest()) .map { AsyncResource.Success(it) } .catch<AsyncResource<List<ArtObjectListItem>>> { emit(AsyncResource.Error(R.string.loading_collection_error)) } private val _isLoading = MutableStateFlow(false) private val _userMessage: MutableStateFlow<Int?> = MutableStateFlow(null) private val _updateState = MutableStateFlow(listOf<ArtObjectListItem>()) val combinedUiState = combine( initialState, _updateState, _isLoading, _userMessage ) { initialState, updateState, isLoading, message -> when (initialState) { is AsyncResource.Loading -> { OverviewUiState(isLoading = true, isEmpty = true) } is AsyncResource.Error -> { OverviewUiState(userMessage = initialState.errorMessage, isEmpty = true) } is AsyncResource.Success -> { val items = initialState.data + updateState OverviewUiState( items = items, isLoading = isLoading, isEmpty = items.isEmpty(), userMessage = message ) } } }.stateIn( scope = viewModelScope, started = WhileUiSubscribed, initialValue = OverviewUiState(isLoading = true, isEmpty = true) ) fun snackbarMessageShown() { _userMessage.value = null } fun loadNextPage() { _isLoading.value = true viewModelScope.launch { overviewRepository.getCollectionFlow( CollectionRequest( page = currentPage.value + 1 ) ).catch { _userMessage.value = R.string.loading_collection_error _isLoading.value = false } .onEach { newState -> currentPage.value += 1 val uniqueStates = (_updateState.value + newState).toSet().toList() _updateState.value = uniqueStates _isLoading.value = false }.collect() } } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/OverviewViewModel.kt
3531356572