content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.fitness.search.screens.time
import com.fitness.search.SearchRecipeStep
import com.fitness.search.RecipeSearchStateHolder
import dagger.hilt.android.lifecycle.HiltViewModel
import failure.GenericFailure
import state.BaseViewState
import viewmodel.IntentViewModel
import javax.inject.Inject
@HiltViewModel
class PickTimeViewModel @Inject constructor(private val searchStateHolder: RecipeSearchStateHolder, ) : IntentViewModel<BaseViewState<PickTimeState>, PickTimeEvent>() {
init { initialize() }
override fun onTriggerEvent(event: PickTimeEvent) {
if(event is PickTimeEvent.TimeSelected){
onTimeSelected(event)
}else{
handleError(GenericFailure())
}
}
private fun initialize() = setState(BaseViewState.Data(PickTimeState()))
private fun onTimeSelected(event: PickTimeEvent.TimeSelected) = safeLaunch {
val state = searchStateHolder.state().copy(hour = event.hour, minute = event.minute)
searchStateHolder.updateState(state)
setState(BaseViewState.Data(PickTimeState(step = SearchRecipeStep.COMPLETE,)))
}
} | body-balance/features/search/impl/src/main/kotlin/com/fitness/search/screens/time/PickTimeViewModel.kt | 4121100791 |
package com.fitness.search
import com.fitness.navigation.AggregateFeatureEntry
interface RecipeSearchEntry: AggregateFeatureEntry
| body-balance/features/search/api/src/main/kotlin/com.fitness.search/RecipeSearchEntry.kt | 3377032902 |
package com.fitness.dashboard.di
import com.fitness.dashboard.DashboardEntry
import com.fitness.dashboard.navigation.DashboardEntryImpl
import com.fitness.navigation.FeatureEntry
import com.fitness.navigation.FeatureEntryKey
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoMap
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
interface DashboardEntryModule {
@Binds
@Singleton
@IntoMap
@FeatureEntryKey(DashboardEntry::class)
fun dashboardEntry(entry: DashboardEntryImpl) : FeatureEntry
} | body-balance/features/dashboard/impl/src/main/kotlin/com/fitness/dashboard/di/DashboardEntryModule.kt | 623975503 |
package com.fitness.dashboard.navigation
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.navigation.NavBackStackEntry
import com.fitness.resources.R
import androidx.navigation.NavHostController
import com.fitness.component.screens.MessageScreen
import com.fitness.dashboard.DashboardEntry
import com.fitness.navigation.Destinations
import com.google.firebase.auth.FirebaseAuth
import javax.inject.Inject
class DashboardEntryImpl @Inject constructor() : DashboardEntry() {
companion object {}
@Composable
override fun Composable(
navController: NavHostController,
destinations: Destinations,
backStackEntry: NavBackStackEntry
) {
MessageScreen(message = R.string.code_verification, onClick = {Log.e("DashboardEntryImpl", "${FirebaseAuth.getInstance().currentUser}")})
}
} | body-balance/features/dashboard/impl/src/main/kotlin/com/fitness/dashboard/navigation/DashboardEntryImpl.kt | 1061941993 |
package com.fitness.dashboard
import com.fitness.navigation.ComposableFeatureEntry
abstract class DashboardEntry: ComposableFeatureEntry {
override val featureRoute: String get() = "dashboard"
} | body-balance/features/dashboard/api/src/main/kotlin/com/fitness/dashboard/DashboardEntry.kt | 807337894 |
package com.fitness.signout.viewmodel
import com.fitness.authentication.manager.AuthenticationState
data class SignOutState(val authenticationState: AuthenticationState = AuthenticationState.UnAuthenticated)
sealed class SignOutEvent {
object ForceSignOut: SignOutEvent()
object SignOut: SignOutEvent()
} | body-balance/features/signout/impl/src/main/kotlin/com/fitness/signout/viewmodel/SignOutContract.kt | 535001957 |
package com.fitness.signout.viewmodel
import com.fitness.authentication.manager.AuthenticationManager
import com.fitness.authentication.manager.AuthenticationState
import com.fitness.domain.usecase.auth.SignOutUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import state.BaseViewState
import viewmodel.IntentViewModel
import javax.inject.Inject
@HiltViewModel
class SignOutViewModel @Inject constructor(
private val signOutUseCase: SignOutUseCase,
private val authStateManager: AuthenticationManager
): IntentViewModel<BaseViewState<SignOutState>, SignOutEvent>() {
init { setState(BaseViewState.Data(SignOutState())) }
override fun onTriggerEvent(event: SignOutEvent) {
when(event){
SignOutEvent.SignOut -> onSignOut()
SignOutEvent.ForceSignOut -> onForceSignOut()
}
}
private fun onSignOut() = safeLaunch {
execute(signOutUseCase(SignOutUseCase.Params)) {
authStateManager.update(AuthenticationState.UnAuthenticated)
}
}
private fun onForceSignOut() = safeLaunch {
execute(signOutUseCase(SignOutUseCase.Params)){
authStateManager.update(AuthenticationState.UnAuthenticated)
}
}
} | body-balance/features/signout/impl/src/main/kotlin/com/fitness/signout/viewmodel/SignOutViewModel.kt | 1690099519 |
package com.fitness.signout.di
import com.fitness.navigation.FeatureEntry
import com.fitness.navigation.FeatureEntryKey
import com.fitness.signout.SignOutEntry
import com.fitness.signout.navigation.SignOutEntryImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoMap
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
interface SignOutEntryModule {
@Binds
@Singleton
@IntoMap
@FeatureEntryKey(SignOutEntry::class)
fun signOutEntry(entry: SignOutEntryImpl) : FeatureEntry
} | body-balance/features/signout/impl/src/main/kotlin/com/fitness/signout/di/SignOutEntryModule.kt | 2783335034 |
package com.fitness.signout.navigation
import androidx.compose.runtime.Composable
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import com.fitness.navigation.Destinations
import com.fitness.signout.SignOutEntry
import com.fitness.signout.view.SignOut
import com.fitness.signout.viewmodel.SignOutViewModel
import javax.inject.Inject
class SignOutEntryImpl @Inject constructor(): SignOutEntry {
@Composable
override fun Composable(navController: NavHostController, destinations: Destinations, backStackEntry: NavBackStackEntry) {
val viewModel: SignOutViewModel = hiltViewModel()
SignOut(onTriggerEvent = { viewModel.onTriggerEvent(it) })
}
} | body-balance/features/signout/impl/src/main/kotlin/com/fitness/signout/navigation/SignOutEntryImpl.kt | 1782399601 |
package com.fitness.signout.view
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import com.fitness.component.screens.LoadingScreen
import com.fitness.signout.viewmodel.SignOutEvent
import com.fitness.signout.viewmodel.SignOutState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import state.BaseViewState
@Composable
fun SignOut(
state: StateFlow<BaseViewState<SignOutState>> = MutableStateFlow(BaseViewState.Data(SignOutState())),
onTriggerEvent: (SignOutEvent) -> Unit,
){
val uiState by state.collectAsState()
when(uiState){
is BaseViewState.Loading,
is BaseViewState.Data -> {
LoadingScreen()
onTriggerEvent(SignOutEvent.SignOut)
}
is BaseViewState.Error,
is BaseViewState.Empty -> {
LoadingScreen()
onTriggerEvent(SignOutEvent.ForceSignOut)
}
}
} | body-balance/features/signout/impl/src/main/kotlin/com/fitness/signout/view/SignOut.kt | 898409235 |
package com.fitness.signout
import com.fitness.navigation.ComposableFeatureEntry
interface SignOutEntry: ComposableFeatureEntry {
override val featureRoute: String get() = "sign-out"
} | body-balance/features/signout/api/src/main/kotlin/com/fitness/signout/SignOutEntry.kt | 2154899234 |
package com.fitness.userprofile.di
import com.fitness.navigation.FeatureEntry
import com.fitness.navigation.FeatureEntryKey
import com.fitness.userprofile.UserProfileEntry
import com.fitness.userprofile.navigation.UserProfileEntryImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoMap
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
interface UserProfileEntryModule {
@Binds
@Singleton
@IntoMap
@FeatureEntryKey(UserProfileEntry::class)
fun userProfileEntry(entry: UserProfileEntryImpl): FeatureEntry
} | body-balance/features/user-profile/impl/src/main/kotlin/com/fitness/userprofile/di/UserProfileEntryModule.kt | 225595245 |
package com.fitness.userprofile.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import com.fitness.navigation.Destinations
import com.fitness.userprofile.UserProfileEntry
import javax.inject.Inject
class UserProfileEntryImpl @Inject constructor(): UserProfileEntry {
@Composable
override fun Composable(navController: NavHostController, destinations: Destinations, backStackEntry: NavBackStackEntry) {}
} | body-balance/features/user-profile/impl/src/main/kotlin/com/fitness/userprofile/navigation/UserProfileEntryImpl.kt | 3121460603 |
package com.fitness.userprofile
import com.fitness.navigation.ComposableFeatureEntry
interface UserProfileEntry: ComposableFeatureEntry {
override val featureRoute: String get() = "user-profile"
} | body-balance/features/user-profile/api/src/main/kotlin/com/fitness/userprofile/UserProfileEntry.kt | 3199757841 |
package com.fitness.authentication.home.viewmodel
import dagger.hilt.android.lifecycle.HiltViewModel
import state.BaseViewState
import viewmodel.IntentViewModel
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(): IntentViewModel<BaseViewState<HomeState>, HomeEvent>() {
init {
setState(
BaseViewState.Data(HomeState())
)
}
override fun onTriggerEvent(event: HomeEvent) {
when(event){
is HomeEvent.CheckBoxChanged -> {
onCheckBoxChanged(event)
}
is HomeEvent.SignIn -> {
onSignIn(event)
}
is HomeEvent.SignUp -> {
onSignUp(event)
}
}
}
private fun onCheckBoxChanged(event: HomeEvent.CheckBoxChanged){
val state = if(event.newState){
CheckBoxState.OK
}
else{
CheckBoxState.NONE
}
setState(BaseViewState.Data(HomeState(hasAgreed = event.newState, checkBoxState = state)))
}
private fun onSignIn(event: HomeEvent.SignIn){
val state = if(event.hasAgreed){
startLoading()
HomeState(hasAgreed = true, direction = Direction.SIGN_IN)
}
else{
HomeState(checkBoxState = CheckBoxState.ERROR)
}
setState(BaseViewState.Data(state))
}
private fun onSignUp(event: HomeEvent.SignUp){
val state = if(event.hasAgreed){
startLoading()
HomeState(hasAgreed = true, direction = Direction.SIGN_UP)
}
else{
HomeState(checkBoxState = CheckBoxState.ERROR)
}
setState(BaseViewState.Data(state))
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/home/viewmodel/HomeViewModel.kt | 306785311 |
package com.fitness.authentication.home.viewmodel
enum class CheckBoxState{
NONE,
ERROR,
OK
}
enum class Direction{
NONE,
SIGN_IN,
SIGN_UP
}
data class HomeState(
val hasAgreed: Boolean = false,
val checkBoxState: CheckBoxState = CheckBoxState.NONE,
val direction: Direction = Direction.NONE
)
sealed class HomeEvent {
data class CheckBoxChanged(val newState: Boolean): HomeEvent()
data class SignIn(val hasAgreed: Boolean): HomeEvent()
data class SignUp(val hasAgreed: Boolean): HomeEvent()
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/home/viewmodel/HomeContract.kt | 324206355 |
package com.fitness.authentication.home.view
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.fitness.authentication.home.viewmodel.CheckBoxState
import com.fitness.authentication.home.viewmodel.Direction
import com.fitness.authentication.home.viewmodel.HomeEvent
import com.fitness.authentication.home.viewmodel.HomeState
import com.fitness.authentication.navigation.AuthEntryImpl.Companion.signInEmail
import com.fitness.authentication.navigation.AuthEntryImpl.Companion.signUp
import com.fitness.authentication.util.TermsAndPrivacyAnnotatedText
import com.fitness.component.components.StandardButton
import com.fitness.component.properties.GuidelineProperties
import com.fitness.component.screens.ErrorScreen
import com.fitness.component.screens.LoadingScreen
import com.fitness.component.screens.MessageScreen
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
import com.fitness.theme.ui.Green
import com.fitness.theme.ui.Red
import extensions.Dark
import extensions.Light
import extensions.cast
import failure.Failure
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import state.BaseViewState
@Dark
@Light
@Composable
private fun AcceptTermsAndPrivacy() = BodyBalanceTheme {
Surface {
AcceptTermsAndPrivacyContent()
}
}
@Composable
fun AcceptTermsAndPrivacy(
state: StateFlow<BaseViewState<HomeState>> = MutableStateFlow(BaseViewState.Data(HomeState())),
onPopBack: () -> Unit = {},
onTriggerEvent: (HomeEvent) -> Unit = {},
onTriggerNavigation: (String) -> Unit = {}
) {
val uiState by state.collectAsState()
when (uiState) {
is BaseViewState.Data -> {
val currentState = uiState.cast<BaseViewState.Data<HomeState>>().value
if (currentState.direction != Direction.NONE && currentState.hasAgreed) {
if (currentState.direction == Direction.SIGN_IN) {
onTriggerNavigation(signInEmail)
} else {
onTriggerNavigation(signUp)
}
}
else {
AcceptTermsAndPrivacyContent(state = currentState, onTriggerEvent = onTriggerEvent)
}
}
is Error -> {
val failure = uiState.cast<BaseViewState.Error>().failure as Failure
ErrorScreen(title = failure.title, description = failure.description) {
onPopBack()
}
}
is BaseViewState.Loading -> {
LoadingScreen()
}
else -> {
MessageScreen(message = R.string.unknown, onClick = onPopBack)
}
}
}
@Composable
private fun AcceptTermsAndPrivacyContent(
state: HomeState = HomeState(), onTriggerEvent: (HomeEvent) -> Unit = {},
) {
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val (
checkmark,
signUp,
signIn,
) = createRefs()
val bottomGuideline = createGuidelineFromBottom(GuidelineProperties.BOTTOM_100)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
val colors = when (state.checkBoxState) {
CheckBoxState.ERROR -> {
CheckboxDefaults.colors(checkedColor = Green, uncheckedColor = Red)
}
CheckBoxState.OK -> {
CheckboxDefaults.colors(checkedColor = Green)
}
CheckBoxState.NONE -> {
CheckboxDefaults.colors(checkedColor = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier.constrainAs(checkmark){
bottom.linkTo(signIn.top, 50.dp)
start.linkTo(startGuideline)
end.linkTo(endGuideline)
width = Dimension.fillToConstraints
}
) {
Checkbox(
checked = state.hasAgreed,
onCheckedChange = {
onTriggerEvent(HomeEvent.CheckBoxChanged(it))
},
colors = colors
)
TermsAndPrivacyAnnotatedText(
onClickTerms = { },
onClickPrivacy = { }
)
}
StandardButton(
text = R.string.sign_in,
onClick = { onTriggerEvent(HomeEvent.SignIn(state.hasAgreed)) },
modifier = Modifier.constrainAs(signIn){
bottom.linkTo(signUp.top, 20.dp)
start.linkTo(startGuideline)
end.linkTo(endGuideline)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.sign_up,
onClick = { onTriggerEvent(HomeEvent.SignUp(state.hasAgreed)) },
modifier = Modifier.constrainAs(signUp){
bottom.linkTo(bottomGuideline)
start.linkTo(startGuideline)
end.linkTo(endGuideline)
width = Dimension.fillToConstraints
}
)
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/home/view/Home.kt | 3297649742 |
package com.fitness.authentication.di
import com.fitness.authentication.AuthEntry
import com.fitness.navigation.FeatureEntry
import com.fitness.navigation.FeatureEntryKey
import com.fitness.authentication.navigation.AuthEntryImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoMap
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
interface AuthEntryModule {
@Binds
@Singleton
@IntoMap
@FeatureEntryKey(AuthEntry::class)
fun authEntry(entry: AuthEntryImpl) : FeatureEntry
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/di/AuthEntryModule.kt | 3695877623 |
package com.fitness.authentication.di
import android.app.Application
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class AuthModule {
@Singleton
@Provides
fun provideGoogleSignInOptions(): GoogleSignInOptions =
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("")
.requestEmail()
.build()
@Singleton
@Provides
fun provideGoogleSignInClient(application: Application, options: GoogleSignInOptions): GoogleSignInClient =
GoogleSignIn.getClient(application, options)
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/di/AuthModule.kt | 115131362 |
package com.fitness.authentication.util
object AuthStateHolder {
private var authState: AuthState = AuthState()
fun getState() = authState
fun updateState(newState: AuthState) {
authState = newState
}
fun clearState() {
authState = AuthState()
}
}
data class AuthState(
val firstName: String = "",
val lastName: String = "",
val email: String? = null,
val phoneNumber: String? = null,
val verificationId: String = ""
)
| body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/util/AuthStateHolder.kt | 3999520587 |
package com.fitness.authentication.util
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.fitness.component.components.StandardButton
import com.fitness.component.components.StandardText
import com.fitness.component.components.StandardTextField
import com.fitness.component.components.StandardTextSmall
import com.fitness.component.properties.GuidelineProperties
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun ConfirmationCodePreview() {
BodyBalanceTheme {
Surface {
ConfirmationCodeScreen()
}
}
}
@Composable
fun ConfirmationCodeScreen(onClickContinue: () -> Unit = {}) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
welcome,
message,
phone,
signUp,
) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
var userCode by remember { mutableStateOf("") }
StandardText(
text = R.string.welcome_to_body_balance,
textAlign = TextAlign.Start,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
top.linkTo(topGuideline)
bottom.linkTo(message.top)
}
)
StandardTextSmall(
text = R.string.in_a_moment_you_receive_a_cod,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userCode,
hint = R.string.enter_code,
label = R.string.label_code,
onValueChanged = { userCode = it },
modifier = Modifier.constrainAs(phone) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.title_continue,
onClick = onClickContinue,
modifier = Modifier.constrainAs(signUp) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(phone.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/util/ConfirmPhoneNumber.kt | 1026775554 |
package com.fitness.authentication.util
import android.content.res.Configuration
import android.util.Patterns
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.Icon
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.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.fitness.resources.R
import com.fitness.theme.ui.Green
import com.fitness.theme.ui.Red
import com.fitness.theme.ui.primaryVariantHub
import extensions.TextFieldState
fun isVerified(vararg credentials: Int): Boolean = credentials.all { it == 0 }
fun verifyName(name: String): Pair<TextFieldState, Int> =
if (name.length >= 2) {
TextFieldState.OK to 0
} else {
TextFieldState.ERROR to R.string.auth_name_length_error
}
fun verifyEmail(email: String): Pair<TextFieldState, Int> =
if (email.matches(Patterns.EMAIL_ADDRESS.toRegex())) {
TextFieldState.OK to 0
} else {
TextFieldState.ERROR to R.string.auth_invalid_email_format
}
fun verifyPhone(phone: String?): Pair<TextFieldState, Int> =
if (phone!= null && Patterns.PHONE.matcher(phone).matches()) {
TextFieldState.OK to 0
} else {
TextFieldState.ERROR to R.string.auth_invalid_phone_format
}
fun verifyPassword(password: String): Pair<TextFieldState, Int> {
val errorMessages = mutableListOf<Int>()
if (password.length < 8) {
errorMessages.add(R.string.auth_password_length_error)
}
if (!password.matches(".*[a-z].*".toRegex())) {
errorMessages.add(R.string.auth_password_lowercase_error)
}
if (!password.matches(".*[A-Z].*".toRegex())) {
errorMessages.add(R.string.auth_password_uppercase_error)
}
if (!password.matches(".*\\d.*".toRegex())) {
errorMessages.add(R.string.auth_password_digit_error)
}
if (!password.matches(".*[@$!%*?&].*".toRegex())) {
errorMessages.add(R.string.auth_password_special_char_error)
}
return if (errorMessages.isEmpty()) {
TextFieldState.OK to 0
} else {
// Assuming you want to return the first error encountered
TextFieldState.ERROR to errorMessages.first()
}
}
@Composable
fun PasswordTrailingIcon(
state: TextFieldState,
isVisible: Boolean,
onIconClick: () -> Unit = {}
){
Row {
DisplayPassword(isVisible = isVisible, onIconClick = onIconClick)
Spacer(modifier = Modifier.size(5.dp))
DisplayFieldState(state = state)
Spacer(modifier = Modifier.size(5.dp))
}
}
@Composable
fun DisplayPassword(
isVisible: Boolean,
onIconClick: () -> Unit = {}
) =
if(isVisible){
Icon(
painter = painterResource(id = R.drawable.icon_open_eye),
contentDescription = stringResource(id = R.string.content_description_open_eye),
tint = Green,
modifier = Modifier.clickable { onIconClick() }
)
}else{
Icon(
painter = painterResource(id = R.drawable.icon_closed_eye),
contentDescription = stringResource(id = R.string.content_description_closed_eye),
tint = Green,
modifier = Modifier.clickable { onIconClick() }
)
}
@Composable
fun DisplayFieldState(state: TextFieldState) =
when (state) {
TextFieldState.PENDING -> {
Spacer(modifier = Modifier.size(24.dp))
}
TextFieldState.OK -> {
Icon(
painter = painterResource(id = R.drawable.icon_checkmark),
contentDescription = stringResource(id = R.string.content_description_email),
tint = Green
)
}
TextFieldState.ERROR -> {
Icon(
painter = painterResource(id = R.drawable.icon_error),
contentDescription = stringResource(id = R.string.content_description_email),
tint = Red
)
}
}
@Composable
fun DisplayErrorMessage(state: TextFieldState, errorMessageId: Int?) {
if (state == TextFieldState.ERROR) {
errorMessageId?.let {
Text(
text = stringResource(id = errorMessageId),
color = Red
)
}
}
}
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun SignUpAnnotatedText(
modifier: Modifier = Modifier,
onClick: () -> Unit = {}
) {
val annotatedString = buildAnnotatedString {
append(stringResource(id = R.string.do_not_have_an_account_1_2))
append(" ")
// Create a clickable part of the text
pushStringAnnotation(tag = "signUp", annotation = "signUp")
withStyle(style = SpanStyle(color = Color.Blue)) {
append(stringResource(id = R.string.sign_up))
}
pop()
}
ClickableText(
text = annotatedString,
modifier = modifier,
onClick = { offset ->
annotatedString.getStringAnnotations(tag = "signUp", start = offset, end = offset)
.firstOrNull()?.let {
onClick()
}
}
)
}
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun SignInAnnotatedText(
modifier: Modifier = Modifier,
onClick: () -> Unit = {}
) {
val annotatedString = buildAnnotatedString {
append(stringResource(id = R.string.already_have_an_account_1_2))
append(" ")
// Create a clickable part of the text
pushStringAnnotation(tag = "signIn", annotation = "signIn")
withStyle(style = SpanStyle(color = primaryVariantHub)) {
append(stringResource(id = R.string.sign_in))
}
pop()
}
ClickableText(
text = annotatedString,
modifier = modifier,
onClick = { offset ->
annotatedString.getStringAnnotations(tag = "signIn", start = offset, end = offset)
.firstOrNull()?.let {
onClick()
}
}
)
}
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun TermsAndPrivacyAnnotatedText(
modifier: Modifier = Modifier,
onClickTerms: () -> Unit = {},
onClickPrivacy: () -> Unit = {}
) {
val annotatedString = buildAnnotatedString {
append(stringResource(id = R.string.terms_and_privacy_1_4))
append(" ")
// Create a clickable part of the text
pushStringAnnotation(tag = "terms", annotation = "terms")
withStyle(style = SpanStyle(color = primaryVariantHub)) {
append(stringResource(id = R.string.terms_and_privacy_2_4))
}
pop()
append(" ")
append(stringResource(id = R.string.terms_and_privacy_3_4))
append(" ")
pushStringAnnotation(tag = "privacy", annotation = "privacy")
withStyle(style = SpanStyle(color = primaryVariantHub)) {
append(stringResource(id = R.string.terms_and_privacy_4_4))
}
pop()
}
ClickableText(
text = annotatedString,
modifier = modifier,
onClick = { offset ->
annotatedString.getStringAnnotations(tag = "terms", start = offset, end = offset)
.firstOrNull()?.let {
onClickTerms()
}
annotatedString.getStringAnnotations(tag = "privacy", start = offset, end = offset)
.firstOrNull()?.let {
onClickPrivacy()
}
}
)
}
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun ForgotPasswordAnnotatedText(
modifier: Modifier = Modifier,
onClick: () -> Unit = {}
) {
val annotatedString = buildAnnotatedString {
pushStringAnnotation(tag = "forgotPassword", annotation = "forgotPassword")
withStyle(style = SpanStyle(color = primaryVariantHub)) {
append(stringResource(id = R.string.forgot_password))
}
pop()
}
ClickableText(
text = annotatedString,
modifier = modifier,
onClick = { offset ->
annotatedString.getStringAnnotations(tag = "forgotPassword", start = offset, end = offset)
.firstOrNull()?.let {
onClick()
}
}
)
}
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun NewNumberAnnotatedText(
modifier: Modifier = Modifier,
onClick: () -> Unit = {}
) {
val annotatedString = buildAnnotatedString {
// Create a clickable part of the text
pushStringAnnotation(tag = "newNumber", annotation = "newNumber")
withStyle(style = SpanStyle(color = primaryVariantHub)) {
append(stringResource(id = R.string.new_number))
}
pop()
}
ClickableText(
text = annotatedString,
modifier = modifier,
onClick = { offset ->
annotatedString.getStringAnnotations(tag = "newNumber", start = offset, end = offset)
.firstOrNull()?.let {
onClick()
}
}
)
}
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun SignUpForFreeAnnotatedText(
modifier: Modifier = Modifier,
onClick: () -> Unit = {}
) {
val annotatedString = buildAnnotatedString {
pushStringAnnotation(tag = "signUpForFree", annotation = "signUpForFree")
withStyle(style = SpanStyle(color = primaryVariantHub)) {
append(stringResource(id = R.string.sign_up_for_free))
}
pop()
}
ClickableText(
text = annotatedString,
modifier = modifier,
onClick = { offset ->
annotatedString.getStringAnnotations(tag = "signUpForFree", start = offset, end = offset)
.firstOrNull()?.let {
onClick()
}
}
)
}
enum class AuthMethod {
NONE, EMAIL, PHONE, GOOGLE, FACEBOOK, X
}
fun updatePhoneState(
firstname: String? = null,
lastname: String? = null,
phoneNumber: String? = null,
verificationId: String? = null
) {
firstname?.let {
if(firstname.isNotEmpty()){
AuthStateHolder.updateState(
AuthStateHolder.getState().copy(firstName = firstname)
)
}
}
lastname?.let {
if (lastname.isNotEmpty()){
AuthStateHolder.updateState(
AuthStateHolder.getState().copy(lastName = lastname)
)
}
}
phoneNumber?.let {
if(phoneNumber.isNotEmpty()){
AuthStateHolder.updateState(
AuthStateHolder.getState().copy(phoneNumber = phoneNumber)
)
}
}
verificationId?.let {
if(verificationId.isNotEmpty()){
AuthStateHolder.updateState(
AuthStateHolder.getState().copy(verificationId = verificationId)
)
}
}
}
| body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/util/Util.kt | 1794631879 |
package com.fitness.authentication.signup.viewmodel
import com.fitness.authentication.util.AuthMethod
import auth.PhoneAuthState
import extensions.TextFieldState
data class SignUpState(
var authMethod: AuthMethod = AuthMethod.NONE,
var phoneAuthState: PhoneAuthState = PhoneAuthState.Idle,
var firstnameState: TextFieldState = TextFieldState.PENDING,
var lastnameState: TextFieldState = TextFieldState.PENDING,
var emailState: TextFieldState = TextFieldState.PENDING,
var phoneState: TextFieldState = TextFieldState.PENDING,
var passwordState: TextFieldState = TextFieldState.PENDING,
var codeState: TextFieldState = TextFieldState.PENDING,
var firstnameErrorMessage: Int? = null,
var lastnameErrorMessage: Int? = null,
var emailErrorMessage: Int? = null,
var phoneErrorMessage: Int? = null,
var passwordErrorMessage: Int? = null,
var codeErrorMessage: Int? = null,
var isSignUpCompleted: Boolean = false
)
sealed class SignUpEvent {
data class EmailPasswordAuthData(
val firstname: String,
val lastname: String,
val email: String,
val password: String
) : SignUpEvent()
data class PhoneAuthentication(
val firstname: String,
val lastname: String,
val phoneNumber: String
) : SignUpEvent()
data class VerifyPhoneAuthentication(val verificationId: String, val code: String) : SignUpEvent()
data class SelectAuthMethod(val method: AuthMethod) : SignUpEvent()
data class ThirdPartyAuthError(val error: Throwable) : SignUpEvent()
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signup/viewmodel/SignUpContract.kt | 791001776 |
package com.fitness.authentication.signup.viewmodel
import auth.PhoneVerificationError
import auth.formatPhoneNumberToE164
import auth.toAuthFailure
import com.fitness.authentication.manager.AuthenticationManager
import com.fitness.authentication.manager.AuthenticationState
import com.fitness.authentication.util.AuthStateHolder
import com.fitness.authentication.util.isVerified
import com.fitness.authentication.util.updatePhoneState
import com.fitness.authentication.util.verifyEmail
import com.fitness.authentication.util.verifyName
import com.fitness.authentication.util.verifyPassword
import com.fitness.authentication.util.verifyPhone
import auth.PhoneAuthState
import com.fitness.domain.model.user.User
import com.fitness.domain.usecase.auth.EmailPasswordSignUpUseCase
import com.fitness.domain.usecase.auth.SendVerificationCodeUseCase
import com.fitness.domain.usecase.auth.VerifyPhoneNumberUseCase
import com.fitness.domain.usecase.user.CreateUserUseCase
import com.fitness.resources.R
import dagger.hilt.android.lifecycle.HiltViewModel
import extensions.TextFieldState
import state.BaseViewState
import viewmodel.IntentViewModel
import javax.inject.Inject
@HiltViewModel
class SignUpViewModel @Inject constructor(
private val sendVerificationCodeUseCase: SendVerificationCodeUseCase,
private val verificationCodeUseCase: VerifyPhoneNumberUseCase,
private val emailPasswordSignUpUseCase: EmailPasswordSignUpUseCase,
private val createUserUseCase: CreateUserUseCase,
private val authManager: AuthenticationManager
) : IntentViewModel<BaseViewState<SignUpState>, SignUpEvent>() {
init {
setState(BaseViewState.Data(SignUpState()))
}
override fun onTriggerEvent(event: SignUpEvent) {
when (event) {
is SignUpEvent.EmailPasswordAuthData -> {
verifyEmailAuthenticationData(event)
}
is SignUpEvent.PhoneAuthentication -> {
verifyPhoneAuthenticationData(event)
}
is SignUpEvent.VerifyPhoneAuthentication -> {
onVerifyPhoneNumber(event)
}
is SignUpEvent.SelectAuthMethod -> {
onSelectAuthMethod(event)
}
is SignUpEvent.ThirdPartyAuthError -> {
handleError(event.error)
}
}
}
override fun handleError(exception: Throwable) {
if (exception is PhoneVerificationError) {
onResetVerifyPhoneNumber()
} else {
super.handleError(exception.toAuthFailure())
}
}
private fun verifyEmailAuthenticationData(event: SignUpEvent.EmailPasswordAuthData) {
val (firstnameState, firstnameError) = verifyName(event.firstname)
val (lastnameState, lastnameError) = verifyName(event.lastname)
val (emailState, emailError) = verifyEmail(event.email)
val (passwordState, passwordError) = verifyPassword(event.password)
if (isVerified(firstnameError, lastnameError, emailError, passwordError)) {
onEmailPasswordAuthentication(
event.firstname,
event.lastname,
event.email,
event.password
)
} else {
onEmailAuthCredentialsError(
firstnameState,
lastnameState,
emailState,
passwordState,
firstnameError,
lastnameError,
emailError,
passwordError
)
}
}
private fun verifyPhoneAuthenticationData(event: SignUpEvent.PhoneAuthentication) {
val (firstnameState, firstnameError) = verifyName(event.firstname)
val (lastnameState, lastnameError) = verifyName(event.lastname)
val (phoneState, phoneError) = verifyPhone(event.phoneNumber)
val formattedPhoneNumber = formatPhoneNumberToE164(event.phoneNumber, "US")
if (formattedPhoneNumber != null && isVerified(firstnameError, lastnameError, phoneError)) {
onPhoneAuthentication(event.firstname, event.lastname, formattedPhoneNumber)
} else {
val phoneStateError =
if (formattedPhoneNumber == null) TextFieldState.ERROR else phoneState
val phoneErrorMsg =
if (formattedPhoneNumber == null) R.string.invalid_phone_number_format else phoneError
onPhoneAuthCredentialsError(
firstnameState,
lastnameState,
phoneStateError,
firstnameError,
lastnameError,
phoneErrorMsg
)
}
}
private fun onEmailAuthCredentialsError(
firstnameState: TextFieldState,
lastnameState: TextFieldState,
emailState: TextFieldState,
passwordState: TextFieldState,
firstnameError: Int,
lastnameError: Int,
emailError: Int,
passwordError: Int
) {
setState(
BaseViewState.Data(
SignUpState(
firstnameState = firstnameState,
lastnameState = lastnameState,
emailState = emailState,
passwordState = passwordState,
firstnameErrorMessage = firstnameError,
lastnameErrorMessage = lastnameError,
emailErrorMessage = emailError,
passwordErrorMessage = passwordError
)
)
)
}
private fun onPhoneAuthCredentialsError(
firstnameState: TextFieldState,
lastnameState: TextFieldState,
phoneState: TextFieldState,
firstnameError: Int,
lastnameError: Int,
phoneError: Int
) {
setState(
BaseViewState.Data(
SignUpState(
firstnameState = firstnameState,
lastnameState = lastnameState,
phoneState = phoneState,
firstnameErrorMessage = firstnameError,
lastnameErrorMessage = lastnameError,
phoneErrorMessage = phoneError
)
)
)
}
private fun onEmailPasswordAuthentication(
firstname: String,
lastname: String,
email: String,
password: String
) = safeLaunch {
val params = EmailPasswordSignUpUseCase.Params(firstname, lastname, email, password)
execute(emailPasswordSignUpUseCase(params)) {
onCreateUser(it)
}
}
private fun onPhoneAuthentication(firstname: String, lastname: String, phone: String) {
updatePhoneState(firstname = firstname, lastname = lastname, phoneNumber = phone)
safeLaunch {
execute(sendVerificationCodeUseCase(SendVerificationCodeUseCase.Params(phone))) {
setState(
BaseViewState.Data(
SignUpState(phoneAuthState = it)
)
)
}
}
}
private fun onVerifyPhoneNumber(event: SignUpEvent.VerifyPhoneAuthentication) = safeLaunch {
updatePhoneState(verificationId = event.verificationId)
execute(
verificationCodeUseCase(
VerifyPhoneNumberUseCase.Params(
verificationId = event.verificationId,
code = event.code
)
)
) {
onCreateUser(it)
}
}
private fun onResetVerifyPhoneNumber() = safeLaunch {
setState(
BaseViewState.Data(
SignUpState(
phoneAuthState = PhoneAuthState.CodeSent(
AuthStateHolder.getState().verificationId
)
)
)
)
}
private fun onSelectAuthMethod(event: SignUpEvent.SelectAuthMethod) {
setState(
BaseViewState.Data(
SignUpState(authMethod = event.method)
)
)
}
private fun onCreateUser(userDomain: User) = safeLaunch {
val params = CreateUserUseCase.Params(userDomain)
call(createUserUseCase(params)) {
authManager.update(AuthenticationState.OnBoard)
}
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signup/viewmodel/SignUpViewModel.kt | 3057737195 |
package com.fitness.authentication.signup.view
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Surface
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.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import auth.AuthFailure
import com.fitness.authentication.navigation.AuthEntryImpl
import com.fitness.authentication.signup.viewmodel.SignUpEvent
import com.fitness.authentication.signup.viewmodel.SignUpState
import com.fitness.authentication.util.DisplayErrorMessage
import com.fitness.authentication.util.DisplayFieldState
import com.fitness.authentication.util.PasswordTrailingIcon
import com.fitness.authentication.util.SignInAnnotatedText
import com.fitness.component.components.StandardButton
import com.fitness.component.components.StandardText
import com.fitness.component.components.StandardTextField
import com.fitness.component.components.StandardTextSmall
import com.fitness.component.properties.GuidelineProperties
import com.fitness.component.screens.ErrorScreen
import com.fitness.component.screens.LoadingScreen
import com.fitness.component.screens.MessageScreen
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
import extensions.TextFieldState
import extensions.cast
import kotlinx.coroutines.flow.StateFlow
import state.BaseViewState
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun SignUpEmailPreview() = BodyBalanceTheme {
Surface {
SignUpEmailContent(state = SignUpState())
}
}
@Composable
fun SignUpEmailScreen(
state: StateFlow<BaseViewState<SignUpState>>,
onPopBack: () -> Unit,
onTriggerEvent: (SignUpEvent) -> Unit = {},
onTriggerNavigation: (String) -> Unit,
onComplete: () -> Unit = {}
) {
val uiState by state.collectAsState()
when (uiState) {
is BaseViewState.Data -> {
val currentState = uiState.cast<BaseViewState.Data<SignUpState>>().value
if (currentState.isSignUpCompleted) {
onComplete()
} else {
SignUpEmailContent(
state = currentState,
onTriggerEvent = onTriggerEvent,
onTriggerNavigation = onTriggerNavigation
)
}
}
is BaseViewState.Error -> {
val failure = uiState.cast<BaseViewState.Error>().failure as AuthFailure
ErrorScreen(title = failure.title, description = failure.description) {
onPopBack()
}
}
is BaseViewState.Loading -> {
LoadingScreen()
}
else -> {
MessageScreen(message = R.string.unknown, onClick = onPopBack)
}
}
}
@Composable
private fun SignUpEmailContent(
state: SignUpState,
onTriggerEvent: (SignUpEvent) -> Unit = {},
onTriggerNavigation: (String) -> Unit = {}
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
signIn,
welcome,
message,
firstname,
lastname,
email,
password,
signUp,
phone,
) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val logoBottomGuideline = createGuidelineFromTop(GuidelineProperties.SECOND_TOP)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
var userFirstname by remember { mutableStateOf("") }
var userLastname by remember { mutableStateOf("") }
var userEmail by remember { mutableStateOf("") }
var userPassword by remember { mutableStateOf("") }
var isPasswordVisible by remember { mutableStateOf(false) }
val lastnameRequester = remember { FocusRequester() }
val emailRequester = remember { FocusRequester() }
val passwordRequester = remember { FocusRequester() }
SignInAnnotatedText(
onClick = { onTriggerNavigation(AuthEntryImpl.signInEmail) },
modifier = Modifier.constrainAs(signIn) {
end.linkTo(endGuideline)
top.linkTo(topGuideline)
})
StandardText(
text = R.string.welcome_to_body_balance,
textAlign = TextAlign.Start,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
top.linkTo(logoBottomGuideline)
bottom.linkTo(message.top)
}
)
StandardTextSmall(
text = R.string.create_account_message,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userFirstname,
hint = R.string.enter_first_name,
label = R.string.label_firstname,
isError = state.firstnameState == TextFieldState.ERROR,
trailingIcon = { DisplayFieldState(state = state.firstnameState) },
supportingText = {
DisplayErrorMessage(
state = state.firstnameState,
errorMessageId = state.firstnameErrorMessage
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
onValueChanged = { userFirstname = it },
modifier = Modifier
.focusRequester(lastnameRequester)
.constrainAs(firstname) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userLastname,
hint = R.string.enter_last_name,
label = R.string.label_lastname,
isError = state.lastnameState == TextFieldState.ERROR,
trailingIcon = { DisplayFieldState(state = state.lastnameState) },
supportingText = {
DisplayErrorMessage(
state = state.lastnameState,
errorMessageId = state.lastnameErrorMessage
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
onValueChanged = { userLastname = it },
modifier = Modifier
.focusRequester(emailRequester)
.constrainAs(lastname) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(firstname.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userEmail,
hint = R.string.enter_email,
label = R.string.label_email,
isError = state.emailState == TextFieldState.ERROR,
trailingIcon = { DisplayFieldState(state = state.emailState) },
supportingText = {
DisplayErrorMessage(
state = state.emailState,
errorMessageId = state.emailErrorMessage
)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
imeAction = ImeAction.Next
),
onValueChanged = { userEmail = it },
modifier = Modifier
.focusRequester(passwordRequester)
.constrainAs(email) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(lastname.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userPassword,
hint = R.string.enter_password,
label = R.string.label_password,
isError = state.passwordState == TextFieldState.ERROR,
visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = {
PasswordTrailingIcon(
state = state.passwordState,
isVisible = isPasswordVisible,
onIconClick = { isPasswordVisible = !isPasswordVisible }
)
},
supportingText = {
DisplayErrorMessage(
state = state.passwordState,
errorMessageId = state.passwordErrorMessage
)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(onDone = {
onTriggerEvent(
SignUpEvent.EmailPasswordAuthData(
firstname = userFirstname,
lastname = userLastname,
email = userEmail,
password = userPassword
)
)
}),
onValueChanged = { userPassword = it },
modifier = Modifier.constrainAs(password) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(email.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.title_continue,
onClick = {
onTriggerEvent(
SignUpEvent.EmailPasswordAuthData(
firstname = userFirstname,
lastname = userLastname,
email = userEmail,
password = userPassword
)
)
},
modifier = Modifier.constrainAs(signUp) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(password.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.auth_button_phone,
onClick = { onTriggerNavigation(AuthEntryImpl.signUpPhone) },
modifier = Modifier.constrainAs(phone) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(signUp.bottom, 5.dp)
width = Dimension.fillToConstraints
}
)
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signup/view/SignUpEmail.kt | 2134830711 |
package com.fitness.authentication.signup.view
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Surface
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.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import auth.AuthFailure
import com.fitness.authentication.navigation.AuthEntryImpl
import com.fitness.authentication.signup.viewmodel.SignUpEvent
import com.fitness.authentication.signup.viewmodel.SignUpState
import com.fitness.authentication.util.DisplayErrorMessage
import com.fitness.authentication.util.DisplayFieldState
import com.fitness.authentication.util.SignInAnnotatedText
import com.fitness.authentication.verification.PhoneVerification
import com.fitness.component.components.StandardButton
import com.fitness.component.components.StandardText
import com.fitness.component.components.StandardTextField
import com.fitness.component.components.StandardTextSmall
import com.fitness.component.properties.GuidelineProperties
import com.fitness.component.screens.ErrorScreen
import com.fitness.component.screens.LoadingScreen
import com.fitness.component.screens.MessageScreen
import auth.PhoneAuthState
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
import extensions.TextFieldState
import extensions.cast
import kotlinx.coroutines.flow.StateFlow
import state.BaseViewState
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun SignUpPhonePreview() {
BodyBalanceTheme {
Surface {
SignUpPhoneContent(state = SignUpState())
}
}
}
@Composable
fun SignUpPhoneScreen(
state: StateFlow<BaseViewState<SignUpState>>,
onPopBack: () -> Unit,
onTriggerEvent: (SignUpEvent) -> Unit = {},
onTriggerNavigation: (String) -> Unit,
onComplete: () -> Unit = {}
) {
val uiState by state.collectAsState()
when (uiState) {
is BaseViewState.Data -> {
val currentState = uiState.cast<BaseViewState.Data<SignUpState>>().value
if (currentState.isSignUpCompleted) {
onComplete()
} else {
SignUpPhoneState(
state = uiState.cast<BaseViewState.Data<SignUpState>>().value,
onTriggerEvent = onTriggerEvent,
onTriggerNavigation = onTriggerNavigation
)
}
}
is BaseViewState.Error -> {
val failure = uiState.cast<BaseViewState.Error>().failure as AuthFailure
ErrorScreen(title = failure.title, description = failure.description) {
onPopBack()
}
}
is BaseViewState.Loading -> {
LoadingScreen()
}
else -> {
MessageScreen(message = R.string.unknown, onClick = onPopBack)
}
}
}
@Composable
private fun SignUpPhoneState(
state: SignUpState,
onTriggerEvent: (SignUpEvent) -> Unit = {},
onTriggerNavigation: (String) -> Unit = {}
){
val authState by remember { mutableStateOf(state.phoneAuthState) }
if(authState is PhoneAuthState.CodeSent){
PhoneVerification(
authState = authState.cast(),
codeState = state.codeState,
errorMessage = state.codeErrorMessage,
onVerify = { id, code -> onTriggerEvent(SignUpEvent.VerifyPhoneAuthentication(id, code)) },
)
}
else{
SignUpPhoneContent(state = state, onTriggerEvent=onTriggerEvent, onTriggerNavigation=onTriggerNavigation)
}
}
@Composable
private fun SignUpPhoneContent(
state: SignUpState,
onTriggerEvent: (SignUpEvent) -> Unit = {},
onTriggerNavigation: (String) -> Unit = {}
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
signIn,
welcome,
message,
firstname,
lastname,
phone,
signUp,
) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val secondTopGuideline = createGuidelineFromTop(GuidelineProperties.SECOND_TOP)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
var userFirstname by remember { mutableStateOf("") }
var userLastname by remember { mutableStateOf("") }
var userPhone by remember { mutableStateOf("") }
val lastnameRequester = remember { FocusRequester() }
val phoneRequester = remember { FocusRequester() }
SignInAnnotatedText(
onClick = { onTriggerNavigation(AuthEntryImpl.signInEmail) },
modifier = Modifier.constrainAs(signIn) {
end.linkTo(endGuideline)
top.linkTo(topGuideline)
})
StandardText(
text = R.string.welcome_to_body_balance,
textAlign = TextAlign.Start,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
top.linkTo(secondTopGuideline)
bottom.linkTo(message.top)
}
)
StandardTextSmall(
text = R.string.create_account_message,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userFirstname,
hint = R.string.enter_first_name,
label = R.string.label_firstname,
isError = state.firstnameState == TextFieldState.ERROR,
trailingIcon = { DisplayFieldState(state = state.firstnameState) },
supportingText = {
DisplayErrorMessage(
state = state.firstnameState,
errorMessageId = state.firstnameErrorMessage
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
onValueChanged = { userFirstname = it },
modifier = Modifier
.focusRequester(lastnameRequester)
.constrainAs(firstname) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userLastname,
hint = R.string.enter_last_name,
label = R.string.label_lastname,
isError = state.lastnameState == TextFieldState.ERROR,
trailingIcon = { DisplayFieldState(state = state.lastnameState) },
supportingText = {
DisplayErrorMessage(
state = state.lastnameState,
errorMessageId = state.lastnameErrorMessage
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
onValueChanged = { userLastname = it },
modifier = Modifier
.focusRequester(phoneRequester)
.constrainAs(lastname) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(firstname.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userPhone,
hint = R.string.enter_phone,
label = R.string.label_phone,
isError = state.phoneState == TextFieldState.ERROR,
trailingIcon = { DisplayFieldState(state = state.phoneState) },
supportingText = {
DisplayErrorMessage(
state = state.phoneState,
errorMessageId = state.phoneErrorMessage
)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Phone,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(onDone = {
onTriggerEvent(
SignUpEvent.PhoneAuthentication(
firstname = userFirstname,
lastname = userLastname,
phoneNumber = userPhone
)
)
}),
onValueChanged = { userPhone = it },
modifier = Modifier.constrainAs(phone) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(lastname.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.title_continue,
onClick = {
onTriggerEvent(
SignUpEvent.PhoneAuthentication(
firstname = userFirstname,
lastname = userLastname,
phoneNumber = userPhone
)
)
},
modifier = Modifier.constrainAs(signUp) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(phone.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
}
}
| body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signup/view/SignUpPhone.kt | 524753662 |
package com.fitness.authentication.signup.view
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import auth.AuthFailure
import com.fitness.authentication.navigation.AuthEntryImpl.Companion.signInEmail
import com.fitness.authentication.navigation.AuthEntryImpl.Companion.signUpEmail
import com.fitness.authentication.navigation.AuthEntryImpl.Companion.signUpPhone
import com.fitness.authentication.signup.viewmodel.SignUpState
import com.fitness.authentication.util.SignInAnnotatedText
import com.fitness.component.components.BodyBalanceImageLogo
import com.fitness.component.components.StandardHeadlineText
import com.fitness.component.components.StandardOutlinedIconButton
import com.fitness.component.components.StandardTitleText
import com.fitness.component.properties.GuidelineProperties.END
import com.fitness.component.properties.GuidelineProperties.LOGO_BOTTOM
import com.fitness.component.properties.GuidelineProperties.LOGO_TOP
import com.fitness.component.properties.GuidelineProperties.START
import com.fitness.component.screens.ErrorScreen
import com.fitness.component.screens.LoadingScreen
import com.fitness.component.screens.MessageScreen
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
import extensions.cast
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import state.BaseViewState
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun SignUpLitePreview() {
BodyBalanceTheme {
Surface {
SignUpContent(onTriggerNavigation = {})
}
}
}
@Composable
fun SignUpScreen(
state: StateFlow<BaseViewState<SignUpState>> = MutableStateFlow(BaseViewState.Data(SignUpState())),
onPopBack: () -> Unit,
onTriggerNavigation: (String) -> Unit
) {
val uiState by state.collectAsState()
when (uiState) {
is BaseViewState.Data -> {
SignUpContent(onTriggerNavigation = onTriggerNavigation)
}
is BaseViewState.Error -> {
val failure = uiState.cast<BaseViewState.Error>().failure as AuthFailure
ErrorScreen(title = failure.title, description = failure.description) {
onPopBack()
}
}
is BaseViewState.Loading -> {
LoadingScreen()
}
else -> {
MessageScreen(message = R.string.unknown, onClick = onPopBack)
}
}
}
@Composable
fun SignUpContent(onTriggerNavigation: (String) -> Unit) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
logo,
welcome,
message,
email,
phone,
login,
) = createRefs()
val logoTopGuideline = createGuidelineFromTop(LOGO_TOP)
val logoBottomGuideline = createGuidelineFromTop(LOGO_BOTTOM)
val startGuideline = createGuidelineFromStart(START)
val endGuideline = createGuidelineFromEnd(END)
BodyBalanceImageLogo(
modifier = Modifier
.size(150.dp)
.constrainAs(logo) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(logoTopGuideline)
bottom.linkTo(logoBottomGuideline)
}
)
StandardTitleText(
text = R.string.welcome_to_body_balance,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(logoBottomGuideline, 25.dp)
bottom.linkTo(message.top)
width = Dimension.fillToConstraints
}
)
StandardHeadlineText(
text = R.string.create_account_message,
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 15.dp)
bottom.linkTo(email.top)
width = Dimension.fillToConstraints
}
)
StandardOutlinedIconButton(
icon = R.drawable.icon_email,
desc = R.string.content_description_email,
text = R.string.auth_button_title_email,
onClick = { onTriggerNavigation(signUpEmail) },
modifier = Modifier.constrainAs(email) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
bottom.linkTo(phone.top)
width = Dimension.fillToConstraints
}
)
StandardOutlinedIconButton(
icon = R.drawable.icon_phone,
desc = R.string.content_description_phone,
text = R.string.auth_button_phone,
onClick = { onTriggerNavigation(signUpPhone) },
modifier = Modifier.constrainAs(phone) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(email.bottom, 10.dp)
bottom.linkTo(login.top)
width = Dimension.fillToConstraints
}
)
SignInAnnotatedText(
onClick = { onTriggerNavigation(signInEmail) },
modifier = Modifier.constrainAs(login) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(phone.bottom, 25.dp)
})
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signup/view/SignUp.kt | 3749433391 |
package com.fitness.authentication.reset.viewmodel
import com.fitness.authentication.util.isVerified
import com.fitness.authentication.util.verifyEmail
import dagger.hilt.android.lifecycle.HiltViewModel
import extensions.TextFieldState
import state.BaseViewState
import viewmodel.IntentViewModel
import javax.inject.Inject
@HiltViewModel
class ResetEmailViewModel @Inject constructor(): IntentViewModel<BaseViewState<ResetEmailState>, ResetEmailEvent>() {
init {
setState(BaseViewState.Data(ResetEmailState()))
}
override fun onTriggerEvent(event: ResetEmailEvent) {
when (event){
is ResetEmailEvent.ResetEmail -> {
verifyEmailCredentials(event)
}
}
}
private fun verifyEmailCredentials(event: ResetEmailEvent.ResetEmail){
val (oldEmailState, oldEmailError) = verifyEmail(event.oldEmail)
val (newEmailState, newEmailError) = verifyEmail(event.newEmail)
if(isVerified(oldEmailError, newEmailError)){
onEmailReset()
}
else{
onEmailCredentialsError(
oldEmailState = oldEmailState,
newEmailState = newEmailState,
oldEmailError = oldEmailError,
newEmailError = newEmailError
)
}
}
private fun onEmailCredentialsError(
oldEmailState: TextFieldState,
newEmailState: TextFieldState,
oldEmailError: Int,
newEmailError: Int
){
setState(
BaseViewState.Data(
ResetEmailState(
oldEmailState=oldEmailState,
newEmailState=newEmailState,
oldEmailError=oldEmailError,
newEmailError=newEmailError
)
)
)
}
private fun onEmailReset() = safeLaunch {}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/reset/viewmodel/ResetEmailViewModel.kt | 3846588725 |
package com.fitness.authentication.reset.viewmodel
import com.fitness.authentication.util.isVerified
import com.fitness.authentication.util.verifyPhone
import extensions.TextFieldState
import state.BaseViewState
import viewmodel.IntentViewModel
import javax.inject.Inject
class ResetPhoneViewModel @Inject constructor(): IntentViewModel<BaseViewState<ResetPhoneNumberState>, ResetPhoneNumberEvent>() {
init {
setState(BaseViewState.Data(ResetPhoneNumberState()))
}
override fun onTriggerEvent(event: ResetPhoneNumberEvent) {
when (event){
is ResetPhoneNumberEvent.ResetPhoneNumber -> {
verifyPhoneCredentials(event)
}
}
}
private fun verifyPhoneCredentials(event: ResetPhoneNumberEvent.ResetPhoneNumber){
val (oldPhoneState, oldPhoneError) = verifyPhone(event.oldPhoneNumber)
val (newPhoneState, newPhoneError) = verifyPhone(event.newPhoneNumber)
if(isVerified(oldPhoneError, newPhoneError)){
onPhoneReset()
}
else{
onPhoneCredentialsError(
oldPhoneState = oldPhoneState,
newPhoneState = newPhoneState,
oldPhoneError = oldPhoneError,
newPhoneError = newPhoneError
)
}
}
private fun onPhoneCredentialsError(
oldPhoneState: TextFieldState,
newPhoneState: TextFieldState,
oldPhoneError: Int,
newPhoneError: Int
){
setState(
BaseViewState.Data(
ResetPhoneNumberState(
oldPhoneState=oldPhoneState,
newPhoneState=newPhoneState,
oldPhoneError=oldPhoneError,
newPhoneError=newPhoneError
)
)
)
}
private fun onPhoneReset() = safeLaunch {}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/reset/viewmodel/ResetPhoneViewModel.kt | 719787912 |
package com.fitness.authentication.reset.viewmodel
import auth.toAuthFailure
import com.fitness.authentication.util.isVerified
import com.fitness.authentication.util.verifyEmail
import com.fitness.domain.usecase.auth.SendPasswordResetEmailUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import extensions.TextFieldState
import state.BaseViewState
import viewmodel.IntentViewModel
import javax.inject.Inject
@HiltViewModel
class ResetPasswordViewModel @Inject constructor(
private val sendPasswordResetEmailUseCase: SendPasswordResetEmailUseCase
): IntentViewModel<BaseViewState<ResetPasswordState>, ResetPasswordEvent>() {
init {
setState(BaseViewState.Data(ResetPasswordState()))
}
override fun onTriggerEvent(event: ResetPasswordEvent) {
when (event){
is ResetPasswordEvent.SendPasswordResetEmail -> {
verifyEmailCredentials(event)
}
}
}
override fun handleError(exception: Throwable) {
super.handleError(exception.toAuthFailure())
}
private fun verifyEmailCredentials(event: ResetPasswordEvent.SendPasswordResetEmail){
val (emailState, emailError) = verifyEmail(event.email)
if(isVerified(emailError)){
onSendPasswordResetEmail(event.email)
}
else{
onEmailCredentialsError(emailState=emailState, emailError=emailError)
}
}
private fun onEmailCredentialsError(emailState: TextFieldState, emailError: Int){
setState(
BaseViewState.Data(
ResetPasswordState(
emailState=emailState,
emailError=emailError
)
)
)
}
private fun onSendPasswordResetEmail(email: String) = safeLaunch {
execute(sendPasswordResetEmailUseCase(SendPasswordResetEmailUseCase.Params(email=email))){
setState(BaseViewState.Data(ResetPasswordState(isComplete = true)))
}
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/reset/viewmodel/ResetPasswordViewModel.kt | 2038877895 |
package com.fitness.authentication.reset.viewmodel
import extensions.TextFieldState
data class ResetPasswordState (
val emailState: TextFieldState = TextFieldState.PENDING,
val emailError: Int? = null,
var isComplete: Boolean = false
)
data class ResetEmailState (
val oldEmailState: TextFieldState = TextFieldState.PENDING,
val newEmailState: TextFieldState = TextFieldState.PENDING,
val oldEmailError: Int? = null,
val newEmailError: Int? = null
)
data class ResetPhoneNumberState (
val oldPhoneState: TextFieldState = TextFieldState.PENDING,
val newPhoneState: TextFieldState = TextFieldState.PENDING,
val oldPhoneError: Int? = null,
val newPhoneError: Int? = null
)
sealed class ResetPasswordEvent {
data class SendPasswordResetEmail(val email: String) : ResetPasswordEvent()
}
sealed class ResetEmailEvent {
data class ResetEmail(val oldEmail: String, val newEmail: String): ResetEmailEvent()
}
sealed class ResetPhoneNumberEvent {
data class ResetPhoneNumber(val oldPhoneNumber: String, val newPhoneNumber: String): ResetPhoneNumberEvent()
}
| body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/reset/viewmodel/ResetContract.kt | 1620227769 |
package com.fitness.authentication.reset.view
import androidx.compose.runtime.Composable
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Surface
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.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.fitness.authentication.reset.viewmodel.ResetPasswordEvent
import com.fitness.authentication.reset.viewmodel.ResetPasswordState
import com.fitness.authentication.util.DisplayErrorMessage
import com.fitness.authentication.util.DisplayFieldState
import com.fitness.component.components.StandardButton
import com.fitness.component.components.StandardText
import com.fitness.component.components.StandardTextField
import com.fitness.component.components.StandardTextSmall
import com.fitness.component.properties.GuidelineProperties
import com.fitness.component.screens.ErrorScreen
import com.fitness.component.screens.LoadingScreen
import com.fitness.component.screens.MessageScreen
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
import extensions.TextFieldState
import extensions.cast
import failure.Failure
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import state.BaseViewState
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun ForgotPasswordScreenPreview() {
BodyBalanceTheme {
Surface {
SendPasswordResetScreen()
}
}
}
@Composable
fun SendPasswordResetScreen(
state: StateFlow<BaseViewState<ResetPasswordState>> = MutableStateFlow(BaseViewState.Data(ResetPasswordState())),
onPopBack: () -> Unit = {},
onTriggerEvent: (ResetPasswordEvent) -> Unit = {},
onComplete: () -> Unit = {}
) {
val uiState by state.collectAsState()
when (uiState) {
is BaseViewState.Data -> {
val currentState = uiState.cast<BaseViewState.Data<ResetPasswordState>>().value
if(currentState.isComplete){
onComplete()
}else{
SendPasswordResetContent(
state = currentState,
onTriggerEvent = onTriggerEvent,
)
}
}
is BaseViewState.Error -> {
val failure = uiState.cast<BaseViewState.Error>().failure as Failure
ErrorScreen(title = failure.title, description = failure.description) {
onPopBack()
}
}
is BaseViewState.Loading -> {
LoadingScreen()
}
else -> {
MessageScreen(message = R.string.unknown, onClick = onPopBack)
}
}
}
@Composable
fun SendPasswordResetContent(
state: ResetPasswordState,
onTriggerEvent: (ResetPasswordEvent) -> Unit,
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
welcome,
message,
email,
signUp,
) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
var userEmail by remember { mutableStateOf("") }
StandardText(
text = R.string.title_enter_your_email,
textAlign = TextAlign.Start,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
top.linkTo(topGuideline)
bottom.linkTo(message.top)
}
)
StandardTextSmall(
text = R.string.desc_send_password_reset_link,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userEmail,
hint = R.string.enter_email,
label = R.string.label_email,
isError = state.emailState == TextFieldState.ERROR,
trailingIcon = { DisplayFieldState(state = state.emailState) },
supportingText = {
DisplayErrorMessage(
state = state.emailState,
errorMessageId = state.emailError
)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email, imeAction = ImeAction.Next),
onValueChanged = { userEmail = it },
modifier = Modifier.constrainAs(email) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.title_continue,
onClick = { onTriggerEvent(ResetPasswordEvent.SendPasswordResetEmail(userEmail)) },
modifier = Modifier.constrainAs(signUp) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(email.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/reset/view/ResetPassword.kt | 4023404265 |
package com.fitness.authentication.reset.view
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.fitness.component.components.StandardButton
import com.fitness.component.components.StandardText
import com.fitness.component.components.StandardTextField
import com.fitness.component.components.StandardTextSmall
import com.fitness.component.properties.GuidelineProperties
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun EnterYourEmailScreenPreview() {
BodyBalanceTheme {
Surface {
EnterYourEmailScreen()
}
}
}
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun ResetEmailScreenPreview() {
BodyBalanceTheme {
Surface {
ResetEmailScreen()
}
}
}
@Composable
fun EnterYourEmailScreen(
onClickContinue: () -> Unit = {},
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
welcome,
message,
phone,
signUp,
) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
var userEmail by remember { mutableStateOf("") }
StandardText(
text = R.string.title_enter_your_email,
textAlign = TextAlign.Start,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
top.linkTo(topGuideline)
bottom.linkTo(message.top)
}
)
StandardTextSmall(
text = R.string.desc_title_enter_your_email,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userEmail,
hint = R.string.enter_email,
label = R.string.label_email,
onValueChanged = { userEmail = it },
modifier = Modifier.constrainAs(phone) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.title_continue,
onClick = onClickContinue,
modifier = Modifier.constrainAs(signUp) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(phone.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
}
}
@Composable
fun ResetEmailScreen(
onClickContinue: () -> Unit = {},
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
welcome,
message,
phone,
signUp,
) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
var userEmail by remember { mutableStateOf("") }
StandardText(
text = R.string.reset_your_email,
textAlign = TextAlign.Start,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
top.linkTo(topGuideline)
bottom.linkTo(message.top)
}
)
StandardTextSmall(
text = R.string.desc_reset_your_email,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userEmail,
hint = R.string.enter_email,
label = R.string.label_email,
onValueChanged = {userEmail = it},
modifier = Modifier.constrainAs(phone) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.title_continue,
onClick = onClickContinue,
modifier = Modifier.constrainAs(signUp) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(phone.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
}
}
| body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/reset/view/ResetEmail.kt | 64702280 |
package com.fitness.authentication.reset.view
import androidx.compose.runtime.Composable
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.fitness.component.components.StandardButton
import com.fitness.component.components.StandardText
import com.fitness.component.components.StandardTextField
import com.fitness.component.components.StandardTextSmall
import com.fitness.component.properties.GuidelineProperties
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun ConfirmPhoneNumberPreview() {
BodyBalanceTheme {
Surface {
ResetPhoneNumberScreen()
}
}
}
@Composable
fun ResetPhoneNumberScreen(
onClickContinue: () -> Unit = {},
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
welcome,
message,
phone,
signUp,
) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
var userPhone by remember { mutableStateOf("") }
StandardText(
text = R.string.reset_your_phone,
textAlign = TextAlign.Start,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
top.linkTo(topGuideline)
bottom.linkTo(message.top)
}
)
StandardTextSmall(
text = R.string.desc_reset_your_phone,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userPhone,
hint = R.string.enter_phone,
label = R.string.label_phone,
onValueChanged = {userPhone = it},
modifier = Modifier.constrainAs(phone) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.title_continue,
onClick = onClickContinue,
modifier = Modifier.constrainAs(signUp) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(phone.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
}
}
| body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/reset/view/Reset.kt | 1564660223 |
package com.fitness.authentication.navigation
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import com.fitness.authentication.AuthEntry
import com.fitness.authentication.home.view.`AcceptTermsAndPrivacy`
import com.fitness.authentication.home.viewmodel.HomeViewModel
import com.fitness.authentication.reset.view.SendPasswordResetScreen
import com.fitness.authentication.reset.viewmodel.ResetPasswordViewModel
import com.fitness.authentication.signin.view.SignInEmailScreen
import com.fitness.authentication.signin.view.SignInPhoneScreen
import com.fitness.authentication.signin.viewmodel.SignInViewModel
import com.fitness.authentication.signup.view.SignUpEmailScreen
import com.fitness.authentication.signup.view.SignUpPhoneScreen
import com.fitness.authentication.signup.view.SignUpScreen
import com.fitness.authentication.signup.viewmodel.SignUpViewModel
import com.fitness.component.screens.MessageScreen
import com.fitness.navigation.Destinations
import com.fitness.resources.R
import extensions.cast
import javax.inject.Inject
class AuthEntryImpl @Inject constructor() : AuthEntry() {
companion object {
const val termsAndPrivacy = "home"
const val signInEmail = "sign_In_email"
const val signInPhone = "sign_In_phone"
const val signUp = "sign_up"
const val signUpEmail = "sign_up_email"
const val signUpPhone = "sign_up_phone"
const val resetPassword = "reset_password"
const val resetConfirmation = "reset_password_confirmation"
}
override fun NavGraphBuilder.navigation(
navController: NavHostController,
destinations: Destinations
) {
navigation(startDestination = termsAndPrivacy, route = featureRoute) {
composable(termsAndPrivacy) {
val viewModel: HomeViewModel = hiltViewModel()
AcceptTermsAndPrivacy(
state = viewModel.uiState.cast(),
onTriggerEvent = { viewModel.onTriggerEvent(it) },
onTriggerNavigation = {
navController.navigate(it) {
popUpTo(termsAndPrivacy) {
inclusive = true
}
}
}
)
}
composable(signUp) {
val viewModel: SignUpViewModel = hiltViewModel()
SignUpScreen(
state = viewModel.uiState.cast(),
onPopBack = { navController.popBackStack() },
onTriggerNavigation = { navController.navigate(it) }
)
}
composable(signUpEmail) {
val viewModel: SignUpViewModel = hiltViewModel()
SignUpEmailScreen(
state = viewModel.uiState.cast(),
onPopBack = { navController.popBackStack() },
onComplete = {},
onTriggerEvent = { viewModel.onTriggerEvent(it) },
onTriggerNavigation = { navController.navigate(it) { popUpTo(signUp) } }
)
}
composable(signUpPhone) {
val viewModel: SignUpViewModel = hiltViewModel()
SignUpPhoneScreen(
state = viewModel.uiState.cast(),
onPopBack = { navController.popBackStack() },
onTriggerEvent = { viewModel.onTriggerEvent(it) },
onTriggerNavigation = {
navController.navigate(it) {
popUpTo(signUpPhone)
}
}
)
}
composable(signInEmail) {
val viewModel: SignInViewModel = hiltViewModel()
SignInEmailScreen(
state = viewModel.uiState.cast(),
onPopBack = { navController.popBackStack() },
onTriggerEvent = { viewModel.onTriggerEvent(it) },
onTriggerNavigation = { navController.navigate(it) { popUpTo(signUp) } }
)
}
composable(signInPhone) {
val viewModel: SignInViewModel = hiltViewModel()
SignInPhoneScreen(
state = viewModel.uiState.cast(),
onPopBack = { navController.popBackStack() },
onComplete = {},
onTriggerEvent = { viewModel.onTriggerEvent(it) },
onTriggerNavigation = { navController.navigate(it) { popUpTo(signInPhone) } }
)
}
composable(resetPassword) {
val viewModel: ResetPasswordViewModel = hiltViewModel()
SendPasswordResetScreen(
state = viewModel.uiState.cast(),
onPopBack = { navController.popBackStack() },
onComplete = { navController.navigate(resetConfirmation) { popUpTo(signInEmail) } },
onTriggerEvent = { viewModel.onTriggerEvent(it) },
)
}
composable(resetConfirmation) {
MessageScreen(
message = R.string.desc_reset_password_email_confirmation,
onClick = { navController.navigate(signInEmail) }
)
}
}
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/navigation/AuthEntryImpl.kt | 3780815078 |
package com.fitness.authentication.verification
import androidx.compose.foundation.layout.Arrangement.SpaceEvenly
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusManager
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.fitness.component.components.StandardText
import com.fitness.component.components.StandardTextSmall
import com.fitness.component.properties.GuidelineProperties
import auth.PhoneAuthState
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
import extensions.Dark
import extensions.Light
import extensions.TextFieldState
@Light
@Dark
@Composable
private fun PhoneVerificationContentPreview() = BodyBalanceTheme {
Surface {
PhoneVerification()
}
}
@Composable
fun PhoneVerification(
authState: PhoneAuthState.CodeSent = PhoneAuthState.CodeSent(""),
codeState: TextFieldState = TextFieldState.OK,
errorMessage: Int? = null,
onVerify: (String, String) -> Unit = { _, _ -> }
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
var resetFields by remember { mutableStateOf(codeState) }
val digits = remember { Array(6) { mutableStateOf("") } }
val (title, message, code, error, verify) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val bottomGuideline = createGuidelineFromBottom(GuidelineProperties.BOTTOM_100)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
digits.forEach {
if (isCodeInvalid(resetFields)) {
it.value = ""
resetFields = TextFieldState.OK
}
}
StandardText(
text = R.string.code_verification,
textAlign = TextAlign.Start,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.constrainAs(title) {
start.linkTo(startGuideline)
top.linkTo(topGuideline)
bottom.linkTo(message.top, 10.dp)
}
)
StandardTextSmall(
text = R.string.code_verification_description,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(title.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
Row(
horizontalArrangement = SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
.constrainAs(code) {
end.linkTo(endGuideline)
start.linkTo(startGuideline)
top.linkTo(message.bottom, 20.dp)
}
) {
digits.forEachIndexed { index, digit ->
val focusManager = LocalFocusManager.current
OutlinedTextField(
value = digit.value,
textStyle = TextStyle(textAlign = TextAlign.Center),
onValueChange = {
handleDigitInput(index, it, focusManager, digits)
},
singleLine = true,
isError = isCodeInvalid(codeState),
modifier = Modifier
.width(50.dp)
.onKeyEvent {
if (it.key == Key.Backspace && digit.value.isEmpty() && index > 0) {
digits[index - 1].value = ""
focusManager.moveFocus(FocusDirection.Previous)
true
} else {
false
}
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
}
}
if(isCodeInvalid(codeState)){
errorMessage?.let {
StandardTextSmall(
text = errorMessage,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(error) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(code.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
}
}
Button(
onClick = {
onVerify(
authState.verificationId,
digits.joinToString(separator = "") { it.value })
},
modifier = Modifier
.fillMaxWidth()
.padding(start = 20.dp, end = 20.dp)
.constrainAs(verify) {
bottom.linkTo(bottomGuideline)
}
) {
Text(stringResource(R.string.verify))
}
}
}
fun handleDigitInput(
index: Int,
digit: String,
focusManager: FocusManager,
digits: Array<MutableState<String>>
) {
val filteredDigit = digit.filter { it.isDigit() }
if (filteredDigit.length <= 1) {
digits[index].value = filteredDigit
if (filteredDigit.length == 1 && index < 5) {
focusManager.moveFocus(FocusDirection.Next)
}
}
}
fun isCodeInvalid(state: TextFieldState) = state == TextFieldState.ERROR
| body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/verification/Verification.kt | 2317595030 |
package com.fitness.authentication.signin.viewmodel
import com.fitness.authentication.util.AuthMethod
import auth.PhoneAuthState
import extensions.TextFieldState
data class SignInState(
var authMethod: AuthMethod = AuthMethod.NONE,
var emailState: TextFieldState = TextFieldState.PENDING,
var phoneState: TextFieldState = TextFieldState.PENDING,
var passwordState: TextFieldState = TextFieldState.PENDING,
var codeState: TextFieldState = TextFieldState.PENDING,
var emailErrorMessage: Int? = null,
var phoneErrorMessage: Int? = null,
var passwordErrorMessage: Int? = null,
var codeErrorMessage: Int? = null,
var phoneAuthState: PhoneAuthState = PhoneAuthState.Idle,
var isAuthenticated: Boolean = false
)
sealed class SignInEvent {
data class EmailPasswordAuthentication(val email:String, val password:String): SignInEvent()
data class PhoneAuthentication(val phoneNumber: String): SignInEvent()
data class VerifyPhoneAuthentication(val verificationId: String, val code: String) : SignInEvent()
data class SelectAuthMethod(val method: AuthMethod): SignInEvent()
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signin/viewmodel/SignInContract.kt | 3260447415 |
package com.fitness.authentication.signin.viewmodel
import auth.PhoneVerificationError
import auth.formatPhoneNumberToE164
import auth.toAuthFailure
import com.fitness.authentication.manager.AuthenticationManager
import com.fitness.authentication.manager.AuthenticationState
import com.fitness.authentication.util.AuthStateHolder
import com.fitness.resources.R
import com.fitness.authentication.util.isVerified
import com.fitness.authentication.util.updatePhoneState
import com.fitness.authentication.util.verifyEmail
import com.fitness.authentication.util.verifyPassword
import com.fitness.authentication.util.verifyPhone
import auth.PhoneAuthState
import com.fitness.domain.usecase.auth.EmailPasswordSignInUseCase
import com.fitness.domain.usecase.auth.SendVerificationCodeUseCase
import com.fitness.domain.usecase.auth.VerifyPhoneNumberUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import extensions.TextFieldState
import state.BaseViewState
import viewmodel.IntentViewModel
import javax.inject.Inject
@HiltViewModel
class SignInViewModel @Inject constructor(
private val sendVerificationCodeUseCase: SendVerificationCodeUseCase,
private val verificationCodeUseCase: VerifyPhoneNumberUseCase,
private val emailPasswordSignInUseCase: EmailPasswordSignInUseCase,
private val authManager: AuthenticationManager
) : IntentViewModel<BaseViewState<SignInState>, SignInEvent>() {
init {
setState(BaseViewState.Data(SignInState()))
}
override fun onTriggerEvent(event: SignInEvent) {
when(event){
is SignInEvent.EmailPasswordAuthentication -> {
verifyEmailAuthenticationData(event)
}
is SignInEvent.PhoneAuthentication -> {
verifyPhoneAuthenticationData(event)
}
is SignInEvent.VerifyPhoneAuthentication -> {
onVerifyPhoneNumber(event)
}
is SignInEvent.SelectAuthMethod ->{
onSelectAuthMethod(event)
}
}
}
override fun handleError(exception: Throwable) {
if(exception is PhoneVerificationError){
onResetVerifyPhoneNumber()
}else{
super.handleError(exception.toAuthFailure())
}
}
private fun verifyEmailAuthenticationData(event: SignInEvent.EmailPasswordAuthentication) {
val (emailState, emailError) = verifyEmail(event.email)
val (passwordState, passwordError) = verifyPassword(event.password)
if (isVerified(emailError, passwordError)){
onEmailPasswordAuthentication(email = event.email, password = event.password)
}
else {
onEmailAuthCredentialsError(
emailState=emailState,
passwordState=passwordState,
emailError=emailError,
passwordError=passwordError
)
}
}
private fun verifyPhoneAuthenticationData(event: SignInEvent.PhoneAuthentication) {
val formattedPhoneNumber = formatPhoneNumberToE164(event.phoneNumber, "US")
val (phoneState, phoneError) = verifyPhone(formattedPhoneNumber)
if (formattedPhoneNumber != null && isVerified(phoneError)){
onPhoneAuthentication(phone=formattedPhoneNumber)
}
else {
onPhoneAuthCredentialsError(
phoneState=phoneState,
phoneError=phoneError,
)
}
}
private fun onEmailAuthCredentialsError(
emailState: TextFieldState,
passwordState: TextFieldState,
emailError: Int,
passwordError: Int
) {
setState(
BaseViewState.Data(
SignInState(
emailState = emailState,
passwordState = passwordState,
emailErrorMessage = emailError,
passwordErrorMessage = passwordError
)
)
)
}
private fun onPhoneAuthCredentialsError(
phoneState: TextFieldState,
phoneError: Int
) {
setState(
BaseViewState.Data(
SignInState(
phoneState = phoneState,
phoneErrorMessage = phoneError
)
)
)
}
private fun onSelectAuthMethod(event: SignInEvent.SelectAuthMethod) {
setState(
BaseViewState.Data(
SignInState(authMethod = event.method)
)
)
}
private fun onEmailPasswordAuthentication(email: String, password:String) = safeLaunch {
execute(emailPasswordSignInUseCase(EmailPasswordSignInUseCase.Params(email, password))) {
authManager.update(AuthenticationState.Authenticated)
}
}
private fun onPhoneAuthentication(phone: String) = safeLaunch {
updatePhoneState(phoneNumber = phone)
execute(sendVerificationCodeUseCase(SendVerificationCodeUseCase.Params(phone))) {
setState(BaseViewState.Data(SignInState(phoneAuthState = it)))
}
}
private fun onVerifyPhoneNumber(event: SignInEvent.VerifyPhoneAuthentication) = safeLaunch {
updatePhoneState(verificationId = event.verificationId)
execute(verificationCodeUseCase(VerifyPhoneNumberUseCase.Params(verificationId=AuthStateHolder.getState().verificationId, code=event.code))){
authManager.update(AuthenticationState.Authenticated)
}
}
private fun onResetVerifyPhoneNumber() = safeLaunch {
setState(
BaseViewState.Data(
SignInState(
phoneAuthState = PhoneAuthState.CodeSent(AuthStateHolder.getState().verificationId),
codeState = TextFieldState.ERROR,
codeErrorMessage = R.string.error_invalid_code
)
)
)
}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signin/viewmodel/SignInViewModel.kt | 147894304 |
package com.fitness.authentication.signin.view
import android.util.Log
import androidx.compose.runtime.Composable
import com.fitness.authentication.signin.viewmodel.SignInEvent
import com.fitness.authentication.util.AuthMethod
@Composable
fun HandleSignInMethod(authMethod: AuthMethod, onTriggerEvent: (SignInEvent) -> Unit) =
when (authMethod) {
AuthMethod.GOOGLE -> {
GoogleBottomAuthSheet(
onSignInResult = {},
onTriggerEvent = onTriggerEvent
)
}
AuthMethod.FACEBOOK -> {
FacebookBottomAuthSheet(
onTriggerEvent = onTriggerEvent
)
}
AuthMethod.X -> {
XBottomAuthSheet(
onTriggerEvent = onTriggerEvent
)
}
else -> {}
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signin/view/SignInUtil.kt | 840681719 |
package com.fitness.authentication.signin.view
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.fitness.authentication.signin.viewmodel.SignInEvent
import com.fitness.authentication.util.AuthMethod
import com.fitness.resources.R
import kotlinx.coroutines.launch
@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun XBottomAuthSheet(
onTriggerEvent: (SignInEvent) -> Unit
) {
val sheetState = rememberModalBottomSheetState()
val coroutineScope = rememberCoroutineScope()
ModalBottomSheet(
onDismissRequest = { onTriggerEvent(SignInEvent.SelectAuthMethod(AuthMethod.NONE)) },
sheetState = sheetState,
content = {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
Text(text = stringResource(id = R.string.auth_button_title_x))
Button(
onClick = {
coroutineScope.launch {
sheetState.hide()
}
}
) {
Text(stringResource(id = R.string.title_continue))
}
}
}
)
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signin/view/SignInX.kt | 2414727596 |
package com.fitness.authentication.signin.view
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Surface
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.Modifier
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.fitness.authentication.navigation.AuthEntryImpl
import com.fitness.authentication.signin.viewmodel.SignInEvent
import com.fitness.authentication.signin.viewmodel.SignInState
import com.fitness.authentication.util.DisplayErrorMessage
import com.fitness.authentication.util.DisplayFieldState
import com.fitness.authentication.util.NewNumberAnnotatedText
import com.fitness.authentication.util.SignUpForFreeAnnotatedText
import com.fitness.authentication.verification.PhoneVerification
import com.fitness.component.components.StandardButton
import com.fitness.component.components.StandardText
import com.fitness.component.components.StandardTextField
import com.fitness.component.properties.GuidelineProperties
import com.fitness.component.screens.ErrorScreen
import com.fitness.component.screens.LoadingScreen
import com.fitness.component.screens.MessageScreen
import auth.PhoneAuthState
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
import extensions.Dark
import extensions.Light
import extensions.TextFieldState
import extensions.cast
import failure.Failure
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import state.BaseViewState
@Light
@Dark
@Composable
private fun SignInPhonePreview() = BodyBalanceTheme {
Surface {
SignInPhoneContent(state = SignInState(), {}, {})
}
}
@Composable
fun SignInPhoneScreen(
state: StateFlow<BaseViewState<SignInState>> = MutableStateFlow(BaseViewState.Data(SignInState())),
onPopBack: () -> Unit = {},
onTriggerEvent: (SignInEvent) -> Unit,
onTriggerNavigation: (String) -> Unit,
onComplete: () -> Unit = {}
) {
val uiState by state.collectAsState()
when (uiState) {
is BaseViewState.Data -> {
val currentState = uiState.cast<BaseViewState.Data<SignInState>>().value
if(currentState.isAuthenticated){
onComplete()
}
else{
SignInPhoneState(
state = currentState,
onTriggerEvent = onTriggerEvent,
onTriggerNavigation = onTriggerNavigation,
)
}
}
is BaseViewState.Error -> {
val failure = uiState.cast<BaseViewState.Error>().failure as Failure
ErrorScreen(title = failure.title, description = failure.description) {
onPopBack()
}
}
is BaseViewState.Loading -> {
LoadingScreen()
}
else -> {
MessageScreen(message = R.string.unknown, onClick = onPopBack)
}
}
}
@Composable
private fun SignInPhoneState(
state: SignInState,
onTriggerEvent: (SignInEvent) -> Unit = {},
onTriggerNavigation: (String) -> Unit = {}
){
val authState by remember { mutableStateOf(state.phoneAuthState) }
if(authState is PhoneAuthState.CodeSent){
PhoneVerification(
authState = authState.cast(),
codeState = state.codeState,
errorMessage = state.codeErrorMessage,
onVerify = { id, code -> onTriggerEvent(SignInEvent.VerifyPhoneAuthentication(id, code)) },
)
}
else{
SignInPhoneContent(state = state, onTriggerEvent=onTriggerEvent, onTriggerNavigation=onTriggerNavigation)
}
}
@Composable
private fun SignInPhoneContent(
state: SignInState,
onTriggerEvent: (SignInEvent) -> Unit,
onTriggerNavigation: (String) -> Unit
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
welcome,
message,
phone,
forgot,
cont,
) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
var userPhone by remember { mutableStateOf("") }
HandleSignInMethod(authMethod = state.authMethod, onTriggerEvent = onTriggerEvent)
StandardText(
text = R.string.not_a_member,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
top.linkTo(topGuideline)
bottom.linkTo(message.top)
}
)
SignUpForFreeAnnotatedText(
onClick = { onTriggerNavigation(AuthEntryImpl.signUp) },
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userPhone,
hint = R.string.enter_phone,
label = R.string.label_phone,
isError = state.phoneState == TextFieldState.ERROR,
trailingIcon = { DisplayFieldState(state = state.phoneState) },
supportingText = {
DisplayErrorMessage(
state = state.phoneState,
errorMessageId = state.phoneErrorMessage
)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = {
onTriggerEvent(
SignInEvent.PhoneAuthentication(
phoneNumber = userPhone
)
)
}),
onValueChanged = { userPhone = it },
modifier = Modifier.constrainAs(phone) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
NewNumberAnnotatedText(
onClick = { onTriggerNavigation(AuthEntryImpl.resetPassword) },
modifier = Modifier.constrainAs(forgot) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(phone.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.title_continue,
onClick = {
onTriggerEvent(
SignInEvent.PhoneAuthentication(
phoneNumber = userPhone
)
)
},
modifier = Modifier.constrainAs(cont) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(forgot.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
// StandardTextSmall(
// text = R.string.or,
// modifier = Modifier
// .padding(20.dp)
// .constrainAs(or) {
// start.linkTo(startGuideline)
// end.linkTo(endGuideline)
// top.linkTo(cont.bottom)
// }
// )
//
// createHorizontalChain(google, facebook, x, chainStyle = ChainStyle.Packed)
//
// StandardIconButton(
// icon = R.drawable.icon_google_logo,
// desc = R.string.content_description_google,
// onClick = { onTriggerEvent(SignInEvent.SelectAuthMethod(AuthMethod.GOOGLE)) },
// modifier = Modifier
// .padding(8.dp)
// .constrainAs(google) {
// start.linkTo(startGuideline)
// end.linkTo(facebook.start)
// top.linkTo(or.bottom, 10.dp)
// }
// )
//
// StandardIconButton(
// icon = R.drawable.icon_facebook_logo,
// desc = R.string.content_description_facebook,
// onClick = { onTriggerEvent(SignInEvent.SelectAuthMethod(AuthMethod.FACEBOOK)) },
// modifier = Modifier
// .padding(8.dp)
// .constrainAs(facebook) {
// start.linkTo(google.end)
// end.linkTo(x.start)
// top.linkTo(or.bottom, 10.dp)
// }
// )
//
// StandardIconButton(
// icon = R.drawable.icon_x_logo,
// desc = R.string.content_description_x,
// onClick = { onTriggerEvent(SignInEvent.SelectAuthMethod(AuthMethod.X)) },
// modifier = Modifier
// .padding(8.dp)
// .constrainAs(x) {
// start.linkTo(facebook.end)
// end.linkTo(endGuideline)
// top.linkTo(or.bottom, 10.dp)
// }
// )
}
}
| body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signin/view/SignInPhone.kt | 1579636450 |
package com.fitness.authentication.signin.view
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.fitness.authentication.signin.viewmodel.SignInEvent
import com.fitness.authentication.util.AuthMethod
import com.fitness.resources.R
import kotlinx.coroutines.launch
@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun FacebookBottomAuthSheet(onTriggerEvent: (SignInEvent) -> Unit) {
val sheetState = rememberModalBottomSheetState()
val coroutineScope = rememberCoroutineScope()
ModalBottomSheet(
onDismissRequest = { onTriggerEvent(SignInEvent.SelectAuthMethod(AuthMethod.NONE)) },
sheetState = sheetState,
content = {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
Text(text = stringResource(id = R.string.auth_button_title_facebook))
Button(
onClick = {
coroutineScope.launch {
sheetState.hide()
}
}
) {
Text(stringResource(id = R.string.title_continue))
}
}
}
)
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signin/view/SignInFacebook.kt | 1261053770 |
package com.fitness.authentication.signin.view
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.fitness.authentication.signin.viewmodel.SignInEvent
import com.fitness.authentication.util.AuthMethod
import com.fitness.resources.R
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import kotlinx.coroutines.launch
@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun GoogleBottomAuthSheet(
onSignInResult: (GoogleSignInAccount?) -> Unit,
onTriggerEvent: (SignInEvent) -> Unit
) {
val sheetState = rememberModalBottomSheetState()
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("442236870595-opv98sfj7qc6fchuqgd8adrd012qtmes.apps.googleusercontent.com")
.requestEmail()
.build()
val googleSignInClient = GoogleSignIn.getClient(context, gso)
val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) { result ->
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
val account = try {
task.getResult(ApiException::class.java)
} catch (e: ApiException) {
null
}
onSignInResult(account)
}
ModalBottomSheet(
onDismissRequest = { onTriggerEvent(SignInEvent.SelectAuthMethod(AuthMethod.NONE)) },
sheetState = sheetState,
content = {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
Text(
text = stringResource(id = R.string.auth_button_title_google),
style = MaterialTheme.typography.headlineMedium
)
Button(
onClick = {
coroutineScope.launch {
sheetState.hide()
val signInIntent = googleSignInClient.signInIntent
launcher.launch(signInIntent)
}
}
) {
Text(stringResource(id = R.string.title_continue))
}
}
}
)
} | body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signin/view/SignInGoogle.kt | 2775951576 |
package com.fitness.authentication.signin.view
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Surface
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.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.fitness.authentication.navigation.AuthEntryImpl
import com.fitness.authentication.navigation.AuthEntryImpl.Companion.signInPhone
import com.fitness.authentication.navigation.AuthEntryImpl.Companion.signUp
import com.fitness.authentication.signin.viewmodel.SignInEvent
import com.fitness.authentication.signin.viewmodel.SignInState
import com.fitness.authentication.util.DisplayErrorMessage
import com.fitness.authentication.util.DisplayFieldState
import com.fitness.authentication.util.ForgotPasswordAnnotatedText
import com.fitness.authentication.util.PasswordTrailingIcon
import com.fitness.authentication.util.SignUpForFreeAnnotatedText
import com.fitness.component.components.StandardButton
import com.fitness.component.components.StandardText
import com.fitness.component.components.StandardTextField
import com.fitness.component.properties.GuidelineProperties
import com.fitness.component.screens.ErrorScreen
import com.fitness.component.screens.LoadingScreen
import com.fitness.component.screens.MessageScreen
import com.fitness.resources.R
import com.fitness.theme.ui.BodyBalanceTheme
import extensions.Dark
import extensions.Light
import extensions.TextFieldState
import extensions.cast
import failure.Failure
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import state.BaseViewState
@Light
@Dark
@Composable
private fun SignInEmailPreview() = BodyBalanceTheme {
Surface {
SignInEmailContent(state = SignInState(), {}, {})
}
}
@Composable
fun SignInEmailScreen(
state: StateFlow<BaseViewState<SignInState>> = MutableStateFlow(BaseViewState.Data(SignInState())),
onPopBack: () -> Unit = {},
onTriggerEvent: (SignInEvent) -> Unit,
onTriggerNavigation: (String) -> Unit,
onComplete: () -> Unit = {}
) {
val uiState by state.collectAsState()
when (uiState) {
is BaseViewState.Data -> {
val currentState = uiState.cast<BaseViewState.Data<SignInState>>().value
if (currentState.isAuthenticated) {
onComplete()
} else {
SignInEmailContent(
state = currentState,
onTriggerEvent = onTriggerEvent,
onTriggerNavigation = onTriggerNavigation,
)
}
}
is BaseViewState.Error -> {
val failure = uiState.cast<BaseViewState.Error>().failure as Failure
ErrorScreen(title = failure.title, description = failure.description) {
onPopBack()
}
}
is BaseViewState.Loading -> {
LoadingScreen()
}
else -> {
MessageScreen(message = R.string.unknown, onClick = onPopBack)
}
}
}
@Composable
fun SignInEmailContent(
state: SignInState,
onTriggerEvent: (SignInEvent) -> Unit,
onTriggerNavigation: (String) -> Unit
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
welcome,
message,
email,
password,
resetPassword,
cont,
phone,
) = createRefs()
val topGuideline = createGuidelineFromTop(GuidelineProperties.TOP)
val startGuideline = createGuidelineFromStart(GuidelineProperties.START)
val endGuideline = createGuidelineFromEnd(GuidelineProperties.END)
var userEmail by remember { mutableStateOf("") }
var userPassword by remember { mutableStateOf("") }
var isPasswordVisible by remember { mutableStateOf(false) }
val passwordRequester = remember { FocusRequester() }
HandleSignInMethod(authMethod = state.authMethod, onTriggerEvent = onTriggerEvent)
StandardText(
text = R.string.not_a_member,
textAlign = TextAlign.Start,
modifier = Modifier.constrainAs(welcome) {
start.linkTo(startGuideline)
top.linkTo(topGuideline)
bottom.linkTo(message.top)
}
)
SignUpForFreeAnnotatedText(
onClick = { onTriggerNavigation(signUp) },
modifier = Modifier.constrainAs(message) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(welcome.bottom, 10.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userEmail,
hint = R.string.enter_email,
label = R.string.label_email,
isError = state.emailState == TextFieldState.ERROR,
trailingIcon = { DisplayFieldState(state = state.emailState) },
supportingText = {
DisplayErrorMessage(
state = state.emailState,
errorMessageId = state.emailErrorMessage
)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
imeAction = ImeAction.Next
),
onValueChanged = { userEmail = it },
modifier = Modifier
.focusRequester(passwordRequester)
.constrainAs(email) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(message.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
StandardTextField(
value = userPassword,
hint = R.string.enter_password,
label = R.string.label_password,
isError = state.passwordState == TextFieldState.ERROR,
visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = {
PasswordTrailingIcon(
state = state.passwordState,
isVisible = isPasswordVisible,
onIconClick = { isPasswordVisible = !isPasswordVisible }
)
},
supportingText = {
DisplayErrorMessage(
state = state.passwordState,
errorMessageId = state.passwordErrorMessage
)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(onDone = {
onTriggerEvent(
SignInEvent.EmailPasswordAuthentication(
email = userEmail,
password = userPassword
)
)
}),
onValueChanged = { userPassword = it },
modifier = Modifier.constrainAs(password) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(email.bottom, 15.dp)
width = Dimension.fillToConstraints
}
)
ForgotPasswordAnnotatedText(
onClick = { onTriggerNavigation(AuthEntryImpl.resetPassword) },
modifier = Modifier.constrainAs(resetPassword) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(password.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.title_continue,
onClick = {
onTriggerEvent(
SignInEvent.EmailPasswordAuthentication(
email = userEmail,
password = userPassword
)
)
},
modifier = Modifier.constrainAs(cont) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(resetPassword.bottom, 25.dp)
width = Dimension.fillToConstraints
}
)
StandardButton(
text = R.string.auth_button_phone,
onClick = { onTriggerNavigation(signInPhone) },
modifier = Modifier.constrainAs(phone) {
start.linkTo(startGuideline)
end.linkTo(endGuideline)
top.linkTo(cont.bottom, 5.dp)
width = Dimension.fillToConstraints
}
)
// StandardTextSmall(
// text = R.string.or,
// modifier = Modifier
// .padding(20.dp)
// .constrainAs(or) {
// start.linkTo(startGuideline)
// end.linkTo(endGuideline)
// top.linkTo(phone.bottom)
// }
// )
//
// createHorizontalChain(google, facebook, x, chainStyle = ChainStyle.Packed)
//
// StandardIconButton(
// icon = R.drawable.icon_google_logo,
// desc = R.string.content_description_google,
// onClick = { onTriggerEvent(SignInEvent.SelectAuthMethod(AuthMethod.GOOGLE)) },
// modifier = Modifier
// .padding(8.dp)
// .constrainAs(google) {
// start.linkTo(startGuideline)
// end.linkTo(facebook.start)
// top.linkTo(or.bottom, 10.dp)
// }
// )
//
// StandardIconButton(
// icon = R.drawable.icon_facebook_logo,
// desc = R.string.content_description_facebook,
// onClick = { onTriggerEvent(SignInEvent.SelectAuthMethod(AuthMethod.FACEBOOK)) },
// modifier = Modifier
// .padding(8.dp)
// .constrainAs(facebook) {
// start.linkTo(google.end)
// end.linkTo(x.start)
// top.linkTo(or.bottom, 10.dp)
// }
// )
//
// StandardIconButton(
// icon = R.drawable.icon_x_logo,
// desc = R.string.content_description_x,
// onClick = { onTriggerEvent(SignInEvent.SelectAuthMethod(AuthMethod.X)) },
// modifier = Modifier
// .padding(8.dp)
// .constrainAs(x) {
// start.linkTo(facebook.end)
// end.linkTo(endGuideline)
// top.linkTo(or.bottom, 10.dp)
// }
// )
}
}
| body-balance/features/authentication/impl/src/main/kotlin/com/fitness/authentication/signin/view/SignInEmail.kt | 1275608333 |
package com.fitness.authentication
interface AuthProvider | body-balance/features/authentication/api/src/main/kotlin/com/fitness/authentication/AuthProvider.kt | 3293735019 |
package com.fitness.authentication
import com.fitness.navigation.AggregateFeatureEntry
abstract class AuthEntry: AggregateFeatureEntry {
override val featureRoute: String get() = "auth"
} | body-balance/features/authentication/api/src/main/kotlin/com/fitness/authentication/AuthEntry.kt | 3046211122 |
package viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import state.DataState
abstract class BaseViewModel : ViewModel() {
private val exceptionHandler = CoroutineExceptionHandler { _, exception ->
handleError(exception)
}
open fun handleError(exception: Throwable) {
exception.printStackTrace()
}
open fun startLoading() {}
protected fun safeLaunch(block: suspend CoroutineScope.() -> Unit) =
viewModelScope.launch(context = exceptionHandler, block = block)
protected suspend fun <T> call(
callFlow: Flow<T>,
completionHandler: (collect: T) -> Unit = {}
) {
callFlow.catch { handleError(it) }
.collect {
completionHandler.invoke(it)
}
}
protected suspend fun <T> execute(
executionFlow: Flow<DataState<T>>,
completionHandler: (collect: T) -> Unit = {}
) {
executionFlow.onStart { startLoading() }
.catch { handleError(it) }
.collect { state ->
when (state) {
is DataState.Success -> completionHandler.invoke(state.result)
is DataState.Error -> handleError(state.error)
}
}
}
} | body-balance/library/framework/src/main/kotlin/viewmodel/BaseViewModel.kt | 3990064127 |
package viewmodel
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.ktx.Firebase
import extensions.cast
import failure.toFailure
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import state.BaseViewState
abstract class IntentViewModel<STATE: BaseViewState<*>, EVENT> : BaseViewModel() {
private val _uiState = MutableStateFlow<BaseViewState<*>>(BaseViewState.Empty)
val uiState get() = _uiState.asStateFlow()
abstract fun onTriggerEvent(event: EVENT)
protected fun setState(state: STATE) = safeLaunch {
_uiState.emit(state)
}
protected fun <T> currentState() = (_uiState.value.cast<BaseViewState<T>>() as BaseViewState.Data).value
override fun startLoading() {
super.startLoading()
_uiState.value = BaseViewState.Loading
}
override fun handleError(exception: Throwable) {
super.handleError(exception)
Firebase.crashlytics.recordException(exception)
_uiState.value = BaseViewState.Error(exception.toFailure())
}
} | body-balance/library/framework/src/main/kotlin/viewmodel/IntentViewModel.kt | 643809570 |
package cache
import java.security.MessageDigest
fun generateUniqueId(input: String): String {
val bytes = MessageDigest.getInstance("SHA-256").digest(input.toByteArray())
return bytes.joinToString("") { "%02x".format(it) }
} | body-balance/library/framework/src/main/kotlin/cache/GenerateUniqueIds.kt | 847998974 |
package cache
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.firebase.firestore.DocumentSnapshot
import failure.FIFTEEN_SECONDS
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withTimeout
import state.DataState
inline fun <reified T> cast(call: () -> DocumentSnapshot): Task<T> {
return try {
val response = call()
Tasks.forResult(response.toObject(T::class.java))
} catch (e: Exception) {
Tasks.forException(e)
}
}
suspend fun <T> firestore(call: () -> Task<T>): DataState<T> {
return try {
withTimeout(FIFTEEN_SECONDS){
val response = call().await()
DataState.Success(response)
}
} catch (e: Exception) {
DataState.Error(e)
}
} | body-balance/library/framework/src/main/kotlin/cache/Firestore.kt | 1778735914 |
package cache
object Collections {
const val USER: String = "USER"
const val USER_BASIC_INFO: String = "USER_BASIC_INFO"
const val USER_BASIC_FITNESS_INFO: String = "USER_BASIC_FITNESS_INFO"
const val USER_NUTRITIONAL_INFO: String = "USER_NUTRITIONAL_INFO"
const val USER_GOALS_INFO: String = "USER_GOALS_INFO"
}
object Fields {
const val ID: String = "id"
const val USER_ID: String = "userId"
const val GOALS: String = "goals"
const val LEVEL: String = "level"
const val HABITS: String = "habits"
const val DISPLAY_NAME: String = "displayName"
const val EMAIL: String = "email"
const val LAST_UPDATED = "lastUpdated"
const val PHONE_NUMBER: String = "phoneNumber"
const val IS_TERMS_PRIVACY_ACCEPTED: String = "isTermAndPrivacyAccepted"
const val PROFILE_PICTURE_URL: String = "profilePictureUrl"
const val IS_NEW_USER: String = "isNewUser"
const val RESTRICTIONS: String = "restrictions"
const val PREFERENCES: String = "preferences"
const val AGE: String = "age"
const val GENDER: String = "gender"
const val HEIGHT: String = "height"
const val WEIGHT: String = "weight"
}
| body-balance/library/framework/src/main/kotlin/cache/Fields.kt | 47243202 |
package util
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class RecipeSearchUseCase
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class RecipeFetchUseCase | body-balance/library/framework/src/main/kotlin/util/Annotations.kt | 947444771 |
package util
import java.time.Instant
import java.time.LocalTime
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
fun convertToDateTimeString(dateLong: Long, hour: Int, minute: Int): String {
val localDate = Instant.ofEpochMilli(dateLong).atZone(ZoneId.systemDefault()).toLocalDate()
val localTime = LocalTime.of(hour, minute)
val zonedDateTime = ZonedDateTime.of(localDate, localTime, ZoneId.systemDefault())
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z")
return zonedDateTime.format(formatter)
}
fun convertLongToDate(timeInMillis: Long?): String {
val formatter = DateTimeFormatter.ofPattern("EEEE, MMMM d", Locale.ENGLISH)
return Instant.ofEpochMilli(timeInMillis ?: System.currentTimeMillis()).atZone(ZoneId.systemDefault()).format(formatter)
}
fun formatTimeWithAmPm(hour: Int?, minute: Int?): String {
val formatHour = hour ?: 7
val formatMinute = minute ?: 30
val amPm = if (formatHour < 12) "AM" else "PM"
val formattedHour = when {
formatHour == 0 -> 12
formatHour > 12 -> formatHour - 12
else -> formatHour
}
val formattedMinute = formatMinute.toString().padStart(2, '0')
return "$formattedHour:$formattedMinute $amPm"
}
| body-balance/library/framework/src/main/kotlin/util/BalanceUtil.kt | 1685475794 |
package auth
import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil
fun formatPhoneNumberToE164(phoneNumber: String, defaultRegion: String): String? {
val phoneUtil = PhoneNumberUtil.getInstance()
return try {
val numberProto = phoneUtil.parse(phoneNumber, defaultRegion)
if (phoneUtil.isValidNumber(numberProto)) {
phoneUtil.format(numberProto, PhoneNumberUtil.PhoneNumberFormat.E164)
} else {
null
}
} catch (e: NumberParseException) {
null
}
} | body-balance/library/framework/src/main/kotlin/auth/FormatPhoneNumber.kt | 3050396008 |
package auth
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.FirebaseUser
import failure.THIRTY_SECONDS
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withTimeout
import state.DataState
suspend fun <T: Task<AuthResult>> authenticate(call: () -> T): DataState<FirebaseUser> {
return try {
withTimeout(THIRTY_SECONDS) {
val response = call().await()
response.user?.let {
DataState.Success(it)
} ?: DataState.Error(Exception("Authentication successful but no user found"))
}
} catch (e: Exception) {
DataState.Error(e)
}
}
suspend fun <T: Task<AuthResult>> phoneAuthenticate(verificationId: String, call: () -> T): DataState<FirebaseUser> =
try {
withTimeout(THIRTY_SECONDS){
val response = call().await()
response.user?.let {
DataState.Success(it)
} ?: DataState.Error(Exception("Authentication successful but no user found"))
}
} catch (e: Exception) {
if(e is FirebaseAuthInvalidCredentialsException){
DataState.Error(PhoneVerificationError(verificationId, e.errorCode, "The code you entered is invalid. Please try again."))
}
else{
DataState.Error(e)
}
}
| body-balance/library/framework/src/main/kotlin/auth/Authenticate.kt | 4191621197 |
package auth
sealed class PhoneAuthState {
object Idle : PhoneAuthState()
object Verified: PhoneAuthState()
data class CodeSent(val verificationId: String) : PhoneAuthState()
data class Error(val exception: Exception) : PhoneAuthState()
} | body-balance/library/framework/src/main/kotlin/auth/PhoneAuthState.kt | 3437375007 |
package auth
import com.google.firebase.auth.FirebaseAuthActionCodeException
import com.google.firebase.auth.FirebaseAuthEmailException
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.FirebaseAuthInvalidUserException
import com.google.firebase.auth.FirebaseAuthMissingActivityForRecaptchaException
import com.google.firebase.auth.FirebaseAuthMultiFactorException
import com.google.firebase.auth.FirebaseAuthRecentLoginRequiredException
import com.google.firebase.auth.FirebaseAuthUserCollisionException
import com.google.firebase.auth.FirebaseAuthWebException
import com.fitness.resources.R
import failure.Failure
import failure.TimeoutCancellationFailure
import kotlinx.coroutines.TimeoutCancellationException
/**
* @param description description of error displayed to user
* @param title title of error displayed to user
*/
sealed class AuthFailure : Failure() {
data class UserError(override val description: Int, override val title: Int): AuthFailure()
data class SystemError(override val description: Int, override val title: Int): AuthFailure()
data class UnknownError(override val description: Int, override val title: Int): AuthFailure()
}
data class PhoneVerificationError(val verificationId: String, val p0: String, val p1: String): FirebaseAuthInvalidCredentialsException(p0, p1)
/**
* @see FirebaseAuthActionCodeException Represents the exception which is a result of an expired or an invalid out of band code.
* @see FirebaseAuthEmailException Represents the exception which is a result of an attempt to send an email via Firebase Auth (e.g. a password reset email)
* @see FirebaseAuthInvalidCredentialsException Thrown when one or more of the credentials passed to a method fail to identify and/or authenticate the user subject of that operation.
* @see FirebaseAuthInvalidUserException Thrown when performing an operation on a FirebaseUser instance that is no longer valid.
* @see FirebaseAuthMissingActivityForRecaptchaException Thrown when the auth request attempted to fetch a reCAPTCHA token, but the activity is missing or null.
* @see FirebaseAuthMultiFactorException This exception is returned when a user that previously enrolled a second factor tries to sign in and passes the first factor successfully.
* @see FirebaseAuthRecentLoginRequiredException Thrown on security sensitive operations on a FirebaseUser instance that require the user to have signed in recently, when the requirement isn't met.
* @see FirebaseAuthUserCollisionException Thrown when an operation on a FirebaseUser instance couldn't be completed due to a conflict with another existing user.
* @see FirebaseAuthWeakPasswordException Thrown when using a weak password (less than 6 chars) to create a new account or to update an existing account's password.
* @see FirebaseAuthWebException Thrown when a web operation couldn't be completed.
*/
fun Throwable.toAuthFailure(): Failure =
when (this) {
is TimeoutCancellationException -> TimeoutCancellationFailure()
is FirebaseAuthInvalidCredentialsException -> {
AuthFailure.UserError(
title = R.string.incorrect_credentials,
description = R.string.invalid_credentials_desc
)
}
is FirebaseAuthInvalidUserException -> {
AuthFailure.UserError(
title = R.string.invalid_user,
description = R.string.invalid_user_desc
)
}
is FirebaseAuthUserCollisionException -> {
handleUserCollisionException(this.errorCode)
}
is FirebaseAuthActionCodeException -> {
AuthFailure.SystemError(
title = R.string.we_are_sorry,
description = R.string.default_error_desc
)
}
is FirebaseAuthEmailException -> {
AuthFailure.SystemError(
title = R.string.we_are_sorry,
description = R.string.default_error_desc
)
}
is FirebaseAuthMissingActivityForRecaptchaException -> {
AuthFailure.SystemError(
title = R.string.we_are_sorry,
description = R.string.default_error_desc
)
}
is FirebaseAuthMultiFactorException -> {
AuthFailure.SystemError(
title = R.string.we_are_sorry,
description = R.string.default_error_desc
)
}
is FirebaseAuthRecentLoginRequiredException -> {
AuthFailure.SystemError(
title = R.string.we_are_sorry,
description = R.string.default_error_desc
)
}
is FirebaseAuthWebException -> {
AuthFailure.SystemError(
title = R.string.we_are_sorry,
description = R.string.default_error_desc
)
}
else -> {
AuthFailure.UnknownError(
title = R.string.we_are_sorry,
description = R.string.default_error_desc
)
}
}
private fun handleUserCollisionException(code: String): AuthFailure {
return if(code == AuthUserCollisionCodes.ERROR_EMAIL_ALREADY_IN_USE.name){
AuthFailure.UserError(
title = R.string.user_exist_email,
description = R.string.user_collision_email_desc
)
} else {
AuthFailure.UserError(
title = R.string.user_exist_phone,
description = R.string.user_collision_phone_desc
)
}
} | body-balance/library/framework/src/main/kotlin/auth/AuthFailure.kt | 1099377023 |
package auth
enum class AuthUserCollisionCodes{
ERROR_EMAIL_ALREADY_IN_USE,
ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL,
ERROR_CREDENTIAL_ALREADY_IN_USE
} | body-balance/library/framework/src/main/kotlin/auth/AuthUserCollisionCodes.kt | 3343430412 |
package network
import android.content.Context
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonQualifier
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import com.squareup.moshi.ToJson
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
private const val CLIENT_TIME_OUT = 60L
private const val CLIENT_CACHE_SIZE = 10 * 1024 * 1024L
private const val CLIENT_CACHE_DIRECTORY = "http"
fun createMoshi(): Moshi =
Moshi.Builder()
.add(NaNToNullAdapter())
.addLast(KotlinJsonAdapterFactory())
.build()
fun createCache(context: Context): Cache = Cache(
directory = File(context.cacheDir, CLIENT_CACHE_DIRECTORY),
maxSize = CLIENT_CACHE_SIZE
)
fun createHttpLoggingInterceptor(isDev: Boolean): HttpLoggingInterceptor =
HttpLoggingInterceptor().apply {
level = if(isDev){
HttpLoggingInterceptor.Level.BODY
} else{
HttpLoggingInterceptor.Level.NONE
}
}
fun createOkHttpClient(context: Context, isCache: Boolean, vararg interceptors: Interceptor): OkHttpClient {
return OkHttpClient.Builder().apply {
interceptors.forEach {
addInterceptor(it)
}
if(isCache) {
cache(createCache(context))
}
connectTimeout(CLIENT_TIME_OUT, TimeUnit.SECONDS)
readTimeout(CLIENT_TIME_OUT, TimeUnit.SECONDS)
writeTimeout(CLIENT_TIME_OUT, TimeUnit.SECONDS)
}.build()
}
/**
* Create Retrofit Client with Moshi
*
* <reified T> private func let us using reflection.
* We can use generics and reflection so ->
* we don't have to define required NewsApi Interface here
*/
inline fun <reified T> createRetrofitWithMoshi(
okHttpClient: OkHttpClient,
moshi: Moshi,
baseUrl: String
): T {
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
return retrofit.create(T::class.java)
}
@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class NaNToNull
class NaNToNullAdapter {
@FromJson
@NaNToNull
fun fromJson(reader: JsonReader): Double? {
if (!reader.hasNext()) return null
val value = reader.peekJson().nextDouble()
return if (value.isNaN()) null else value
}
@ToJson
fun toJson(writer: JsonWriter, value: Double?) {
writer.value(value)
}
}
| body-balance/library/framework/src/main/kotlin/network/NetworkUtil.kt | 3955887380 |
package network
| body-balance/library/framework/src/main/kotlin/network/Call.kt | 3454244614 |
package network.nutrition
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@Retention(AnnotationRetention.RUNTIME)
annotation class Nutrition(val source: NutritionSource) | body-balance/library/framework/src/main/kotlin/network/nutrition/NutritionAnnotations.kt | 4190076954 |
package network.nutrition
object RecipeParameters {
const val AMERICAN = "american"
const val ASIAN = "asian"
const val BRITISH = "british"
const val CARIBBEAN = "caribbean"
const val CENTRAL_EUROPE = "central europe"
const val CHINESE = "chinese"
const val EASTERN_EUROPE = "eastern europe"
const val FRENCH = "french"
const val GREEK = "greek"
const val INDIAN = "indian"
const val ITALIAN = "italian"
const val JAPANESE = "japanese"
const val KOREAN = "korean"
const val KOSHER = "kosher"
const val MEDITERRANEAN = "mediterranean"
const val MEXICAN = "mexican"
const val MIDDLE_EASTERN = "middle eastern"
const val NORDIC = "nordic"
const val SOUTH_AMERICAN = "south american"
const val SOUTH_EAST_ASIAN = "south east asian"
const val WORLD = "world"
const val BREAKFAST = "breakfast"
const val BRUNCH = "brunch"
const val LUNCH_DINNER = "lunch/dinner"
const val SNACK = "snack"
const val TEATIME = "teatime"
const val BISCUITS_AND_COOKIES = "biscuits and cookies"
const val BREAD = "bread"
const val CEREALS = "cereals"
const val CONDIMENTS_AND_SAUCES = "condiments and sauces"
const val DESSERTS = "desserts"
const val DRINKS = "drinks"
const val EGG = "egg"
const val ICE_CREAM_AND_CUSTARD = "ice cream and custard"
const val MAIN_COURSE = "main course"
const val PANCAKE = "pancake"
const val PASTA = "pasta"
const val PASTRY = "pastry"
const val PIES_AND_TARTS = "pies and tarts"
const val PIZZA = "pizza"
const val PREPS = "preps"
const val PRESERVE = "preserve"
const val SALAD = "salad"
const val SANDWICHES = "sandwiches"
const val SEAFOOD = "seafood"
const val SIDE_DISH = "side dish"
const val SOUP = "soup"
const val SPECIAL_OCCASIONS = "special occasions"
const val STARTER = "starter"
const val SWEETS = "sweets"
const val OMELET = "omelet"
const val ALCOHOL_COCKTAIL = "alcohol-cocktail"
const val ALCOHOL_FREE = "alcohol-free"
const val CELERY_FREE = "celery-free"
const val CRUSTACEAN_FREE = "crustacean-free"
const val DAIRY_FREE = "dairy-free"
const val DASH = "DASH"
const val EGG_FREE = "egg-free"
const val FISH_FREE = "fish-free"
const val FODMAP_FREE = "fodmap-free"
const val GLUTEN_FREE = "gluten-free"
const val IMMUNO_SUPPORTIVE = "immuno-supportive"
const val KETO_FRIENDLY = "keto-friendly"
const val KIDNEY_FRIENDLY = "kidney-friendly"
const val LOW_POTASSIUM = "low-potassium"
const val LOW_SUGAR = "low-sugar"
const val LUPINE_FREE = "lupine-free"
const val MOLLUSK_FREE = "mollusk-free"
const val MUSTARD_FREE = "mustard-free"
const val NO_OIL_ADDED = "No-oil-added"
const val PALEO = "paleo"
const val PEANUT_FREE = "peanut-free"
const val PESCATARIAN = "pecatarian"
const val PORK_FREE = "pork-free"
const val RED_MEAT_FREE = "red-meat-free"
const val SESAME_FREE = "sesame-free"
const val SHELLFISH_FREE = "shellfish-free"
const val SOY_FREE = "soy-free"
const val SUGAR_CONSCIOUS = "sugar-conscious"
const val SULFITE_FREE = "sulfite-free"
const val TREE_NUT_FREE = "tree-nut-free"
const val VEGAN = "vegan"
const val VEGETARIAN = "vegetarian"
const val WHEAT_FREE = "wheat-free"
const val BALANCED = "balanced"
const val HIGH_FIBER = "high-fiber"
const val HIGH_PROTEIN = "high-protein"
const val LOW_CARB = "low-carb"
const val LOW_FAT = "low-fat"
const val LOW_SODIUM = "low-sodium"
} | body-balance/library/framework/src/main/kotlin/network/nutrition/Parameters.kt | 2266956179 |
package network.nutrition
fun createNutritionInterceptor(): NutritionInterceptor = NutritionInterceptor()
const val APP_ID = "app_id"
const val APP_KEY = "app_key"
const val EDAMAM_NUTRITION_ID = "c3496110"
const val EDAMAM_NUTRITION_KEY = "b1b1df67fc29ab0e2083f90f20699d4b"
const val EDAMAM_RECIPE_ID = "28ac4d0d"
const val EDAMAM_RECIPE_KEY = "e8c5eb12c9a3bf152ddd572571147a9f"
const val EDAMAM_FOOD_ID = "94526f7b"
const val EDAMAM_FOOD_KEY = "68a3da668152e9aecc483299c5900fd3" | body-balance/library/framework/src/main/kotlin/network/nutrition/NutritionUtil.kt | 104495064 |
package network.nutrition
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import retrofit2.Invocation
class NutritionInterceptor : Interceptor {
private val registration: MutableMap<Int, Nutrition> = mutableMapOf()
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
val annotation = findAnnotation(request)
if (annotation != null) {
request = buildRequest(chain, annotation.source)
}
return chain.proceed(request)
}
private fun findAnnotation(request: Request): Nutrition? {
val key = request.url.hashCode()
return registration[key] ?: request.tag(Invocation::class.java)
?.method()
?.annotations
?.filterIsInstance<Nutrition>()
?.firstOrNull()
?.also { registration[key] = it }
}
private fun buildRequest(chain: Interceptor.Chain, source: NutritionSource): Request {
val urlBuilder = chain.request().url.newBuilder()
when (source) {
NutritionSource.RECIPE -> {
urlBuilder
.addQueryParameter(APP_ID, EDAMAM_RECIPE_ID)
.addQueryParameter(APP_KEY, EDAMAM_RECIPE_KEY)
}
NutritionSource.NUTRITION -> {
urlBuilder
.addQueryParameter(APP_ID, EDAMAM_NUTRITION_ID)
.addQueryParameter(APP_KEY, EDAMAM_NUTRITION_KEY)
}
NutritionSource.FOOD -> {
urlBuilder
.addQueryParameter(APP_ID, EDAMAM_FOOD_ID)
.addQueryParameter(APP_KEY, EDAMAM_FOOD_KEY)
}
}
return chain.request().newBuilder().url(urlBuilder.build()).build()
}
} | body-balance/library/framework/src/main/kotlin/network/nutrition/NutritionInterceptor.kt | 3523341439 |
package network.nutrition
enum class NutritionSource{
FOOD,
RECIPE,
NUTRITION,
} | body-balance/library/framework/src/main/kotlin/network/nutrition/NutritionSource.kt | 2060070866 |
package enums
import com.fitness.resources.R
import extensions.GeneralItem
import network.nutrition.RecipeParameters
enum class EDietLabel(override val title: Int, override val desc: Int?, override val apiParameter: String?): GeneralItem {
BALANCED(title = R.string.balanced_title, desc = R.string.balanced_description, apiParameter = RecipeParameters.BALANCED),
HIGH_FIBER(title = R.string.high_fiber_title, desc = R.string.high_fiber_description, apiParameter = RecipeParameters.HIGH_FIBER),
HIGH_PROTEIN(title = R.string.high_protein_title, desc = R.string.high_protein_description, apiParameter = RecipeParameters.HIGH_PROTEIN),
LOW_CARB(title = R.string.low_carb_title, desc = R.string.low_carb_description, apiParameter = RecipeParameters.LOW_CARB),
LOW_FAT(title = R.string.low_fat_title, desc = R.string.low_fat_description, apiParameter = RecipeParameters.LOW_FAT),
LOW_SODIUM(title = R.string.low_sodium_title, desc = R.string.low_sodium_description, apiParameter = RecipeParameters.LOW_SODIUM)
}
| body-balance/library/framework/src/main/kotlin/enums/EDietLabel.kt | 1559941583 |
package enums
import com.fitness.resources.R
import extensions.GeneralItem
enum class EFitnessInterest(override val title: Int, override val desc: Int? = null, override val apiParameter: String? = null): GeneralItem {
CARDIO(R.string.fitness_habit_cardio),
STRENGTH_TRAINING(R.string.fitness_habit_strength),
WEIGHTLIFTING(R.string.fitness_habit_weightlifting),
YOGA(R.string.fitness_habit_yoga),
PILATES(R.string.fitness_habit_pilates),
SWIMMING(R.string.fitness_habit_swimming),
CYCLING(R.string.fitness_habit_cycling),
RUNNING(R.string.fitness_habit_running),
WALKING(R.string.fitness_habit_walking),
HIIT(R.string.fitness_habit_hiit),
DANCING(R.string.fitness_habit_dancing),
SPORTS(R.string.fitness_habit_sports),
QUALITY_SLEEP(R.string.fitness_habit_quality_sleep),
STRESS_MANAGEMENT(R.string.fitness_habit_stress_mgmt),
DAILY_ACTIVITY(R.string.fitness_habit_daily_activity),
MOTIVATION(R.string.fitness_habit_motivation),
FLEXIBILITY(R.string.fitness_habit_flexibility),
MINDFUL_EATING(R.string.fitness_habit_mindful_eating),
EXERCISE_VARIETY(R.string.fitness_habit_exercise_variety),
GOOD_POSTURE(R.string.fitness_habit_good_posture),
ACTIVE_COMMUTE(R.string.fitness_habit_active_commute),
REST_DAYS(R.string.fitness_habit_rest_days),
BODY_LISTENING(R.string.fitness_habit_body_listening),
MENTAL_HEALTH(R.string.fitness_habit_mental_health),
SOCIAL_INTERACTION(R.string.fitness_habit_socializing),
OUTDOOR_TIME(R.string.fitness_habit_outdoor_time),
PERSONAL_HYGIENE(R.string.fitness_habit_hygiene),
STRETCHING(R.string.fitness_habit_stretching),
REGULAR_ROUTINE(R.string.fitness_habit_regular_routine),
MEDITATION(R.string.fitness_habit_meditation),
BODYWEIGHT_EXERCISE(R.string.fitness_habit_bodyweight),
FUNCTIONAL_TRAINING(R.string.fitness_habit_functional),
KICKBOXING(R.string.fitness_habit_kickboxing),
ROCK_CLIMBING(R.string.fitness_habit_climbing),
SKIPPING(R.string.fitness_habit_skipping),
ROWING(R.string.fitness_habit_rowing),
BOOTCAMP(R.string.fitness_habit_bootcamp),
CROSSFIT(R.string.fitness_habit_crossfit),
ZUMBA(R.string.fitness_habit_zumba)
}
| body-balance/library/framework/src/main/kotlin/enums/EFitnessInterest.kt | 3770617172 |
package enums
import com.fitness.resources.R
enum class EMassUnit(val toKilogram: Double, val unitResourceId: Int, systemOfMeasurement: SystemOfMeasurement): Units {
GRAM(0.001, R.string.unit_gram, SystemOfMeasurement.METRIC),
KILOGRAM(1.0, R.string.unit_kilogram, SystemOfMeasurement.METRIC),
MILLIGRAM(1e-6, R.string.unit_milligram, SystemOfMeasurement.METRIC),
MICROGRAM(1e-9, R.string.unit_microgram, SystemOfMeasurement.METRIC),
OUNCES(0.0283495, R.string.unit_ounces, SystemOfMeasurement.CUSTOMARY),
POUNDS(0.453592, R.string.unit_pounds, SystemOfMeasurement.CUSTOMARY)
} | body-balance/library/framework/src/main/kotlin/enums/EMassUnit.kt | 4188507771 |
package enums
import com.fitness.resources.R
import extensions.GeneralItem
import network.nutrition.RecipeParameters
enum class ECuisineType(override val title: Int, override val desc: Int? = null, override val apiParameter: String?): GeneralItem {
AMERICAN(title = R.string.title_american, apiParameter = RecipeParameters.AMERICAN),
ASIAN(title = R.string.title_asian, apiParameter = RecipeParameters.ASIAN),
BRITISH(title = R.string.title_british, apiParameter = RecipeParameters.BRITISH),
CARIBBEAN(title = R.string.title_caribbean, apiParameter = RecipeParameters.CARIBBEAN),
CENTRAL_EUROPE(title = R.string.title_central_europe, apiParameter = RecipeParameters.CENTRAL_EUROPE),
CHINESE(title = R.string.title_chinese, apiParameter = RecipeParameters.CHINESE),
EASTERN_EUROPE(title = R.string.title_eastern_europe, apiParameter = RecipeParameters.EASTERN_EUROPE),
FRENCH(title = R.string.title_french, apiParameter = RecipeParameters.FRENCH),
GREEK(title = R.string.title_greek, apiParameter = RecipeParameters.GREEK),
INDIAN(title = R.string.title_indian, apiParameter = RecipeParameters.INDIAN),
ITALIAN(title = R.string.title_italian, apiParameter = RecipeParameters.ITALIAN),
JAPANESE(title = R.string.title_japanese, apiParameter = RecipeParameters.JAPANESE),
KOREAN(title = R.string.title_korean, apiParameter = RecipeParameters.KOREAN),
KOSHER(title = R.string.title_kosher, apiParameter = RecipeParameters.KOSHER),
MEDITERRANEAN(title = R.string.title_mediterranean, apiParameter = RecipeParameters.MEDITERRANEAN),
MEXICAN(title = R.string.title_mexican, apiParameter = RecipeParameters.MEXICAN),
MIDDLE_EASTERN(title = R.string.title_middle_eastern, apiParameter = RecipeParameters.MIDDLE_EASTERN),
NORDIC(title = R.string.title_nordic, apiParameter = RecipeParameters.NORDIC),
SOUTH_AMERICAN(title = R.string.title_south_american, apiParameter = RecipeParameters.SOUTH_AMERICAN),
SOUTH_EAST_ASIAN(title = R.string.title_south_east_asian, apiParameter = RecipeParameters.SOUTH_EAST_ASIAN),
WORLD(title = R.string.title_world, apiParameter = RecipeParameters.WORLD),
}
| body-balance/library/framework/src/main/kotlin/enums/ECuisineType.kt | 1685577981 |
package enums
import com.fitness.resources.R
enum class EPhysicalActivityLevel(val title: Int, val description: Int, val factor: Double) {
SEDENTARY(R.string.title_fitness_frequency_sedentary, R.string.desc_fitness_frequency_sedentary, 1.2),
LIGHTLY_ACTIVE(R.string.title_fitness_frequency_lightly, R.string.desc_fitness_frequency_lightly, 1.375),
MODERATELY_ACTIVE(R.string.title_fitness_frequency_moderately_active, R.string.desc_fitness_frequency_moderately_active, 1.55),
VERY_ACTIVE(R.string.title_fitness_frequency_very_active, R.string.desc_fitness_frequency_very_active, 1.725),
EXTRA_ACTIVE(R.string.title_fitness_frequency_extra_active, R.string.desc_fitness_frequency_extra_active, 1.9)
} | body-balance/library/framework/src/main/kotlin/enums/EPhysicalActivityLevel.kt | 3629725610 |
package enums
import com.fitness.resources.R
import extensions.GeneralItem
import network.nutrition.RecipeParameters
enum class EHealthLabel(override val title: Int, override val desc: Int?, override val apiParameter: String?): GeneralItem {
ALCOHOL_COCKTAIL(title = R.string.title_alcohol_cocktail, desc = R.string.def_alcohol_cocktail, apiParameter = RecipeParameters.ALCOHOL_COCKTAIL),
ALCOHOL_FREE(title = R.string.title_alcohol_free, desc = R.string.def_alcohol_free, apiParameter = RecipeParameters.ALCOHOL_FREE),
CELERY_FREE(title = R.string.title_celery_free, desc = R.string.def_celery_free, apiParameter = RecipeParameters.CELERY_FREE),
CRUSTACEAN_FREE(title = R.string.title_crustacean_free, desc = R.string.def_crustacean_free, apiParameter = RecipeParameters.CRUSTACEAN_FREE),
DAIRY_FREE(title = R.string.title_dairy_free, desc = R.string.def_dairy_free, apiParameter = RecipeParameters.DAIRY_FREE),
DASH(title = R.string.title_dash, desc = R.string.def_dash, apiParameter = RecipeParameters.DASH),
EGG_FREE(title = R.string.title_egg_free, desc = R.string.def_egg_free, apiParameter = RecipeParameters.EGG_FREE),
FISH_FREE(title = R.string.title_fish_free, desc = R.string.def_fish_free, apiParameter = RecipeParameters.FISH_FREE),
FODMAP_FREE(title = R.string.title_fodmap_free, desc = R.string.def_fodmap_free, apiParameter = RecipeParameters.FODMAP_FREE),
GLUTEN_FREE(title = R.string.title_gluten_free, desc = R.string.def_gluten_free, apiParameter = RecipeParameters.GLUTEN_FREE),
IMMUNO_SUPPORTIVE(title = R.string.title_immuno_supportive, desc = R.string.def_immuno_supportive, apiParameter = RecipeParameters.IMMUNO_SUPPORTIVE),
KETO_FRIENDLY(title = R.string.title_keto_friendly, desc = R.string.def_keto_friendly, apiParameter = RecipeParameters.KETO_FRIENDLY),
KIDNEY_FRIENDLY(title = R.string.title_kidney_friendly, desc = R.string.def_kidney_friendly, apiParameter = RecipeParameters.KIDNEY_FRIENDLY),
KOSHER(title = R.string.title_kosher, desc = R.string.def_kosher, apiParameter = RecipeParameters.KOSHER),
LOW_POTASSIUM(title = R.string.title_low_potassium, desc = R.string.def_low_potassium, apiParameter = RecipeParameters.LOW_POTASSIUM),
LOW_SUGAR(title = R.string.title_low_sugar, desc = R.string.def_low_sugar, apiParameter = RecipeParameters.LOW_SUGAR),
LUPINE_FREE(title = R.string.title_lupine_free, desc = R.string.def_lupine_free, apiParameter = RecipeParameters.LUPINE_FREE),
MEDITERRANEAN(title = R.string.title_mediterranean, desc = R.string.def_mediterranean, apiParameter = RecipeParameters.MEDITERRANEAN),
MOLLUSK_FREE(title = R.string.title_mollusk_free, desc = R.string.def_mollusk_free, apiParameter = RecipeParameters.MOLLUSK_FREE),
MUSTARD_FREE(title = R.string.title_mustard_free, desc = R.string.def_mustard_free, apiParameter = RecipeParameters.MUSTARD_FREE),
NO_OIL_ADDED(title = R.string.title_no_oil_added, desc = R.string.def_no_oil_added, apiParameter = RecipeParameters.NO_OIL_ADDED),
PALEO(title = R.string.title_paleo, desc = R.string.def_paleo, apiParameter = RecipeParameters.PALEO),
PEANUT_FREE(title = R.string.title_peanut_free, desc = R.string.def_peanut_free, apiParameter = RecipeParameters.PEANUT_FREE),
PESCATARIAN(title = R.string.title_pescatarian, desc = R.string.def_pescatarian, apiParameter = RecipeParameters.PESCATARIAN),
PORK_FREE(title = R.string.title_pork_free, desc = R.string.def_pork_free, apiParameter = RecipeParameters.PORK_FREE),
RED_MEAT_FREE(title = R.string.title_red_meat_free, desc = R.string.def_red_meat_free, apiParameter = RecipeParameters.RED_MEAT_FREE),
SESAME_FREE(title = R.string.title_sesame_free, desc = R.string.def_sesame_free, apiParameter = RecipeParameters.SESAME_FREE),
SHELLFISH_FREE(title = R.string.title_shellfish_free, desc = R.string.def_shellfish_free, apiParameter = RecipeParameters.SHELLFISH_FREE),
SOY_FREE(title = R.string.title_soy_free, desc = R.string.def_soy_free, apiParameter = RecipeParameters.SOY_FREE),
SUGAR_CONSCIOUS(title = R.string.title_sugar_conscious, desc = R.string.def_sugar_conscious, apiParameter = RecipeParameters.SUGAR_CONSCIOUS),
SULFITE_FREE(title = R.string.title_sulfite_free, desc = R.string.def_sulfite_free, apiParameter = RecipeParameters.SULFITE_FREE),
TREE_NUT_FREE(title = R.string.title_tree_nut_free, desc = R.string.def_tree_nut_free, apiParameter = RecipeParameters.TREE_NUT_FREE),
VEGAN(title = R.string.title_vegan, desc = R.string.def_vegan, apiParameter = RecipeParameters.VEGAN),
VEGETARIAN(title = R.string.title_vegetarian, desc = R.string.def_vegetarian, apiParameter = RecipeParameters.VEGETARIAN),
WHEAT_FREE(title = R.string.title_wheat_free, desc = R.string.def_wheat_free, apiParameter = RecipeParameters.WHEAT_FREE)
}
| body-balance/library/framework/src/main/kotlin/enums/EHealthLabel.kt | 4213342764 |
package enums
enum class ETimeUnits{
SECONDS,
MINUTES,
HOUR
} | body-balance/library/framework/src/main/kotlin/enums/ETimeUnits.kt | 3181263431 |
package enums
import com.fitness.resources.R
enum class ELengthUnit(val toMeter: Double, val unitResourceId: Int, systemOfMeasurement: SystemOfMeasurement){
METER(1.0, R.string.unit_meter, SystemOfMeasurement.METRIC),
KILOMETER(1000.0, R.string.unit_kilometer, SystemOfMeasurement.METRIC),
CENTIMETER(0.01, R.string.unit_centimeter, SystemOfMeasurement.METRIC),
MILLIMETER(0.001, R.string.unit_millimeter, SystemOfMeasurement.METRIC),
INCHES(0.0254, R.string.unit_inches, SystemOfMeasurement.CUSTOMARY),
FEET(0.3048, R.string.unit_feet, SystemOfMeasurement.CUSTOMARY),
YARDS(0.9144, R.string.unit_yards, SystemOfMeasurement.CUSTOMARY),
MILES(1609.34, R.string.unit_miles, SystemOfMeasurement.CUSTOMARY)
} | body-balance/library/framework/src/main/kotlin/enums/ELengthUnit.kt | 2174000991 |
package enums
import com.fitness.resources.R
import extensions.GeneralItem
import network.nutrition.RecipeParameters
enum class EDishType(override val title: Int, override val desc: Int? = null, override val apiParameter: String?): GeneralItem {
ALCOHOL_COCKTAIL(title = R.string.title_alcohol_cocktail, apiParameter = RecipeParameters.ALCOHOL_COCKTAIL),
BISCUITS_AND_COOKIES(title = R.string.title_biscuits_and_cookies, apiParameter = RecipeParameters.BISCUITS_AND_COOKIES),
BREAD(title = R.string.title_bread, apiParameter = RecipeParameters.BREAD),
CEREALS(title = R.string.title_cereals, apiParameter = RecipeParameters.CEREALS),
CONDIMENTS_AND_SAUCES(title = R.string.title_condiments_and_sauces, apiParameter = RecipeParameters.CONDIMENTS_AND_SAUCES),
DESSERTS(title = R.string.title_desserts, apiParameter = RecipeParameters.DESSERTS),
DRINKS(title = R.string.title_drinks, apiParameter = RecipeParameters.DRINKS),
EGG(title = R.string.title_egg, apiParameter = RecipeParameters.EGG),
ICE_CREAM_AND_CUSTARD(title = R.string.title_ice_cream_and_custard, apiParameter = RecipeParameters.ICE_CREAM_AND_CUSTARD),
MAIN_COURSE(title = R.string.title_main_course, apiParameter = RecipeParameters.MAIN_COURSE),
PANCAKE(title = R.string.title_pancake, apiParameter = RecipeParameters.PANCAKE),
PASTA(title = R.string.title_pasta, apiParameter = RecipeParameters.PASTA),
PASTRY(title = R.string.title_pastry, apiParameter = RecipeParameters.PASTRY),
PIES_AND_TARTS(title = R.string.title_pies_and_tarts, apiParameter = RecipeParameters.PIES_AND_TARTS),
PIZZA(title = R.string.title_pizza, apiParameter = RecipeParameters.PIZZA),
PREPS(title = R.string.title_preps, apiParameter = RecipeParameters.PREPS),
PRESERVE(title = R.string.title_preserve, apiParameter = RecipeParameters.PRESERVE),
SALAD(title = R.string.title_salad, apiParameter = RecipeParameters.SALAD),
SANDWICHES(title = R.string.title_sandwiches, apiParameter = RecipeParameters.SANDWICHES),
SEAFOOD(title = R.string.title_seafood, apiParameter = RecipeParameters.SEAFOOD),
SIDE_DISH(title = R.string.title_side_dish, apiParameter = RecipeParameters.SIDE_DISH),
SOUP(title = R.string.title_soup, apiParameter = RecipeParameters.SOUP),
SPECIAL_OCCASIONS(title = R.string.title_special_occasions, apiParameter = RecipeParameters.SPECIAL_OCCASIONS),
STARTER(title = R.string.title_starter, apiParameter = RecipeParameters.STARTER),
SWEETS(title = R.string.title_sweets, apiParameter = RecipeParameters.SWEETS),
OMELET(title = R.string.title_omelet, apiParameter = RecipeParameters.OMELET),
}
| body-balance/library/framework/src/main/kotlin/enums/EDishType.kt | 3426792599 |
package enums
import com.fitness.resources.R
enum class ETemperatureUnit(val unitResourceId: Int, systemOfMeasurement: SystemOfMeasurement) {
CELSIUS(R.string.unit_celsius, SystemOfMeasurement.METRIC),
FAHRENHEIT(R.string.unit_fahrenheit, SystemOfMeasurement.CUSTOMARY)
} | body-balance/library/framework/src/main/kotlin/enums/ETemperatureUnit.kt | 3107606066 |
package enums
import com.fitness.resources.R
import extensions.GeneralItem
import network.nutrition.RecipeParameters
enum class EMealType(override val title: Int, override val desc: Int? = null, override val apiParameter: String?): GeneralItem {
BREAKFAST(title = R.string.title_breakfast, apiParameter = RecipeParameters.BREAKFAST),
BRUNCH(title = R.string.title_brunch, apiParameter = RecipeParameters.BRUNCH),
LUNCH_DINNER(title = R.string.title_lunch_dinner, apiParameter = RecipeParameters.LUNCH_DINNER),
SNACK(title = R.string.title_snack, apiParameter = RecipeParameters.SNACK),
TEATIME(title = R.string.title_teatime, apiParameter = RecipeParameters.TEATIME)
} | body-balance/library/framework/src/main/kotlin/enums/EMealType.kt | 1718119355 |
package enums
import com.fitness.resources.R
import extensions.GeneralItem
enum class ENutritionPreferences(override val title: Int, override val desc: Int? = null, override val apiParameter: String? = null): GeneralItem {
BALANCED_DIET(R.string.title_balanced_diet),
VEGAN_DIET(R.string.title_vegan),
VEGETARIAN_DIET(R.string.title_vegetarian),
KETO_DIET(R.string.title_keto),
PALEO_DIET(R.string.title_paleo),
PESCETARIAN_DIET(R.string.title_pescetarian),
MEDITERRANEAN_DIET(R.string.title_mediterranean),
WHOLE30_DIET(R.string.title_whole30),
LOW_CARB_DIET(R.string.title_low_carb),
HIGH_PROTEIN_DIET(R.string.title_high_protein),
INTERMITTENT_FASTING(R.string.title_intermittent_fasting),
PLANT_BASED_DIET(R.string.title_plant_based),
GLUTEN_FREE_DIET(R.string.title_gluten_free),
DAIRY_FREE_DIET(R.string.title_dairy_free),
DETOX_DIET(R.string.title_detox),
HYDRATION(R.string.title_hydration),
WEIGHT_CONTROL(R.string.title_weight_control),
PORTION_SIZE(R.string.title_portion_size),
LESS_SCREEN(R.string.title_less_screen),
WHOLE_FOODS(R.string.title_whole_foods),
HEALTHY_SNACKS(R.string.title_healthy_snacks),
LESS_SUGAR(R.string.title_less_sugar),
LESS_CAFFEINE(R.string.title_less_caffeine),
NO_SMOKING(R.string.title_no_smoking),
MODERATE_ALCOHOL(R.string.title_moderate_alcohol);
}
| body-balance/library/framework/src/main/kotlin/enums/ENutritionPreferences.kt | 3723577008 |
package enums
interface Units | body-balance/library/framework/src/main/kotlin/enums/Units.kt | 625235011 |
package enums
import com.fitness.resources.R
enum class EVolumeUnit(val toLiter: Double, val unitResourceId: Int, systemOfMeasurement: SystemOfMeasurement): Units {
LITER(1.0, R.string.unit_liter, SystemOfMeasurement.METRIC),
MILLILITER(0.001, R.string.unit_milliliter, SystemOfMeasurement.METRIC),
TEASPOON(0.00492892, R.string.unit_teaspoon, SystemOfMeasurement.CUSTOMARY),
TABLESPOON(0.0147868, R.string.unit_tablespoon, SystemOfMeasurement.CUSTOMARY),
FLUID_OUNCES(0.0295735, R.string.unit_fluid_ounces, SystemOfMeasurement.CUSTOMARY),
CUPS(0.236588, R.string.unit_cups, SystemOfMeasurement.CUSTOMARY),
PINTS(0.473176, R.string.unit_pints, SystemOfMeasurement.CUSTOMARY),
QUARTS(0.946353, R.string.unit_quarts, SystemOfMeasurement.CUSTOMARY),
GALLONS(3.78541, R.string.unit_gallons, SystemOfMeasurement.CUSTOMARY)
}
| body-balance/library/framework/src/main/kotlin/enums/EVolumeUnit.kt | 2589541983 |
package enums
import com.fitness.resources.R
import extensions.GeneralItem
enum class EGoals(override val title: Int, override val desc: Int? = null, override val apiParameter: String? = null): GeneralItem {
INCREASE_CARDIO_ENDURANCE(R.string.title_increase_cardio_endurance),
BUILD_MUSCLE_STRENGTH(R.string.title_build_muscle_strength),
ENHANCE_FLEXIBILITY(R.string.title_enhance_flexibility),
IMPROVE_BALANCE(R.string.title_improve_balance),
WEIGHT_LOSS(R.string.title_weight_loss),
WEIGHT_GAIN(R.string.title_weight_gain),
IMPROVE_CORE_STRENGTH(R.string.title_improve_core_strength),
REDUCE_STRESS(R.string.title_reduce_stress),
IMPROVE_SLEEP_QUALITY(R.string.title_improve_sleep_quality),
EAT_HEALTHIER(R.string.title_eat_healthier),
STAY_HYDRATED(R.string.title_stay_hydrated),
INCREASE_ACTIVITY_LEVEL(R.string.title_increase_activity_level),
IMPROVE_MENTAL_HEALTH(R.string.title_improve_mental_health),
QUIT_SMOKING(R.string.title_quit_smoking),
REDUCE_ALCOHOL_CONSUMPTION(R.string.title_reduce_alcohol_consumption),
PRACTICE_MINDFULNESS(R.string.title_practice_mindfulness),
RUN_A_MARATHON(R.string.title_run_a_marathon),
PARTICIPATE_IN_A_TRIATHLON(R.string.title_participate_in_a_triathlon),
LEARN_A_NEW_SPORT(R.string.title_learn_a_new_sport),
IMPROVE_POSTURE(R.string.title_improve_posture),
INCREASE_FLEXIBILITY(R.string.title_increase_flexibility),
BOOST_IMMUNE_SYSTEM(R.string.title_boost_immune_system),
IMPROVE_DIGESTION(R.string.title_improve_digestion),
DECREASE_SCREEN_TIME(R.string.title_decrease_screen_time),
ACHIEVE_WORK_LIFE_BALANCE(R.string.title_achieve_work_life_balance);
}
| body-balance/library/framework/src/main/kotlin/enums/EGoals.kt | 4125815878 |
package enums
import com.fitness.resources.R
enum class SystemOfMeasurement(val title: Int, val description: Int) {
METRIC(R.string.metric_system_title, R.string.metric_system_description),
CUSTOMARY(R.string.customary_system_title, R.string.customary_system_description)
}
| body-balance/library/framework/src/main/kotlin/enums/ESystemOfMeasurements.kt | 354674884 |
package enums
enum class EGender {
MALE,
FEMALE,
} | body-balance/library/framework/src/main/kotlin/enums/EGender.kt | 2745522956 |
package enums
enum class EHealthCondition {
NONE,
DIABETES,
HYPERTENSION,
HYPOTHYROIDISM,
HYPERCHOLESTEROLEMIA,
ASTHMA,
ARTHRITIS,
CHRONIC_KIDNEY_DISEASE,
COPD,
DEPRESSION,
ANXIETY,
OBESITY,
CORONARY_HEART_DISEASE,
OSTEOPOROSIS,
CANCER,
CHRONIC_BACK_PAIN,
MIGRAINE,
IRRITABLE_BOWEL_SYNDROME,
CELIAC_DISEASE,
MULTIPLE_SCLEROSIS,
PARKINSONS_DISEASE,
FIBROMYALGIA,
SLEEP_APNEA,
GASTROESOPHAGEAL_REFLUX_DISEASE,
EPILEPSY,
ALZHEIMERS_DISEASE,
HIV_AIDS,
STROKE,
POLYCYSTIC_OVARY_SYNDROME,
ENDOMETRIOSIS,
CHRONIC_FATIGUE_SYNDROME,
RHEUMATOID_ARTHRITIS,
LUPUS,
CROHNS_DISEASE,
ULCERATIVE_COLITIS,
ANEMIA,
CYSTIC_FIBROSIS,
PSORIASIS,
VITILIGO,
LYME_DISEASE,
TUBERCULOSIS,
HEPATITIS,
PEPTIC_ULCER_DISEASE,
PANCREATITIS,
HEART_FAILURE,
ATRIAL_FIBRILLATION,
THYROID_CANCER,
BREAST_CANCER,
LUNG_CANCER,
PROSTATE_CANCER,
LEUKEMIA,
LYMPHOMA,
MELANOMA,
BIPOLAR_DISORDER,
SCHIZOPHRENIA,
DEMENTIA,
ADDICTION,
AUTISM_SPECTRUM_DISORDER,
DOWN_SYNDROME,
EATING_DISORDERS
}
| body-balance/library/framework/src/main/kotlin/enums/EHealthCondition.kt | 2507083011 |
package enums
import com.fitness.resources.R
inline fun <reified T : Enum<T>> safeEnumValueOf(type: String): T? {
return try {
enumValueOf<T>(type)
} catch (e: IllegalArgumentException) {
null
}
}
fun convertLength(value: Double, fromUnit: ELengthUnit, toUnit: ELengthUnit): Double {
return value * fromUnit.toMeter / toUnit.toMeter
}
fun convertMass(value: Double, fromUnit: EMassUnit, toUnit: EMassUnit): Double {
return value * fromUnit.toKilogram / toUnit.toKilogram
}
fun convertVolume(value: Double, fromUnit: EVolumeUnit, toUnit: EVolumeUnit): Double {
return value * fromUnit.toLiter / toUnit.toLiter
}
fun convertTemperature(value: Double, fromUnit: ETemperatureUnit, toUnit: ETemperatureUnit): Double {
return when {
fromUnit == ETemperatureUnit.CELSIUS && toUnit == ETemperatureUnit.FAHRENHEIT -> value * 1.8 + 32
fromUnit == ETemperatureUnit.FAHRENHEIT && toUnit == ETemperatureUnit.CELSIUS -> (value - 32) / 1.8
else -> value
}
}
fun formatWeight(value: Double, toUnit: EMassUnit): String {
return when (toUnit) {
EMassUnit.GRAM -> {
val grams = value * 453.592 // Convert pounds to grams
"${grams.toInt()} g"
}
EMassUnit.KILOGRAM -> {
val kilograms = value * 0.453592 // Convert pounds to kilograms
"${String.format("%.2f", kilograms)} kg"
}
else -> "${String.format("%.2f", value)} lbs" // Pounds
}
}
fun Double.toFeetAndInchesFromCm(): Pair<Int, Int> {
val totalInches = this / 2.54
val feet = (totalInches / 12).toInt()
val remainingInches = (totalInches % 12).toInt()
return Pair(feet, remainingInches)
}
fun formatHeight(value: Double, toUnit: ELengthUnit): String {
return when (toUnit) {
ELengthUnit.FEET -> {
val (feet, inches) = value.toFeetAndInchesFromCm()
"$feet' $inches\""
}
ELengthUnit.METER -> {
val meters = value / 100.0 // Convert centimeters to meters
"${String.format("%.2f", meters)} m"
}
else -> "${value.toInt()} cm" // Centimeters
}
}
fun formatLength(value: Double, unit: ELengthUnit): String {
return when (unit) {
ELengthUnit.METER -> "${String.format("%.1f", value)} m"
ELengthUnit.KILOMETER -> "${String.format("%.1f", value)} km"
ELengthUnit.CENTIMETER -> "${String.format("%.1f", value)} cm"
ELengthUnit.MILLIMETER -> "${String.format("%.1f", value)} mm"
ELengthUnit.INCHES -> "${String.format("%.1f", value)} in"
ELengthUnit.FEET -> "${String.format("%.1f", value)} ft"
ELengthUnit.YARDS -> "${String.format("%.1f", value)} yd"
ELengthUnit.MILES -> "${String.format("%.1f", value)} mi"
}
}
| body-balance/library/framework/src/main/kotlin/enums/Util.kt | 3065371312 |
package enums
import com.fitness.resources.R
import extensions.GeneralItem
enum class EDietaryRestrictions(override val title: Int, override val desc: Int? = null, override val apiParameter: String? = null): GeneralItem {
NO_DAIRY(R.string.title_no_dairy),
NO_GLUTEN(R.string.title_no_gluten),
NO_NUTS(R.string.title_no_nuts),
NO_SOY(R.string.title_no_soy),
NO_EGGS(R.string.title_no_eggs),
NO_SHELLFISH(R.string.title_no_shellfish),
NO_FISH(R.string.title_no_fish),
LOW_SODIUM(R.string.title_low_sodium),
LOW_SUGAR(R.string.title_low_sugar),
DIABETIC_FRIENDLY(R.string.title_diabetic_friendly),
HALAL(R.string.title_halal),
KOSHER(R.string.title_kosher),
VEGAN(R.string.title_vegan),
VEGETARIAN(R.string.title_vegetarian),
PESCETARIAN(R.string.title_pescetarian),
LACTOSE_FREE(R.string.title_lactose_free),
FODMAP(R.string.title_fodmap),
PALEO(R.string.title_paleo),
KETO(R.string.title_keto),
WHOLE30(R.string.title_whole30),
NIGHTSHADE_FREE(R.string.title_nightshade_free),
LOW_FODMAP(R.string.title_low_fodmap),
AIP(R.string.title_aip), // Autoimmune Protocol
CORN_FREE(R.string.title_corn_free),
SUGAR_FREE(R.string.title_sugar_free);
}
| body-balance/library/framework/src/main/kotlin/enums/EDietaryRestrictions.kt | 691872923 |
package enums
import com.fitness.resources.R
enum class ENutrient(val ntrCodeResId: Int, val nameResId: Int, val unit: Units) {
ADDED_SUGAR(R.string.ntr_added_sugar_code, R.string.ntr_added_sugar, EMassUnit.GRAM),
CALCIUM(R.string.ntr_calcium_code, R.string.ntr_calcium, EMassUnit.MILLIGRAM),
NET_CARBOHYDRATE(R.string.ntr_net_carbohydrate_code, R.string.ntr_net_carbohydrate, EMassUnit.GRAM),
CARBOHYDRATE(R.string.ntr_carbohydrate_code, R.string.ntr_carbohydrate, EMassUnit.GRAM),
CHOLESTEROL(R.string.ntr_cholesterol_code, R.string.ntr_cholesterol, EMassUnit.MILLIGRAM),
ENERGY(R.string.ntr_energy_code, R.string.ntr_energy, EMassUnit.KILOGRAM), // Adjust as needed for ENERGY unit
FATTY_ACIDS_MONO(R.string.ntr_fatty_acids_mono_code, R.string.ntr_fatty_acids_mono, EMassUnit.GRAM),
FATTY_ACIDS_POLY(R.string.ntr_fatty_acids_poly_code, R.string.ntr_fatty_acids_poly, EMassUnit.GRAM),
FATTY_ACIDS_SAT(R.string.ntr_fatty_acids_sat_code, R.string.ntr_fatty_acids_sat, EMassUnit.GRAM),
TRANS_FAT(R.string.ntr_trans_fat_code, R.string.ntr_trans_fat, EMassUnit.GRAM),
DIETARY_FIBER(R.string.ntr_fiber_code, R.string.ntr_fiber, EMassUnit.GRAM),
FOLATE_DFE(R.string.ntr_folate_dfe_code, R.string.ntr_folate_dfe, EMassUnit.MICROGRAM),
FOLATE_FOOD(R.string.ntr_folate_food_code, R.string.ntr_folate_food, EMassUnit.MICROGRAM),
FOLIC_ACID(R.string.ntr_folic_acid_code, R.string.ntr_folic_acid, EMassUnit.MICROGRAM),
IRON(R.string.ntr_iron_code, R.string.ntr_iron, EMassUnit.MILLIGRAM),
MAGNESIUM(R.string.ntr_magnesium_code, R.string.ntr_magnesium, EMassUnit.MILLIGRAM),
NIACIN(R.string.ntr_niacin_code, R.string.ntr_niacin, EMassUnit.MILLIGRAM),
PHOSPHORUS(R.string.ntr_phosphorus_code, R.string.ntr_phosphorus, EMassUnit.MILLIGRAM),
POTASSIUM(R.string.ntr_potassium_code, R.string.ntr_potassium, EMassUnit.MILLIGRAM),
PROTEIN(R.string.ntr_protein_code, R.string.ntr_protein, EMassUnit.GRAM),
RIBOFLAVIN(R.string.ntr_riboflavin_code, R.string.ntr_riboflavin, EMassUnit.MILLIGRAM),
SODIUM(R.string.ntr_sodium_code, R.string.ntr_sodium, EMassUnit.MILLIGRAM),
SUGAR_ALCOHOL(R.string.ntr_sugar_alcohol_code, R.string.ntr_sugar_alcohol, EMassUnit.GRAM),
TOTAL_SUGARS(R.string.ntr_sugars_total_code, R.string.ntr_sugars_total, EMassUnit.GRAM),
THIAMIN(R.string.ntr_thiamin_code, R.string.ntr_thiamin, EMassUnit.MILLIGRAM),
TOTAL_FAT(R.string.ntr_total_fat_code, R.string.ntr_total_fat, EMassUnit.GRAM),
VITAMIN_A(R.string.ntr_vitamin_a_code, R.string.ntr_vitamin_a, EMassUnit.MICROGRAM),
VITAMIN_B12(R.string.ntr_vitamin_b12_code, R.string.ntr_vitamin_b12, EMassUnit.MICROGRAM),
VITAMIN_B6(R.string.ntr_vitamin_b6_code, R.string.ntr_vitamin_b6, EMassUnit.MILLIGRAM),
VITAMIN_C(R.string.ntr_vitamin_c_code, R.string.ntr_vitamin_c, EMassUnit.MILLIGRAM),
VITAMIN_D(R.string.ntr_vitamin_d_code, R.string.ntr_vitamin_d, EMassUnit.MICROGRAM),
VITAMIN_E(R.string.ntr_vitamin_e_code, R.string.ntr_vitamin_e, EMassUnit.MILLIGRAM),
VITAMIN_K(R.string.ntr_vitamin_k_code, R.string.ntr_vitamin_k, EMassUnit.MICROGRAM),
WATER(R.string.ntr_water_code, R.string.ntr_water, EVolumeUnit.LITER),
ZINC(R.string.ntr_zinc_code, R.string.ntr_zinc, EMassUnit.MILLIGRAM)
}
| body-balance/library/framework/src/main/kotlin/enums/ENutrient.kt | 996886167 |
package state
sealed interface BaseViewState<out T> {
object Loading: BaseViewState<Nothing>
object Empty: BaseViewState<Nothing>
data class Data<T>(val value: T): BaseViewState<T>
data class Error(val failure: Throwable) : BaseViewState<Nothing>
} | body-balance/library/framework/src/main/kotlin/state/BaseViewState.kt | 3604555041 |
package state
sealed class DataState<out T> {
data class Success<out T>(val result: T) : DataState<T>()
data class Error(val error: Throwable) : DataState<Nothing>()
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$result]"
is Error -> "Error[exception=$error]"
}
}
inline fun <R : Any> map(transform: (T) -> R): DataState<R> {
return when (this) {
is Error -> Error(this.error)
is Success -> Success(transform(this.result))
}
}
} | body-balance/library/framework/src/main/kotlin/state/DataState.kt | 1764905605 |
package extensions
fun Float.format(length: Int) = String.format("%.${length}f", this) | body-balance/library/framework/src/main/kotlin/extensions/FloatExtensions.kt | 1437617008 |
package extensions
import android.content.res.Configuration
import androidx.compose.ui.tooling.preview.Device
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
annotation class Dark
@Preview(name = "Light", showBackground = true)
annotation class Light | body-balance/library/framework/src/main/kotlin/extensions/ComposeExtensions.kt | 690620558 |
package extensions
enum class TextFieldState{
OK,
ERROR,
PENDING,
} | body-balance/library/framework/src/main/kotlin/extensions/TextFieldExtension.kt | 2974683620 |
package extensions
interface GeneralItem {
val title: Int
val desc: Int?
val apiParameter: String?
} | body-balance/library/framework/src/main/kotlin/extensions/LazyListUtil.kt | 3867881208 |
package extensions
inline fun <reified T : Any> Any.cast(): T {
return this as T
}
fun <T> T.update(updateFn: T.() -> T): T {
return updateFn()
} | body-balance/library/framework/src/main/kotlin/extensions/AnyExtension.kt | 391413157 |
package failure
import com.fitness.resources.R
abstract class Failure: Throwable() {
abstract val description: Int
abstract val title: Int
}
fun Throwable.toFailure(): Failure =
if(this is Failure){
this
}
else{
GenericFailure()
}
data class GenericFailure(
override val description: Int = R.string.desc_generic_error,
override val title: Int = R.string.title_generic_error
): Failure()
data class AuthStateFailure(
override val description: Int = R.string.desc_login_status_changed,
override val title: Int = R.string.login_status_changed
): Failure()
data class TimeoutCancellationFailure(
override val description: Int = R.string.desc_connection_timeout,
override val title: Int = R.string.title_connection_timeout
): Failure()
data class MinimumNumberOfSelectionFailure(
override val description: Int = R.string.desc_error_min_items_required,
override val title: Int = R.string.title_error,
val minSelection: Int
): Failure() | body-balance/library/framework/src/main/kotlin/failure/Failure.kt | 517847546 |
package failure
const val TEN_SECONDS = 10000L
const val FIFTEEN_SECONDS = 15000L
const val TWENTY_SECONDS = 20000L
const val THIRTY_SECONDS = 30000L | body-balance/library/framework/src/main/kotlin/failure/Timeout.kt | 2330763575 |
package usecase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
abstract class LocalUseCase<in Params, ReturnType> where ReturnType: Any {
protected abstract suspend fun FlowCollector<ReturnType>.execute(params: Params)
suspend operator fun invoke(params: Params) = flow {
execute(params)
}.flowOn(Dispatchers.IO)
} | body-balance/library/framework/src/main/kotlin/usecase/LocalUseCase.kt | 1015719782 |
package usecase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import state.DataState
abstract class DataStateUseCase<in Params, ReturnType> where ReturnType: Any{
protected abstract suspend fun FlowCollector<DataState<ReturnType>>.execute(params: Params)
suspend operator fun invoke(params: Params) = flow { execute(params) }.flowOn(Dispatchers.IO)
} | body-balance/library/framework/src/main/kotlin/usecase/DataStateUseCase.kt | 3716957132 |
package usecase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
abstract class ReturnUseCase<in Params, ReturnType> where ReturnType: Any {
protected abstract suspend fun execute(params: Params): Flow<ReturnType>
suspend operator fun invoke(params: Params) = execute(params).flowOn(Dispatchers.IO)
} | body-balance/library/framework/src/main/kotlin/usecase/ReturnUseCase.kt | 3749076727 |
package media
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import androidx.annotation.OptIn
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.util.Log
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.RawResourceDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.media3.ui.PlayerView
import kotlinx.coroutines.delay
@OptIn(UnstableApi::class)
@Composable
fun VideoPlayer(video: Int) {
val context = LocalContext.current
val exoPlayer = remember {
ExoPlayer.Builder(context).build().apply {
val uri = RawResourceDataSource.buildRawResourceUri(video)
setMediaItem(MediaItem.fromUri(uri))
prepare()
playWhenReady = true
repeatMode = Player.REPEAT_MODE_OFF
}
}
DisposableEffect(exoPlayer) {
onDispose {
exoPlayer.release()
}
}
val fadeOutDurationMillis = 2000L
val fadeOutStartMillis = exoPlayer.duration - fadeOutDurationMillis
val fadingOut = remember { mutableStateOf(false) }
LaunchedEffect(exoPlayer) {
while (true) {
val currentPosition = exoPlayer.currentPosition
Log.e("VideoView", "Current Position: $currentPosition, Duration: ${exoPlayer.duration}")
if (currentPosition >= fadeOutStartMillis && !fadingOut.value) {
Log.e("VideoView", "Fading Out")
fadingOut.value = true
}
if (fadingOut.value && currentPosition <= 500) {
Log.e("VideoView", "Resetting")
exoPlayer.seekTo(0)
fadingOut.value = false
}
delay(500)
}
}
Box(
modifier = Modifier.fillMaxSize()
) {
AndroidView(
factory = {
PlayerView(context).apply {
player = exoPlayer
layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)
resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
useController = false
}
}
)
if (fadingOut.value) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.5f)) // Adjust the alpha as needed
) {
// You can add additional UI elements or animations here during the fade-out
}
}
}
}
| body-balance/library/framework/src/main/kotlin/media/VideoPlayer.kt | 3714998538 |
package com.fitness.analytics
import enums.EPhysicalActivityLevel
fun calculateTDEE(bmr: Double, activityLevel: EPhysicalActivityLevel): Double {
return bmr * activityLevel.factor
}
fun calculateProtein(tdee: Double): Double {
// Define protein percentage (Adjust as needed)
val proteinPercentage = 0.25 // 25% of total calories from protein
return (proteinPercentage * tdee) / 4.0 // 4 calories per gram of protein
}
fun calculateFat(tdee: Double): Double {
// Define fat percentage (Adjust as needed)
val fatPercentage = 0.25 // 25% of total calories from fat
return (fatPercentage * tdee) / 9.0 // 9 calories per gram of fat
}
fun calculateCarbs(tdee: Double): Double {
// Define carbohydrate percentage (Adjust as needed)
val proteinPercentage = 0.25 // 25% of total calories from protein
val fatPercentage = 0.25 // 25% of total calories from fat
val carbPercentage = 1.0 - (proteinPercentage + fatPercentage) // Remaining from carbs
return (carbPercentage * tdee) / 4.0 // 4 calories per gram of carbohydrate
}
fun calculateFiber(totalCalories: Double): Double {
// Define fiber percentage (Adjust as needed)
val fiberPercentage = 0.014 // 14 grams of fiber per 1000 calories
return fiberPercentage * totalCalories / 1000.0
}
| body-balance/library/analytics/src/main/kotlin/com/fitness/analytics/Macros.kt | 2899939427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.