content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.rafver.read.domain.usecases
import com.rafver.core_domain.models.UserModel
import com.rafver.core_data.repositories.UserRepository
import com.rafver.core_domain.models.toDomainModel
import javax.inject.Inject
class GetUserList @Inject constructor(private val userRepository: UserRepository){
operator fun invoke(): Result<List<UserModel>> {
val result = userRepository.getUserList()
if(result.isSuccess) {
return Result.success(result.getOrNull().orEmpty().toDomainModel())
}
// ToDo implement proper error handling
return Result.failure(Exception("GetUserList operation failed"))
}
} | simple-crud/features/read/src/main/java/com/rafver/read/domain/usecases/GetUserList.kt | 587419629 |
package com.rafver.details.ui
import androidx.lifecycle.SavedStateHandle
import app.cash.turbine.expectNoEvents
import app.cash.turbine.test
import com.rafver.core_domain.models.UserModel
import com.rafver.core_testing.util.TestCoroutineRule
import com.rafver.core_ui.models.toUiModel
import com.rafver.details.R
import com.rafver.core_domain.usecases.GetUser
import com.rafver.details.domain.usecases.DeleteUser
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import io.mockk.verifyOrder
import kotlinx.coroutines.test.runTest
import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should be instance of`
import org.amshove.kluent.`should not be`
import org.junit.Rule
import org.junit.Test
class DetailsViewModelTest {
@get:Rule
val testCoroutineRule = TestCoroutineRule()
private val getUser: GetUser = mockk(relaxed = true)
private val deleteUser: DeleteUser = mockk(relaxed = true)
private lateinit var viewModel: DetailsViewModel
@Test
fun `when the view model is initialized, if DetailsArgs is invalid, an exception is thrown`() = runTest {
// Given
val invalidSavedStateHandleArgs = emptyMap<String, Any>()
val expectedException = IllegalStateException("Required value was null.")
var exception: Exception? = null
try {
`given the tested view model`(invalidSavedStateHandleArgs)
} catch (e: Exception) {
exception = e
}
// When
// Then
exception `should not be` null
exception `should be instance of` IllegalStateException::class
exception!!.message `should be equal to` expectedException.message
}
@Test
fun `when the view model is initialized, if get user operation succeeds, the ui state is properly updated`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
val expectedUserModel = UserModel(id = "1", name = "john", age = 20, email = "[email protected]")
val expectedUserUiModel = expectedUserModel.toUiModel()
every { getUser("1") } returns Result.success(expectedUserModel)
// When
// Then
viewModel.uiState.test {
awaitItem().userModel `should be equal to` null
awaitItem().userModel `should be equal to` expectedUserUiModel
expectNoEvents()
}
verify(exactly = 1) {
getUser("1")
}
}
@Test
fun `when the view model is initialized, if get user operation fails, an error snackbar is shown`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
every { getUser("1") } returns Result.failure(Exception("some exception"))
// When
// Then
viewModel.uiState.test {
awaitItem().userModel `should be equal to` null
expectNoEvents()
}
viewModel.effectsChannel.receive() `should be equal to`
DetailsViewModelEffect.DisplaySnackbar(R.string.error_details_generic)
viewModel.effectsChannel.expectNoEvents()
verify(exactly = 1) {
getUser("1")
}
}
// ToDo: test OnDeleteClicked event
@Test
fun `when edit button is clicked, the correct effect is emitted`() = runTest {
// Given
val expectedUserId = "1"
`given the tested view model`(mapOf(Pair("userId", "1")))
every {
getUser("1")
} returns Result.success(
UserModel(id = "1", name = "john", age = 20, email = "[email protected]")
)
// When
viewModel.uiState.test {
viewModel.onViewEvent(DetailsViewEvent.OnEditClicked)
cancelAndIgnoreRemainingEvents()
}
// Then
viewModel.effectsChannel.receive() `should be equal to` DetailsViewModelEffect.NavigateToEdit(expectedUserId)
}
@Test
fun `when delete button is clicked, then showDeleteDialog state is set to true`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
every {
getUser("1")
} returns Result.success(
UserModel(id = "1", name = "john", age = 20, email = "[email protected]")
)
viewModel.uiState.test {
// initial state
awaitItem().showDeleteDialog `should be equal to` false
// state after GetUser
awaitItem().showDeleteDialog `should be equal to` false
// When
viewModel.onViewEvent(DetailsViewEvent.OnDeleteClicked)
awaitItem().showDeleteDialog `should be equal to` true
expectNoEvents()
}
}
@Test
fun `when delete dialog is cancelled, then showDeleteDialog state is set to false`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
every {
getUser("1")
} returns Result.success(
UserModel(id = "1", name = "john", age = 20, email = "[email protected]")
)
viewModel.uiState.test {
// skip initial state and state after GetUser
skipItems(2)
// forcing state change
viewModel.updateState(viewModel.currentState.copy(showDeleteDialog = true))
awaitItem().showDeleteDialog `should be equal to` true
// When
viewModel.onViewEvent(DetailsViewEvent.OnDeleteCancelClicked)
// Then
awaitItem().showDeleteDialog `should be equal to` false
expectNoEvents()
}
}
@Test
fun `when delete dialog is confirmed, if deletion fails, then showDeleteDialog state is set to false and snackbar effect is emitted`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
every { deleteUser("1") } returns Result.failure(Exception("Some exception"))
val expectedSnackbarEffect = DetailsViewModelEffect.DisplaySnackbar(R.string.error_details_generic)
every {
getUser("1")
} returns Result.success(
UserModel(id = "1", name = "john", age = 20, email = "[email protected]")
)
viewModel.uiState.test {
// skip initial state and state after GetUser
skipItems(2)
// forcing state change
viewModel.updateState(viewModel.currentState.copy(showDeleteDialog = true))
awaitItem().showDeleteDialog `should be equal to` true
// When
viewModel.onViewEvent(DetailsViewEvent.OnDeleteConfirmationClicked)
// Then
awaitItem().showDeleteDialog `should be equal to` false
expectNoEvents()
}
viewModel.effectsChannel.receive() `should be equal to` expectedSnackbarEffect
verifyOrder {
getUser("1")
deleteUser("1")
}
}
@Test
fun `when delete dialog is confirmed, if deletion succeeds, then showDeleteDialog state is set to false and navigate up effect is emitted`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
every { deleteUser("1") } returns Result.success(true)
val expectedEffect = DetailsViewModelEffect.NavigateUp
every {
getUser("1")
} returns Result.success(
UserModel(id = "1", name = "john", age = 20, email = "[email protected]")
)
viewModel.uiState.test {
// skip initial state and state after GetUser
skipItems(2)
// forcing state change
viewModel.updateState(viewModel.currentState.copy(showDeleteDialog = true))
awaitItem().showDeleteDialog `should be equal to` true
// When
viewModel.onViewEvent(DetailsViewEvent.OnDeleteConfirmationClicked)
// Then
awaitItem().showDeleteDialog `should be equal to` false
expectNoEvents()
}
viewModel.effectsChannel.receive() `should be equal to` expectedEffect
verifyOrder {
getUser("1")
deleteUser("1")
}
}
private fun `given the tested view model`(savedStateHandleArgs: Map<String, Any?> = emptyMap()) {
viewModel = DetailsViewModel(
savedStateHandle = SavedStateHandle(savedStateHandleArgs),
getUser = getUser,
deleteUser = deleteUser,
)
}
} | simple-crud/features/details/src/test/java/com/rafver/details/ui/DetailsViewModelTest.kt | 4143298178 |
package com.rafver.details.ui.navigation
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.SavedStateHandle
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import com.rafver.details.ui.DetailsScreen
import com.rafver.details.ui.DetailsViewModel
private const val navigationRoute = "details"
private const val userIdArg = "userId"
fun NavGraphBuilder.detailsScreen(navController: NavController) {
composable("${navigationRoute}/{$userIdArg}") {
val viewModel: DetailsViewModel = hiltViewModel<DetailsViewModel>()
DetailsScreen(
navController = navController,
viewModel = viewModel,
)
}
}
fun NavController.navigateToDetails(userId: String) {
this.navigate("${navigationRoute}/${userId}")
}
internal class DetailsArgs(val userId: String) {
constructor(savedStateHandle: SavedStateHandle)
: this(checkNotNull(savedStateHandle[userIdArg]) as String)
}
| simple-crud/features/details/src/main/java/com/rafver/details/ui/navigation/DetailsNavigation.kt | 1844035775 |
package com.rafver.details.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.rafver.core_ui.extensions.collectUiState
import com.rafver.core_ui.models.UserUiModel
import com.rafver.core_ui.theme.Dimensions
import com.rafver.core_ui.theme.SimpleCRUDTheme
import com.rafver.core_ui.widgets.AlertDialogWidget
import com.rafver.create.ui.models.CreateViewEvent
import com.rafver.create.ui.models.CreateViewModelEffect
import com.rafver.create.ui.navigation.navigateToEdit
import com.rafver.details.R
@Composable
fun DetailsScreen(
navController: NavController,
viewModel: DetailsViewModel = hiltViewModel<DetailsViewModel>(),
) {
val uiState by viewModel.collectUiState()
val onViewEvent = viewModel::onViewEvent
val snackbarHostState = remember { SnackbarHostState() }
val context = LocalContext.current
LaunchedEffect(key1 = viewModel.effects) {
viewModel.effects.collect { effect ->
when(effect) {
is DetailsViewModelEffect.DisplaySnackbar -> {
snackbarHostState.showSnackbar(context.getString(effect.resId))
}
is DetailsViewModelEffect.NavigateToEdit -> {
navController.navigateToEdit(effect.userId)
}
DetailsViewModelEffect.NavigateUp -> {
navController.navigateUp()
}
}
}
}
Scaffold(
topBar = {
DetailsTopBar(
uiState = uiState,
)
}
) { padding ->
DetailsContent(
modifier = Modifier.padding(padding),
uiState = uiState,
onViewEvent = onViewEvent,
)
if(uiState.showDeleteDialog) {
AlertDialogWidget(
onDismissRequest = { onViewEvent(DetailsViewEvent.OnDeleteCancelClicked) },
onConfirmation = { onViewEvent(DetailsViewEvent.OnDeleteConfirmationClicked) },
dialogTitle = stringResource(id = R.string.dialog_title_delete_user),
dialogText = stringResource(id = R.string.dialog_description_delete_user),
confirmationText = stringResource(id = R.string.action_delete),
dismissText = stringResource(id = R.string.action_cancel),
icon = Icons.Filled.Warning,
iconContentDescription = "Warning"
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun DetailsTopBar(
uiState: DetailsUiState,
) {
TopAppBar(
title = {
Text(text = uiState.userModel?.name ?: stringResource(id = R.string.user_not_found))
},
navigationIcon = {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Back")
},
)
}
@Composable
private fun DetailsContent(
modifier: Modifier = Modifier,
uiState: DetailsUiState,
onViewEvent: (DetailsViewEvent) -> Unit,
) {
if(uiState.loading) {
//ToDo: implement loading spinner
return
}
Surface(modifier = modifier) {
if (uiState.userModel == null) {
Box(modifier = Modifier
.fillMaxSize()
.padding(Dimensions.NORMAL_100)
) {
Text(stringResource(id = R.string.user_not_found))
}
return@Surface
}
Column(
verticalArrangement = Arrangement.spacedBy(Dimensions.NORMAL_100),
modifier = Modifier
.fillMaxSize()
.padding(Dimensions.NORMAL_100)
.verticalScroll(state = rememberScrollState())
) {
Row {
Text(
text = stringResource(id = R.string.lbl_name),
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.size(Dimensions.SMALL_100))
Text(text = uiState.userModel.name)
}
Row {
Text(
text = stringResource(id = R.string.lbl_age),
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.size(Dimensions.SMALL_100))
Text(text = uiState.userModel.age.toString())
}
Row {
Text(
text = stringResource(id = R.string.lbl_email),
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.size(Dimensions.SMALL_100))
Text(text = uiState.userModel.email)
}
Spacer(modifier = Modifier.weight(1f))
Row(modifier = Modifier.fillMaxWidth()) {
Button(
modifier = Modifier.weight(1f),
onClick = { onViewEvent(DetailsViewEvent.OnEditClicked) }
) {
Text(text = stringResource(id = R.string.action_edit))
}
Spacer(modifier = Modifier.size(Dimensions.NORMAL_100))
Button(
modifier = Modifier.weight(1f),
onClick = { onViewEvent(DetailsViewEvent.OnDeleteClicked) }
) {
Text(text = stringResource(id = R.string.action_delete))
}
}
}
}
}
@Preview
@Composable
private fun PreviewDetailsContent() {
SimpleCRUDTheme {
DetailsContent(
uiState = DetailsUiState(
userModel = UserUiModel(
id = "1",
name = "John",
age = 20,
email = "[email protected]"
),
loading = false
),
onViewEvent = {},
)
}
} | simple-crud/features/details/src/main/java/com/rafver/details/ui/DetailsScreen.kt | 1029034908 |
package com.rafver.details.ui
import androidx.annotation.StringRes
import com.rafver.core_ui.models.UserUiModel
import com.rafver.core_ui.viewmodel.UiState
import com.rafver.core_ui.viewmodel.ViewEvent
import com.rafver.core_ui.viewmodel.ViewModelEffect
data class DetailsUiState(
val userModel: UserUiModel? = null,
val loading: Boolean = false,
val showDeleteDialog: Boolean = false,
) : UiState
sealed class DetailsViewEvent: ViewEvent {
data object OnInitialize: DetailsViewEvent()
data object OnEditClicked: DetailsViewEvent()
data object OnDeleteClicked: DetailsViewEvent()
data object OnDeleteConfirmationClicked: DetailsViewEvent()
data object OnDeleteCancelClicked: DetailsViewEvent()
}
sealed class DetailsViewModelEffect: ViewModelEffect {
data class DisplaySnackbar(@StringRes val resId: Int): DetailsViewModelEffect()
data class NavigateToEdit(val userId: String): DetailsViewModelEffect()
data object NavigateUp: DetailsViewModelEffect()
} | simple-crud/features/details/src/main/java/com/rafver/details/ui/DetailsUiState.kt | 1910145320 |
package com.rafver.details.ui
import androidx.lifecycle.SavedStateHandle
import com.rafver.core_domain.usecases.GetUser
import com.rafver.core_ui.models.toUiModel
import com.rafver.core_ui.viewmodel.BaseViewModel
import com.rafver.details.R
import com.rafver.details.domain.usecases.DeleteUser
import com.rafver.details.ui.navigation.DetailsArgs
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class DetailsViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val getUser: GetUser,
private val deleteUser: DeleteUser,
) : BaseViewModel<DetailsUiState, DetailsViewEvent, DetailsViewModelEffect>(
DetailsUiState()
) {
private val detailArgs = DetailsArgs(savedStateHandle)
init {
onViewEvent(DetailsViewEvent.OnInitialize)
}
override suspend fun handleViewEvent(event: DetailsViewEvent) {
when(event) {
DetailsViewEvent.OnInitialize -> {
val result = getUser(detailArgs.userId)
val user = result.getOrNull()
if(user != null) {
updateState(currentState.copy(userModel = user.toUiModel()))
} else {
handleException(result.exceptionOrNull())
}
}
DetailsViewEvent.OnDeleteClicked -> {
updateState(currentState.copy(showDeleteDialog = true))
}
DetailsViewEvent.OnDeleteCancelClicked -> {
updateState(currentState.copy(showDeleteDialog = false))
}
DetailsViewEvent.OnDeleteConfirmationClicked -> {
updateState(currentState.copy(showDeleteDialog = false))
val result = deleteUser(detailArgs.userId)
if(result.isSuccess) {
// ToDo: implement "user deleted" message
onViewModelEffect(DetailsViewModelEffect.NavigateUp)
} else {
val error = result.exceptionOrNull()
handleException(error)
}
}
DetailsViewEvent.OnEditClicked -> {
onViewModelEffect(DetailsViewModelEffect.NavigateToEdit(detailArgs.userId))
}
}
}
override fun handleException(error: Throwable?) {
println("An error has occurred: ${error?.message}")
when(error) {
else -> {
onViewModelEffect(
DetailsViewModelEffect.DisplaySnackbar(
resId = R.string.error_details_generic,
)
)
}
}
}
} | simple-crud/features/details/src/main/java/com/rafver/details/ui/DetailsViewModel.kt | 3150480744 |
package com.rafver.details.domain.usecases
import com.rafver.core_data.repositories.UserRepository
import javax.inject.Inject
class DeleteUser @Inject constructor(private val userRepository: UserRepository) {
operator fun invoke(id: String): Result<Boolean> {
return userRepository.deleteUser(id)
}
} | simple-crud/features/details/src/main/java/com/rafver/details/domain/usecases/DeleteUser.kt | 892546207 |
package com.rafver.create.ui
import androidx.lifecycle.SavedStateHandle
import app.cash.turbine.test
import com.rafver.core_domain.models.UserModel
import com.rafver.core_domain.usecases.GetUser
import com.rafver.core_testing.util.TestCoroutineRule
import com.rafver.create.R
import com.rafver.create.data.CreateResultType
import com.rafver.create.domain.usecases.CreateUser
import com.rafver.create.domain.usecases.UpdateUser
import com.rafver.create.domain.usecases.ValidateUser
import com.rafver.create.ui.models.CreateUiErrorState
import com.rafver.create.ui.models.CreateUiState
import com.rafver.create.ui.models.CreateViewEvent
import com.rafver.create.ui.models.CreateViewModelEffect
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import io.mockk.verifyOrder
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.amshove.kluent.`should be equal to`
import org.junit.After
import org.junit.Rule
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class CreateViewModelTest {
@get:Rule
val testCoroutineRule = TestCoroutineRule()
private val validateUser: ValidateUser = mockk(relaxed = true)
private val createUser: CreateUser = mockk(relaxed = true)
private val updateUser: UpdateUser = mockk(relaxed = true)
private val getUser: GetUser = mockk(relaxed = true)
private lateinit var viewModel: CreateViewModel
@Test
fun `when user inputs a new name, the ui state is properly updated`() = runTest {
// Given
`given the tested view model`()
val expectedName = "john"
viewModel.uiState.test {
awaitItem().name `should be equal to` ""
// When
viewModel.onViewEvent(CreateViewEvent.OnNameChanged("john"))
// Then
awaitItem().name `should be equal to` expectedName
}
}
@Test
fun `when user inputs a new name, if errors are present, the name error is removed, but not the others`() = runTest {
// Given
`given the tested view model`()
val expectedName = "john"
val initialErrors = CreateUiErrorState(
mandatoryNameError = 123,
mandatoryAgeError = 234,
invalidAgeError = 345,
mandatoryEmailError = 456
)
val expectedErrors = CreateUiErrorState(
mandatoryNameError = null,
mandatoryAgeError = 234,
invalidAgeError = 345,
mandatoryEmailError = 456
)
viewModel.updateState(CreateUiState(errors = initialErrors))
viewModel.uiState.test {
awaitItem().run {
name `should be equal to` ""
errors `should be equal to` initialErrors
}
// When
viewModel.onViewEvent(CreateViewEvent.OnNameChanged("john"))
// Then
awaitItem().run {
name `should be equal to` expectedName
errors `should be equal to` expectedErrors
}
}
}
@Test
fun `when user inputs a new age, the ui state is properly updated`() = runTest {
// Given
`given the tested view model`()
val expectedAge = "20"
viewModel.uiState.test {
awaitItem().age `should be equal to` ""
// When
viewModel.onViewEvent(CreateViewEvent.OnAgeChanged("20"))
advanceUntilIdle()
// Then
awaitItem().age `should be equal to` expectedAge
}
}
@Test
fun `when user inputs a new age, if errors are present, the age errors are removed, but not the others`() = runTest {
// Given
`given the tested view model`()
val expectedAge = "20"
val initialErrors = CreateUiErrorState(
mandatoryNameError = 123,
mandatoryAgeError = 234,
invalidAgeError = 345,
mandatoryEmailError = 456
)
val expectedErrors = CreateUiErrorState(
mandatoryNameError = 123,
mandatoryAgeError = null,
invalidAgeError = null,
mandatoryEmailError = 456
)
viewModel.updateState(CreateUiState(errors = initialErrors))
viewModel.uiState.test {
awaitItem().run {
age `should be equal to` ""
errors `should be equal to` initialErrors
}
// When
viewModel.onViewEvent(CreateViewEvent.OnAgeChanged("20"))
// Then
awaitItem().run {
age `should be equal to` expectedAge
errors `should be equal to` expectedErrors
}
}
}
@Test
fun `when user inputs a new email, the ui state is properly updated`() = runTest {
// Given
`given the tested view model`()
val expectedEmail = "[email protected]"
viewModel.uiState.test {
awaitItem().email `should be equal to` ""
// When
viewModel.onViewEvent(CreateViewEvent.OnEmailChanged("[email protected]"))
advanceUntilIdle()
// Then
awaitItem().email `should be equal to` expectedEmail
}
}
@Test
fun `when user inputs a new email, if errors are present, the email error is removed, but not the others`() = runTest {
// Given
`given the tested view model`()
val expectedEmail = "[email protected]"
val initialErrors = CreateUiErrorState(
mandatoryNameError = 123,
mandatoryAgeError = 234,
invalidAgeError = 345,
mandatoryEmailError = 456
)
val expectedErrors = CreateUiErrorState(
mandatoryNameError = 123,
mandatoryAgeError = 234,
invalidAgeError = 345,
mandatoryEmailError = null
)
viewModel.updateState(CreateUiState(errors = initialErrors))
viewModel.uiState.test {
awaitItem().run {
email `should be equal to` ""
errors `should be equal to` initialErrors
}
// When
viewModel.onViewEvent(CreateViewEvent.OnEmailChanged("[email protected]"))
// Then
awaitItem().run {
email `should be equal to` expectedEmail
errors `should be equal to` expectedErrors
}
}
}
@Test
fun `when discard button is clicked, the correct snackbar event is triggered and the text input focus clear effect is triggered`() = runTest {
// Given
`given the tested view model`()
viewModel.effects.test {
// When
viewModel.onViewEvent(CreateViewEvent.OnDiscardClicked)
// Then
advanceUntilIdle()
assertEquals(CreateViewModelEffect.DisplaySnackbar(R.string.snackbar_msg_changes_discarded), awaitItem())
assertEquals(CreateViewModelEffect.OnNameTextInputFocusRequest, awaitItem())
cancelAndIgnoreRemainingEvents()
}
}
@Test
fun `when create button is clicked, if inputs are valid and creation succeeds, the correct snackbar event is triggered and the state is cleared`() = runTest {
// Given
`given the tested view model`()
every {
validateUser(name = "john", age = "30", email = "[email protected]")
} returns emptyList()
every {
createUser(name = "john", age = "30", email = "[email protected]")
} returns Result.success(true)
val expectedSnackbarEvent = CreateViewModelEffect.DisplaySnackbar(R.string.snackbar_msg_user_created)
// Then
viewModel.uiState.test {
// initial state
awaitItem().run {
name `should be equal to` ""
age `should be equal to` ""
email `should be equal to` ""
}
// When
viewModel.updateState(CreateUiState(name = "john", age = "30", email = "[email protected]"))
// updated state
awaitItem().run {
name `should be equal to` "john"
age `should be equal to` "30"
email `should be equal to` "[email protected]"
}
viewModel.onViewEvent(CreateViewEvent.OnCreateClicked)
// state after clearForm() is called
awaitItem().run {
name `should be equal to` ""
age `should be equal to` ""
email `should be equal to` ""
}
expectNoEvents()
}
viewModel.effectsChannel.receive() `should be equal to` expectedSnackbarEvent
verifyOrder {
validateUser("john", "30", "[email protected]")
createUser("john", "30", "[email protected]")
}
}
@Test
fun `when create button is clicked, if inputs are valid but creation fails, the error snackbar event is triggered and the state is not cleared`() = runTest {
// Given
`given the tested view model`()
every {
validateUser(name = "john", age = "30", email = "[email protected]")
} returns emptyList()
every {
createUser(name = "john", age = "30", email = "[email protected]")
} returns Result.failure(Exception("Can't add user"))
val expectedSnackbarEvent = CreateViewModelEffect.DisplaySnackbar(R.string.error_create_generic)
// Then
viewModel.uiState.test {
// initial state
awaitItem().run {
name `should be equal to` ""
age `should be equal to` ""
email `should be equal to` ""
}
// When
viewModel.updateState(CreateUiState(name = "john", age = "30", email = "[email protected]"))
// updated state
awaitItem().run {
name `should be equal to` "john"
age `should be equal to` "30"
email `should be equal to` "[email protected]"
}
viewModel.onViewEvent(CreateViewEvent.OnCreateClicked)
viewModel.currentState.run {
name `should be equal to` "john"
age `should be equal to` "30"
email `should be equal to` "[email protected]"
}
expectNoEvents()
}
viewModel.effectsChannel.receive() `should be equal to` expectedSnackbarEvent
verifyOrder {
validateUser("john", "30", "[email protected]")
createUser("john", "30", "[email protected]")
}
}
@Test
fun `when create button is clicked, if name field is empty the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`()
val expectedErrorState = CreateResultType.Error.NameMandatory(R.string.error_create_mandatory_field)
every {
validateUser(name = "", age = any(), email = any())
} returns listOf(expectedErrorState)
// When
viewModel.uiState.test {
// Then
awaitItem().errors.mandatoryNameError `should be equal to` null
viewModel.onViewEvent(CreateViewEvent.OnCreateClicked)
awaitItem().errors.mandatoryNameError `should be equal to` expectedErrorState.resId
expectNoEvents()
}
verify(exactly = 1) {
validateUser(name = "", age = any(), email = any())
}
verify(exactly = 0) {
createUser(name = any(), age = any(), email = any())
}
}
@Test
fun `when create button is clicked, if age field is empty the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`()
val expectedErrorState = CreateResultType.Error.AgeMandatory(R.string.error_create_mandatory_field)
every {
validateUser(name = any(), age = "", email = any())
} returns listOf(expectedErrorState)
// When
viewModel.uiState.test {
// Then
awaitItem().errors.mandatoryAgeError `should be equal to` null
viewModel.onViewEvent(CreateViewEvent.OnCreateClicked)
awaitItem().errors.mandatoryAgeError `should be equal to` expectedErrorState.resId
expectNoEvents()
}
verify(exactly = 1) {
validateUser(name = any(), age = "", email = any())
}
verify(exactly = 0) {
createUser(name = any(), age = any(), email = any())
}
}
@Test
fun `when create button is clicked, if age field is invalid the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`()
val expectedErrorState = CreateResultType.Error.InvalidAge(R.string.error_create_invalid_age)
every {
validateUser(name = any(), age = "abc", email = any())
} returns listOf(expectedErrorState)
viewModel.updateState(CreateUiState(age = "abc"))
// When
viewModel.uiState.test {
// Then
awaitItem().errors.invalidAgeError `should be equal to` null
viewModel.onViewEvent(CreateViewEvent.OnCreateClicked)
awaitItem().errors.invalidAgeError `should be equal to` expectedErrorState.resId
expectNoEvents()
}
verify(exactly = 1) {
validateUser(name = any(), age = "abc", email = any())
}
verify(exactly = 0) {
createUser(name = any(), age = any(), email = any())
}
}
@Test
fun `when create button is clicked, if email field is empty the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`()
val expectedErrorState = CreateResultType.Error.EmailMandatory(R.string.error_create_mandatory_field)
every {
validateUser(name = any(), age = any(), email = "")
} returns listOf(expectedErrorState)
// When
viewModel.uiState.test {
// Then
awaitItem().errors.mandatoryEmailError `should be equal to` null
viewModel.onViewEvent(CreateViewEvent.OnCreateClicked)
awaitItem().errors.mandatoryEmailError `should be equal to` expectedErrorState.resId
expectNoEvents()
}
verify(exactly = 1) {
validateUser(name = any(), age = any(), email = "")
}
verify(exactly = 0) {
createUser(name = any(), age = any(), email = any())
}
}
@Test
fun `when create button is clicked, if multiple fields are empty the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`()
val expectedNameErrorState = CreateResultType.Error.NameMandatory(R.string.error_create_mandatory_field)
val expectedAgeErrorState = CreateResultType.Error.AgeMandatory(R.string.error_create_mandatory_field)
val expectedEmailErrorState = CreateResultType.Error.EmailMandatory(R.string.error_create_mandatory_field)
every {
validateUser(name = "", age = "", email = "")
} returns listOf(
expectedNameErrorState,
expectedAgeErrorState,
expectedEmailErrorState,
)
// When
viewModel.uiState.test {
// Then
awaitItem().errors.run {
mandatoryNameError `should be equal to` null
mandatoryAgeError `should be equal to` null
invalidAgeError `should be equal to` null
mandatoryEmailError `should be equal to` null
}
viewModel.onViewEvent(CreateViewEvent.OnCreateClicked)
awaitItem().errors.mandatoryNameError `should be equal to` expectedNameErrorState.resId
awaitItem().errors.run {
mandatoryAgeError `should be equal to` expectedAgeErrorState.resId
invalidAgeError `should be equal to` null
}
awaitItem().errors.mandatoryEmailError `should be equal to` expectedEmailErrorState.resId
expectNoEvents()
}
verify(exactly = 1) {
validateUser(name = "", age = "", email = "")
}
verify(exactly = 0) {
createUser(name = any(), age = any(), email = any())
}
}
@Test
fun `if user id is not present in savedStateHandle, then edit mode is false in ui state`() = runTest {
// Given
`given the tested view model`()
// When
// Then
viewModel.uiState.test {
awaitItem().isEditMode `should be equal to` false
expectNoEvents()
}
verify(exactly = 0) {
getUser(any())
}
}
@Test
fun `if user id is present in savedStateHandle, then getUser use case is called and if successful, ui state is properly updated`() = runTest {
// Given
val expectedUserId = "3"
val expectedUserName = "Audrey"
val expectedUserAge = "25"
val expectedUserEmail = "[email protected]"
every {
getUser("3")
} returns Result.success(UserModel(
id = "3",
name = "Audrey",
age = 25,
email = "[email protected]"
))
`given the tested view model`(mapOf(Pair("userId", expectedUserId)))
// When
// Then
viewModel.uiState.test {
awaitItem().run {
isEditMode `should be equal to` false
name `should be equal to` ""
age `should be equal to` ""
email `should be equal to` ""
}
awaitItem().run {
isEditMode `should be equal to` true
name `should be equal to` expectedUserName
age `should be equal to` expectedUserAge
email `should be equal to` expectedUserEmail
}
expectNoEvents()
}
verify(exactly = 1) {
getUser(expectedUserId)
}
}
@Test
fun `if user id is present in savedStateHandle, then getUser use case is called and if it fails, the error snackbar effect is called`() = runTest {
// Given
val expectedUserId = "3"
every {
getUser("3")
} returns Result.failure(Exception("some exception"))
`given the tested view model`(mapOf(Pair("userId", expectedUserId)))
// When
// Then
viewModel.uiState.test {
awaitItem().run {
isEditMode `should be equal to` false
name `should be equal to` ""
age `should be equal to` ""
email `should be equal to` ""
}
expectNoEvents()
}
viewModel.effectsChannel.receive() `should be equal to` CreateViewModelEffect.DisplaySnackbar(resId = R.string.error_create_generic)
verify(exactly = 1) {
getUser(expectedUserId)
}
}
@Test
fun `when update button is clicked, if inputs are valid and update operation succeeds, the correct snackbar event is triggered and the state is cleared`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
`given that get user returns john doe of id 1`()
every {
validateUser(name = "john", age = "30", email = "[email protected]")
} returns emptyList()
every {
updateUser(id = "1", name = "john", age = "30", email = "[email protected]")
} returns Result.success(true)
val expectedSnackbarEvent = CreateViewModelEffect.DisplaySnackbar(R.string.snackbar_msg_user_updated)
// Then
viewModel.uiState.test {
// initial state
awaitItem().run {
name `should be equal to` ""
age `should be equal to` ""
email `should be equal to` ""
}
// state after get user
awaitItem().run {
name `should be equal to` "john"
age `should be equal to` "30"
email `should be equal to` "[email protected]"
}
// When
viewModel.updateState(CreateUiState(name = "johnny", age = "31", email = "[email protected]"))
// updated state
awaitItem().run {
name `should be equal to` "johnny"
age `should be equal to` "31"
email `should be equal to` "[email protected]"
}
viewModel.onViewEvent(CreateViewEvent.OnUpdateClicked)
// state after clearForm() is called
awaitItem().run {
name `should be equal to` ""
age `should be equal to` ""
email `should be equal to` ""
}
expectNoEvents()
}
viewModel.effectsChannel.receive() `should be equal to` expectedSnackbarEvent
verifyOrder {
getUser("1")
validateUser("johnny", "31", "[email protected]")
updateUser("1","johnny", "31", "[email protected]")
}
}
@Test
fun `when update button is clicked, if inputs are valid but update operation fails, the error snackbar event is triggered and the state is not cleared`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
`given that get user returns john doe of id 1`()
every {
validateUser(name = "johnny", age = "31", email = "[email protected]")
} returns emptyList()
every {
updateUser(id = "1", name = "johnny", age = "31", email = "[email protected]")
} returns Result.failure(Exception("Can't update user"))
val expectedSnackbarEvent = CreateViewModelEffect.DisplaySnackbar(R.string.error_create_generic)
// Then
viewModel.uiState.test {
// initial state
awaitItem().run {
name `should be equal to` ""
age `should be equal to` ""
email `should be equal to` ""
}
// state after GetUser
awaitItem().run {
name `should be equal to` "john"
age `should be equal to` "30"
email `should be equal to` "[email protected]"
}
// When
viewModel.updateState(CreateUiState(name = "johnny", age = "31", email = "[email protected]"))
// updated state
awaitItem().run {
name `should be equal to` "johnny"
age `should be equal to` "31"
email `should be equal to` "[email protected]"
}
viewModel.onViewEvent(CreateViewEvent.OnUpdateClicked)
viewModel.currentState.run {
name `should be equal to` "johnny"
age `should be equal to` "31"
email `should be equal to` "[email protected]"
}
expectNoEvents()
}
viewModel.effectsChannel.receive() `should be equal to` expectedSnackbarEvent
verifyOrder {
getUser("1")
validateUser("johnny", "31", "[email protected]")
updateUser("1","johnny", "31", "[email protected]")
}
}
@Test
fun `when update button is clicked, if name field is empty the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
`given that get user returns john doe of id 1`()
val expectedErrorState = CreateResultType.Error.NameMandatory(R.string.error_create_mandatory_field)
every {
validateUser(name = "", age = "30", email = "[email protected]")
} returns listOf(expectedErrorState)
// When
viewModel.uiState.test {
// initial state
awaitItem().errors.mandatoryNameError `should be equal to` null
// state after GetUser
awaitItem().errors.mandatoryNameError `should be equal to` null
// Then
viewModel.updateState(viewModel.currentState.copy(name = ""))
awaitItem().errors.mandatoryNameError `should be equal to` null
viewModel.onViewEvent(CreateViewEvent.OnUpdateClicked)
awaitItem().errors.mandatoryNameError `should be equal to` expectedErrorState.resId
expectNoEvents()
}
verifyOrder {
getUser("1")
validateUser(name = "", age = "30", email = "[email protected]")
}
verify(exactly = 0) {
updateUser(id = any(), name = any(), age = any(), email = any())
}
}
@Test
fun `when update button is clicked, if age field is empty the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
`given that get user returns john doe of id 1`()
val expectedErrorState = CreateResultType.Error.AgeMandatory(R.string.error_create_mandatory_field)
every {
validateUser(name = "john", age = "", email = "[email protected]")
} returns listOf(expectedErrorState)
// When
viewModel.uiState.test {
// initial state
awaitItem().errors.mandatoryAgeError `should be equal to` null
// state after GetUser
awaitItem().errors.mandatoryAgeError `should be equal to` null
// Then
viewModel.updateState(viewModel.currentState.copy(age = ""))
awaitItem().errors.mandatoryAgeError `should be equal to` null
viewModel.onViewEvent(CreateViewEvent.OnUpdateClicked)
awaitItem().errors.mandatoryAgeError `should be equal to` expectedErrorState.resId
expectNoEvents()
}
verifyOrder {
getUser("1")
validateUser(name = "john", age = "", email = "[email protected]")
}
verify(exactly = 0) {
updateUser(id = any(), name = any(), age = any(), email = any())
}
}
@Test
fun `when update button is clicked, if age field is invalid the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
`given that get user returns john doe of id 1`()
val expectedErrorState = CreateResultType.Error.InvalidAge(R.string.error_create_invalid_age)
every {
validateUser(name = "john", age = "abc", email = "[email protected]")
} returns listOf(expectedErrorState)
// When
viewModel.uiState.test {
// initial state
awaitItem().errors.invalidAgeError `should be equal to` null
// state after GetUser
awaitItem().errors.invalidAgeError `should be equal to` null
// Then
viewModel.updateState(viewModel.currentState.copy(age = "abc"))
awaitItem().errors.invalidAgeError `should be equal to` null
viewModel.onViewEvent(CreateViewEvent.OnUpdateClicked)
awaitItem().errors.invalidAgeError `should be equal to` expectedErrorState.resId
expectNoEvents()
}
verifyOrder {
getUser("1")
validateUser(name = "john", age = "abc", email = "[email protected]")
}
verify(exactly = 0) {
updateUser(id = any(), name = any(), age = any(), email = any())
}
}
@Test
fun `when update button is clicked, if email field is empty the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
`given that get user returns john doe of id 1`()
val expectedErrorState = CreateResultType.Error.EmailMandatory(R.string.error_create_mandatory_field)
every {
validateUser(name = "john", age = "30", email = "")
} returns listOf(expectedErrorState)
// When
viewModel.uiState.test {
// initial state
awaitItem().errors.mandatoryEmailError `should be equal to` null
// state after GetUser
awaitItem().errors.mandatoryEmailError `should be equal to` null
// Then
viewModel.updateState(viewModel.currentState.copy(email = ""))
awaitItem().errors.mandatoryEmailError `should be equal to` null
viewModel.onViewEvent(CreateViewEvent.OnUpdateClicked)
awaitItem().errors.mandatoryEmailError `should be equal to` expectedErrorState.resId
expectNoEvents()
}
verifyOrder {
getUser("1")
validateUser(name = "john", age = "30", email = "")
}
verify(exactly = 0) {
updateUser(id = any(), name = any(), age = any(), email = any())
}
}
@Test
fun `when update button is clicked, if multiple fields are empty the ui state is updated with the correct error state`() = runTest {
// Given
`given the tested view model`(mapOf(Pair("userId", "1")))
`given that get user returns john doe of id 1`()
val expectedNameErrorState = CreateResultType.Error.NameMandatory(R.string.error_create_mandatory_field)
val expectedAgeErrorState = CreateResultType.Error.AgeMandatory(R.string.error_create_mandatory_field)
val expectedEmailErrorState = CreateResultType.Error.EmailMandatory(R.string.error_create_mandatory_field)
every {
validateUser(name = "", age = "", email = "")
} returns listOf(
expectedNameErrorState,
expectedAgeErrorState,
expectedEmailErrorState,
)
// When
viewModel.uiState.test {
// initial state
awaitItem().errors.run {
mandatoryNameError `should be equal to` null
mandatoryAgeError `should be equal to` null
invalidAgeError `should be equal to` null
mandatoryEmailError `should be equal to` null
}
// after GetUser
awaitItem().errors.run {
mandatoryNameError `should be equal to` null
mandatoryAgeError `should be equal to` null
invalidAgeError `should be equal to` null
mandatoryEmailError `should be equal to` null
}
// Then
viewModel.updateState(viewModel.currentState.copy(name = "", age = "", email = ""))
awaitItem().errors.run {
mandatoryNameError `should be equal to` null
mandatoryAgeError `should be equal to` null
invalidAgeError `should be equal to` null
mandatoryEmailError `should be equal to` null
}
viewModel.onViewEvent(CreateViewEvent.OnUpdateClicked)
awaitItem().errors.mandatoryNameError `should be equal to` expectedNameErrorState.resId
awaitItem().errors.run {
mandatoryAgeError `should be equal to` expectedAgeErrorState.resId
invalidAgeError `should be equal to` null
}
awaitItem().errors.mandatoryEmailError `should be equal to` expectedEmailErrorState.resId
}
verifyOrder {
getUser("1")
validateUser(name = "", age = "", email = "")
}
verify(exactly = 0) {
updateUser(id = any(), name = any(), age = any(), email = any())
}
}
@After
fun tearDown() {
viewModel.effectsChannel.cancel()
}
private fun `given that get user returns john doe of id 1`() {
every {
getUser(userId = "1")
} returns Result.success(UserModel(id = "1", name = "john", age = 30, email = "[email protected]"))
}
private fun `given the tested view model`(savedStateHandleArgs: Map<String, Any?> = emptyMap()) {
viewModel = CreateViewModel(
savedStateHandle = SavedStateHandle(savedStateHandleArgs),
validateUser = validateUser,
createUser = createUser,
updateUser = updateUser,
getUser = getUser,
)
}
} | simple-crud/features/create/src/test/java/com/rafver/create/ui/CreateViewModelTest.kt | 2548284002 |
package com.rafver.create.domain.usecases
import com.rafver.create.R
import com.rafver.create.data.CreateResultType
import org.amshove.kluent.`should be equal to`
import org.junit.Test
class ValidateUserTest {
private lateinit var useCase: ValidateUser
@Test
fun `when name is empty, the correct error is returned`() {
// Given
`given the tested use case`()
val name = ""
val age = "30"
val email = "[email protected]"
val expectedResult = listOf(
CreateResultType.Error.NameMandatory(R.string.error_create_mandatory_field)
)
// When
val result = useCase(name, age, email)
// Then
result `should be equal to` expectedResult
}
@Test
fun `when age is empty, the correct error is returned`() {
// Given
`given the tested use case`()
val name = "John"
val age = ""
val email = "[email protected]"
val expectedResult = listOf(
CreateResultType.Error.AgeMandatory(R.string.error_create_mandatory_field)
)
// When
val result = useCase(name, age, email)
// Then
result `should be equal to` expectedResult
}
@Test
fun `when age is not an int number, the correct error is returned`() {
// Given
`given the tested use case`()
val name = "John"
val age = "abc"
val email = "[email protected]"
val expectedResult = listOf(
CreateResultType.Error.InvalidAge(R.string.error_create_invalid_age)
)
// When
val result = useCase(name, age, email)
// Then
result `should be equal to` expectedResult
}
@Test
fun `when email is empty, the correct error is returned`() {
// Given
`given the tested use case`()
val name = "John"
val age = "30"
val email = ""
val expectedResult = listOf(
CreateResultType.Error.EmailMandatory(R.string.error_create_mandatory_field)
)
// When
val result = useCase(name, age, email)
// Then
result `should be equal to` expectedResult
}
@Test
fun `when multiple fields are empty, the correct errors are returned`() {
// Given
`given the tested use case`()
val name = ""
val age = ""
val email = ""
val expectedResult = listOf(
CreateResultType.Error.NameMandatory(R.string.error_create_mandatory_field),
CreateResultType.Error.AgeMandatory(R.string.error_create_mandatory_field),
CreateResultType.Error.EmailMandatory(R.string.error_create_mandatory_field)
)
// When
val result = useCase(name, age, email)
// Then
result `should be equal to` expectedResult
}
private fun `given the tested use case`() {
useCase = ValidateUser()
}
} | simple-crud/features/create/src/test/java/com/rafver/create/domain/usecases/ValidateUserTest.kt | 2187312622 |
package com.rafver.create.domain.usecases
import com.rafver.core_data.repositories.UserRepository
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.amshove.kluent.`should be equal to`
import org.junit.Test
class CreateUserTest {
private val userRepository: UserRepository = mockk(relaxed = true)
private lateinit var useCase: CreateUser
@Test
fun `when use case is invoked, if age is not int, an error is thrown`() {
//Given
`given the tested use case`()
val name = "john"
val age = "abc"
val email = "[email protected]"
val expectedExceptionMessage = "User data validation failed"
// when
var caughtException: Exception? = null
var result: Result<Boolean>? = null
try {
result = useCase(name, age, email)
} catch (e: Exception) {
caughtException = e
}
// Then
result `should be equal to` null
caughtException?.message `should be equal to` expectedExceptionMessage
verify(exactly = 0) {
userRepository.createUser(any(), any(), any())
}
}
@Test
fun `when use case is invoked, if all params are valid but repo operation fails, fail result is returned`() {
//Given
`given the tested use case`()
val expectedName = "john"
val expectedAge = 20
val expectedEmail = "[email protected]"
val expectedException = Exception("Some Exception")
every { userRepository.createUser(
expectedName,
expectedAge,
expectedEmail
) } returns Result.failure(expectedException)
// when
val result = useCase(name = "john", age = "20", email = "[email protected]")
// Then
result.isFailure `should be equal to` true
result.exceptionOrNull() `should be equal to` expectedException
verify(exactly = 1) {
userRepository.createUser(expectedName, expectedAge, expectedEmail)
}
}
@Test
fun `when use case is invoked, if all params are valid and repo operation succeeds, success result is returned`() {
//Given
`given the tested use case`()
val name = "john"
val age = "20"
val email = "[email protected]"
val expectedResult = true
every { userRepository.createUser(any(), any(), any()) } returns Result.success<Boolean>(true)
// when
val result = useCase(name, age, email)
// Then
result.isSuccess `should be equal to` true
result.getOrNull() `should be equal to` expectedResult
}
private fun `given the tested use case`() {
useCase = CreateUser(userRepository = userRepository)
}
} | simple-crud/features/create/src/test/java/com/rafver/create/domain/usecases/CreateUserTest.kt | 1022502626 |
package com.rafver.create.ui
import androidx.lifecycle.SavedStateHandle
import com.rafver.core_domain.usecases.GetUser
import com.rafver.core_ui.viewmodel.BaseViewModel
import com.rafver.create.R
import com.rafver.create.data.CreateResultType
import com.rafver.create.domain.usecases.CreateUser
import com.rafver.create.domain.usecases.UpdateUser
import com.rafver.create.domain.usecases.ValidateUser
import com.rafver.create.ui.models.CreateUiState
import com.rafver.create.ui.models.CreateViewEvent
import com.rafver.create.ui.models.CreateViewModelEffect
import com.rafver.create.ui.navigation.EditArgs
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class CreateViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val validateUser: ValidateUser,
private val createUser: CreateUser,
private val updateUser: UpdateUser,
private val getUser: GetUser,
) : BaseViewModel<CreateUiState, CreateViewEvent, CreateViewModelEffect>(CreateUiState())
{
private val editArgs = EditArgs(savedStateHandle)
init {
onViewEvent(CreateViewEvent.OnInitialize)
}
override suspend fun handleViewEvent(event: CreateViewEvent) {
when(event) {
CreateViewEvent.OnInitialize -> {
if(editArgs.userId != null) {
val result = getUser(editArgs.userId)
val user = result.getOrNull()
if(user != null) {
updateState(currentState.copy(
isEditMode = true,
name = user.name,
age = user.age.toString(),
email = user.email,
))
} else {
handleException(Exception("User not found"))
}
}
}
CreateViewEvent.OnDiscardClicked -> {
clearForm()
onViewModelEffect(
CreateViewModelEffect.DisplaySnackbar(
resId = R.string.snackbar_msg_changes_discarded,
)
)
onViewModelEffect(CreateViewModelEffect.OnNameTextInputFocusRequest)
}
CreateViewEvent.OnCreateClicked,
CreateViewEvent.OnUpdateClicked -> {
val validationErrors = validateUser(
name = currentState.name,
age = currentState.age,
email = currentState.email,
)
if(validationErrors.isEmpty()) {
val messageResId: Int
val result =
when(event) {
CreateViewEvent.OnCreateClicked -> {
println("OnCreateClicked called!")
messageResId = R.string.snackbar_msg_user_created
createUser(currentState.name, currentState.age, currentState.email)
}
CreateViewEvent.OnUpdateClicked -> {
println("OnUpdateClicked called!")
val userId = editArgs.userId ?: throw IllegalStateException("Missing userId")
messageResId = R.string.snackbar_msg_user_updated
updateUser(userId, currentState.name, currentState.age, currentState.email)
}
else -> {
throw IllegalStateException("Operation can only be either CreateUser or UpdateUser here.")
}
}
if(result.isSuccess) {
clearForm()
onViewModelEffect(
CreateViewModelEffect.DisplaySnackbar(resId = messageResId)
)
} else {
val error = result.exceptionOrNull()
handleException(error)
}
} else {
validationErrors.forEach { error ->
when(error) {
is CreateResultType.Error.AgeMandatory -> {
updateState(
currentState.copy(
errors = currentState.errors.copy(mandatoryAgeError = error.resId)
)
)
}
is CreateResultType.Error.EmailMandatory -> {
updateState(
currentState.copy(
errors = currentState.errors.copy(mandatoryEmailError = error.resId)
)
)
}
is CreateResultType.Error.InvalidAge -> {
updateState(
currentState.copy(
errors = currentState.errors.copy(invalidAgeError = error.resId)
)
)
}
is CreateResultType.Error.NameMandatory -> {
updateState(
currentState.copy(
errors = currentState.errors.copy(mandatoryNameError = error.resId)
)
)
}
}
}
}
}
is CreateViewEvent.OnAgeChanged -> {
updateState(currentState.copy(
age = event.newValue,
errors = currentState.errors.copy(mandatoryAgeError = null, invalidAgeError = null)
))
}
is CreateViewEvent.OnEmailChanged -> {
updateState(currentState.copy(
email = event.newValue,
errors = currentState.errors.copy(mandatoryEmailError = null)
))
}
is CreateViewEvent.OnNameChanged -> {
updateState(currentState.copy(
name = event.newValue,
errors = currentState.errors.copy(mandatoryNameError = null)
))
}
}
}
override fun handleException(error: Throwable?) {
println("An error has occurred: ${error?.message}")
when(error) {
else -> {
onViewModelEffect(
CreateViewModelEffect.DisplaySnackbar(
resId = R.string.error_create_generic,
)
)
}
}
}
private fun clearForm() {
updateState(currentState.copy(name = "", age = "", email = ""))
}
} | simple-crud/features/create/src/main/java/com/rafver/create/ui/CreateViewModel.kt | 4214090685 |
package com.rafver.create.ui.navigation
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.SavedStateHandle
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import com.rafver.create.ui.CreateScreen
import com.rafver.create.ui.CreateViewModel
private const val navigationRoute = "create"
private const val userIdArg = "userId"
fun NavGraphBuilder.editScreen() {
composable("${navigationRoute}/{$userIdArg}") {
val viewModel: CreateViewModel = hiltViewModel<CreateViewModel>()
CreateScreen(viewModel = viewModel)
}
}
fun NavController.navigateToEdit(userId: String) {
this.navigate("${navigationRoute}/${userId}")
}
internal class EditArgs(val userId: String?) {
constructor(savedStateHandle: SavedStateHandle): this(savedStateHandle.get<String>(userIdArg))
}
| simple-crud/features/create/src/main/java/com/rafver/create/ui/navigation/CreateNavigation.kt | 3725169457 |
package com.rafver.create.ui.models
import androidx.annotation.StringRes
import com.rafver.core_ui.viewmodel.UiState
import com.rafver.core_ui.viewmodel.ViewEvent
import com.rafver.core_ui.viewmodel.ViewModelEffect
data class CreateUiState(
val name: String = "",
val age: String = "",
val email: String = "",
val loading: Boolean = false,
val errors: CreateUiErrorState = CreateUiErrorState(),
val isEditMode: Boolean = false,
): UiState
data class CreateUiErrorState(
@StringRes val mandatoryNameError: Int? = null,
@StringRes val mandatoryAgeError: Int? = null,
@StringRes val invalidAgeError: Int? = null,
@StringRes val mandatoryEmailError: Int? = null,
)
sealed class CreateViewEvent: ViewEvent {
data object OnInitialize: CreateViewEvent()
data class OnNameChanged(val newValue: String): CreateViewEvent()
data class OnAgeChanged(val newValue: String): CreateViewEvent()
data class OnEmailChanged(val newValue: String): CreateViewEvent()
data object OnDiscardClicked: CreateViewEvent()
data object OnCreateClicked: CreateViewEvent()
data object OnUpdateClicked: CreateViewEvent()
}
sealed class CreateViewModelEffect: ViewModelEffect {
data class DisplaySnackbar(@StringRes val resId: Int): CreateViewModelEffect()
data object OnNameTextInputFocusRequest: CreateViewModelEffect()
} | simple-crud/features/create/src/main/java/com/rafver/create/ui/models/CreateUiState.kt | 2537463096 |
package com.rafver.create.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
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.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
import com.rafver.core_ui.extensions.collectUiState
import com.rafver.core_ui.theme.Dimensions
import com.rafver.core_ui.theme.SimpleCRUDTheme
import com.rafver.create.R
import com.rafver.create.ui.models.CreateUiState
import com.rafver.create.ui.models.CreateViewEvent
import com.rafver.create.ui.models.CreateViewModelEffect
@Composable
fun CreateScreen(
viewModel: CreateViewModel = viewModel()
) {
val uiState by viewModel.collectUiState()
val onViewEvent = viewModel::onViewEvent
val focusRequester = remember { FocusRequester() }
val snackbarHostState = remember { SnackbarHostState() }
val context = LocalContext.current
LaunchedEffect(key1 = viewModel.effects) {
viewModel.effects.collect { effect ->
when(effect) {
is CreateViewModelEffect.DisplaySnackbar -> {
snackbarHostState.showSnackbar(context.getString(effect.resId))
}
CreateViewModelEffect.OnNameTextInputFocusRequest -> {
focusRequester.freeFocus()
}
}
}
}
Scaffold(
topBar = { CreateTopBar() },
snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
) { padding ->
CreateContent(
uiState = uiState,
onViewEvent = onViewEvent,
focusRequester = focusRequester,
modifier = Modifier.padding(padding)
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CreateTopBar() {
TopAppBar(
title = { Text(stringResource(id = R.string.title_create_user)) }
)
}
@Composable
private fun CreateContent(
uiState: CreateUiState,
onViewEvent: (CreateViewEvent) -> Unit,
focusRequester: FocusRequester,
modifier: Modifier = Modifier
) {
Surface(modifier = modifier) {
Column(
verticalArrangement = Arrangement.spacedBy(Dimensions.NORMAL_100),
modifier = Modifier
.fillMaxSize()
.padding(Dimensions.NORMAL_100)
.verticalScroll(state = rememberScrollState())
) {
OutlinedTextField(
value = uiState.name,
onValueChange = { newValue -> onViewEvent(CreateViewEvent.OnNameChanged(newValue)) },
label = { Text(stringResource(id = R.string.lbl_name)) },
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
isError = uiState.errors.mandatoryNameError != null,
maxLines = 1,
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Words,
imeAction = ImeAction.Next,
),
supportingText = {
uiState.errors.mandatoryNameError?.let {
Text(text = stringResource(id = it))
}
}
)
OutlinedTextField(
value = uiState.age,
onValueChange = { newValue -> onViewEvent(CreateViewEvent.OnAgeChanged(newValue)) },
label = { Text(stringResource(id = R.string.lbl_age)) },
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
maxLines = 1,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next,
),
isError = uiState.errors.mandatoryAgeError != null || uiState.errors.invalidAgeError != null,
supportingText = {
uiState.errors.mandatoryAgeError?.let {
Text(text = stringResource(id = it))
}
uiState.errors.invalidAgeError?.let {
Text(text = stringResource(id = it))
}
}
)
OutlinedTextField(
value = uiState.email,
onValueChange = { newValue -> onViewEvent(CreateViewEvent.OnEmailChanged(newValue)) },
label = { Text(stringResource(id = R.string.lbl_email)) },
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
maxLines = 1,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
capitalization = KeyboardCapitalization.None,
imeAction = ImeAction.Done,
),
isError = uiState.errors.mandatoryEmailError != null,
supportingText = {
uiState.errors.mandatoryEmailError?.let {
Text(text = stringResource(id = it))
}
}
)
Spacer(modifier = Modifier.weight(1f))
Row(modifier = Modifier.fillMaxWidth()) {
if(!uiState.isEditMode) {
Button(
enabled = uiState.name.isNotEmpty() || uiState.age.isNotEmpty() || uiState.email.isNotEmpty(),
modifier = Modifier.weight(1f),
onClick = { onViewEvent(CreateViewEvent.OnDiscardClicked) }
) {
Text(text = stringResource(id = R.string.action_discard))
}
}
Spacer(modifier = Modifier.size(Dimensions.NORMAL_100))
Button(
modifier = Modifier.weight(1f),
onClick = {
if(uiState.isEditMode) {
onViewEvent(CreateViewEvent.OnUpdateClicked)
} else {
onViewEvent(CreateViewEvent.OnCreateClicked)
}
}
) {
Text(text = stringResource(
id = if(uiState.isEditMode) {
R.string.action_update
} else {
R.string.action_create
}
))
}
}
}
}
}
@Preview
@Composable
private fun PreviewCreateScreen() {
SimpleCRUDTheme {
CreateScreen()
}
} | simple-crud/features/create/src/main/java/com/rafver/create/ui/CreateScreen.kt | 2577937242 |
package com.rafver.create.data
import androidx.annotation.StringRes
sealed class CreateResultType {
sealed class Error: CreateResultType() {
data class NameMandatory(@StringRes val resId: Int): Error()
data class AgeMandatory(@StringRes val resId: Int): Error()
data class InvalidAge(@StringRes val resId: Int): Error()
data class EmailMandatory(@StringRes val resId: Int): Error()
}
} | simple-crud/features/create/src/main/java/com/rafver/create/data/CreateResultType.kt | 131380690 |
package com.rafver.create.domain.usecases
import com.rafver.create.R
import com.rafver.create.data.CreateResultType
import javax.inject.Inject
class ValidateUser @Inject constructor() {
operator fun invoke(name: String, age: String, email: String): List<CreateResultType.Error> {
val errors = mutableListOf<CreateResultType.Error>()
if(name.isEmpty()) {
errors.add(CreateResultType.Error.NameMandatory(R.string.error_create_mandatory_field))
}
if(age.isEmpty()) {
errors.add(CreateResultType.Error.AgeMandatory(R.string.error_create_mandatory_field))
} else {
age.toIntOrNull()
?: errors.add(CreateResultType.Error.InvalidAge(R.string.error_create_invalid_age))
}
if(email.isEmpty()) {
errors.add(CreateResultType.Error.EmailMandatory(R.string.error_create_mandatory_field))
}
return errors
}
} | simple-crud/features/create/src/main/java/com/rafver/create/domain/usecases/ValidateUser.kt | 1385932736 |
package com.rafver.create.domain.usecases
import com.rafver.core_data.repositories.UserRepository
import javax.inject.Inject
class UpdateUser @Inject constructor(private val userRepository: UserRepository) {
operator fun invoke(id: String, name: String, age: String, email: String): Result<Boolean> {
val ageInt = age.toIntOrNull() ?: throw IllegalStateException("User data validation failed")
return userRepository.updateUser(id, name, ageInt, email)
}
} | simple-crud/features/create/src/main/java/com/rafver/create/domain/usecases/UpdateUser.kt | 3932435354 |
package com.rafver.create.domain.usecases
import com.rafver.core_data.repositories.UserRepository
import javax.inject.Inject
class CreateUser @Inject constructor(private val userRepository: UserRepository) {
operator fun invoke(name: String, age: String, email: String): Result<Boolean> {
val ageInt = age.toIntOrNull() ?: throw IllegalStateException("User data validation failed")
return userRepository.createUser(name, ageInt, email)
}
} | simple-crud/features/create/src/main/java/com/rafver/create/domain/usecases/CreateUser.kt | 2738500316 |
package com.example.riyadal_qulub
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("com.example.riyadal_qulub", appContext.packageName)
}
} | RiyadAl-QulubComposed/app/src/androidTest/java/com/example/riyadal_qulub/ExampleInstrumentedTest.kt | 1312277566 |
package com.example.riyadal_qulub
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)
}
} | RiyadAl-QulubComposed/app/src/test/java/com/example/riyadal_qulub/ExampleUnitTest.kt | 3669414954 |
package com.example.riyadal_qulub.ui.navigation
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemColors
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.painterResource
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavController
import com.example.riyadal_qulub.R
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.Secondary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
@Composable
fun NavBar(backStackEntry: NavBackStackEntry?, navController: NavController) {
NavigationBar(
containerColor = Secondary,
contentColor = Primary
) {
NavigationBarItem(
selected = backStackEntry?.destination?.route == Screen.HomeScreen.route,
onClick = { navController.navigate(Screen.HomeScreen.route) },
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_home),
contentDescription = "Home icon"
)
},
label = {
Text(text = "الرئيسية", fontFamily = rubikSansFamily)
}
)
NavigationBarItem(
selected = backStackEntry?.destination?.route == Screen.StatisticsScreen.route,
onClick = { navController.navigate(Screen.StatisticsScreen.route) },
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_statistics),
contentDescription = "statistics icon"
)
},
label = {
Text(text = "الإحصائيات", fontFamily = rubikSansFamily)
}
)
NavigationBarItem(
selected = backStackEntry?.destination?.route == Screen.SettingsScreen.route,
onClick = { navController.navigate(Screen.SettingsScreen.route) },
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_setting),
contentDescription = "setting"
)
},
label = {
Text(text = "الإعدادات", fontFamily = rubikSansFamily)
}
)
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/navigation/NavigationBar.kt | 2729650151 |
package com.example.riyadal_qulub.ui.navigation
import android.content.Context
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.riyadal_qulub.ui.screens.addingWirdScreen.AddWirdScreen
import com.example.riyadal_qulub.ui.screens.authenticate.signin.SignInScreen
import com.example.riyadal_qulub.ui.screens.authenticate.signup.SignUpScreen
import com.example.riyadal_qulub.ui.screens.homeScreen.HomeScreen
import com.example.riyadal_qulub.ui.screens.onBoarding.OnBoardingScreen
import com.example.riyadal_qulub.ui.screens.settings.SettingsScreen
import com.example.riyadal_qulub.ui.screens.statisticsScreen.StatisticsScreen
import com.example.riyadal_qulub.ui.screens.wirdScreen.WirdScreen
@Composable
fun Navigation(innerPadding: PaddingValues, navController: NavHostController, context: Context) {
val sharedPreferences = context.getSharedPreferences("MyApp", Context.MODE_PRIVATE)
val hasSeenOnboarding = sharedPreferences.getBoolean("hasSeenOnboarding", false)
val hasSignedIn = sharedPreferences.getBoolean("hasSignedIn", false)
val startDestination =
when {
!hasSeenOnboarding -> Screen.OnBoardingScreen.route
!hasSignedIn -> Screen.SignInScreen.route
else -> Screen.HomeScreen.route
}
NavHost(navController = navController, startDestination = startDestination) {
composable(Screen.OnBoardingScreen.route) {
OnBoardingScreen(navController = navController, context = context)
}
composable(Screen.HomeScreen.route) {
HomeScreen(navController = navController, padding = innerPadding)
}
composable(Screen.AddWirdScreen.route) {
AddWirdScreen(navController = navController)
}
composable(Screen.SettingsScreen.route) {
SettingsScreen(context = context)
}
composable(Screen.StatisticsScreen.route) {
StatisticsScreen(navController = navController, padding = innerPadding)
}
composable(Screen.WirdScreen.route("{wirdId}")) { backStackEntry ->
val arguments = backStackEntry.arguments
val wirdId = arguments?.getString("wirdId")
if (wirdId != null) {
WirdScreen(wirdId = wirdId.toInt(), navController = navController)
}
}
composable(Screen.SignInScreen.route) {
SignInScreen(navController = navController, context = context)
}
composable(Screen.SignUpScreen.route) {
SignUpScreen(navController = navController , context = context)
}
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/navigation/Navigation.kt | 837819474 |
package com.example.riyadal_qulub.ui.navigation
import androidx.navigation.NamedNavArgument
sealed class Screen(val route: String) {
data object OnBoardingScreen : Screen("on_boarding_screen")
data object HomeScreen : Screen("home_screen")
data object AddWirdScreen : Screen("add_wird_screen")
data object WirdDetailScreen : Screen("wird_detail_screen")
data object SettingsScreen : Screen("settings_screen")
data object StatisticsScreen : Screen("statistics_screen")
data object SignInScreen : Screen("sign_in_screen")
data object SignUpScreen : Screen("sign_up_screen")
data object WirdScreen : Screen("wird_screen/{wirdId}") {
fun route(wirdId: String) = "wird_screen/$wirdId"
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/navigation/Destination.kt | 3095354490 |
package com.example.riyadal_qulub.ui.screens.settings
import android.content.Context
import android.content.SharedPreferences
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.riyadal_qulub.R
import com.example.riyadal_qulub.ui.components.dialogs.AlertDialogExample
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
@Composable
fun SettingsScreen(
viewModel: SettingViewModel = hiltViewModel(),
context: Context
) {
val sharedPreferences = context.getSharedPreferences("MyApp", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
val openAlertDialog = remember { mutableStateOf(false) }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
) {
Text(
text = "الإعدادات",
textAlign = TextAlign.Center,
fontSize = 40.sp,
fontFamily = rubikSansFamily,
modifier = Modifier.fillMaxWidth(),
fontWeight = FontWeight.Bold,
color = Primary
)
SettingsItem("تسجيل الخروج",
onClick = {
viewModel.logout()
changeTheSharedPrefrences(editor)
}
)
SettingsItem(
"مسح جميع الأوراد",
//todo: add dialog to confirm
onClick = {
openAlertDialog.value = true
},
color = Color.Red
)
when {
openAlertDialog.value -> {
AlertDialogExample(
onDismissRequest = { openAlertDialog.value = false },
onConfirmation = {
openAlertDialog.value = false
viewModel.deleteAllWirds()
},
dialogTitle = "حذف جميع الأوراد",
dialogText = "هل انت متأكد من حذف جميع الأوراد ؟"
)
}
}
SettingsItem("التنبيهات")
SettingsItem("تواصل معنا")
SettingsItem("سياسة الخصوصية")
// SettingsItem("تغيير اللغة")
}
}
private fun changeTheSharedPrefrences(editor: SharedPreferences.Editor) {
editor.putBoolean(
"hasSignedIn",
false
)
editor.apply()
}
@Composable
fun SettingsItem(name: String, onClick: () -> Unit = {}, color: Color = Color.Black) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp)
.clickable {
onClick()
},
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painter = painterResource(id = R.drawable.ic_arrow),
contentDescription = "arrow",
tint = color
)
Text(
text = name,
textAlign = TextAlign.Right,
fontSize = 20.sp,
fontFamily = rubikSansFamily,
modifier = Modifier.fillMaxWidth(),
color = color
)
}
Spacer(modifier = Modifier.padding(8.dp))
Divider(modifier = Modifier.padding(1.dp), color = Color.LightGray)
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/settings/SettingsScreen.kt | 2185314522 |
package com.example.riyadal_qulub.ui.screens.settings
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.riyadal_qulub.domain.repository.WirdRepository
import com.google.firebase.auth.FirebaseAuth
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SettingViewModel @Inject constructor(
val repository: WirdRepository,
val auth: FirebaseAuth,
) : ViewModel() {
fun deleteAllWirds() {
viewModelScope.launch(Dispatchers.IO) {
repository.deleteAllWirds()
}
}
fun logout() {
auth.signOut()
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/settings/SettingViewModel.kt | 3980874153 |
package com.example.riyadal_qulub.ui.screens.authenticate.signup
import android.content.Context
import com.example.riyadal_qulub.ui.screens.authenticate.signin.SignInViewModel
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
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.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import com.example.riyadal_qulub.R
import com.example.riyadal_qulub.ui.navigation.Screen
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
@Composable
fun SignUpScreen(
viewModel: SignUpViewModel = hiltViewModel(), navController: NavController ,context: Context
) {
val state by viewModel.state.collectAsStateWithLifecycle()
val signInResult by viewModel.signUpResult.collectAsState()
val sharedPreferences = context.getSharedPreferences("MyApp", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "تسجيل حساب جديد",
textAlign = TextAlign.Center,
fontSize = 40.sp,
fontFamily = rubikSansFamily,
modifier = Modifier.fillMaxWidth(),
fontWeight = FontWeight.Bold,
color = Primary
)
OutlinedTextField(
value = state.email,
onValueChange = { viewModel.updateEmail(it) },
modifier = Modifier.fillMaxWidth(),
placeholder = {
Text(
text = "email",
fontFamily = rubikSansFamily,
textAlign = TextAlign.Right,
modifier = Modifier.fillMaxWidth()
)
})
Spacer(modifier = Modifier.padding(16.dp))
OutlinedTextField(
value = state.password,
onValueChange = { viewModel.updatePassword(it) },
placeholder = {
Text(
text = "password",
fontFamily = rubikSansFamily,
textAlign = TextAlign.Right,
modifier = Modifier.fillMaxWidth()
)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier
.fillMaxWidth()
)
Spacer(modifier = Modifier.padding(16.dp))
Text(
text = "تملك حساباً بالفعل ؟ سجل دخول ",
textAlign = TextAlign.Right,
modifier = Modifier.fillMaxWidth().clickable {
navController.navigate(Screen.SignInScreen.route)
},
fontFamily = rubikSansFamily,
fontSize = 16.sp,
color = Primary
)
Spacer(modifier = Modifier.padding(16.dp))
Button(
onClick = { viewModel.signUp(state.email, state.password) }, modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(text = "تسجيل الدخول", fontFamily = rubikSansFamily, fontSize = 16.sp)
}
if (signInResult == "Success") {
navController.navigate(Screen.HomeScreen.route)
editor.putBoolean(
"hasSignedIn",
true
)
editor.apply()
} else if (signInResult == "Failure") {
// todo Handle failure and loading
}
}
}
/*
@Preview
@Composable
fun SignInScreenPreview() {
SignInScreen(
)
}
*/
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/authenticate/signup/SignUpScreen.kt | 1748856369 |
package com.example.riyadal_qulub.ui.screens.authenticate.signup
import android.util.Log
import androidx.lifecycle.ViewModel
import com.example.riyadal_qulub.ui.screens.authenticate.signin.SignInViewState
import com.google.firebase.auth.FirebaseAuth
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
const val TAG = "signUpViewModel"
@HiltViewModel
class SignUpViewModel @Inject constructor(
val auth: FirebaseAuth
) : ViewModel() {
private val _signUpResult = MutableStateFlow<String?>(null)
val signUpResult: StateFlow<String?> get() = _signUpResult
private val _state = MutableStateFlow(SignInViewState())
val state = _state.asStateFlow()
fun signUp(email: String, password: String) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "createUserWithEmail:success")
_signUpResult.value = "Success"
} else {
Log.w(TAG, "createUserWithEmail:failure", task.exception)
_signUpResult.value = "Failure"
}
}
}
fun updateEmail(newEmail: String) {
_state.value = _state.value.copy(email = newEmail)
}
fun updatePassword(newPassword: String) {
_state.value = _state.value.copy(password = newPassword)
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/authenticate/signup/SignUpViewModel.kt | 1529144898 |
package com.example.riyadal_qulub.ui.screens.authenticate.signin
data class SignInViewState(
var email : String = "",
var password : String = "",
) | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/authenticate/signin/SignInViewState.kt | 53747784 |
package com.example.riyadal_qulub.ui.screens.authenticate.signin
import android.content.Context
import android.util.Log
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseAuth
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
const val TAG = "signInViewModel"
@HiltViewModel
class SignInViewModel @Inject constructor(
val auth: FirebaseAuth
) : ViewModel() {
private val _signInResult = MutableStateFlow<String?>(null)
val signInResult: StateFlow<String?> get() = _signInResult
private val _state = MutableStateFlow(SignInViewState())
val state = _state.asStateFlow()
fun signIn(email: String, password: String) {
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "createUserWithEmail:success")
_signInResult.value = "Success"
} else {
Log.w(TAG, "createUserWithEmail:failure", task.exception)
_signInResult.value = "Failure"
}
}
}
fun updateEmail(newEmail: String) {
_state.value = _state.value.copy(email = newEmail)
}
fun updatePassword(newPassword: String) {
_state.value = _state.value.copy(password = newPassword)
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/authenticate/signin/SignInViewModel.kt | 1270679129 |
package com.example.riyadal_qulub.ui.screens.authenticate.signin
import android.content.Context
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
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.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import com.example.riyadal_qulub.R
import com.example.riyadal_qulub.ui.navigation.Screen
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
@Composable
fun SignInScreen(
viewModel: SignInViewModel = hiltViewModel(), navController: NavController,context: Context
) {
val state by viewModel.state.collectAsStateWithLifecycle()
val signInResult by viewModel.signInResult.collectAsState()
val sharedPreferences = context.getSharedPreferences("MyApp", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "تسجيل الدخول",
textAlign = TextAlign.Center,
fontSize = 40.sp,
fontFamily = rubikSansFamily,
modifier = Modifier.fillMaxWidth(),
fontWeight = FontWeight.Bold,
color = Primary
)
Image(
painter = painterResource(id = R.drawable.img_auth),
contentDescription = "auth img",
modifier = Modifier.padding(16.dp)
)
OutlinedTextField(
value = state.email,
onValueChange = { viewModel.updateEmail(it) },
modifier = Modifier.fillMaxWidth(),
placeholder = {
Text(
text = "email",
fontFamily = rubikSansFamily,
textAlign = TextAlign.Right,
modifier = Modifier.fillMaxWidth()
)
})
Spacer(modifier = Modifier.padding(16.dp))
OutlinedTextField(
value = state.password,
onValueChange = { viewModel.updatePassword(it) },
placeholder = { Text("Password") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier
.fillMaxWidth()
)
Spacer(modifier = Modifier.padding(16.dp))
Text(
text = "هل انت مستخدم جديد؟ سجل حساب ",
textAlign = TextAlign.Right,
modifier = Modifier
.fillMaxWidth()
.clickable {
navController.navigate(Screen.SignUpScreen.route)
},
fontFamily = rubikSansFamily,
fontSize = 16.sp,
color = Primary
)
Spacer(modifier = Modifier.padding(16.dp))
Button(
onClick = { viewModel.signIn(state.email, state.password) }, modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(text = "تسجيل حساب جديد", fontFamily = rubikSansFamily, fontSize = 16.sp)
}
if (signInResult == "Success") {
navController.navigate(Screen.HomeScreen.route)
editor.putBoolean(
"hasSignedIn",
true
)
editor.apply()
} else if (signInResult == "Failure") {
// Handle failure
}
}
}
/*
@Preview
@Composable
fun SignInScreenPreview() {
SignInScreen(
)
}
*/
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/authenticate/signin/SignInScreen.kt | 631815829 |
package com.example.riyadal_qulub.ui.screens.addingWirdScreen
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.riyadal_qulub.domain.model.Wird
import com.example.riyadal_qulub.domain.repository.WirdRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import javax.inject.Inject
@HiltViewModel
class AddViewModel @Inject constructor(
val repository: WirdRepository
) :ViewModel(){
private val _state =MutableStateFlow(AddWirdViewState())
val state = _state
fun updateWirdName(newName: String) {
state.value = state.value.copy(wirdName = newName)
}
fun updateIsMorningWird(isMorningWird: Boolean) {
state.value = state.value.copy(isMorningWird = isMorningWird)
}
fun updateIsEveningWird(isEveningWird: Boolean) {
state.value = state.value.copy(isEveningWird = isEveningWird)
}
fun addWird(){
viewModelScope.launch(Dispatchers.IO) {
repository.insertWird(
Wird(
name = state.value.wirdName,
isMorningWird = state.value.isMorningWird,
isEveningWird = state.value.isEveningWird,
wirdDays = state.value.daysCheckedState.value,
startDate = state.value.startedDate,
doneDays = listOf() // Provide an empty list for doneDays
)
)
}
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/addingWirdScreen/AddViewModel.kt | 474662404 |
package com.example.riyadal_qulub.ui.screens.addingWirdScreen
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.example.riyadal_qulub.domain.model.WeekDays
import java.time.LocalDateTime
data class AddWirdViewState (
var wirdName: String = "",
val repeatedDays :List<WeekDays> = emptyList(),
var startedDate:LocalDateTime = LocalDateTime.now(),
val isMorningWird:Boolean = false,
val isEveningWird:Boolean = false,
val wirdNotificationTime:LocalDateTime = LocalDateTime.now(),
val daysCheckedState: MutableState<List<WeekDays>> = mutableStateOf(emptyList()),
) | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/addingWirdScreen/AddWirdViewState.kt | 3611429810 |
package com.example.riyadal_qulub.ui.screens.addingWirdScreen
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TimeInput
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import com.example.riyadal_qulub.R
import com.example.riyadal_qulub.ui.components.ClickableWeekDays
import com.example.riyadal_qulub.ui.components.dialogs.MyDatePickerDialog
import com.example.riyadal_qulub.ui.components.dialogs.TimePickerDialog
import com.example.riyadal_qulub.ui.navigation.Screen
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
import com.example.riyadal_qulub.util.convertMillisToDate
import com.example.riyadal_qulub.util.formatLocalDateTime
import com.example.riyadal_qulub.util.toLocalDateTime
import java.time.LocalDateTime
private const val TAG = "AddWirdScreen"
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddWirdScreen(
viewModel: AddViewModel = hiltViewModel(), navController: NavController
) {
val timePickerState = rememberTimePickerState()
val state by viewModel.state.collectAsStateWithLifecycle()
val datePickerState = rememberDatePickerState()
var showDatePicker by remember {
mutableStateOf(false)
}
val selectedDate = datePickerState.selectedDateMillis?.let {
convertMillisToDate(it)
} ?: ""
val timeDialogState = remember { mutableStateOf(false) }
when (timeDialogState.value) {
true -> {
TimePickerDialog(
onCancel = { timeDialogState.value = false },
onConfirm = {
timeDialogState.value = false
Log.i(TAG, "AddWirdScreen: ${timePickerState.hour}:${timePickerState.minute}")
Log.i(TAG, timePickerState.toLocalDateTime().toString())
},
content = {
TimeInput(
state = timePickerState,
modifier = Modifier.padding(16.dp)
)
}
)
}
false -> {
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
OutlinedTextField(
value = state.wirdName,
onValueChange = { viewModel.updateWirdName(it) },
modifier = Modifier.fillMaxWidth(),
label = {
Text(
text = "اسم الورد",
fontFamily = rubikSansFamily,
textAlign = TextAlign.Right,
modifier = Modifier.fillMaxWidth()
)
},
//todo add colors
)
Divider(modifier = Modifier.padding(vertical = 16.dp))
Text(
text = "تكرار الورد",
fontFamily = rubikSansFamily,
fontSize = 24.sp,
color = Color.Black,
textAlign = TextAlign.End,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.padding(8.dp))
ClickableWeekDays(
daysChecked = state.daysCheckedState
)
Divider(modifier = Modifier.padding(vertical = 16.dp))
Text(
text = "تنبيهات الورد",
fontFamily = rubikSansFamily,
fontSize = 24.sp,
color = Color.Black,
textAlign = TextAlign.End,
modifier = Modifier.fillMaxWidth()
)
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Add",
tint = Primary,
modifier = Modifier
.size(12.dp) // Adjust the size as needed
.clickable {
timeDialogState.value = true
}
)
Text(text = "إضافة تنبيه",
fontFamily = rubikSansFamily,
fontSize = 12.sp,
color = Primary,
textAlign = TextAlign.End,
modifier = Modifier.clickable {
})
}
Divider(modifier = Modifier.padding(vertical = 16.dp))
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Icon(painter = painterResource(id = R.drawable.ic_calender), contentDescription = "Add",
modifier = Modifier
.size(24.dp)
.clickable {
showDatePicker = true
})
Spacer(modifier = Modifier.padding(4.dp))
Text(
text = if (state.startedDate.dayOfMonth == LocalDateTime.now().dayOfMonth) "بداية الورد من اليوم " else "بداية الورد من ${
formatLocalDateTime(
state.startedDate
)
}",
fontFamily = rubikSansFamily,
fontSize = 24.sp,
color = Primary,
textAlign = TextAlign.End
)
}
if (showDatePicker) {
MyDatePickerDialog(onDateSelected = {
state.startedDate = it
}, onDismiss = { showDatePicker = false })
}
Divider(modifier = Modifier.padding(vertical = 16.dp))
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Icon(painter = painterResource(id = R.drawable.ic_sun), contentDescription = "Add",
modifier = Modifier
.size(24.dp)
.clickable {
})
Spacer(modifier = Modifier.padding(4.dp))
Text(
text = "معاد الورد",
fontFamily = rubikSansFamily,
fontSize = 24.sp,
color = Primary,
textAlign = TextAlign.End
)
}
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(checked = state.isMorningWird,
onCheckedChange = { viewModel.updateIsMorningWird(it) })
Spacer(modifier = Modifier.padding(4.dp))
Text(text = "صباحاً",
fontFamily = rubikSansFamily,
fontSize = 12.sp,
color = Color.Black,
textAlign = TextAlign.End,
modifier = Modifier.clickable {
})
}
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(checked = state.isEveningWird,
onCheckedChange = { viewModel.updateIsEveningWird(it) })
Spacer(modifier = Modifier.padding(4.dp))
Text(text = "مساءً",
fontFamily = rubikSansFamily,
fontSize = 12.sp,
color = Color.Black,
textAlign = TextAlign.End,
modifier = Modifier.clickable {
})
}
Button(
onClick = {
viewModel.addWird()
navController.navigate(Screen.HomeScreen.route)
},
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 62.dp, horizontal = 16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Primary,
)
) {
Text(text = "إضافة الورد")
}
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/addingWirdScreen/AddWirdScreen.kt | 3111705746 |
package com.example.riyadal_qulub.ui.screens.homeScreen
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.riyadal_qulub.data.local.db.WirdDatabase
import com.example.riyadal_qulub.domain.model.Wird
import com.example.riyadal_qulub.domain.repository.WirdRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import javax.inject.Inject
private const val TAG = "HomeViewModel"
@HiltViewModel
open class HomeViewModel @Inject constructor(
private val repository: WirdRepository,
// private val database : WirdDatabase
) : ViewModel() {
private val _state = MutableStateFlow(HomeViewState())
val state = _state.asStateFlow()
fun updateDoneDays(wird: Wird, doneDate: LocalDateTime) {
viewModelScope.launch(Dispatchers.IO) {
val currentWird = repository.getWirdById(wird.id)
val currentDoneDates = currentWird.doneDays
// Check if the Wird is already done
if (currentDoneDates.contains(doneDate)) {
Log.i(TAG, "updateDoneDays: Wird is already done")
//todo add functionality to remove the wird from the list of done wirds
return@launch
}
val updatedDoneDates = currentDoneDates.toMutableList().apply { add(doneDate) }
repository.updateDoneDates(wird.id, updatedDoneDates)
val updatedWird = repository.getWirdById(wird.id)
_state.value = state.value.copy(wirds = state.value.wirds.map {
if (it.id == updatedWird.id) updatedWird else it
})
}
}
fun deleteWird(wird: Wird) {
viewModelScope.launch(Dispatchers.IO) {
repository.deleteWird(wird)
_state.value = state.value.copy(wirds = state.value.wirds.filter { it.id != wird.id })
}
}
init {
getWirds()
}
private fun getWirds() {
viewModelScope.launch(Dispatchers.IO) {
val wirds = repository.getAllWirds()
_state.value = state.value.copy(wirds = wirds)
Log.i(TAG, "getWirds: Done ")
}
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/homeScreen/HomeViewModel.kt | 1677655185 |
package com.example.riyadal_qulub.ui.screens.homeScreen
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.example.riyadal_qulub.domain.model.Wird
import java.time.LocalDate
import java.time.LocalDateTime
data class HomeViewState (
val isLoading: Boolean = false,
val isEmpty : Boolean = false,
val wirds:List<Wird> = emptyList(),
var selectedDate: MutableState<LocalDate> = mutableStateOf(LocalDate.now()),
var doneDays :List<LocalDateTime> = emptyList(),
) | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/homeScreen/HomeViewState.kt | 1253976521 |
package com.example.riyadal_qulub.ui.screens.homeScreen
import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.FabPosition
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import com.example.riyadal_qulub.R
import com.example.riyadal_qulub.ui.components.dialogs.AlertDialogExample
import com.example.riyadal_qulub.ui.components.calender.WeeklyCalendarItem
import com.example.riyadal_qulub.ui.components.WirdItem
import com.example.riyadal_qulub.ui.navigation.Screen
import com.example.riyadal_qulub.ui.theme.Secondary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
import com.example.riyadal_qulub.util.convertDayOfWeekToWeekDays
import com.kizitonwose.calendar.compose.WeekCalendar
import com.kizitonwose.calendar.compose.weekcalendar.rememberWeekCalendarState
import java.time.LocalDate
private const val TAG = "HomeScreen"
@Composable
fun HomeScreen(
padding: PaddingValues,
viewModel: HomeViewModel = hiltViewModel(),
navController: NavController
) {
val state by viewModel.state.collectAsStateWithLifecycle()
val weekCalendarState = rememberWeekCalendarState(
startDate = LocalDate.now(),
endDate = LocalDate.now().plusDays(6)
)
val openAlertDialog = remember { mutableStateOf(false) }
//todo add loading state
//todo fix the bug of the wirds filtering
Scaffold(
modifier = Modifier
.padding(padding)
.fillMaxSize(),
floatingActionButton = {
FloatingActionButton(
onClick = { navController.navigate(Screen.AddWirdScreen.route) },
containerColor = Secondary
) {
Icon(Icons.Filled.Add, contentDescription = "Add", tint = Color.White)
}
},
floatingActionButtonPosition = FabPosition.End
) { innerPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.padding(8.dp)
) {
WeekCalendar(
state = weekCalendarState,
dayContent = {
WeeklyCalendarItem(it, onClick = { day ->
state.selectedDate.value = day.date
}, selectedDate = state.selectedDate.value)
}
)
Spacer(modifier = Modifier.padding(8.dp))
// Get the selected day of the week
val selectedDayOfWeek = state.selectedDate.value.dayOfWeek
val selectedWeekDay = convertDayOfWeekToWeekDays(selectedDayOfWeek)
// Filter the wirds based on the selected day of the week
val filteredWirds = state.wirds.filter { it.wirdDays.contains(selectedWeekDay) }
LazyColumn(
modifier = Modifier
.weight(1f)
.padding(8.dp)
) {
items(filteredWirds.size) { index ->
val wird = remember { mutableStateOf(filteredWirds[index]) }
WirdItem(
wird = wird,
onButtonClicked = {
viewModel.updateDoneDays(
wird.value,
state.selectedDate.value.atStartOfDay()
)
state.doneDays = state.doneDays.toMutableList().apply {
add(state.selectedDate.value.atStartOfDay())
}
},
onWirdClicked = {
Log.i(TAG, it.name)
Log.i(TAG, it.id.toString())
navController.navigate(Screen.WirdScreen.route(it.id.toString()))
},
onWirdLongPressed = {
Log.i(
TAG,
"wird."
)
openAlertDialog.value = true
},
state = state
)
when {
openAlertDialog.value -> {
AlertDialogExample(
onDismissRequest = { openAlertDialog.value = false },
onConfirmation = {
openAlertDialog.value = false
viewModel.deleteWird(wird.value)
},
dialogTitle = "حذف الورد",
dialogText = "هل تريد حذف الورد؟",
)
}
}
Spacer(modifier = Modifier.padding(vertical = 8.dp))
// Print the selected days for the Wird
Log.i("Wird Days", "${wird.value.name}: ${wird.value.wirdDays}")
Log.i(
"Filtered Wirds",
filteredWirds.joinToString { "${it.name}: ${it.wirdDays}" })
}
}
if (filteredWirds.isEmpty()) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Icon(
painter = painterResource(id = R.drawable.ic_empty),
contentDescription = "empty",
modifier = Modifier.size(100.dp),
tint = Secondary
)
Text(
text = "لم يتم إضافة اوراد بعد",
fontSize = 20.sp,
fontFamily = rubikSansFamily,
color = Color.Black,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/homeScreen/HomeScreen.kt | 135804822 |
package com.example.riyadal_qulub.ui.screens.wirdScreen
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import com.example.riyadal_qulub.ui.components.calender.MonthCalenderItem
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
private const val TAG = "WirdScreen"
@Composable
fun WirdScreen(
wirdId: Int,
viewModel: WirdViewModel = hiltViewModel(),
navController: NavController
) {
val state by viewModel.state.collectAsStateWithLifecycle()
Log.i(TAG, "WirdScreen: $wirdId")
viewModel.getWirdById(wirdId)
Column(modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) {
Text(
modifier = Modifier.padding(16.dp),
text = state.wird.name,
fontSize = 24.sp,
fontFamily = rubikSansFamily,
color = Primary
)
// todo you need to make your calculation for the card info
Card(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp), horizontalAlignment = Alignment.End
) {
Text(
text = "ملخص الورد",
fontSize = 12.sp,
fontFamily = rubikSansFamily,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.padding(8.dp))
Text(
text = "عدد أيام الإنجاز في الشهر ",
fontSize = 12.sp,
fontFamily = rubikSansFamily
)
Text(
text = "اجمالي عدد أيام الإنجاز 77 يوم",
fontSize = 12.sp,
fontFamily = rubikSansFamily
)
Text(
text = "نسبة انجاز الشهر 93%",
fontSize = 12.sp,
fontFamily = rubikSansFamily
)
Text(
text = "الإستمرارية 5 أيام",
fontSize = 12.sp,
fontFamily = rubikSansFamily
)
}
}
MonthCalenderItem(state.wird)
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/wirdScreen/WirdScreen.kt | 1193931776 |
package com.example.riyadal_qulub.ui.screens.wirdScreen
import com.example.riyadal_qulub.domain.model.Wird
import java.time.LocalDateTime
data class WirdViewState(
val wird: Wird = Wird(),
) | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/wirdScreen/WirdViewState.kt | 2198549602 |
package com.example.riyadal_qulub.ui.screens.wirdScreen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.riyadal_qulub.domain.model.Wird
import com.example.riyadal_qulub.domain.repository.WirdRepository
import com.example.riyadal_qulub.ui.screens.addingWirdScreen.AddWirdViewState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class WirdViewModel @Inject constructor(
val repository: WirdRepository
) : ViewModel(){
private val _state = MutableStateFlow(WirdViewState())
val state = _state
fun getWirdById(wirdId: Int) {
viewModelScope.launch(Dispatchers.IO) {
val wird = repository.getWirdById(wirdId)
withContext(Dispatchers.Main) {
if (wird != null) {
_state.value = state.value.copy(wird = wird)
} else {
// Handle the case where the Wird is not found
}
}
}
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/wirdScreen/WirdViewModel.kt | 2763259003 |
package com.example.riyadal_qulub.ui.screens.statisticsScreen
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.riyadal_qulub.ui.components.charts.WeeklyChart
import com.example.riyadal_qulub.ui.components.charts.WeeklyProgress
private const val TAG = "StatisticsScreen"
@Composable
fun StatisticsScreen(
padding: PaddingValues,
viewModel: StatisticsViewModel = hiltViewModel(),
navController: NavController
) {
val state by viewModel.state.collectAsState(
initial = StatisticsViewState(
listOf(
0f,
0f,
0f,
0f,
0f,
0f,
0f
)
)
)
Log.d(TAG, "Week Percentage: ${state.weekPercentage}")
if (state.weekPercentage != listOf(0f, 0f, 0f, 0f, 0f, 0f, 0f)) {
Column(modifier = Modifier
.padding(padding)
.padding(16.dp)
.fillMaxSize()) {
WeeklyProgress(
weekPrev = state.weekPercentage
)
Spacer(modifier = Modifier.padding(16.dp))
WeeklyChart(
state.weekPercentage[0],
state.weekPercentage[1],
state.weekPercentage[2],
state.weekPercentage[3],
state.weekPercentage[4],
state.weekPercentage[5],
state.weekPercentage[6]
)
}
}else{
Column(modifier = Modifier
.padding(padding)
.padding(16.dp)
.fillMaxSize()) {
WeeklyProgress(
weekPrev = listOf(0f,0f,0f,0f,0f,0f,0f)
)
Spacer(modifier = Modifier.padding(16.dp))
WeeklyChart(
0f,
0f,
0f,
0f,
0f,
0f,
0f
)
}
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/statisticsScreen/StatisticsScreen.kt | 4232584484 |
package com.example.riyadal_qulub.ui.screens.statisticsScreen
data class StatisticsViewState (
val weekPercentage: List<Float> = listOf(0f, 0f, 0f, 0f, 0f, 0f, 0f)
) | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/statisticsScreen/StatisticsViewState.kt | 2394324942 |
package com.example.riyadal_qulub.ui.screens.statisticsScreen
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.riyadal_qulub.domain.model.WeekDays
import com.example.riyadal_qulub.domain.model.Wird
import com.example.riyadal_qulub.domain.repository.WirdRepository
import com.example.riyadal_qulub.util.convertDayOfWeekToWeekDays
import com.example.riyadal_qulub.util.daysOfWeek
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.temporal.TemporalAdjusters
import javax.inject.Inject
private const val TAG = "StatisticsViewModel"
@HiltViewModel
class StatisticsViewModel @Inject constructor(
val repository: WirdRepository
) : ViewModel() {
init {
getDailyWirdsAndCalculateDonePercentage()
}
private val _state = MutableStateFlow(StatisticsViewState())
val state = _state.asStateFlow()
// if the wird day is not selected but it's showing in the home screen
fun getDailyWirdsAndCalculateDonePercentage() {
viewModelScope.launch(Dispatchers.IO) {
// Get the current date
val currentDate = LocalDate.now()
// Calculate the start and end of the week
val startOfWeek = currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SATURDAY))
val endOfWeek = currentDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY))
// Create a mutable list for weekPrestating
val weekPrestating = mutableListOf<Float>()
// For each day of the week
for (dayOfWeek in daysOfWeek) {
// Convert the DayOfWeek to WeekDays
val weekDay = convertDayOfWeekToWeekDays(dayOfWeek)
// Get all the Wirds that should be done on that day
val dailyWirds = repository.getWirdByWirdDays(listOf(weekDay))
// Filter the Wirds that have been done on that day and within the current week
val doneDailyWirds = dailyWirds.filter { wird ->
wird.doneDays.any { doneDate ->
val localDate = doneDate.toLocalDate()
localDate.dayOfWeek == dayOfWeek &&
!localDate.isBefore(startOfWeek) &&
!localDate.isAfter(endOfWeek)
}
}
// Calculate the percentage of done Wirds for that day
val donePercentage = if (dailyWirds.isNotEmpty()) {
doneDailyWirds.size * 100 / dailyWirds.size
} else {
0
}
// Add the donePercentage to the weekPrestating list
weekPrestating.add(donePercentage.toFloat())
Log.d(TAG, "Day: $dayOfWeek")
//Log.d(TAG, "Daily Wirds: $dailyWirds")
//Log.d(TAG, "Done Daily Wirds: $doneDailyWirds")
Log.d(TAG, "Done Percentage: $donePercentage%")
}
// Update the state with the new weekPrestating list
_state.value = StatisticsViewState(weekPrestating)
}
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/statisticsScreen/StatisticsViewModel.kt | 971671545 |
package com.example.riyadal_qulub.ui.screens.onBoarding
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.res.painterResource
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 com.example.riyadal_qulub.R
import com.example.riyadal_qulub.ui.theme.PrimaryVariant
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
@Composable
fun Screen1(image:Int , text:String, onclick:()-> Unit) {
Column(
verticalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.weight(1f))
Image(
painter = painterResource(id = image),
contentDescription = "image1",
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.weight(1f))
Text(
text = text,
modifier = Modifier.fillMaxWidth().padding(20.dp),
fontFamily = rubikSansFamily,
color = Color.Black,
fontSize = 20.sp,
textAlign = TextAlign.Center,
lineHeight = 30.sp
)
Spacer(modifier = Modifier.weight(1f))
Button(onClick = { onclick() }, modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
,
colors = ButtonDefaults.buttonColors(containerColor = PrimaryVariant)
) {
Text(text = "التالي", fontFamily = rubikSansFamily)
}
Spacer(modifier = Modifier.weight(1f))
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/onBoarding/Screen1.kt | 3332071960 |
package com.example.riyadal_qulub.ui.screens.onBoarding
import android.content.Context
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.navigation.NavController
import com.example.riyadal_qulub.R
import com.example.riyadal_qulub.ui.navigation.Screen
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.coroutines.coroutineContext
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun OnBoardingScreen(
navController: NavController,
context: Context
) {
val pagerState = rememberPagerState(pageCount = {
3
})
val scope = rememberCoroutineScope()
val sharedPreferences = context.getSharedPreferences("MyApp", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
HorizontalPager(state = pagerState) { page ->
when (page) {
0 -> {
Column(modifier = Modifier.fillMaxSize()) {
Screen1(
R.drawable.on_boarding_image1,
"هل انت جاهز لمتابعة اورادك اليومية ؟",
onclick = {
scope.launch {
pagerState.scrollToPage(1)
}
})
}
}
1 -> {
Column(modifier = Modifier.fillMaxSize()) {
Screen1(
R.drawable.on_boarding_image2,
"واعلم أنه لا يستقيم مع الإهمال حال، ولا يصلح مع الإغفال بال",
onclick = {
scope.launch {
pagerState.scrollToPage(2)
}
})
}
}
2 -> {
Column(modifier = Modifier.fillMaxSize()) {
Screen1(
R.drawable.on_boarding_image3,
"ينبغي أن توزع أوقاتك وترتب أورادك وتعين لكل وقت شغلًا لا تتعداه ولا تؤثر فيه سواه، وأما من ترك نفسه مهملًا سدى إهمال البهائم يشتغل في كل وقت بما اتفق كيف اتفق فتمضي أكثر أوقاته ضائعة",
onclick = {
editor.putBoolean(
"hasSeenOnboarding",
true
)
editor.apply()
navController.navigate(Screen.HomeScreen.route) {
popUpTo("onBoardingScreen") { inclusive = true;saveState = false }
//todo fix the backstack
}
})
}
}
}
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/screens/onBoarding/OnBoardingScreen.kt | 2102064696 |
package com.example.riyadal_qulub.ui.components
import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import com.example.riyadal_qulub.domain.model.WeekDays
import com.example.riyadal_qulub.ui.components.calender.ClickableDayCircle
import com.example.riyadal_qulub.util.daysOfWeekInArabic
@Composable
fun ClickableWeekDays(
daysChecked: MutableState<List<WeekDays>>
) {
val daysOfWeek = WeekDays.values().toList()
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
for ((index, dayOfWeek) in daysOfWeek.withIndex()) {
// Get the name in Arabic from the map
val dayOfWeekInArabic = daysOfWeekInArabic[dayOfWeek]
ClickableDayCircle(
day = dayOfWeekInArabic!!,
clicked = daysChecked.value.contains(dayOfWeek),
onCheckedChange = { isChecked ->
if (isChecked) {
daysChecked.value = daysChecked.value + dayOfWeek
} else {
daysChecked.value = daysChecked.value - dayOfWeek
}
}
)
}
}
Log.i("TAG", "ClickableWeekDays: ${daysChecked.value} ")
}
/*
@Composable
@Preview
fun clickableWeekDaysPreview() {
ClickableWeekDays()
}
*/
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/RawDays.kt | 3059463674 |
package com.example.riyadal_qulub.ui.components
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
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 com.example.riyadal_qulub.domain.model.Wird
import com.example.riyadal_qulub.ui.screens.homeScreen.HomeViewState
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.Secondary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
import java.time.LocalDateTime
import androidx.compose.runtime.collectAsState
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun WirdItem(
wird: MutableState<Wird>,
onButtonClicked: (Wird) -> Unit,
onWirdClicked: (Wird) -> Unit,
onWirdLongPressed: (Wird) -> Unit,
modifier: Modifier = Modifier,
state: HomeViewState,
) {
// Print the Wird
Log.i("Wird Item", "${wird.value.name}: ${wird.value.doneDays}")
Box(
modifier = modifier
.clip(RoundedCornerShape(4.dp))
.border(2.dp, color = Secondary)
.fillMaxWidth()
.height(82.dp)
.combinedClickable(
onClick = { onWirdClicked(wird.value) },
onLongClick = { onWirdLongPressed(wird.value) }
),
) {
Row(
modifier = Modifier
.fillMaxSize(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = CenterVertically
) {
Button(
onClick = {
// Update the doneDays list immediately
wird.value = wird.value.copy(
doneDays = wird.value.doneDays.toMutableList().apply {
add(state.selectedDate.value.atStartOfDay())
}
)
onButtonClicked(wird.value)
},
modifier = Modifier
// .width(150.dp)
.padding(16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Primary,
)
) {
Row(verticalAlignment = CenterVertically) {
Icon(
imageVector = if (!wird.value.doneDays.asIterable().map { it.toLocalDate() }
.contains(state.selectedDate.value)) Icons.Default.Check else Icons.Default.Refresh,
contentDescription = null,
tint = Color.White,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.padding(4.dp))
Text(
text = "انهيت الورد",
fontFamily = rubikSansFamily,
color = Color.White,
fontSize = 8.sp,
)
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.End,
) {
Text(
text = wird.value.name,
fontFamily = rubikSansFamily,
color = Color.Black,
fontSize = 16.sp,
textAlign = TextAlign.Right
)
}
}
}
}
/*
@Composable
@Preview
fun WirdItemPreview() {
val wirdState = remember { mutableStateOf(Wird(name = "قرائة قران")) }
WirdItem(wirdState, {}, {}, {})
}*/
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/WirdItem.kt | 1639045619 |
package com.example.riyadal_qulub.ui.components.calender
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.riyadal_qulub.domain.model.Wird
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
import com.kizitonwose.calendar.compose.HorizontalCalendar
import com.kizitonwose.calendar.compose.rememberCalendarState
import com.kizitonwose.calendar.core.CalendarDay
import com.kizitonwose.calendar.core.DayPosition
import com.kizitonwose.calendar.core.daysOfWeek
import com.kizitonwose.calendar.core.firstDayOfWeekFromLocale
import java.time.DayOfWeek
import java.time.LocalDateTime
import java.time.YearMonth
import java.time.format.TextStyle
import java.util.Locale
@Composable
fun MonthCalenderItem(wird: Wird) {
val daysOfWeek = remember { daysOfWeek(firstDayOfWeek = DayOfWeek.SUNDAY) }
val currentMonth = remember { YearMonth.now() }
val startMonth = remember { currentMonth.minusMonths(100) } // Adjust as needed
val endMonth = remember { currentMonth.plusMonths(100) } // Adjust as needed
val firstDayOfWeek = remember { firstDayOfWeekFromLocale() } // Available from the library
val doneDays = wird.doneDays
val state = rememberCalendarState(
startMonth = startMonth,
endMonth = endMonth,
firstVisibleMonth = currentMonth,
firstDayOfWeek = firstDayOfWeek
)
Box(modifier = Modifier.padding(16.dp)) {
HorizontalCalendar(
state = state,
dayContent = { Day(it,doneDays) },
monthHeader = {
DaysOfWeekTitle(daysOfWeek = daysOfWeek) // Use the title as month header
}
)
}
}
@Composable
fun DaysOfWeekTitle(daysOfWeek: List<DayOfWeek>) {
Row(modifier = Modifier.fillMaxWidth()) {
for (dayOfWeek in daysOfWeek) {
Text(
modifier = Modifier.weight(1f),
textAlign = TextAlign.Center,
text = dayOfWeek.getDisplayName(TextStyle.SHORT, Locale("ar")),
fontFamily = rubikSansFamily,
fontSize = 15.sp,
)
}
}
}
@Composable
fun Day(day: CalendarDay, doneDays: List<LocalDateTime>) {
val isDone = doneDays.any { it.toLocalDate() == day.date }
Box(
modifier = Modifier
.aspectRatio(1f)
.clickable { },
contentAlignment = Alignment.Center
) {
if (isDone) {
Canvas(modifier = Modifier.size(36.dp)) {
val radius = size.minDimension / 2 - 1.dp.toPx()
drawCircle(
color = Primary,
center = center,
radius = radius,
style = Fill
)
}
}
Text(
text = day.date.dayOfMonth.toString(),
color = if (isDone) {
Color.White
} else if(day.position == DayPosition.MonthDate) {
Color.Black
} else {
Color.LightGray
}
)
}
}
/*
@Preview
@Composable
fun MainScreenPreview() {
MonthCalenderItem()
}*/
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/calender/MounthCalenderItem.kt | 569826439 |
package com.example.riyadal_qulub.ui.components.calender
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
private const val BOX_SIZE = 46
@Composable
fun DayCircle(
clickedState: MutableState<Boolean>, onCheckedChange: (Boolean) -> Unit = {} // Add this line
) {
Canvas(modifier = Modifier
.size(BOX_SIZE.dp)
.clickable {
clickedState.value = !clickedState.value
onCheckedChange(clickedState.value) // Add this line
}) {
val radius = size.minDimension / 2 - 1.dp.toPx()
drawCircle(
color = Primary,
center = center,
radius = radius,
style = if (clickedState.value) Fill else Stroke(width = 1.dp.toPx())
)
}
}
@Composable
fun ClickableDayCircle(
day: String = "الأحد",
clicked: Boolean = false,
onCheckedChange: (Boolean) -> Unit = {} // Add this line
) {
val clickedState = remember { mutableStateOf(clicked) }
Box(contentAlignment = Alignment.Center) {
DayCircle(clickedState = clickedState, onCheckedChange = onCheckedChange)
DayText(day = day, clickedState = clickedState.value)
}
}
@Composable
fun DayText(day: String, clickedState: Boolean) {
Text(
text = day,
color = if (clickedState) Color.White else Color.Black,
fontFamily = rubikSansFamily,
fontSize = 12.sp,
)
}
@Preview
@Composable
fun ClickableDayCirclePreview() {
ClickableDayCircle()
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/calender/ClickableDayCircle.kt | 1787777171 |
package com.example.riyadal_qulub.ui.components.calender
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.riyadal_qulub.ui.theme.LabelGrey
import com.example.riyadal_qulub.ui.theme.Secondary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
import com.kizitonwose.calendar.compose.WeekCalendar
import com.kizitonwose.calendar.compose.weekcalendar.rememberWeekCalendarState
import com.kizitonwose.calendar.core.WeekDay
import java.time.LocalDate
import java.time.format.TextStyle
import java.util.Locale
@Composable
fun WeeklyCalendarItem(day: WeekDay, onClick: (WeekDay) -> Unit, selectedDate: LocalDate) {
val isSelected = day.date == selectedDate
val dayOfWeekInArabic = day.date.dayOfWeek.getDisplayName(TextStyle.FULL, Locale("ar"))
Box(
modifier = Modifier
.aspectRatio(1f)
.size(48.dp)
.clickable(
onClick = {
onClick(day)
}
)
.clip(RoundedCornerShape(14.dp))
.background(
color = if (isSelected) Secondary else Color.Transparent,
),
contentAlignment = Alignment.Center,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
Text(
text = dayOfWeekInArabic,
fontFamily = rubikSansFamily,
fontSize = 12.sp,
// fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Normal,
color = if (isSelected) Color.Black else LabelGrey
)
Text(
text = day.date.dayOfMonth.toString(),
fontFamily = rubikSansFamily,
fontSize = 16.sp,
color = if (isSelected) Color.Black else LabelGrey
)
}
}
}
@Preview
@Composable
fun WeeklyCalenderPreview() {
val state = rememberWeekCalendarState(
startDate = LocalDate.now(),
endDate = LocalDate.now().plusDays(6),
)
var selectedDate = remember { mutableStateOf(LocalDate.now()) }
WeekCalendar(
state = state,
dayContent = {
WeeklyCalendarItem(it, onClick = { day ->
Log.i("TAG", "DayPreview: ${day.date}")
selectedDate.value = day.date
}, selectedDate = selectedDate.value)
}
)
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/calender/WeeklyCalendarItem.kt | 2192015010 |
package com.example.riyadal_qulub.ui.components.charts
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.drawscope.DrawScope
import com.example.riyadal_qulub.ui.theme.Secondary
import com.github.tehras.charts.bar.BarChartData
import com.github.tehras.charts.bar.renderer.bar.BarDrawer
class MyBarDrawer(recurrence: Float = 24f) :
BarDrawer {
private val barPaint = Paint().apply {
this.isAntiAlias = true
}
private val rightOffset = 24f
override fun drawBar(
drawScope: DrawScope,
canvas: Canvas,
barArea: Rect,
bar: BarChartData.Bar
) {
canvas.drawRoundRect(
barArea.left,
0f,
barArea.right + rightOffset,
barArea.bottom,
16f,
16f,
barPaint.apply {
color = Secondary
},
)
canvas.drawRoundRect(
barArea.left,
barArea.top,
barArea.right + rightOffset,
barArea.bottom,
16f,
16f,
barPaint.apply {
color = bar.color
},
)
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/charts/MyBarDrawer.kt | 1584198955 |
package com.example.riyadal_qulub.ui.components.charts
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.progressSemantics
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
@Composable
fun AnimatedCircularProgressIndicator(
targetValue: Float,
progressBackgroundColor: Color,
progressIndicatorColor: Color,
completedColor: Color,
day: String,
modifier: Modifier = Modifier
) {
val stroke = with(LocalDensity.current) {
Stroke(width = 6.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round)
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Box(modifier = modifier, contentAlignment = Alignment.Center) {
val animateFloat = remember { Animatable(0f) }
LaunchedEffect(animateFloat) {
animateFloat.animateTo(
targetValue = targetValue,
animationSpec = tween(durationMillis = 2000, easing = FastOutSlowInEasing)
)
}
Canvas(
Modifier
.progressSemantics(targetValue)
.size(CircularIndicatorDiameter)
) {
// Start at 12 O'clock
val startAngle = 270f
val sweep: Float = animateFloat.value * 360f
val diameterOffset = stroke.width / 2
drawCircle(
color = progressBackgroundColor,
style = stroke,
radius = size.minDimension / 2.0f - diameterOffset
)
drawCircularProgressIndicator(startAngle, sweep, progressIndicatorColor, stroke)
}
}
Text(text = day, fontFamily = rubikSansFamily, fontSize = 12.sp, color = Color.Black)
}
}
private fun DrawScope.drawCircularProgressIndicator(
startAngle: Float,
sweep: Float,
color: Color,
stroke: Stroke
) {
// To draw this circle we need a rect with edges that line up with the midpoint of the stroke.
// To do this we need to remove half the stroke width from the total diameter for both sides.
val diameterOffset = stroke.width / 2
val arcDimen = size.width - 2 * diameterOffset
drawArc(
color = color,
startAngle = startAngle,
sweepAngle = sweep,
useCenter = false,
topLeft = Offset(diameterOffset, diameterOffset),
size = Size(arcDimen, arcDimen),
style = stroke
)
}
// Diameter of the indicator circle
private val CircularIndicatorDiameter = 42.dp | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/charts/AnimatedCircularProgressIndicator.kt | 2636568622 |
package com.example.riyadal_qulub.ui.components.charts
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.nativeCanvas
import com.example.riyadal_qulub.ui.theme.Secondary
import com.github.tehras.charts.piechart.utils.toLegacyInt
class MyLabelDrawer :
com.github.tehras.charts.bar.renderer.label.LabelDrawer {
private val leftOffset = 45f
override fun drawLabel(
drawScope: DrawScope,
canvas: Canvas,
label: String,
barArea: Rect,
xAxisArea: Rect
) {
val paint = android.graphics.Paint().apply {
this.textAlign = android.graphics.Paint.Align.CENTER
this.color = Secondary.toLegacyInt()
this.textSize = 24f
}
canvas.nativeCanvas.drawText(
label,
barArea.left + leftOffset,
barArea.top + 38f,
paint
)
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/charts/MyLabelDrawer.kt | 1994031466 |
package com.example.riyadal_qulub.ui.components.charts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
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 com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.Purple80
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
@Composable
fun WeeklyProgress(weekPrev: List<Float>) {
Box {
Card(
modifier = Modifier
.fillMaxWidth(),
// .shadow(2.dp),
elevation = CardDefaults.elevatedCardElevation(2.dp),
colors = CardDefaults.cardColors(Color.White)
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "نظرة عامة علي إنتاجية الأسبوع",
textAlign = TextAlign.Right,
fontFamily = rubikSansFamily,
fontSize = 16.sp,
color = Color.Black
)
Row(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
AnimatedCircularProgressIndicator(
targetValue = weekPrev[0] / 100,
progressBackgroundColor = Purple80,
progressIndicatorColor = Primary,
day = "السبت",
completedColor = Primary
)
AnimatedCircularProgressIndicator(
targetValue = weekPrev[1]/100,
progressBackgroundColor = Purple80,
progressIndicatorColor = Primary,
day = "الأحد",
completedColor = Primary
)
AnimatedCircularProgressIndicator(
targetValue = weekPrev[2]/100,
progressBackgroundColor = Purple80,
progressIndicatorColor = Primary,
day = "الأثنين",
completedColor = Primary
)
AnimatedCircularProgressIndicator(
targetValue = weekPrev[3]/100,
progressBackgroundColor = Purple80,
progressIndicatorColor = Primary,
day = "الثلاثاء",
completedColor = Primary
)
AnimatedCircularProgressIndicator(
targetValue = weekPrev[4]/100,
progressBackgroundColor = Purple80,
progressIndicatorColor = Primary,
day = "الأربعاء",
completedColor = Primary
)
AnimatedCircularProgressIndicator(
targetValue = weekPrev[5]/100,
progressBackgroundColor = Purple80,
progressIndicatorColor = Primary,
day = "الخميس",
completedColor = Primary
)
AnimatedCircularProgressIndicator(
targetValue = weekPrev[6]/100,
progressBackgroundColor = Purple80,
progressIndicatorColor = Primary,
day = "الجمعة",
completedColor = Primary
)
}
}
}
}
}
@Preview
@Composable
fun show() {
WeeklyProgress(weekPrev = listOf(0.0f, 33.0f, 0.0f, 100.0f, 20.0f, 0.0f, 0.0f))
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/charts/WeeklyProgress.kt | 1950864897 |
package com.example.riyadal_qulub.ui.components.charts
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.util.MyYAxisDrawer
import com.example.riyadal_qulub.util.NoOpXAxisDrawer
import com.example.riyadal_qulub.util.simplifyNumber
import com.github.tehras.charts.bar.BarChart
import com.github.tehras.charts.bar.BarChartData
import com.github.tehras.charts.bar.renderer.label.LabelDrawer
import com.github.tehras.charts.bar.renderer.xaxis.XAxisDrawer
import com.github.tehras.charts.bar.renderer.yaxis.SimpleYAxisDrawer
import com.github.tehras.charts.bar.renderer.yaxis.YAxisDrawer
import java.time.DayOfWeek
@Composable
fun WeeklyChart(
saturday: Float?,
sunday: Float?,
monday: Float?,
tuesday: Float?,
wednesday: Float?,
thursday: Float?,
friday: Float?
) {
// val groupedExpenses = expenses.groupedByDayOfWeek()
Column(
modifier = Modifier
.padding(bottom = 20.dp)
.fillMaxWidth()
.height(300.dp)
,
horizontalAlignment = Alignment.CenterHorizontally
) {
BarChart(
barChartData = BarChartData(
bars = listOf(
BarChartData.Bar(
label = "سبت",
value = saturday
?: 0f,
color = Primary,
),
BarChartData.Bar(
label = "الاحد",
value = sunday
?: 0f,
color = Primary
),
BarChartData.Bar(
label = "الاثنين",
value = monday
?: 0f,
color = Primary
),
BarChartData.Bar(
label = "الثلاثاء",
value = tuesday
?: 0f,
color = Primary
),
BarChartData.Bar(
label = "الأربعاء",
value = wednesday
?: 0f,
color = Primary
),
BarChartData.Bar(
label = "الخميس",
value = thursday
?: 0f,
color = Primary
),
BarChartData.Bar(
label = "الجمعة",
value = friday
?: 0f,
color = Primary
),
)
),
labelDrawer = MyLabelDrawer(),
/* yAxisDrawer = SimpleYAxisDrawer(
labelValueFormatter = ::simplifyNumber,
labelRatio = 7,
labelTextSize = 14.sp,
labelTextColor = Primary,
)*/
yAxisDrawer = MyYAxisDrawer(),
xAxisDrawer = NoOpXAxisDrawer(),
barDrawer = MyBarDrawer(),
modifier = Modifier
.padding(bottom = 20.dp, end = 28.dp)
.fillMaxWidth()
.height(300.dp)
)
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/charts/WeeklyChart.kt | 460328198 |
package com.example.riyadal_qulub.ui.components.dialogs
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TimePickerDialog(
title: String = "Select Time",
onCancel: () -> Unit,
onConfirm: () -> Unit,
toggle: @Composable () -> Unit = {},
content: @Composable () -> Unit,
) {
Dialog(
onDismissRequest = onCancel,
properties = DialogProperties(
usePlatformDefaultWidth = false
),
) {
Surface(
shape = MaterialTheme.shapes.extraLarge,
tonalElevation = 6.dp,
modifier = Modifier
.width(IntrinsicSize.Min)
.height(IntrinsicSize.Min)
.background(
shape = MaterialTheme.shapes.extraLarge,
color = MaterialTheme.colorScheme.surface
),
) {
Column(
modifier = Modifier.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 20.dp),
text = title,
style = MaterialTheme.typography.labelMedium
)
content(
)
Row(
modifier = Modifier
.height(40.dp)
.fillMaxWidth()
) {
toggle()
Spacer(modifier = Modifier.weight(1f))
TextButton(
onClick = onCancel
) { Text("Cancel") }
TextButton(
onClick = onConfirm
) { Text("OK") }
}
}
}
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/dialogs/TimePickerDialog.kt | 1910710361 |
package com.example.riyadal_qulub.ui.components.dialogs
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AlertDialogDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.text.style.TextAlign
import com.example.riyadal_qulub.ui.theme.Primary
import com.example.riyadal_qulub.ui.theme.Secondary
import com.example.riyadal_qulub.ui.theme.rubikSansFamily
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AlertDialogExample(
onDismissRequest: () -> Unit,
onConfirmation: () -> Unit,
dialogTitle: String,
dialogText: String,
) {
AlertDialog(
title = {
Text(text = dialogTitle, fontFamily = rubikSansFamily, textAlign = TextAlign.Center)
},
text = {
Text(text = dialogText, fontFamily = rubikSansFamily, textAlign = TextAlign.Right)
},
onDismissRequest = {
onDismissRequest()
},
confirmButton = {
TextButton(
onClick = {
onConfirmation()
}
) {
Text(
"حذف",
color = androidx.compose.ui.graphics.Color.Red,
fontFamily = rubikSansFamily
)
}
},
dismissButton = {
TextButton(
onClick = {
onDismissRequest()
}
) {
Text(
"الرجوع",
//color = androidx.compose.ui.graphics.Color.Red,
fontFamily = rubikSansFamily
)
}
},
containerColor = Secondary
)
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/dialogs/AlertDialog.kt | 1294678423 |
package com.example.riyadal_qulub.ui.components.dialogs
import androidx.compose.material3.Button
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import com.example.riyadal_qulub.util.convertMillisToDate
import java.time.LocalDateTime
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyDatePickerDialog(
onDateSelected: (LocalDateTime) -> Unit,
onDismiss: () -> Unit
) {
val datePickerState = rememberDatePickerState()
val selectedDate = datePickerState.selectedDateMillis?.let {
convertMillisToDate(it)
} ?: LocalDateTime.now()
DatePickerDialog(
onDismissRequest = { onDismiss() },
confirmButton = {
Button(onClick = {
onDateSelected(selectedDate)
onDismiss()
}
) {
Text(text = "OK")
}
},
dismissButton = {
Button(onClick = {
onDismiss()
}) {
Text(text = "Cancel")
}
}
) {
DatePicker(
state = datePickerState
)
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/components/dialogs/DatePickerView.kt | 2108222225 |
package com.example.riyadal_qulub.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val Primary = Color(0xFF6750A4)
val PrimaryVariant = Color(0xFF8F52AC)
val Gold = Color(0xFFE9A12C)
val Secondary = Color(0xFFEBDEFF)
val LabelGrey = Color(0xFFC6C6C6)
val LabelNight = Color(0xFF5800B3) | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/theme/Color.kt | 799666695 |
package com.example.riyadal_qulub.ui.theme
import android.app.Activity
import android.os.Build
import android.view.WindowManager
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = PrimaryVariant,
secondary = Secondary,
tertiary = Pink40,
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun RiyadAlQulubcomposeTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = PrimaryVariant.toArgb()
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/theme/Theme.kt | 4029883791 |
package com.example.riyadal_qulub.ui.theme
import androidx.compose.material3.Typography
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.unit.sp
import com.example.riyadal_qulub.R
// 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
)
*/
)
val rubikSansFamily = FontFamily(
Font(R.font.rubik_italic_variable_font_wght, FontWeight.Light),
Font(R.font.rubik_variable_font_wght, FontWeight.Normal),
Font(R.font.rubik_variable_font_wght_bold, FontWeight.Bold),
)
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/ui/theme/Type.kt | 1229584171 |
package com.example.riyadal_qulub
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import com.example.riyadal_qulub.notification.CounterNotificationService
import dagger.hilt.android.HiltAndroidApp
import java.util.Locale
@HiltAndroidApp
class MyApplication : Application(){
override fun attachBaseContext(base: Context) {
super.attachBaseContext(updateBaseContextLocale(base))
}
private fun updateBaseContextLocale(context: Context): Context {
val locale = Locale("ar") // Arabic locale
Locale.setDefault(locale)
val res: Resources = context.resources
val configuration: Configuration = res.configuration
configuration.setLocale(locale)
return context.createConfigurationContext(configuration)
}
override fun onCreate() {
super.onCreate()
// Create notification channel
createNotificationChannel()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
CounterNotificationService.CHANNEL_ID,
CounterNotificationService.CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = CounterNotificationService.CHANNEL_DESCRIPTION
}
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(notificationChannel)
}
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/MyApplication.kt | 2141031658 |
package com.example.riyadal_qulub
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.riyadal_qulub.notification.CounterNotificationService
import com.example.riyadal_qulub.notification.alarm.AlarmItem
import com.example.riyadal_qulub.notification.alarm.AndroidAlarmScheduler
import com.example.riyadal_qulub.ui.navigation.NavBar
import com.example.riyadal_qulub.ui.navigation.Navigation
import com.example.riyadal_qulub.ui.navigation.Screen
import com.example.riyadal_qulub.ui.theme.RiyadAlQulubcomposeTheme
import dagger.hilt.android.AndroidEntryPoint
import java.time.LocalDateTime
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RiyadAlQulubcomposeTheme {
val navController = rememberNavController()
val backStackEntry by navController.currentBackStackEntryAsState()
var showBottomBar by rememberSaveable { mutableStateOf(true) }
//to hide bottom bar in onboarding screen
showBottomBar = when (backStackEntry?.destination?.route) {
Screen.OnBoardingScreen.route -> false
Screen.SignInScreen.route -> false
Screen.SignUpScreen.route -> false
else -> true
}
Scaffold(
bottomBar = {
if (showBottomBar) {
NavBar(backStackEntry = backStackEntry, navController = navController)
}
}
) { innerPadding ->
Navigation(innerPadding, navController = navController, context = this)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestPermissions(
arrayOf(
android.Manifest.permission.POST_NOTIFICATIONS,
android.Manifest.permission.SCHEDULE_EXACT_ALARM,
), 99
)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 99) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//granted
Log.i("Main", "onRequestPermissionsResult: Granted")
} else {
//not granted
}
}
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/MainActivity.kt | 2760589786 |
package com.example.riyadal_qulub.di
import android.app.Application
import androidx.room.Room
import com.example.riyadal_qulub.data.local.db.WirdDatabase
import com.google.firebase.auth.FirebaseAuth
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideWirdDatabase(app: Application): WirdDatabase {
return Room.databaseBuilder(
app,
WirdDatabase::class.java,
"wird_db.db"
).build()
}
@Provides
@Singleton
fun provideFirebaseAuth(): FirebaseAuth {
return FirebaseAuth.getInstance()
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/di/AppModule.kt | 48107348 |
package com.example.riyadal_qulub.di
import com.example.riyadal_qulub.domain.repository.WirdRepository
import com.example.riyadal_qulub.data.repository.WirdRepositoryImp
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
@Singleton
abstract fun bindWirdRepository(
bindWirdRepository: WirdRepositoryImp
): WirdRepository
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/di/RepositoryModule.kt | 1994255487 |
package com.example.riyadal_qulub.util
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.TimePickerState
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
import com.example.riyadal_qulub.domain.model.WeekDays
import com.github.tehras.charts.bar.renderer.xaxis.XAxisDrawer
import com.github.tehras.charts.bar.renderer.yaxis.YAxisDrawer
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.time.DayOfWeek
import java.time.LocalDateTime
import java.util.Date
fun convertMillisToDate(millis: Long): LocalDateTime {
return LocalDateTime.ofInstant(Date(millis).toInstant(), java.time.ZoneId.systemDefault())
}
fun formatLocalDateTime(localDateTime: LocalDateTime): String {
// arabic date format
val formatter = SimpleDateFormat("MM/dd")
// localizing date to ar
return formatter.format(Date.from(localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant()))
}
fun convertDayOfWeekToWeekDays(dayOfWeek: DayOfWeek): WeekDays {
return when (dayOfWeek) {
DayOfWeek.MONDAY -> WeekDays.MONDAY
DayOfWeek.TUESDAY -> WeekDays.TUESDAY
DayOfWeek.WEDNESDAY -> WeekDays.WEDNESDAY
DayOfWeek.THURSDAY -> WeekDays.THURSDAY
DayOfWeek.FRIDAY -> WeekDays.FRIDAY
DayOfWeek.SATURDAY -> WeekDays.SATURDAY
DayOfWeek.SUNDAY -> WeekDays.SUNDAY
}
}
fun convertDayOfWeekToWeekDaysForStatistics(dayOfWeek: DayOfWeek): WeekDays {
return when (dayOfWeek) {
DayOfWeek.MONDAY -> WeekDays.MONDAY
DayOfWeek.TUESDAY -> WeekDays.TUESDAY
DayOfWeek.WEDNESDAY -> WeekDays.WEDNESDAY
DayOfWeek.THURSDAY -> WeekDays.THURSDAY
DayOfWeek.FRIDAY -> WeekDays.FRIDAY
DayOfWeek.SATURDAY -> WeekDays.SATURDAY
DayOfWeek.SUNDAY -> WeekDays.SUNDAY
}
}
fun simplifyNumber(value: Float): String {
return when {
value >= 1000 && value < 1_000_000 -> DecimalFormat("0.#K").format(value / 1000)
value >= 1_000_000 -> DecimalFormat("0.#M").format(value / 1_000_000)
else -> DecimalFormat("0.#").format(value)
}
}
class MyYAxisDrawer : YAxisDrawer {
override fun drawAxisLabels(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect,
minValue: Float,
maxValue: Float
) {
// Do nothing
}
override fun drawAxisLine(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect
) {
// Do nothing
}
}
class NoOpXAxisDrawer : XAxisDrawer {
override fun drawAxisLine(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect
) {
// Do nothing
}
override fun requiredHeight(drawScope: DrawScope): Float {
return 0f
}
}
@OptIn(ExperimentalMaterial3Api::class)
fun TimePickerState.toLocalDateTime(): LocalDateTime {
val currentDateTime = LocalDateTime.now()
return currentDateTime.withHour(this.hour).withMinute(this.minute)} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/util/utils.kt | 2563754680 |
package com.example.riyadal_qulub.util
sealed class WirdStatus {
data object Done : WirdStatus()
data object NotDone : WirdStatus()
data object IsToday : WirdStatus()
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/util/WirdStatus.kt | 1352472898 |
package com.example.riyadal_qulub.util
import com.example.riyadal_qulub.domain.model.WeekDays
import java.time.DayOfWeek
object DatabaseConstants {
const val DATABASE_NAME = "wird_database"
}
// Map of WeekDays enum values to their names in Arabic
val daysOfWeekInArabic = mapOf(
WeekDays.FRIDAY to "الجمعة",
WeekDays.THURSDAY to "الخميس",
WeekDays.WEDNESDAY to "الأربعاء",
WeekDays.TUESDAY to "الثلاثاء",
WeekDays.MONDAY to "الاثنين",
WeekDays.SUNDAY to "الأحد",
WeekDays.SATURDAY to "السبت"
)
// Helper function to convert DayOfWeek to WeekDays
val daysOfWeek = listOf(
DayOfWeek.SATURDAY,
DayOfWeek.SUNDAY,
DayOfWeek.MONDAY,
DayOfWeek.TUESDAY,
DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY,
DayOfWeek.FRIDAY
) | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/util/Constants.kt | 16875008 |
package com.example.riyadal_qulub.notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import com.example.riyadal_qulub.MainActivity
import com.example.riyadal_qulub.R
class CounterNotificationService(private val context: Context) {
fun showNotification(wirdName: String, wirdMessage: String) {
val activityIntent = Intent(context, MainActivity::class.java)
val activityPendingIntent = PendingIntent.getActivity(
context,
1,
activityIntent,
PendingIntent.FLAG_UPDATE_CURRENT or
PendingIntent.FLAG_IMMUTABLE
)
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("Wird")
.setContentText("you have $wirdName")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setStyle(
NotificationCompat.BigTextStyle()
.bigText(wirdMessage)
)
.setContentIntent(activityPendingIntent) // This line sets the PendingIntent to the notification
.build()
val notificationManger =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManger.notify(1, notification)
}
companion object {
const val CHANNEL_ID = "counter_notification"
const val CHANNEL_NAME = "Counter"
const val CHANNEL_DESCRIPTION = "this is to show the wird notifications"
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/notification/CounterNotificationService.kt | 1978833491 |
package com.example.riyadal_qulub.notification.alarm
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import java.time.ZoneId
import java.time.ZoneOffset
class AndroidAlarmScheduler(
private val context: Context
) : AlarmScheduler {
private val alarmManager = context.getSystemService(AlarmManager::class.java)
override fun schedule(alarmItem: AlarmItem) {
val intent = Intent(context, AlarmReceiver::class.java).apply {
putExtra("EXTRA_MESSAGE", alarmItem.message)
}
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
alarmItem.time.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
PendingIntent.getBroadcast(
context,
alarmItem.hashCode(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
}
override fun cancel(alarmItem: AlarmItem) {
alarmManager.cancel(
PendingIntent.getBroadcast(
context,
alarmItem.hashCode(),
Intent(context, AlarmReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/notification/alarm/AndroidAlarmScheduler.kt | 1143897967 |
package com.example.riyadal_qulub.notification.alarm
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.example.riyadal_qulub.notification.CounterNotificationService
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val message = intent?.getStringExtra("EXTRA_MESSAGE") ?: return
println(message)
Log.i("TAG", "onReceive: $message")
val service = CounterNotificationService(context!!)
service.showNotification("name" , message)
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/notification/alarm/AlarmReceiver.kt | 474071868 |
package com.example.riyadal_qulub.notification.alarm
import java.time.LocalDateTime
data class AlarmItem(
val time :LocalDateTime,
val message :String,
) | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/notification/alarm/AlarmItem.kt | 629430140 |
package com.example.riyadal_qulub.notification.alarm
interface AlarmScheduler {
fun schedule(alarmItem: AlarmItem)
fun cancel(alarmItem: AlarmItem)
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/notification/alarm/AlarmScheduler.kt | 1081854055 |
package com.example.riyadal_qulub.data.repository
import com.example.riyadal_qulub.data.local.db.WirdDatabase
import com.example.riyadal_qulub.domain.model.WeekDays
import com.example.riyadal_qulub.domain.model.Wird
import com.example.riyadal_qulub.domain.repository.WirdRepository
import java.time.LocalDateTime
import javax.inject.Inject
class WirdRepositoryImp @Inject constructor(
private val db: WirdDatabase,
) : WirdRepository {
private val dao = db.dao
override suspend fun getAllWirds(): List<Wird> {
return dao.getAll()
}
override suspend fun insertWird(vararg wird: Wird) {
dao.insertWird(*wird)
}
override suspend fun deleteWird(wird: Wird) {
dao.delete(wird)
}
override suspend fun updateIsDone(wirdId: Int, isDone: Boolean) {
dao.updateIsDone(wirdId, isDone)
}
override suspend fun updateWirdDays(wirdId: Int, doneDates: List<LocalDateTime>) {
dao.updateWirdDays(wirdId, doneDates)
}
override suspend fun updateDoneDates(wirdId: Int, doneDates: List<LocalDateTime>) {
dao.updateDoneDates(wirdId, doneDates)
}
override suspend fun getWirdById(wirdId: Int): Wird {
return dao.getWirdById(wirdId)
}
override suspend fun getWirdByWirdDays(wirdDays: List<WeekDays>): List<Wird> {
return dao.getAll().filter { it.wirdDays.intersect(wirdDays).isNotEmpty() }
}
override suspend fun deleteAllWirds() {
dao.deleteAllWirds()
}
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/data/repository/WirdRepositoryImp.kt | 684685745 |
package com.example.riyadal_qulub.data.local.db
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import com.example.riyadal_qulub.domain.model.WeekDays
import com.example.riyadal_qulub.domain.model.Wird
import java.time.LocalDateTime
@Dao
interface WirdDao {
@Query("SELECT * FROM wirds")
fun getAll(): List<Wird>
@Insert
fun insertWird(vararg wird: Wird)
@Delete
fun delete(wird: Wird)
@Query("DELETE FROM wirds")
fun deleteAllWirds()
/* @Query("UPDATE wirds SET doneDays = :doneDays WHERE id = :wirdId")
fun updateDoneDays(wirdId: Int, doneDays: List<LocalDateTime>)*/
@Query("UPDATE wirds SET isDone = :isDone WHERE id = :wirdId")
fun updateIsDone(wirdId: Int, isDone: Boolean)
//add date to doneDates
@Query("UPDATE wirds SET doneDays = :doneDates WHERE id = :wirdId")
fun updateDoneDates(wirdId: Int, doneDates: List<LocalDateTime>)
@Query("UPDATE wirds SET wirdDays = :wirdDays WHERE id = :wirdId")
fun updateWirdDays(wirdId: Int, wirdDays: List<LocalDateTime>)
@Query("SELECT * FROM wirds WHERE id = :wirdId")
fun getWirdById(wirdId: Int): Wird
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/data/local/db/WirdDao.kt | 3164852455 |
@file:Suppress("Since15")
package com.example.riyadal_qulub.data.local.db
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.room.TypeConverter
import com.example.riyadal_qulub.domain.model.WeekDays
import java.time.LocalDateTime
object Converters {
@RequiresApi(Build.VERSION_CODES.O)
@TypeConverter
fun fromTimestamp(value: String?): LocalDateTime? {
return if (value != null) LocalDateTime.parse(value) else null
}
@TypeConverter
fun dateToTimestamp(date: LocalDateTime?): String? {
return date?.toString()
}
@RequiresApi(Build.VERSION_CODES.O)
@TypeConverter
fun fromStringList(value: String?): List<LocalDateTime>? {
return if (value != null) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
java.util.List.of(
*value.split(",".toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray())
.stream()
.map { text: String? ->
LocalDateTime.parse(
text
)
}
.toList()
} else {
TODO("VERSION.SDK_INT < UPSIDE_DOWN_CAKE")
} else null
}
@TypeConverter
fun dateListToString(dateList: List<LocalDateTime>?): String? {
return if (dateList.isNullOrEmpty()) {
"" // Return an empty string when the list is null or empty
} else {
dateList.stream().map { obj: LocalDateTime -> obj.toString() }
.reduce { s1: String?, s2: String? -> "$s1,$s2" }?.orElse(null)
}
}
@TypeConverter
fun fromStringListToString(stringList: List<String?>?): String? {
return if (stringList != null) java.lang.String.join(",", stringList) else null
}
@TypeConverter
fun fromStringToStringList(value: String?): List<String>? {
return if (value != null) java.util.List.of(
*value.split(",".toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray()) else null
}
@TypeConverter
fun fromWeekDaysListToString(weekDaysList: List<WeekDays>?): String? {
return if (weekDaysList != null) java.lang.String.join(
",",
weekDaysList.map { it.name }) else null
}
@TypeConverter
fun fromStringToWeekDaysList(value: String?): List<WeekDays>? {
return if (value != null) listOf(
*value.split(",".toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray()).map { WeekDays.valueOf(it) } else null
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/data/local/db/Converters.kt | 2768582200 |
package com.example.riyadal_qulub.data.local.db
import android.content.Context
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.example.riyadal_qulub.domain.model.Wird
import com.example.riyadal_qulub.util.DatabaseConstants.DATABASE_NAME
@Database(entities = [Wird::class], version = 1)
@TypeConverters(Converters::class)
abstract class WirdDatabase : RoomDatabase() {
abstract val dao : WirdDao
companion object {
private var INSTANCE: WirdDatabase? = null
fun getDatabase(context: Context): WirdDatabase {
if (INSTANCE == null) {
INSTANCE = androidx.room.Room.databaseBuilder(
context.applicationContext,
WirdDatabase::class.java,
DATABASE_NAME
).build()
}
return INSTANCE!!
}
}
}
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/data/local/db/WirdDatabase.kt | 568831070 |
package com.example.riyadal_qulub.domain.repository
import com.example.riyadal_qulub.domain.model.WeekDays
import com.example.riyadal_qulub.domain.model.Wird
import java.time.LocalDateTime
interface WirdRepository {
suspend fun getAllWirds(): List<Wird>
suspend fun insertWird(vararg wird: Wird)
suspend fun deleteWird(wird: Wird)
suspend fun updateIsDone(wirdId: Int, isDone: Boolean)
suspend fun updateWirdDays(wirdId: Int, doneDates: List<LocalDateTime>)
suspend fun updateDoneDates(wirdId: Int, doneDates: List<LocalDateTime>)
suspend fun getWirdById(wirdId: Int): Wird
suspend fun getWirdByWirdDays(wirdDays: List<WeekDays>): List<Wird>
suspend fun deleteAllWirds()
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/domain/repository/WirdRepository.kt | 3440130761 |
package com.example.riyadal_qulub.domain.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.time.LocalDateTime
import java.util.Date
@Entity(tableName = "wirds")
data class Wird(
@PrimaryKey(autoGenerate = true) var id: Int = 0,
var name: String = "",
var description: String = "",
var count: Int = 0,
var countDone: Int = 0,
var isDone: Boolean = false,
var isAlarm: Boolean = false,
var alarmTime: String = "",
var wirdDays: List<WeekDays> = emptyList(),
var doneDays: List<LocalDateTime> = emptyList(),
var unit: String = "",
var quantity: Int = 0,
var isDaily: Boolean = false,
var startDate: LocalDateTime = LocalDateTime.now(),
var isMorningWird: Boolean = false,
var isEveningWird: Boolean = false,
)
| RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/domain/model/Wird.kt | 1572729445 |
package com.example.riyadal_qulub.domain.model
enum class WeekDays {
SATURDAY, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
} | RiyadAl-QulubComposed/app/src/main/java/com/example/riyadal_qulub/domain/model/WeekDays.kt | 3540503290 |
package com.bitcodetech.sharedpreferences
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("com.bitcodetech.sharedpreferences", appContext.packageName)
}
} | 2023-10-16-Android-SharedPreferences/app/src/androidTest/java/com/bitcodetech/sharedpreferences/ExampleInstrumentedTest.kt | 1849264820 |
package com.bitcodetech.sharedpreferences
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)
}
} | 2023-10-16-Android-SharedPreferences/app/src/test/java/com/bitcodetech/sharedpreferences/ExampleUnitTest.kt | 220504200 |
package com.bitcodetech.sharedpreferences
import android.app.Activity
import android.content.Context
object UserData {
private val USER_PREF_NAME = "user_preferences"
private val KEY_TOKEN = "token"
fun storeToken(context: Context, token : String) : Boolean{
context.getSharedPreferences(USER_PREF_NAME, Activity.MODE_PRIVATE)
.edit()
.putString(KEY_TOKEN, token)
.commit()
return true
}
fun getToken(context: Context) : String? {
return context.getSharedPreferences(USER_PREF_NAME, Activity.MODE_PRIVATE)
.getString(KEY_TOKEN, null)
}
} | 2023-10-16-Android-SharedPreferences/app/src/main/java/com/bitcodetech/sharedpreferences/UserData.kt | 2626357955 |
package com.bitcodetech.sharedpreferences
import android.app.Activity
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val pref : SharedPreferences =
getSharedPreferences("my_prefs", Activity.MODE_PRIVATE)
val editor = pref.edit()
editor.putString("name", "Vishal")
editor.putInt("code", 1234)
editor.commit()
val name = pref.getString("name", "NA")
val code = pref.getInt("code", -1)
mt("$name $code")
UserData.storeToken(this, "ADET456@#DFE90")
mt(UserData.getToken(this)!!)
val pref1 = getPreferences(Activity.MODE_PRIVATE)
pref1.edit()
.putString("some_data", "Sample data")
.commit()
mt(pref1.getString("some_data", "Not Available")!!)
}
private fun mt(text : String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
} | 2023-10-16-Android-SharedPreferences/app/src/main/java/com/bitcodetech/sharedpreferences/MainActivity.kt | 957746890 |
package dev.mambo.play.navigate
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("dev.mambo.play.navigate", appContext.packageName)
}
} | JustNavigate/app/src/androidTest/java/dev/mambo/play/navigate/ExampleInstrumentedTest.kt | 2823670406 |
package dev.mambo.play.navigate
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)
}
} | JustNavigate/app/src/test/java/dev/mambo/play/navigate/ExampleUnitTest.kt | 389052101 |
package dev.mambo.play.navigate.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | JustNavigate/app/src/main/java/dev/mambo/play/navigate/ui/theme/Color.kt | 2171457485 |
package dev.mambo.play.navigate.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun NavigateTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | JustNavigate/app/src/main/java/dev/mambo/play/navigate/ui/theme/Theme.kt | 814058906 |
package dev.mambo.play.navigate.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
)
*/
) | JustNavigate/app/src/main/java/dev/mambo/play/navigate/ui/theme/Type.kt | 3670823490 |
package dev.mambo.play.navigate
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import dev.mambo.play.navigate.navigation.Navigator
import dev.mambo.play.navigate.ui.theme.NavigateTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
NavigateTheme {
Navigator()
}
}
}
}
| JustNavigate/app/src/main/java/dev/mambo/play/navigate/MainActivity.kt | 2223350699 |
package dev.mambo.play.navigate.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import dev.mambo.play.navigate.list.ListScreen
import dev.mambo.play.navigate.listdetail.ListDetailScreen
/**
* project : Navigate
* date : Tuesday 23/04/2024
* user : mambo
* email : [email protected]
*/
// TODO : 4 - declare a composable to handle all your navigation
@Composable
fun Navigator() {
// TODO : 6 - declare a nav controller
val navController = rememberNavController()
// TODO : 7 - declare a nav host with a prefilled start destination
NavHost(navController = navController, startDestination = Destinations.List.route) {
// TODO : 8 - for each destination, add a route and the composable to show
composable(route = Destinations.List.route) {
ListScreen(onClickItem = { navController.navigate(Destinations.Detail(id = it).route) })
}
composable(
route = Destinations.Detail.route,
arguments = listOf(navArgument(Destinations.Detail.KEY) { type = NavType.IntType })
) {
val id: Int? = it.arguments?.getInt(Destinations.Detail.KEY)
ListDetailScreen(id = id, onClickNavigateBack = { navController.popBackStack() })
}
}
} | JustNavigate/app/src/main/java/dev/mambo/play/navigate/navigation/Navigator.kt | 1127225605 |
package dev.mambo.play.navigate.navigation
/**
* project : Navigate
* date : Tuesday 23/04/2024
* user : mambo
* email : [email protected]
*/
// TODO : 5 - declare a class to hold all your destination routes (decided to use a sealed class cause of difference in class type declarations)
sealed class Destinations(private val path: String) {
val route: String
get() = buildString {
append("navigate/")
append(path)
}
data object List : Destinations(path = "list")
data class Detail(val id: Int) : Destinations(path = "list/$id") {
companion object : Destinations(path = "list/{id}") {
const val KEY: String = "id"
}
}
} | JustNavigate/app/src/main/java/dev/mambo/play/navigate/navigation/Destinations.kt | 407500451 |
package dev.mambo.play.navigate.listdetail
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("dev.mambo.play.navigate.listdetail.test", appContext.packageName)
}
} | JustNavigate/features/listdetail/src/androidTest/java/dev/mambo/play/navigate/listdetail/ExampleInstrumentedTest.kt | 3470798659 |
package dev.mambo.play.navigate.listdetail
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)
}
} | JustNavigate/features/listdetail/src/test/java/dev/mambo/play/navigate/listdetail/ExampleUnitTest.kt | 304347800 |
package dev.mambo.play.navigate.listdetail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* project : Navigate
* date : Tuesday 23/04/2024
* user : mambo
* email : [email protected]
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ListDetailScreen(
id: Int?,
onClickNavigateBack: () -> Unit,
) {
Scaffold(topBar = {
TopAppBar(navigationIcon = {
IconButton(onClick = onClickNavigateBack) {
Icon(imageVector = Icons.Rounded.ArrowBack, contentDescription = "navigate back")
}
}, title = { Text(text = "Detail") })
}) {
Column(
modifier = Modifier
.padding(it)
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Card(
modifier = Modifier
.fillMaxSize()
.padding(24.dp)
) {
Column(
modifier = Modifier
.padding(it)
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "$id", fontSize = 48.sp)
}
}
}
}
} | JustNavigate/features/listdetail/src/main/java/dev/mambo/play/navigate/listdetail/ListDetailScreen.kt | 1939751150 |
package dev.mambo.play.navigate.list
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("dev.mambo.play.navigate.list.test", appContext.packageName)
}
} | JustNavigate/features/list/src/androidTest/java/dev/mambo/play/navigate/list/ExampleInstrumentedTest.kt | 3850524772 |
package dev.mambo.play.navigate.list
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)
}
} | JustNavigate/features/list/src/test/java/dev/mambo/play/navigate/list/ExampleUnitTest.kt | 3037713917 |
package dev.mambo.play.navigate.list
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* project : Navigate
* date : Tuesday 23/04/2024
* user : mambo
* email : [email protected]
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ListScreen(onClickItem: (Int) -> Unit) {
Scaffold(topBar = { TopAppBar(title = { Text(text = "Navigate") }) }) {
Column(
modifier = Modifier
.padding(it)
.fillMaxSize()
) {
LazyColumn {
items(20) {
Card(
modifier = Modifier
.padding(8.dp)
.fillParentMaxWidth(),
onClick = { onClickItem.invoke(it) }
) {
Text(modifier = Modifier.padding(16.dp), text = "$it", fontSize = 24.sp)
}
}
}
}
}
} | JustNavigate/features/list/src/main/java/dev/mambo/play/navigate/list/ListScreen.kt | 1467140739 |
package com.stepan.listpay
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("com.stepan.listpay", appContext.packageName)
}
} | ListPay/app/src/androidTest/java/com/stepan/listpay/ExampleInstrumentedTest.kt | 2613689308 |
package com.stepan.listpay
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)
}
} | ListPay/app/src/test/java/com/stepan/listpay/ExampleUnitTest.kt | 2351368665 |
package com.stepan.listpay
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
class MainActivity : AppCompatActivity() {
private var navController: NavController? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host) as NavHostFragment
navController = navHostFragment.navController
}
} | ListPay/app/src/main/java/com/stepan/listpay/MainActivity.kt | 459526082 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.