content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.fitness.analytics import enums.EGender import enums.EPhysicalActivityLevel fun calculateBMR(gender: EGender, weightKg: Double, heightCm: Double, waistCm: Double, ageYears: Int): Double { val bmr: Double = when (gender) { EGender.MALE -> (10 * weightKg) + (6.25 * heightCm) - (5 * ageYears) + 5 EGender.FEMALE -> (10 * weightKg) + (6.25 * heightCm) - (5 * ageYears) - 161 } val waistFactor = when (gender) { EGender.MALE -> 1.0 EGender.FEMALE -> 0.8 } return bmr * (waistCm / heightCm) * waistFactor }
body-balance/library/analytics/src/main/kotlin/com/fitness/analytics/BasalMetabolicRate.kt
343927286
package com.fitness.navigation import dagger.MapKey import kotlin.reflect.KClass @MapKey annotation class FeatureEntryKey(val value: KClass<out FeatureEntry>)
body-balance/common/navigation/src/main/kotlin/com/fitness/navigation/FeatureEntryKey.kt
1226169851
package com.fitness.navigation data class BottomNavItem( val name:String, val route:String, val icon:Int, )
body-balance/common/navigation/src/main/kotlin/com/fitness/navigation/BottomNavItem.kt
758250236
package com.fitness.navigation data class DrawerItem( val name: String, val icon: Int, val contentDescription: Int, val route: String )
body-balance/common/navigation/src/main/kotlin/com/fitness/navigation/DrawerItem.kt
282349737
package com.fitness.navigation import androidx.compose.runtime.Composable import androidx.navigation.NamedNavArgument import androidx.navigation.NavBackStackEntry import androidx.navigation.NavDeepLink import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.composable typealias Destinations = Map<Class<out FeatureEntry>, @JvmSuppressWildcards FeatureEntry> interface FeatureEntry { val featureRoute: String val arguments: List<NamedNavArgument> get() = emptyList() val deepLinks: List<NavDeepLink> get() = emptyList() } interface ComposableFeatureEntry: FeatureEntry { fun NavGraphBuilder.composable(navController: NavHostController, destinations: Destinations) { composable(featureRoute, arguments, deepLinks) { backStackEntry -> Composable(navController, destinations, backStackEntry) } } @Composable fun Composable( navController: NavHostController, destinations: Destinations, backStackEntry: NavBackStackEntry ) } interface AggregateFeatureEntry : FeatureEntry { fun NavGraphBuilder.navigation(navController: NavHostController, destinations: Destinations) } inline fun <reified T: FeatureEntry> Destinations.find(): T = findOrNull() ?: error("Unable to find '${T::class.java}' destination.") inline fun <reified T: FeatureEntry> Destinations.findOrNull(): T? = this[T::class.java] as? T
body-balance/common/navigation/src/main/kotlin/com/fitness/navigation/Destinations.kt
435003125
package com.fitness.navigation import com.fitness.resources.R object NavigationUtil { const val SettingsRoute = "settings" const val ProfileRoute = "home" const val HealthPlanningRoute = "health_planning" const val HealthAnalysisRoute = "health_analysis" } object BottomNavigationUtil{ private const val TrainingHubRoute = "training-hub" private const val HomeRoute = "home" private const val WorkoutTrackingRoute = "workout-tracking" private const val HealthAnalysisRoute = "analysis" private const val HealthTrackingRoute = "health-tracking" private const val TrainingHubTitle = "Training Hub" private const val HomeTitle = "Home" private const val WorkoutTracking = "Workout Tracking" private const val HealthAnalysisTitle = "Health Analysis" private const val HealthTrackingTitle = "Health Tracking" val bottomNavItems = listOf( BottomNavItem( name = HealthAnalysisTitle, route = HealthAnalysisRoute, icon = R.drawable.icon_analysis ), BottomNavItem( name = HealthTrackingTitle, route = HealthTrackingRoute, icon = R.drawable.icon_diet_tracking ), BottomNavItem(name = HomeTitle, route = HomeRoute, icon = R.drawable.icon_home), BottomNavItem( name = WorkoutTracking, route = WorkoutTrackingRoute, icon = R.drawable.icon_laps ), BottomNavItem( name = TrainingHubTitle, route = TrainingHubRoute, icon = R.drawable.icon_sprint ) ) } object DrawerNavigationUtil{ private const val AccountManagementRoute = "account" private const val HomeRoute = "home" private const val LogOutRoute = "sign-out" private const val SettingsRoute = "settings" private const val AccountManagementTitle = "Account Management" private const val HomeTitle = "Home" private const val SettingsTitle = "Settings" private const val LogOutTitle = "Log Out" val drawerNavItems = listOf( DrawerItem( name = HomeTitle, route = HomeRoute, icon = R.drawable.icon_home, contentDescription = R.string.content_description_home ), DrawerItem( name = SettingsTitle, route = SettingsRoute, icon = R.drawable.icon_person, contentDescription = R.string.content_description_settings ), DrawerItem( name = AccountManagementTitle, route = AccountManagementRoute, icon = R.drawable.icon_settings, contentDescription = R.string.content_description_account ), DrawerItem( name = LogOutTitle, route = LogOutRoute, icon = R.drawable.icon_settings, contentDescription = R.string.content_description_logout ) ) }
body-balance/common/navigation/src/main/kotlin/com/fitness/navigation/NavigationUtil.kt
3571780617
package com.fitness.component import android.media.MediaPlayer import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.TweenSpec import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.drawable.toBitmap import com.fitness.resources.R import enums.EMealType import extensions.GeneralItem import java.io.IOException @Composable fun WindIcon() { val animatable = remember { Animatable(0f) } // Start the animation LaunchedEffect(Unit) { animatable.animateTo( targetValue = 1f, animationSpec = TweenSpec(durationMillis = 600) // Adjust duration as needed ) } val context = LocalContext.current val drawable = ResourcesCompat.getDrawable(context.resources, R.drawable.icon_wind, context.theme) val bitmap = drawable?.toBitmap()?.asImageBitmap() Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { if (bitmap != null) { Canvas( modifier = Modifier.size(150.dp) // Increase the size as needed ) { val iconWidth = size.width * animatable.value val centerX = (size.width - bitmap.width) / 2f val centerY = (size.height - bitmap.height) / 2f clipRect(left = 0f, top = 0f, right = iconWidth, bottom = size.height) { drawImage(bitmap, topLeft = Offset(centerX, centerY)) } } } } } @Composable fun PlayWavSound() { val context = LocalContext.current DisposableEffect(Unit) { val mediaPlayer = MediaPlayer() try { val afd = context.resources.openRawResourceFd(R.raw.wind_sound) // Replace 'wind' with your file's name (without extension) mediaPlayer.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length) afd.close() mediaPlayer.setOnPreparedListener { it.start() } mediaPlayer.prepareAsync() } catch (e: IOException) { e.printStackTrace() } onDispose { mediaPlayer.release() } } } enum class ItemState { SELECTED, UNSELECTED } fun ItemState.onItemClickState() = if (this == ItemState.SELECTED) { ItemState.UNSELECTED } else { ItemState.SELECTED } fun <T : GeneralItem> List<GeneralItem>.isSelected(t: T) = if (this.contains(t)) { ItemState.SELECTED } else { ItemState.UNSELECTED } fun selectPlate(type: EMealType = EMealType.BREAKFAST): Int = when (type) { EMealType.BRUNCH -> R.drawable.ic_blue_plate EMealType.LUNCH_DINNER -> R.drawable.ic_cast_iron else -> R.drawable.ic_plate } fun isLeapYear(year: Int): Boolean { return (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0) }
body-balance/common/components/src/main/kotlin/com/fitness/component/ComponentUtils.kt
2822766819
package com.fitness.component.screens import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.fitness.resources.R import com.fitness.theme.ui.BodyBalanceTheme import com.fitness.theme.ui.Green import enums.EMealType import extensions.Dark import extensions.Light @Light @Dark @Composable private fun SelectMealTypePreview(onSelect: (EMealType) -> Unit = {}) = BodyBalanceTheme { Surface { SelectMealType() } } @Composable fun SelectMealType(onConfirm: (EMealType) -> Unit = {}) = Box(contentAlignment = Alignment.BottomEnd, modifier = Modifier.fillMaxSize()) { var showInstructions by remember { mutableStateOf(true) } var selected by remember { mutableIntStateOf(-1) } var selectedType by remember { mutableStateOf<EMealType?>(null) } LazyColumn( contentPadding = PaddingValues(10.dp), verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier.fillMaxSize() ) { itemsIndexed(EMealType.values()) { index, item -> MealTypeItem( type = item, isSelected = selected == index, onSelect = { selected = index selectedType = item } ) } } if (selected != -1 && selectedType is EMealType) { selectedType?.title?.let { MessageDialog( title = stringResource(id = R.string.confirmation_dialog_title), description = stringResource( id = R.string.confirmation_dialog_description, stringResource(id = it) ), onContinue = { onConfirm(selectedType as EMealType) }, onCancel = { selected = -1 selectedType = null } ) } } if (showInstructions) { MessageDialog( title = stringResource(id = R.string.select_meal_type_dialog_title), description = stringResource(id = R.string.select_meal_type_description), onContinue = { showInstructions = false }, ) } } @Composable fun MealTypeItem( type: EMealType, isSelected: Boolean, modifier: Modifier = Modifier, onSelect: () -> Unit = {}, ) { Box( contentAlignment = Alignment.CenterStart, modifier = Modifier .fillMaxWidth() .height(150.dp) .clickable { onSelect() } ) { Card( elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), colors = CardDefaults.cardColors(containerColor = if (isSelected) Green else MaterialTheme.colorScheme.surface), shape = RoundedCornerShape( topStart = 100.dp, bottomStart = 100.dp, topEnd = 5.dp, bottomEnd = 5.dp ), modifier = modifier .fillMaxWidth() .height(150.dp) .padding(start = 5.dp) .background(color = MaterialTheme.colorScheme.surface) ) { AnimatedVisibility(visible = !isSelected) { BackgroundImage(type = type) } } Card( elevation = CardDefaults.cardElevation(defaultElevation = 3.dp), shape = RoundedCornerShape(topStart = 5.dp, bottomStart = 5.dp), modifier = modifier.size(150.dp), ) { Box( contentAlignment = Alignment.Center, modifier = Modifier .fillMaxWidth() .height(150.dp) .clickable { onSelect() } .background(color = MaterialTheme.colorScheme.surface) ) { Text( text = stringResource(id = type.title), fontSize = 18.sp, textAlign = TextAlign.Center, modifier = modifier.padding(10.dp) ) } } } } @Composable fun BackgroundImage(type: EMealType) { val image = when (type) { EMealType.BREAKFAST -> R.drawable.image_breakfast EMealType.BRUNCH -> R.drawable.image_brunch EMealType.SNACK -> R.drawable.image_snack EMealType.TEATIME -> R.drawable.image_teatime EMealType.LUNCH_DINNER -> R.drawable.image_lunch_dinner } Image( painter = painterResource(id = image), contentDescription = "", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillWidth, ) }
body-balance/common/components/src/main/kotlin/com/fitness/component/screens/SelectMealTypeScreen.kt
3460140779
package com.fitness.component.screens import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.AlertDialog 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.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.fitness.component.components.ContinueButton import com.fitness.resources.R import com.fitness.theme.ui.BodyBalanceTheme import com.fitness.theme.ui.Red import extensions.Dark import extensions.Light @Light @Dark @Composable private fun MessageScreenPreview() { BodyBalanceTheme { Surface { MessageScreen(message = R.string.desc_reset_password_email_confirmation) } } } @Composable fun MessageScreen(message: Int, modifier: Modifier = Modifier, onClick: () -> Unit = {}) { Column( modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(id = message), textAlign = TextAlign.Center, modifier = modifier .fillMaxWidth() .padding(50.dp) ) Spacer( modifier = Modifier .fillMaxWidth() .height(12.dp) ) ContinueButton(onClick) } } @Composable fun MessageScreen(message: String, modifier: Modifier = Modifier, onClick: () -> Unit = {}) { Column( modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = message, textAlign = TextAlign.Center, modifier = modifier .fillMaxWidth() .padding(50.dp) ) Spacer( modifier = Modifier .fillMaxWidth() .height(12.dp) ) ContinueButton(onClick) } }
body-balance/common/components/src/main/kotlin/com/fitness/component/screens/MessageScreen.kt
2283454956
package com.fitness.component.screens import android.util.Log import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.res.stringResource 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.BalanceItem import com.fitness.component.components.StandardTextSmall import com.fitness.component.components.StandardTitleText import com.fitness.component.isSelected import com.fitness.component.properties.GuidelineProperties import com.fitness.resources.R import com.fitness.theme.ui.BodyBalanceTheme import enums.EHealthLabel import extensions.Dark import extensions.GeneralItem import extensions.Light @Light @Dark @Composable private fun PreviewBalanceLazyGrid() = BodyBalanceTheme { Surface { BalanceLazyColumn( title = R.string.title_fitness_habits, description = R.string.desc_fitness_habits, items = EHealthLabel.values(), selections = mutableListOf(), onButtonClicked = { Log.e("Preview", it.toString()) } ) } } @Composable fun <T : GeneralItem> BalanceLazyColumn( title: Int, description: Int, items: Array<T>, selections: MutableList<T>, modifier: Modifier = Modifier, onButtonClicked: (List<T>) -> Unit ) = ConstraintLayout(modifier = modifier.fillMaxSize()) { val bottomGuide = createGuidelineFromBottom(GuidelineProperties.BOTTOM_100) val endGuide = createGuidelineFromEnd(GuidelineProperties.END) val (titleRef, listRef, okRef) = createRefs() val gridState = rememberLazyGridState() val isScrolling = gridState.isScrollInProgress LazyVerticalGrid( state = gridState, modifier = Modifier .constrainAs(listRef) { start.linkTo(parent.start) end.linkTo(parent.end) top.linkTo(titleRef.bottom) bottom.linkTo(parent.bottom) height = Dimension.fillToConstraints }, columns = GridCells.Fixed(3) ) { items(items) { item -> BalanceItem( item = item, selectedState = selections.isSelected(item), onClick = { if (selections.contains(it)) { selections.remove(it) } else { selections.add(it) } } ) } } AnimatedVisibility( visible = !isScrolling, modifier = Modifier.constrainAs(titleRef) { top.linkTo(parent.top) start.linkTo(parent.start) } ) { Card( shape = RectangleShape, colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), modifier = Modifier .wrapContentHeight() .fillMaxWidth() .constrainAs(titleRef) { top.linkTo(parent.top) start.linkTo(parent.start) }) { Column( modifier = Modifier .padding(20.dp) .wrapContentHeight() .fillMaxWidth() ) { StandardTitleText( text = title, modifier = Modifier.padding() ) Spacer(modifier = Modifier.size(10.dp)) StandardTextSmall( text = description, textAlign = TextAlign.Start, modifier = Modifier.padding() ) Spacer(modifier = Modifier.size(20.dp)) } } } AnimatedVisibility( visible = !isScrolling, modifier = Modifier .constrainAs(okRef) { end.linkTo(endGuide) bottom.linkTo(bottomGuide) } ) { Button( onClick = { onButtonClicked(selections) }, elevation = ButtonDefaults.buttonElevation(defaultElevation = 2.dp), modifier = Modifier .constrainAs(okRef) { end.linkTo(endGuide) bottom.linkTo(bottomGuide) } ) { Text(text = stringResource(id = R.string.title_continue)) } } }
body-balance/common/components/src/main/kotlin/com/fitness/component/screens/GeneralListScreem.kt
932615962
package com.fitness.component.screens import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.rememberDismissState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import com.fitness.component.components.SquareItem import com.fitness.resources.R import com.fitness.theme.ui.BodyBalanceTheme import com.fitness.theme.ui.Red import enums.SystemOfMeasurement import extensions.Dark import extensions.Light @Light @Dark @Composable private fun PreviewSystemOfMeasurementDialog() = BodyBalanceTheme { Surface { SystemOfMeasurementDialog() } } @Composable fun SystemOfMeasurementDialog( onClick: (SystemOfMeasurement) -> Unit = {} ) { var showDialog by remember { mutableStateOf(true) } if (showDialog) { Dialog(onDismissRequest = { showDialog = false onClick(SystemOfMeasurement.METRIC) }) { Card { Column(Modifier.padding(20.dp)) { var measurement by remember { mutableStateOf(SystemOfMeasurement.METRIC) } Text(text = stringResource(id = R.string.select_a_unit_of_measure)) Spacer(modifier = Modifier.size(25.dp)) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxWidth() ) { SquareItem( title = stringResource(id = SystemOfMeasurement.METRIC.title), isSelected = measurement == SystemOfMeasurement.METRIC, onClick = { if (measurement != SystemOfMeasurement.METRIC) { measurement = SystemOfMeasurement.METRIC } } ) SquareItem( title = stringResource(id = SystemOfMeasurement.CUSTOMARY.title), isSelected = measurement == SystemOfMeasurement.CUSTOMARY, onClick = { if (measurement != SystemOfMeasurement.CUSTOMARY) { measurement = SystemOfMeasurement.CUSTOMARY } } ) } Spacer(modifier = Modifier.size(25.dp)) Text(text = stringResource(id = measurement.description)) Spacer(modifier = Modifier.size(25.dp)) Row( horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth() ) { Button(onClick = { onClick(SystemOfMeasurement.METRIC) }) { Text(text = stringResource(id = R.string.title_dismiss)) } Spacer(modifier = Modifier.size(20.dp)) Button(onClick = { onClick(measurement) showDialog = false }) { Text(text = stringResource(id = R.string.title_continue)) } } } } } } } @Light @Dark @Composable fun ErrorDialog( title: String = stringResource(id = R.string.title_error), description: String = stringResource(id = R.string.desc_error_min_items_required), onDismiss: () -> Unit = {} ) { AlertDialog( onDismissRequest = onDismiss, title = { Text(text = title) }, text = { Text(text = description) }, confirmButton = { Button( colors = ButtonDefaults.buttonColors(containerColor = Color.Red), onClick = onDismiss ) { Text(stringResource(id = R.string.title_dismiss)) } } ) } @Light @Dark @Composable fun MessageDialog( title: String = stringResource(id = R.string.title_error), description: String = stringResource(id = R.string.desc_error_min_items_required), onContinue: () -> Unit = {}, onCancel: () -> Unit = {} ) { AlertDialog( onDismissRequest = onCancel, title = { Text(text = title) }, text = { Text(text = description) }, confirmButton = { Button(onClick = onContinue) { Text(stringResource(id = R.string.title_continue)) } }, dismissButton = { Button(onClick = onCancel) { Text(stringResource(id = R.string.title_dismiss)) } } ) } @Light @Dark @Composable fun MessageDialog( title: String = stringResource(id = R.string.title_error), description: String = stringResource(id = R.string.desc_error_min_items_required), onContinue: () -> Unit = {}, ) { AlertDialog( onDismissRequest = onContinue, title = { Text(text = title) }, text = { Text(text = description) }, confirmButton = { Button(onClick = onContinue) { Text(stringResource(id = R.string.title_dismiss)) } }, ) } @Light @Dark @Composable fun PromptUserDialog( title: String = stringResource(id = R.string.title_chefs_corner), description: String = stringResource(id = R.string.create_recipe_name_prompt), label: String = stringResource(id = R.string.recipe_name_dialog_label), onContinue: (String) -> Unit = {}, onCancel: () -> Unit = {} ) { var inputText by remember { mutableStateOf("") } var showError by remember { mutableStateOf(false) } AlertDialog( onDismissRequest = onCancel, title = { Text(text = title) }, text = { Column { Text(text = description, modifier = Modifier.padding(bottom = 10.dp)) OutlinedTextField( value = inputText, onValueChange = { inputText = it showError = false }, label = { Text(label) }, isError = showError, modifier = Modifier.fillMaxWidth() ) if (showError) { Text( text = stringResource(id = R.string.please_enter_a_name), color = Red, modifier = Modifier.padding(top = 4.dp) ) } } }, confirmButton = { Button(onClick = { if (inputText.isBlank()) { showError = true } else { onContinue(inputText) } }) { Text(stringResource(id = R.string.title_continue)) } }, dismissButton = { Button(onClick = onCancel) { Text(stringResource(id = R.string.title_dismiss)) } } ) }
body-balance/common/components/src/main/kotlin/com/fitness/component/screens/Dialogs.kt
4136385506
package com.fitness.component.screens import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color.Companion.Red import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.fitness.component.components.ContinueButton import com.fitness.resources.R import com.fitness.theme.ui.BodyBalanceTheme import extensions.Dark import extensions.Light @Light @Dark @Composable private fun ErrorScreenPreview() { BodyBalanceTheme { Surface { ErrorScreen(R.string.calories, R.string.calories_compact) } } } @Composable fun ErrorScreen( title: Int, description: Int, onClick: () -> Unit = {} ) { Column( modifier = Modifier .padding(50.dp) .fillMaxSize() .wrapContentHeight(Alignment.CenterVertically) ) { Icon( painter = painterResource(id = R.drawable.icon_empty_hourglass), contentDescription = null, tint = Red, modifier = Modifier .fillMaxWidth() .wrapContentSize(Alignment.Center) ) Spacer(modifier = Modifier .fillMaxWidth() .height(12.dp)) Text( text = stringResource(id = title), style = MaterialTheme.typography.displaySmall, modifier = Modifier .fillMaxWidth() .wrapContentHeight(), textAlign = TextAlign.Center ) Spacer(modifier = Modifier .fillMaxWidth() .height(12.dp)) Text( text = stringResource(id = description), modifier = Modifier .fillMaxWidth() .wrapContentHeight(), textAlign = TextAlign.Center ) Spacer(modifier = Modifier .fillMaxWidth() .height(12.dp)) ContinueButton(onClick) } }
body-balance/common/components/src/main/kotlin/com/fitness/component/screens/ErrorScreen.kt
2874892038
package com.fitness.component.screens import android.util.Log import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TimePicker import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.fitness.resources.R import com.fitness.theme.ui.BodyBalanceTheme import extensions.Dark import extensions.Light import java.util.Calendar @Light @Dark @Composable private fun PreviewBalanceTimePicker() = BodyBalanceTheme { Surface { BalanceTimePicker(onTimePicked = { hour, minute -> Log.e( "PreviewSimpleCalendar", "hour: $hour -- minute:${minute}" ) }) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun BalanceTimePicker( modifier: Modifier = Modifier, title: String = stringResource(id = R.string.title_pick_time), message: String = stringResource(id = R.string.description_pick_time), onTimePicked: (hour: Int, minute: Int) -> Unit ) { Column(modifier = Modifier.fillMaxSize()) { Text( text = title, fontSize = 18.sp, modifier = Modifier.padding(20.dp) ) Text( text = message, modifier = Modifier.padding(top = 20.dp, start = 20.dp, end = 20.dp, bottom = 40.dp) ) Box(contentAlignment = Alignment.BottomEnd) { val calendar = Calendar.getInstance() val hour = calendar.get(Calendar.HOUR_OF_DAY) val minute = calendar.get(Calendar.MINUTE) val timePickerState = rememberTimePickerState( initialHour = hour, initialMinute = minute, ) TimePicker( state = timePickerState, modifier = modifier .padding(16.dp) .fillMaxSize() ) Button( onClick = { onTimePicked(timePickerState.hour, timePickerState.minute) }, modifier = Modifier.padding(end = 20.dp, bottom = 60.dp) ) { Text(text = stringResource(id = R.string.title_continue)) } } } }
body-balance/common/components/src/main/kotlin/com/fitness/component/screens/TimerPickerScreen.kt
577703127
package com.fitness.component.screens import android.util.Log import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.DatePicker import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.rememberDatePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.fitness.resources.R import com.fitness.theme.ui.BodyBalanceTheme import extensions.Dark import extensions.Light @Light @Dark @Composable private fun PreviewSimpleCalendar() = BodyBalanceTheme { Surface { BalanceDatePicker(onDatesPicked = { Log.e("PreviewSimpleCalendar", it.toString()) }) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun BalanceDatePicker(modifier: Modifier = Modifier, onDatesPicked: (Long) -> Unit = {}) { Box(contentAlignment = Alignment.BottomEnd) { var showErrorDialog by remember { mutableStateOf(false) } val datePickerState = rememberDatePickerState(initialSelectedDateMillis = System.currentTimeMillis()) DatePicker( state = datePickerState, modifier = modifier .padding(16.dp) .fillMaxSize() ) Button(onClick = { datePickerState.selectedDateMillis?.let(onDatesPicked) ?: kotlin.run { showErrorDialog = true } }, modifier = Modifier.padding(end = 20.dp, bottom = 60.dp)) { Text(text = stringResource(id = R.string.title_continue)) } if (showErrorDialog) { ErrorDialog( title = stringResource(id = R.string.title_date_selection), description = stringResource(id = R.string.error_no_date), onDismiss = {showErrorDialog = false} ) } } }
body-balance/common/components/src/main/kotlin/com/fitness/component/screens/CalendarScreen.kt
605641526
package com.fitness.component.screens import androidx.compose.animation.core.CubicBezierEasing import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.VectorConverter import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.animateValue import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.keyframes import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.progressSemantics import androidx.compose.material3.ProgressIndicatorDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlin.math.PI import kotlin.math.abs import kotlin.math.max @Preview @Composable fun LoadingScreen() = Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize() ) { val color: Color = ProgressIndicatorDefaults.circularColor val strokeWidth = ProgressIndicatorDefaults.CircularStrokeWidth val rotationsPerCycle = 5 val rotationDuration = 1332 val baseRotationAngle = 286f val jumpRotationAngle = 290f val startAngleOffset = -90f val headAndTailAnimationDuration = (rotationDuration * 0.5).toInt() val circularEasing = CubicBezierEasing(0.4f, 0f, 0.2f, 1f) val circularIndicatorDiameter = 48.dp - 4.0.dp * 2 val rotationAngleOffset = (baseRotationAngle + jumpRotationAngle) % 360f val stroke = with(LocalDensity.current) { Stroke(width = strokeWidth.toPx(), cap = StrokeCap.Square) } val transition = rememberInfiniteTransition(label = "") // The current rotation around the circle, so we know where to start the rotation from val currentRotation = transition.animateValue( 0, rotationsPerCycle, Int.VectorConverter, infiniteRepeatable( animation = tween( durationMillis = rotationDuration * rotationsPerCycle, easing = LinearEasing ) ), label = "" ) // How far forward (degrees) the base point should be from the start point val baseRotation = transition.animateFloat( 0f, baseRotationAngle, infiniteRepeatable( animation = tween( durationMillis = rotationDuration, easing = LinearEasing ) ), label = "" ) // How far forward (degrees) both the head and tail should be from the base point val endAngle = transition.animateFloat( 0f, jumpRotationAngle, infiniteRepeatable( animation = keyframes { durationMillis = headAndTailAnimationDuration + headAndTailAnimationDuration 0f at 0 with circularEasing jumpRotationAngle at headAndTailAnimationDuration } ), label = "" ) val startAngle = transition.animateFloat( 0f, jumpRotationAngle, infiniteRepeatable( animation = keyframes { durationMillis = headAndTailAnimationDuration + headAndTailAnimationDuration 0f at headAndTailAnimationDuration with circularEasing jumpRotationAngle at durationMillis } ), label = "" ) Canvas(Modifier.progressSemantics().size(circularIndicatorDiameter)) { val currentRotationAngleOffset = (currentRotation.value * rotationAngleOffset) % 360f // How long a line to draw using the start angle as a reference point val sweep = abs(endAngle.value - startAngle.value) // Offset by the constant offset and the per rotation offset val offset = startAngleOffset + currentRotationAngleOffset + baseRotation.value drawIndeterminateCircularIndicator( startAngle.value + offset, strokeWidth, sweep, color, stroke ) } } private fun DrawScope.drawIndeterminateCircularIndicator( startAngle: Float, strokeWidth: Dp, sweep: Float, color: Color, stroke: Stroke ) { val circularIndicatorDiameter = 48.0.dp - 4.0.dp * 2 val squareStrokeCapOffset = (180.0 / PI).toFloat() * (strokeWidth / (circularIndicatorDiameter / 2)) / 2f val adjustedStartAngle = startAngle + squareStrokeCapOffset val adjustedSweep = max(sweep, 0.1f) drawCircularIndicator(adjustedStartAngle, adjustedSweep, color, stroke) } private fun DrawScope.drawCircularIndicator( startAngle: Float, sweep: Float, color: Color, stroke: Stroke ) { // To draw this circle we need a rect with edges that line up with the midpoint of the stroke. // To do this we need to remove half the stroke width from the total diameter for both sides. val diameterOffset = stroke.width / 2 val arcDimen = size.width - 2 * diameterOffset drawArc( color = color, startAngle = startAngle, sweepAngle = sweep, useCenter = false, topLeft = Offset(diameterOffset, diameterOffset), size = Size(arcDimen, arcDimen), style = stroke ) }
body-balance/common/components/src/main/kotlin/com/fitness/component/screens/LoadingScreen.kt
1258155507
package com.fitness.component.components import androidx.compose.material3.Surface 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.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.TextUnit import com.fitness.resources.R import com.fitness.component.properties.HEADLINE_TEXT_SIZE import com.fitness.component.properties.STANDARD_TEXT_SIZE import com.fitness.component.properties.STANDARD_TEXT_SIZE_SMALL import com.fitness.component.properties.TITLE_TEXT_SIZE import extensions.Light @Light @Composable private fun StandardTitleTextPreview() = Surface { StandardTitleText() } @Light @Composable private fun StandardHeadlineTextPreview() = Surface { StandardHeadlineText() } @Light @Composable private fun StandardTextPreview() = Surface { StandardText() } @Light @Composable private fun StandardTextSmallPreview() = Surface { StandardTextSmall() } @Composable fun StandardTitleText( modifier: Modifier = Modifier, textAlign: TextAlign = TextAlign.Center, fontSize: TextUnit = TITLE_TEXT_SIZE, text: Int = R.string.create_account_message ){ Text( text = stringResource(text), textAlign = textAlign, fontSize = fontSize, fontWeight = FontWeight.SemiBold, modifier = modifier ) } @Composable fun StandardHeadlineText( modifier: Modifier = Modifier, textAlign: TextAlign = TextAlign.Center, text: Int = R.string.create_account_message ){ Text( text = stringResource(text), textAlign = textAlign, fontSize = HEADLINE_TEXT_SIZE, fontWeight = FontWeight.Normal, modifier = modifier ) } @Composable fun StandardText( modifier: Modifier = Modifier, textAlign: TextAlign = TextAlign.Center, fontWeight: FontWeight = FontWeight.Normal, text: Int = R.string.create_account_message ){ Text( text = stringResource(text), textAlign = textAlign, fontSize = STANDARD_TEXT_SIZE, fontWeight = fontWeight, modifier = modifier ) } @Composable fun StandardTextSmall( modifier: Modifier = Modifier, textAlign: TextAlign = TextAlign.Center, fontWeight: FontWeight = FontWeight.Normal, color: Color = Color.Unspecified, text: Int = R.string.create_account_message ){ Text( text = stringResource(text), textAlign = textAlign, color = color, fontSize = STANDARD_TEXT_SIZE_SMALL, fontWeight = fontWeight, modifier = modifier ) }
body-balance/common/components/src/main/kotlin/com/fitness/component/components/Text.kt
2901891066
package com.fitness.component.components import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.fitness.resources.R import com.fitness.theme.ui.BodyBalanceTheme import com.fitness.theme.ui.Green import extensions.Dark import extensions.Light import kotlinx.coroutines.delay @Dark @Light @Composable private fun StandardIconButtonPreview() { BodyBalanceTheme { Surface { StandardIconButton( R.drawable.icon_google_logo, R.string.content_description_google ) } } } @Dark @Light @Composable private fun StandardOutlinedButtonPreview() { BodyBalanceTheme { Surface { StandardOutlinedIconButton( icon = R.drawable.icon_google_logo, desc = R.string.content_description_google, text = R.string.content_description_google ) } } } @Dark @Light @Composable private fun StandardButtonPreview() { BodyBalanceTheme { Surface { StandardButton( text = R.string.content_description_google, enabled = true, ) } } } @Composable fun StandardIconButton( icon: Int, desc: Int, modifier: Modifier = Modifier, onClick: () -> Unit = {} ) { IconButton(modifier = modifier, onClick = onClick) { Icon( painter = painterResource(id = icon), contentDescription = stringResource(id = desc), tint = Color.Unspecified ) } } @Composable fun StandardOutlinedIconButton( icon: Int, desc: Int, text: Int, modifier: Modifier = Modifier, iconSize: Int = 24, onClick: () -> Unit = {} ) { OutlinedButton( modifier = modifier, onClick = onClick, ) { Row(modifier = Modifier.padding(2.dp)) { Icon( painterResource(id = icon), contentDescription = stringResource(id = desc), modifier = Modifier.size(iconSize.dp), tint = Color.Unspecified ) Spacer(Modifier.width(8.dp)) Text(stringResource(id = text)) } } } @Composable fun StandardButton( text: Int, modifier: Modifier = Modifier, enabled: Boolean = true, onClick: () -> Unit = {} ) { Button( modifier = modifier, enabled = enabled, onClick = onClick, ) { Row { Text(stringResource(id = text)) } } } @Composable fun ContinueButton(onClick: () -> Unit = {}){ Button( modifier = Modifier .fillMaxWidth() .wrapContentSize(Alignment.Center), onClick = { onClick() } ) { Text(text = stringResource(id = R.string.title_continue)) } } @Composable fun AddToPlannerButton(modifier: Modifier = Modifier) { Card( elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), shape = RoundedCornerShape(5f), modifier = modifier ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(5.dp) ) { Icon( painter = painterResource(id = R.drawable.icon_add_more), contentDescription = stringResource(id = R.string.content_description_icon_add), modifier = Modifier .padding(3.dp) .size(16.dp) ) Text(text = stringResource(id = R.string.title_planner)) } } } @Composable fun TransitionButton(modifier: Modifier = Modifier) { val color by animateColorAsState( targetValue = Green, animationSpec = tween(durationMillis = 250), label = "textColor" ) Card( elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), colors = CardDefaults.cardColors(containerColor = color), shape = RoundedCornerShape(40f), modifier = modifier.size(50.dp) ) {} } @Composable fun CheckmarkConfirmButton(modifier: Modifier = Modifier) { var startAnimations by remember { mutableStateOf(false) } var offsetX by remember { mutableIntStateOf(-50) } var offsetY by remember { mutableIntStateOf(50) } val animatedOffsetX by animateDpAsState( targetValue = offsetX.dp, label = "animatedOffsetX", animationSpec = spring( dampingRatio = Spring.DampingRatioHighBouncy, stiffness = Spring.StiffnessMedium ) ) val animatedOffsetY by animateDpAsState( targetValue = offsetY.dp, label = "animatedOffsetY", animationSpec = spring( dampingRatio = Spring.DampingRatioHighBouncy, stiffness = Spring.StiffnessMedium ) ) LaunchedEffect(key1 = Unit) { delay(100) startAnimations = true offsetX = 0 offsetY = 0 } Card( elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), colors = CardDefaults.cardColors(containerColor = Green), shape = CircleShape, modifier = modifier ) { Box(contentAlignment = Alignment.Center) { Icon( painter = painterResource(id = R.drawable.icon_checkmark), contentDescription = stringResource(id = R.string.content_description_checkmark), modifier = Modifier .padding(10.dp) .offset(x = animatedOffsetX, y = animatedOffsetY) ) } } }
body-balance/common/components/src/main/kotlin/com/fitness/component/components/Buttons.kt
1903935281
package com.fitness.component.components import android.content.res.Configuration import androidx.compose.foundation.Image import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview 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 BodyBalanceImageLogoPreview() { BodyBalanceTheme { Surface { BodyBalanceImageLogo(modifier = Modifier) } } } @Composable fun BodyBalanceImageLogo(contentScale: ContentScale = ContentScale.Fit, modifier: Modifier){ Image( modifier = modifier, contentScale = contentScale, painter = painterResource(id = R.drawable.cloud_no_shadow), contentDescription = stringResource(id = R.string.content_description_training), ) }
body-balance/common/components/src/main/kotlin/com/fitness/component/components/Brand.kt
3997164055
package com.fitness.component.components import android.util.Log.e import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.FastOutLinearInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.unit.dp import com.fitness.theme.ui.BodyBalanceTheme import com.fitness.theme.ui.Green import extensions.Dark import extensions.Light import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.material3.Text import androidx.compose.runtime.mutableDoubleStateOf import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color.Companion.Black import androidx.compose.ui.graphics.Color.Companion.White import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.sp import com.fitness.component.calculateWeightProgressAsFraction import com.fitness.component.formatWeightProgress import com.fitness.component.isOnTrack import com.fitness.resources.R import com.fitness.theme.ui.Red @Light @Dark @Composable private fun CircleProgressPreview() { BodyBalanceTheme { Surface { CircleProgressWithTextComponent() } } } @Light @Dark @Composable private fun WeightProgressPreview() { BodyBalanceTheme { Surface { WeightProgressComponent() } } } @Light @Dark @Composable private fun LineProgressPreview() { BodyBalanceTheme { Surface { LineProgressComponent() } } } @Composable fun CircleProgressComponent( modifier: Modifier = Modifier, isTimer: Boolean = false, progress: Double = .25, progressColor: Color = Green, canvasSize: Int = 50, isDarkTheme: Boolean = isSystemInDarkTheme() ) { Column( modifier = modifier .wrapContentSize() .padding(2.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { val sweepAngleFormula = if (isTimer) (360 - (360f * progress)) else (360 * progress) val animateFloat by remember { mutableStateOf(Animatable((360 * progress).toFloat())) } LaunchedEffect(animateFloat) { animateFloat.animateTo( targetValue = sweepAngleFormula.toFloat(), animationSpec = tween(durationMillis = 1000, easing = FastOutLinearInEasing) ) } Canvas(modifier = Modifier.size(canvasSize.dp)) { drawArc( color = if (isDarkTheme) White else Black, startAngle = 0f, sweepAngle = 360f, useCenter = false, style = Stroke(width = 2f, cap = StrokeCap.Round) ) drawArc( color = progressColor, startAngle = -90f, sweepAngle = animateFloat.value, useCenter = false, style = Stroke(width = 10f, cap = StrokeCap.Round) ) } } } @Composable fun CircleProgressWithTextComponent( modifier: Modifier = Modifier, title: String = "Carb", currentValue: Double = 90.0, targetValue: Double = 100.0 ) { val progress by remember { mutableDoubleStateOf(currentValue.div(targetValue)) } e("Progress", progress.toString()) Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier.wrapContentSize()) { Box(contentAlignment = Alignment.Center, modifier = Modifier.size(150.dp)) { CircleProgressComponent( isTimer = false, progress = progress, progressColor = if(progress <= 1.0) Green else Red, canvasSize = 200, modifier = Modifier.size(150.dp) ) Text( text = title, fontSize = 10.sp, textAlign = TextAlign.Center, modifier = Modifier .width(150.dp) .padding(5.dp) ) } } } @Composable fun WeightProgressComponent( modifier: Modifier = Modifier, startedWeight: Double = 298.0, currentWeight: Double = 288.0, targetWeight: Double = 290.0 ) { val weightProgress = calculateWeightProgressAsFraction(startedWeight, currentWeight, targetWeight) Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier.wrapContentSize()) { Box(contentAlignment = Alignment.Center, modifier = Modifier.size(150.dp)) { CircleProgressComponent( isTimer = false, progress = weightProgress, progressColor = if (isOnTrack( startedWeight, currentWeight, targetWeight ) ) Green else Color.Red, canvasSize = 200, modifier = Modifier.size(150.dp) ) Text( text = "${ formatWeightProgress( startedWeight, currentWeight, targetWeight ) } target weight", fontSize = 18.sp, textAlign = TextAlign.Center, modifier = Modifier .padding(2.dp) .width(150.dp) ) } Spacer(modifier = modifier.size(15.dp)) Text( text = stringResource(id = R.string.target_weight_desc, targetWeight), fontSize = 14.sp, textAlign = TextAlign.Center ) } } @Composable fun LineProgressComponent( modifier: Modifier = Modifier, progress: Double = .45, progressBarColor: Color = Green, isDarkTheme: Boolean = isSystemInDarkTheme() ) { Column( verticalArrangement = Arrangement.Center, modifier = modifier .fillMaxWidth() .height(5.dp) ) { val animateFloat by remember { mutableStateOf(Animatable(0f)) } LaunchedEffect(animateFloat) { animateFloat.animateTo( targetValue = progress.toFloat(), animationSpec = tween(durationMillis = 1000, easing = FastOutLinearInEasing) ) } Canvas(modifier = Modifier.fillMaxWidth()) { drawLine( start = Offset(x = 0f, y = 1f), end = Offset(x = size.width, y = 1f), color = if (isDarkTheme) White else Black, strokeWidth = 4f, alpha = .5f, cap = StrokeCap.Round, ) drawLine( start = Offset(x = 0f, y = 0f), end = Offset(x = (size.width * animateFloat.value), y = 0f), color = progressBarColor, strokeWidth = 8f, cap = StrokeCap.Round ) } } }
body-balance/common/components/src/main/kotlin/com/fitness/component/components/Progress.kt
4135227075
package com.fitness.component.components import androidx.compose.foundation.border import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults 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.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.fitness.component.properties.textFieldShape import com.fitness.resources.R @Preview @Composable fun StandardTextFieldPreview() { StandardTextField( "", R.string.enter_email, R.string.label_email ) } @Composable fun StandardTextField( value: String, hint: Int, label: Int, modifier: Modifier = Modifier, isError: Boolean = false, supportingText: @Composable (() -> Unit)? = null, trailingIcon: @Composable (() -> Unit)? = null, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, visualTransformation: VisualTransformation = VisualTransformation.None, onValueChanged: (String) -> Unit = {}, ) { TextField( value = value, trailingIcon = trailingIcon, shape = textFieldShape(), onValueChange = onValueChanged, singleLine = true, isError = isError, supportingText = supportingText, visualTransformation = visualTransformation, placeholder = { Text(text = stringResource(id = hint)) }, label = { Text(text = stringResource(id = label)) }, modifier = modifier.border(1.dp, Color.Black, textFieldShape()), keyboardOptions = keyboardOptions, keyboardActions = keyboardActions, colors = TextFieldDefaults.colors( focusedContainerColor = Color.Transparent, unfocusedContainerColor = Color.Transparent, disabledContainerColor = Color.Transparent, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, ) ) }
body-balance/common/components/src/main/kotlin/com/fitness/component/components/TextField.kt
3029760113
package com.fitness.component.components import android.util.Log import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateIntAsState import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Info import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.Dimension import com.fitness.component.ItemState import com.fitness.component.PlayWavSound import com.fitness.component.WindIcon import com.fitness.component.onItemClickState import com.fitness.component.properties.STANDARD_TEXT_SIZE import com.fitness.component.properties.STANDARD_TEXT_SIZE_SMALL import com.fitness.component.selectPlate import com.fitness.resources.R import com.fitness.theme.ui.BodyBalanceTheme import com.fitness.theme.ui.DeepOrange import com.fitness.theme.ui.Green import com.fitness.theme.ui.Saffron import com.fitness.theme.ui.primaryVariantHub import com.skydoves.landscapist.coil.CoilImage import extensions.Dark import extensions.GeneralItem import extensions.Light import kotlinx.coroutines.delay @Light @Dark @Composable fun SquareItem( title: String = "Kreplach", isSelected: Boolean = false, onClick: () -> Unit = {}, ) = Card( colors = CardDefaults.cardColors(containerColor = if(isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant), elevation = CardDefaults.cardElevation(defaultElevation = 1.dp), modifier = Modifier .size(75.dp) .clickable { onClick() } ) { Column(verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize()) { Text( text = title, fontSize = 8.sp, textAlign = TextAlign.Center, overflow = TextOverflow.Ellipsis, maxLines = 1, modifier = Modifier .fillMaxWidth() .padding(5.dp) ) } } @Composable fun <T : GeneralItem> BalanceItem( item: T, onClick: (T) -> Unit, modifier: Modifier = Modifier, size: Dp = 120.dp, selectedState: ItemState = ItemState.UNSELECTED ) { val animatable = remember { Animatable(0f) } var itemState by remember { mutableStateOf(selectedState) } LaunchedEffect(key1 = itemState) { when (itemState) { ItemState.SELECTED -> { animatable.animateTo( targetValue = 360f, animationSpec = tween(durationMillis = 500, easing = LinearEasing) ) } else -> { animatable.animateTo( targetValue = 0f, animationSpec = tween(durationMillis = 500, easing = LinearEasing) ) } } } Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier .clickable { itemState = itemState.onItemClickState() onClick(item) } .wrapContentSize() .graphicsLayer { rotationY = animatable.value } ) { if (animatable.value < 70f) { TextItemUnSelected( title = item.title, desc = item.desc, size = size ) } else if (animatable.value > 270f) { TextItemSelected(title = item.title, size = size) } } if (animatable.value > 40f && animatable.value < 270f) { TextItemTransition(size = size) } } @Composable private fun TextItemUnSelected( title: Int, modifier: Modifier = Modifier, desc: Int? = null, size: Dp = 120.dp, ) { var showInfo by remember { mutableStateOf(false) } var targetValue by remember { mutableIntStateOf(5) } val animateInt = animateIntAsState( targetValue = targetValue, label = "TextItemUnSelected", finishedListener = { targetValue = if (targetValue == 5) { 40 } else { 5 } } ) Card( modifier = modifier .wrapContentSize() .padding(5.dp), shape = RoundedCornerShape(animateInt.value, 40, 5, 40), ) { ConstraintLayout( modifier = Modifier .size(size) .padding(10.dp) ) { val (text, icon) = createRefs() desc?.let { TransitionalTextItem( title = stringResource(id = title), desc = stringResource(id = desc), showInfo = showInfo, modifier = Modifier.constrainAs(text) { start.linkTo(parent.start) top.linkTo(parent.top) bottom.linkTo(icon.top) } ) TransitionalIcon( iconDefault = Icons.Default.Info, iconTransition = Icons.Default.ArrowBack, onTapInfo = { showInfo = it }, showInfo = showInfo, modifier = Modifier.constrainAs(icon) { end.linkTo(parent.end) bottom.linkTo(parent.bottom) } ) } ?: run { Text( text = stringResource(id = title), modifier = Modifier .constrainAs(text) { start.linkTo(parent.start) top.linkTo(parent.top) bottom.linkTo(icon.top) } ) Icon( imageVector = Icons.Default.Add, contentDescription = stringResource(id = R.string.content_description_checkmark), modifier = Modifier .padding(5.dp) .constrainAs(icon) { end.linkTo(parent.end) bottom.linkTo(parent.bottom) } ) } } } } @Composable private fun TransitionalTextItem( title: String, desc: String, showInfo: Boolean, modifier: Modifier ) { Box(modifier = modifier) { AnimatedVisibility(visible = !showInfo) { Text(text = title, modifier = Modifier) } AnimatedVisibility(visible = showInfo) { Text( text = desc, overflow = TextOverflow.Ellipsis, maxLines = 3, fontSize = STANDARD_TEXT_SIZE, modifier = modifier ) } } } @Composable private fun TransitionalIcon( iconDefault: ImageVector, iconTransition: ImageVector, showInfo: Boolean, modifier: Modifier, onTapInfo: (Boolean) -> Unit ) { var showInfoState by remember { mutableStateOf(showInfo) } Box(modifier = modifier) { AnimatedVisibility(visible = !showInfoState) { Icon( imageVector = iconDefault, contentDescription = stringResource(id = R.string.content_description_checkmark), modifier = Modifier .padding(5.dp) .clickable { showInfoState = !showInfoState onTapInfo(showInfoState) } ) } AnimatedVisibility(visible = showInfoState) { Icon( imageVector = iconTransition, contentDescription = stringResource(id = R.string.content_description_checkmark), modifier = Modifier .padding(5.dp) .clickable { showInfoState = !showInfoState onTapInfo(showInfoState) } ) } } } @Composable fun TextItemTransition(size: Dp = 120.dp) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.size(size) ) { WindIcon() PlayWavSound() } } @Composable fun TextItemSelected(title: Int, modifier: Modifier = Modifier, size: Dp = 120.dp) { var startAnimations by remember { mutableStateOf(false) } var offsetX by remember { mutableIntStateOf(-50) } var offsetY by remember { mutableIntStateOf(50) } val animatedOffsetX by animateDpAsState( targetValue = offsetX.dp, label = "animatedOffsetX", animationSpec = spring( dampingRatio = Spring.DampingRatioHighBouncy, stiffness = Spring.StiffnessMedium ) ) val animatedOffsetY by animateDpAsState( targetValue = offsetY.dp, label = "animatedOffsetY", animationSpec = spring( dampingRatio = Spring.DampingRatioHighBouncy, stiffness = Spring.StiffnessMedium ) ) val color by animateColorAsState( targetValue = if (startAnimations) Green else MaterialTheme.colorScheme.surfaceVariant, animationSpec = tween(durationMillis = 500), label = "textColor" ) LaunchedEffect(key1 = Unit) { delay(100) startAnimations = true offsetX = 0 offsetY = 0 } Card( modifier = modifier .wrapContentSize() .padding(5.dp), shape = RoundedCornerShape(40, 5, 40, 5), ) { ConstraintLayout( modifier = Modifier .background(color = color) .size(size) .padding(10.dp) ) { val (textRef, checkMark) = createRefs() Text(text = stringResource(id = title), modifier = Modifier.constrainAs(textRef) { start.linkTo(parent.start) end.linkTo(parent.end) top.linkTo(parent.top) bottom.linkTo(checkMark.top) } ) Icon( imageVector = Icons.Default.Check, contentDescription = stringResource(id = R.string.content_description_checkmark), modifier = Modifier .offset(x = animatedOffsetX, y = animatedOffsetY) .constrainAs(checkMark) { start.linkTo(parent.start) bottom.linkTo(parent.bottom) } ) } } } @Light @Dark @Composable fun NutritionItemWithImage( title: String = "Kreplach", imageModel: String = "", itemState: ItemState = ItemState.UNSELECTED, time: Double? = 0.0, energy: Double? = 0.0, fat: Double? = 0.0, net: Double? = 0.0, onClickItem: () -> Unit = {}, onClickAdd: () -> Unit = {}, onClickShare: () -> Unit = {} ) = BodyBalanceTheme { Surface { ConstraintLayout( modifier = Modifier .fillMaxWidth() .height(200.dp) ) { val (titleRef, imageRef, contentRef, shareRef, addRef) = createRefs() val guideTop = createGuidelineFromTop(.20f) val guideEnd = createGuidelineFromEnd(.05f) val guideStart = createGuidelineFromStart(.05f) val guideBottom = createGuidelineFromBottom(.20f) val guideAddButtonTop = createGuidelineFromBottom(.40f) Text(text = title, overflow = TextOverflow.Ellipsis, maxLines = 1, modifier = Modifier.constrainAs(titleRef) { start.linkTo(imageRef.end, 5.dp) top.linkTo(parent.top, 5.dp) end.linkTo(contentRef.end, 5.dp) bottom.linkTo(contentRef.top, 5.dp) width = Dimension.fillToConstraints } ) ItemContent( energy = energy, fat = fat, net = net, modifier = Modifier.constrainAs(contentRef) { start.linkTo(guideStart) end.linkTo(guideEnd) top.linkTo(guideTop) bottom.linkTo(guideBottom) width = Dimension.fillToConstraints height = Dimension.fillToConstraints } ) ItemImage( imageModel = imageModel, modifier = Modifier.constrainAs(imageRef) { top.linkTo(parent.top, 5.dp) start.linkTo(parent.start, 5.dp) } ) Card( elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), shape = CircleShape, modifier = Modifier .clickable { Log.e("NutritionItemWithImage", "share") } .constrainAs(shareRef) { start.linkTo(contentRef.start, 15.dp) top.linkTo(guideAddButtonTop, 5.dp) bottom.linkTo(parent.bottom, 5.dp) } ) { Icon( painter = painterResource(id = R.drawable.icon_share), contentDescription = stringResource(id = R.string.content_description_share), tint = primaryVariantHub, modifier = Modifier.padding(5.dp) ) } val animatable = remember { Animatable(0f) } LaunchedEffect(key1 = itemState) { when (itemState) { ItemState.SELECTED -> { animatable.animateTo( targetValue = 720f, animationSpec = tween(durationMillis = 500, easing = LinearEasing) ) } else -> { animatable.animateTo( targetValue = 0f, animationSpec = tween(durationMillis = 500, easing = LinearEasing) ) } } } if (animatable.value < 270f) { AddToPlannerButton(modifier = Modifier .clickable { onClickAdd() } .graphicsLayer { rotationZ = animatable.value } .constrainAs(addRef) { end.linkTo(contentRef.end, 10.dp) top.linkTo(guideAddButtonTop, 5.dp) bottom.linkTo(parent.bottom, 5.dp) } ) } else if (animatable.value > 270f && animatable.value < 540f) { TransitionButton(modifier = Modifier .graphicsLayer { rotationZ = animatable.value } .constrainAs(addRef) { end.linkTo(contentRef.end, 10.dp) top.linkTo(guideAddButtonTop, 5.dp) bottom.linkTo(parent.bottom, 5.dp) } ) } else if (animatable.value > 540f) { CheckmarkConfirmButton(modifier = Modifier .clickable { onClickAdd() } .graphicsLayer { rotationZ = animatable.value } .constrainAs(addRef) { end.linkTo(contentRef.end, 10.dp) top.linkTo(guideAddButtonTop, 5.dp) bottom.linkTo(parent.bottom, 5.dp) } ) } } } } @Composable private fun ItemContent( modifier: Modifier = Modifier, energy: Double? = 0.0, fat: Double? = 0.0, net: Double? = 0.0 ) { Card(modifier = modifier, shape = RoundedCornerShape(5), colors = CardDefaults.cardColors()) { ConstraintLayout( modifier = Modifier .fillMaxSize() .padding(5.dp) ) { val ( title, energyIcon, energyValue, fatIcon, fatValue, carbsIcon, carbsValue, ) = createRefs() val midGuide = createGuidelineFromTop(.45f) val startGuide = createGuidelineFromStart(.40f) Text( text = stringResource(id = R.string.title_nutritional_summary), fontSize = STANDARD_TEXT_SIZE_SMALL, fontWeight = FontWeight.Thin, modifier = Modifier.constrainAs(title) { start.linkTo(startGuide) bottom.linkTo(midGuide, 8.dp) } ) energy?.let { Icon( painter = painterResource(id = R.drawable.icon_calories), contentDescription = stringResource(id = R.string.content_description_icon_energy), tint = DeepOrange, modifier = Modifier.constrainAs(energyIcon) { start.linkTo(startGuide) top.linkTo(midGuide) } ) Text( text = "${energy.toInt()}", fontSize = STANDARD_TEXT_SIZE_SMALL, fontWeight = FontWeight.Thin, modifier = Modifier.constrainAs(energyValue) { start.linkTo(energyIcon.end, 5.dp) top.linkTo(energyIcon.top) bottom.linkTo(energyIcon.bottom) } ) } fat?.let { Icon( painter = painterResource(id = R.drawable.icon_fat), contentDescription = stringResource(id = R.string.content_description_icon_fat), tint = primaryVariantHub, modifier = Modifier.constrainAs(fatIcon) { top.linkTo(midGuide) start.linkTo(energyValue.end, 30.dp) } ) Text( text = "${fat.toInt()}", fontSize = STANDARD_TEXT_SIZE_SMALL, fontWeight = FontWeight.Thin, modifier = Modifier.constrainAs(fatValue) { start.linkTo(fatIcon.end, 5.dp) top.linkTo(fatIcon.top) bottom.linkTo(fatIcon.bottom) } ) } net?.let { Icon( painter = painterResource(id = R.drawable.icon_carbs), contentDescription = stringResource(id = R.string.content_description_icon_net_carbs), tint = Saffron, modifier = Modifier.constrainAs(carbsIcon) { top.linkTo(midGuide) start.linkTo(fatValue.end, 30.dp) } ) Text( text = "${net.toInt()}", fontSize = STANDARD_TEXT_SIZE_SMALL, fontWeight = FontWeight.Thin, modifier = Modifier.constrainAs(carbsValue) { top.linkTo(carbsIcon.top) start.linkTo(carbsIcon.end, 5.dp) bottom.linkTo(carbsIcon.bottom) } ) } } } } @Composable fun ItemImage(modifier: Modifier = Modifier, imageModel: String = "") { val plate by remember { mutableIntStateOf(selectPlate()) } Card( colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), shape = CircleShape, modifier = modifier.size(135.dp) ) { Box(contentAlignment = Alignment.Center) { Image( painter = painterResource(id = plate), contentDescription = stringResource(id = R.string.content_description_icon_plate), contentScale = ContentScale.Crop, modifier = Modifier .fillMaxSize() .background( MaterialTheme.colorScheme.surface, CircleShape ) ) var isVisible by remember { mutableStateOf(false) } Card( shape = CircleShape, modifier = if (isVisible) Modifier.size(90.dp) else Modifier ) { CoilImage( imageModel = { imageModel }, success = { _, painter -> isVisible = true Image( painter = painter, contentDescription = "Loaded image", modifier = Modifier.fillMaxSize() // Adjust modifier as needed ) }, failure = { isVisible = false } ) } } } }
body-balance/common/components/src/main/kotlin/com/fitness/component/components/List.kt
3203929643
body-balance/common/components/src/main/kotlin/com/fitness/component/components/Icons.kt
0
package com.fitness.component.properties import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ButtonDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.unit.dp @Composable fun buttonElevation() = ButtonDefaults.buttonElevation( defaultElevation = 5.dp, pressedElevation = 10.dp, ) @Composable fun buttonShape() = RoundedCornerShape(50.dp)
body-balance/common/components/src/main/kotlin/com/fitness/component/properties/ButtonProperties.kt
1358611770
package com.fitness.component.properties import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.ui.unit.dp fun textFieldShape() = RoundedCornerShape(15.dp)
body-balance/common/components/src/main/kotlin/com/fitness/component/properties/TextFieldProperties.kt
3788774624
package com.fitness.component.properties import androidx.compose.ui.unit.dp object GuidelineProperties { val TOP = 25.dp val BOTTOM_100 = 100.dp val BOTTOM= 20.dp val SECOND_TOP = 175.dp val START = 20.dp val END = 20.dp val LOGO_TOP = 25.dp val LOGO_BOTTOM = 200.dp }
body-balance/common/components/src/main/kotlin/com/fitness/component/properties/GuidelineProperties.kt
1904797425
package com.fitness.component.properties import androidx.compose.ui.unit.sp val TITLE_TEXT_SIZE = 20.sp val HEADLINE_TEXT_SIZE = 17.sp val STANDARD_TEXT_SIZE = 16.sp val STANDARD_TEXT_SIZE_SMALL = 14.sp
body-balance/common/components/src/main/kotlin/com/fitness/component/properties/TextProperties.kt
24738772
package com.fitness.component import kotlin.math.abs fun calculateWeightProgressAsFraction(startWeight:Double, currentWeight:Double, targetWeight:Double) :Double { val totalWeightDifference = startWeight-targetWeight val currentWeightDifference = currentWeight-startWeight return abs(currentWeightDifference/totalWeightDifference) } fun calculateWeightProgress(startWeight:Double, currentWeight:Double, targetWeight:Double) :Double = calculateWeightProgressAsFraction(startWeight, currentWeight, targetWeight) *100 fun formatWeightProgress(startWeight:Double, currentWeight:Double, targetWeight:Double) : String { val overUnder = if( isOnTrack(startWeight, currentWeight, targetWeight) ){ "towards" } else if(isGoalToGain(startWeight = startWeight, targetWeight = targetWeight)){ "under" }else if(!isGoalToGain(startWeight = startWeight, targetWeight = targetWeight)){ "over" } else{ return "Completed" } return "${"%.1f".format(calculateWeightProgress(startWeight, currentWeight, targetWeight))}% $overUnder" } private fun isGoalToGain(startWeight:Double, targetWeight:Double) : Boolean = (startWeight-targetWeight) < 0 fun isOnTrack(startWeight:Double, currentWeight:Double, targetWeight:Double) : Boolean = isGoalToGain(startWeight, targetWeight) && currentWeight-startWeight > 0 || !isGoalToGain(startWeight, targetWeight) && currentWeight-startWeight < 0
body-balance/common/components/src/main/kotlin/com/fitness/component/ScreenUtil.kt
4072523013
package com.fitness.component import android.graphics.Paint import android.graphics.Typeface import androidx.compose.foundation.Canvas import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowLeft import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material3.Icon import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.fitness.theme.ui.BodyBalanceTheme import com.fitness.theme.ui.OffBlack import com.fitness.theme.ui.OffWhite import extensions.Dark import extensions.Light @Light @Dark @Composable private fun HorizontalRulerPreview() = BodyBalanceTheme { Surface { HorizontalRuler(steps = 1000, onValueChanged = {}) } } @Light @Dark @Composable private fun VerticalRulerPreview() = BodyBalanceTheme { Surface { VerticalRuler(steps = 1000, onValueChanged = {}) } } @Composable fun VerticalRuler( steps: Int, modifier: Modifier = Modifier, onValueChanged: (Float) -> Unit ) { BoxWithConstraints( contentAlignment = Alignment.CenterEnd, modifier = modifier.fillMaxHeight() ) { val contentColor: Color = if(isSystemInDarkTheme()) OffWhite else OffBlack val centerOfScreen = constraints.maxHeight / 2.0 VerticalRuler( steps = steps, centerOfScreen = centerOfScreen, contentColor = contentColor, onValueChanged = onValueChanged ) Icon( imageVector = Icons.Filled.KeyboardArrowLeft, contentDescription = "", ) } } @Composable private fun VerticalRuler( steps: Int, centerOfScreen: Double, contentColor: Color, onValueChanged: (Float) -> Unit, ) { val scrollState = rememberScrollState() BoxWithConstraints( contentAlignment = Alignment.TopCenter, modifier = Modifier .wrapContentWidth() .fillMaxHeight() .verticalScroll(scrollState) ) { val width = 100.dp val stepHeight = 20.dp val canvasHeight = stepHeight * steps + ( Dp(centerOfScreen.toFloat()) / 2 ) Canvas( modifier = Modifier .width(width) .height(canvasHeight) ) { val canvasWidth = size.width for (i in 0 until steps + 1) { val yPosition = i * stepHeight.toPx() + centerOfScreen.toFloat() val xStart = (canvasWidth / 2) var xEndUp = (xStart * .85f) var xEndDown = (xStart * 1.15f) if (i % 5 == 0) { xEndUp = (xStart * .75f) xEndDown = (xStart * 1.25f) } drawLine( color = contentColor, start = Offset(xStart, yPosition), end = Offset(xEndUp, yPosition), strokeWidth = 3f ) drawLine( color = contentColor, start = Offset(xStart, yPosition), end = Offset(xEndDown, yPosition), strokeWidth = 3f ) val measurement = i + 20 if (measurement % 5 == 0) { drawContext.canvas.nativeCanvas.drawText( i.toString(), (xStart * .50f), yPosition+15, Paint().apply { color = contentColor.toArgb() textSize = 40f // Size of the label textAlign = Paint.Align.CENTER typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) } ) } } } val density = LocalDensity.current LaunchedEffect(scrollState.value) { val measurement = (scrollState.value).div(density.density).div(stepHeight.value) onValueChanged(measurement) } } } @Composable fun HorizontalRuler( steps: Int, modifier: Modifier = Modifier, onValueChanged: (Float) -> Unit ) { val contentColor: Color = if(isSystemInDarkTheme()) OffWhite else OffBlack BoxWithConstraints( contentAlignment = Alignment.BottomCenter, modifier = modifier .fillMaxWidth() .wrapContentHeight() ) { val centerOfScreen = constraints.maxWidth / 2.0 HorizontalRuler( steps = steps, centerOfScreen = centerOfScreen, contentColor = contentColor, onValueChanged = onValueChanged ) Icon( imageVector = Icons.Filled.KeyboardArrowUp, contentDescription = "", tint = contentColor ) } } @Composable private fun HorizontalRuler( steps: Int, centerOfScreen: Double, contentColor: Color, onValueChanged: (Float) -> Unit, ) { val scrollState = rememberScrollState() val stepWidth = 20.dp val height = 100.dp val canvasWidth = stepWidth * steps BoxWithConstraints( contentAlignment = Alignment.TopCenter, modifier = Modifier .height(height) .horizontalScroll(scrollState) ) { Canvas( modifier = Modifier .height(height) .width(canvasWidth) ) { val canvasHeight = size.height for (i in 0 until steps) { val xPosition = stepWidth.times(i).toPx() + centerOfScreen.toFloat() val yStart = (canvasHeight / 2) var yEndUp = (yStart * .85f) var yEndDown = (yStart * 1.15f) if (i % 5 == 0) { yEndUp = (yStart * .75f) yEndDown = (yStart * 1.25f) } drawLine( color = contentColor, start = Offset(xPosition, yStart), end = Offset(xPosition, yEndUp), strokeWidth = 3f ) drawLine( color = contentColor, start = Offset(xPosition, yStart), end = Offset(xPosition, yEndDown), strokeWidth = 3f ) if (i % 5 == 0) { drawContext.canvas.nativeCanvas.drawText( i.toString(), xPosition, (yStart * .50f), // Adjust label position Paint().apply { color = contentColor.toArgb() textSize = 40f // Size of the label textAlign = Paint.Align.CENTER typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) } ) } } } val density = LocalDensity.current LaunchedEffect(scrollState.value) { val measurement = (scrollState.value).div(density.density).div(stepWidth.value) onValueChanged(measurement) } } }
body-balance/common/components/src/main/kotlin/com/fitness/component/Ruler.kt
303400375
package com.fitness.theme.ui import androidx.compose.ui.graphics.Color /** * * BASE COLORS */ val primaryBaseColor = Color(0xFF007BFF) // Vivid Sky Blue val secondaryBaseColor = Color(0xFF48C9B0) // Mint Green val tertiaryBaseColor = Color(0xFFE91E63) // Vivid Bright Pink val neutralBackgroundColor = Color(0xFFFFFFFF) // White val OffWhite = Color(0xFFF5F5F5) // Light Grey val textOnDarkColor = Color(0xFFFFFFFF) // White val OffBlack = Color(0xFF212121) // Dark Grey /** * * MAIN HUB COLORS */ // Primary color and its variant val primaryColorHub = Color(0xFF007BFF) // Vivid Sky Blue val primaryVariantHub = Color(0xFF005AC1) // A darker shade of Vivid Sky Blue // Secondary color and its variant val secondaryColorHub = Color(0xFFE91E63) // Vivid Bright Pink (as an accent) val secondaryVariantHub = Color(0xFFC2185B) // A darker shade of Vivid Bright Pink val tertiaryColorHub = Color(0xFF48C9B0) // Mint Green, complementing Vivid Sky Blue and Vivid Bright Pink // Background and surface colors val backgroundColorHub = Color(0xFFFFFFFF) // White val surfaceColorHub = Color(0xFFF5F5F5) // Light Grey // Text colors val textOnPrimaryHub = Color(0xFFFFFFFF) // White (for text on Vivid Sky Blue) val textOnSecondaryHub = Color(0xFFFFFFFF) // White (for text on Vivid Bright Pink) val textOnBackgroundHub = Color(0xFF212121) // Dark Grey /** * * AUTH HUB COLORS */ // Primary color and its variant val primaryColorAuth = Color(0xFF48C9B0) // Mint Green val primaryVariantAuth = Color(0xFF36A79A) // A darker shade of Mint Green // Secondary color and its variant val secondaryColorAuth = Color(0xFF007BFF) // Vivid Sky Blue (as an accent) val secondaryVariantAuth = Color(0xFF005AC1) // A darker shade of Vivid Sky Blue val tertiaryColorAuth = Color(0xFFE91E63) // Vivid Bright Pink, complementing Mint Green and Vivid Sky Blue // Background and surface colors val backgroundColorAuth = Color(0xFFFFFFFF) // White val surfaceColorAuth = Color(0xFFF5F5F5) // Light Grey // Text colors val textOnPrimaryAuth = Color(0xFF212121) // Dark Grey (for text on Mint Green) val textOnSecondaryAuth = Color(0xFFFFFFFF) // White (for text on Vivid Sky Blue) val textOnBackgroundAuth = Color(0xFF212121) // Dark Grey /** * * SPOKE COLORS */ // Primary color and its variant val primaryColorSpoke = Color(0xFFE91E63) // Vivid Bright Pink val primaryVariantSpoke = Color(0xFFC2185B) // A darker shade of Vivid Bright Pink // Secondary color and its variant val secondaryColorSpoke = Color(0xFF48C9B0) // Mint Green (as an accent) val secondaryVariantSpoke = Color(0xFF36A79A) // A darker shade of Mint Green val tertiaryColorSpoke = Color(0xFF007BFF) // Vivid Sky Blue, complementing Vivid Bright Pink and Mint Green // Background and surface colors val backgroundColorSpoke = Color(0xFFFFFFFF) // White val surfaceColorSpoke = Color(0xFFF5F5F5) // Light Grey // Text colors val textOnPrimarySpoke = Color(0xFFFFFFFF) // White (for text on Vivid Bright Pink) val textOnSecondarySpoke = Color(0xFF212121) // Dark Grey (for text on Mint Green) val textOnBackgroundSpoke = Color(0xFF212121) // Dark Grey val Green = Color(0xFF32DE84) val Red = Color(0xFFB20710) val Saffron = Color(0xFFF4C430) val DeepOrange = Color(0xFFF04A00)
body-balance/common/theme/src/main/kotlin/com/fitness/theme/ui/Color.kt
3198355237
package com.fitness.theme.ui import android.app.Activity import android.os.Build import android.view.Window import android.view.WindowInsets import android.view.WindowInsetsController import android.view.WindowManager import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.ColorScheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.State import androidx.compose.runtime.collectAsState import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat import com.fitness.theme.AppTheme import kotlinx.coroutines.flow.MutableStateFlow @Composable fun BodyBalanceTheme( appTheme: State<AppTheme> = MutableStateFlow(AppTheme.Auth).collectAsState(), darkTheme: Boolean = isSystemInDarkTheme(), dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = colorScheme( appTheme = appTheme, darkTheme = darkTheme, dynamicColor = dynamicColor ) HandleSideEffects( colorScheme = colorScheme, darkTheme = darkTheme ) MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) } private val mainDarkColorScheme = darkColorScheme( primary = primaryColorHub.copy(alpha = 0.8f), // Adjusted for better visibility on dark backgrounds secondary = secondaryColorHub.copy(alpha = 0.8f), tertiary = tertiaryColorHub.copy(alpha = 0.8f), background = Color(0xFF121212), // Typical dark theme background surface = Color(0xFF1E1E1E), // Slightly lighter than the background for contrast onPrimary = Color.White, // Text color on primary onSecondary = Color.White, // Text color on secondary onTertiary = Color.White, // Text color on tertiary onBackground = Color.White, // Text color on background onSurface = Color.White // Text color on surface ) private val onboardingLightColorScheme = lightColorScheme( primary = primaryColorAuth, secondary = secondaryColorAuth, tertiary = tertiaryColorAuth ) private val authLightColorScheme = lightColorScheme( primary = primaryColorAuth, secondary = secondaryColorAuth, tertiary = tertiaryColorAuth ) private val hubLightColorScheme = lightColorScheme( primary = primaryColorHub, secondary = secondaryColorHub, tertiary = tertiaryColorHub ) private val spokeLightColorScheme = lightColorScheme( primary = primaryColorSpoke, secondary = secondaryColorSpoke, tertiary = tertiaryColorSpoke ) @Composable fun colorScheme( appTheme: State<AppTheme>, darkTheme: Boolean, dynamicColor: Boolean ): ColorScheme { return when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> mainDarkColorScheme else -> when (appTheme.value) { // Use the appTheme parameter to switch color schemes AppTheme.Onboarding -> onboardingLightColorScheme AppTheme.Auth -> authLightColorScheme AppTheme.Hub -> hubLightColorScheme AppTheme.Spoke -> spokeLightColorScheme } } } @Composable fun HandleSideEffects( colorScheme: ColorScheme, darkTheme: Boolean ){ val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme hideSystemUI(window) } } } fun hideSystemUI(window: Window) { //Hides the ugly action bar at the top //Hide the status bars WindowCompat.setDecorFitsSystemWindows(window, false) window.setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS ) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { @Suppress("DEPRECATION") window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) } else { window.insetsController?.apply { hide(WindowInsets.Type.statusBars()) hide(WindowInsets.Type.systemBars()) systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } } }
body-balance/common/theme/src/main/kotlin/com/fitness/theme/ui/Theme.kt
2861084928
package com.fitness.theme.ui import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import androidx.compose.ui.text.font.Font import com.fitness.resources.R private val fredoka = FontFamily( Font(R.font.fredoka_regular, weight = FontWeight.Normal), Font(R.font.fredoka_bold, weight = FontWeight.Bold), Font(R.font.fredoka_light, weight = FontWeight.Light), Font(R.font.fredoka_light, weight = FontWeight.ExtraLight), Font(R.font.fredoka_medium, weight = FontWeight.Medium), Font(R.font.fredoka_light, weight = FontWeight.Thin), Font(R.font.fredoka_semi_bold, weight = FontWeight.SemiBold) ) val Typography = Typography( displayLarge = TextStyle( fontFamily = fredoka, fontWeight = FontWeight.Bold, fontSize = 28.sp ), displayMedium = TextStyle( fontFamily = fredoka, fontWeight = FontWeight.Bold, fontSize = 21.sp ), displaySmall = TextStyle( fontFamily = fredoka, fontWeight = FontWeight.SemiBold, fontSize = 18.sp ), headlineMedium = TextStyle( fontFamily = fredoka, fontWeight = FontWeight.Medium, fontSize = 15.sp ), headlineSmall = TextStyle( fontFamily = fredoka, fontWeight = FontWeight.Medium, fontSize = 18.sp ), titleLarge = TextStyle( fontFamily = fredoka, fontWeight = FontWeight.Bold, fontSize = 16.sp ), titleMedium = TextStyle( fontFamily = fredoka, fontWeight = FontWeight.Medium, fontSize = 14.sp ), bodyLarge = TextStyle( fontFamily = fredoka, fontWeight = FontWeight.Normal, fontSize = 14.sp ), bodyMedium = TextStyle( fontFamily = fredoka, fontWeight = FontWeight.Bold, fontSize = 14.sp ), labelLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), bodySmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) )
body-balance/common/theme/src/main/kotlin/com/fitness/theme/ui/Type.kt
2510040541
package com.fitness.theme.di import com.fitness.theme.ThemeManager import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class ThemeModule { @Provides @Singleton fun provideThemeManager(): ThemeManager = ThemeManager() }
body-balance/common/theme/src/main/kotlin/com/fitness/theme/di/ThemeModule.kt
1491545233
package com.fitness.theme enum class AppTheme { Onboarding, Auth, Hub, Spoke }
body-balance/common/theme/src/main/kotlin/com/fitness/theme/AppTheme.kt
1813094334
package com.fitness.theme import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import javax.inject.Inject class ThemeManager @Inject constructor() { val appTheme: StateFlow<AppTheme> = MutableStateFlow(AppTheme.Auth) }
body-balance/common/theme/src/main/kotlin/com/fitness/theme/ThemeManager.kt
459750405
package com.fitness.authentication.di import com.fitness.authentication.manager.AuthenticationManager import com.fitness.authentication.manager.AuthenticationManagerImpl import com.google.firebase.auth.FirebaseAuth import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class CommonAuthModule { @Provides @Singleton fun provideAuthenticationManager(firebaseAuth: FirebaseAuth): AuthenticationManager = AuthenticationManagerImpl(firebaseAuth) }
body-balance/common/authentication/src/main/kotlin/com/fitness/authentication/di/CommonAuthModule.kt
2900568328
package com.fitness.authentication.manager sealed class AuthenticationState { object OnBoard: AuthenticationState() object UnAuthenticated: AuthenticationState() object Authenticated: AuthenticationState() }
body-balance/common/authentication/src/main/kotlin/com/fitness/authentication/manager/AuthenticationState.kt
353001139
package com.fitness.authentication.manager import com.google.firebase.auth.FirebaseAuth import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import javax.inject.Inject class AuthenticationManagerImpl @Inject constructor(firebaseAuth: FirebaseAuth): AuthenticationManager{ private var _authState: MutableStateFlow<AuthenticationState> = MutableStateFlow( if(firebaseAuth.currentUser != null){ AuthenticationState.Authenticated } else{ AuthenticationState.UnAuthenticated } ) override val authState: StateFlow<AuthenticationState> get() = _authState override fun update(authState: AuthenticationState) { _authState.value = authState } }
body-balance/common/authentication/src/main/kotlin/com/fitness/authentication/manager/AuthenticationManagerImpl.kt
735895974
package com.fitness.authentication.manager import kotlinx.coroutines.flow.StateFlow interface AuthenticationManager { val authState: StateFlow<AuthenticationState> fun update(authState: AuthenticationState) }
body-balance/common/authentication/src/main/kotlin/com/fitness/authentication/manager/AuthenticationManager.kt
2571118968
import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.dsl.DependencyHandler import org.gradle.kotlin.dsl.project import config.* /** * Adds a dependency to the `kapt` configuration. * * @param dependencyNotation name of dependency to add at specific configuration * * @return the dependency */ fun DependencyHandler.kapt(dependencyNotation: Any): Dependency? = add("kapt", dependencyNotation) /** * Adds a dependency to the `api` configuration. * * @param dependencyNotation name of dependency to add at specific configuration * * @return the dependency */ fun DependencyHandler.api(dependencyNotation: Any): Dependency? = add("api", dependencyNotation) /** * Adds a dependency to the `implementation` configuration. * * @param dependencyNotation name of dependency to add at specific configuration * * @return the dependency */ fun DependencyHandler.implementation(dependencyNotation: Any): Dependency? = add("implementation", dependencyNotation) /** * Adds a dependency to the `TestImplementation` configuration. * * @param dependencyNotation name of dependency to add at specific configuration * * @return the dependency */ fun DependencyHandler.testImplementation(dependencyNotation: Any): Dependency? = add("testImplementation", dependencyNotation) /** * Adds a dependency to the `DestImplementation` configuration. * * @param dependencyNotation name of dependency to add at specific configuration * * @return the dependency */ fun DependencyHandler.debugImplementation(dependencyNotation: Any): Dependency? = add("debugImplementation", dependencyNotation) fun DependencyHandler.annotationProcessor(dependencyNotation: Any): Dependency? = add("annotationProcessor", dependencyNotation) //Common val DependencyHandler.AUTHENTICATION_MANAGER get() = api(project(":common:authentication")) val DependencyHandler.COMPONENTS get() = api(project(":common:components")) val DependencyHandler.NAVIGATION get() = implementation(project(":common:navigation")) val DependencyHandler.RESOURCES get() = implementation(project(":common:resources")) val DependencyHandler.THEME get() = implementation(project(":common:theme")) //Data val DependencyHandler.DATA_IMPL get() = implementation(project(":data:impl")) val DependencyHandler.DATA_API get() = api(project(":data:api")) //Domain val DependencyHandler.DOMAIN_API get() = api(project(":domain:api")) val DependencyHandler.DOMAIN_IMPL get() = implementation(project(":domain:impl")) //Feature val DependencyHandler.AUTHENTICATION get() = implementation(project(":features:authentication:impl")) val DependencyHandler.AUTHENTICATION_API get() = api(project(":features:authentication:api")) val DependencyHandler.DASHBOARD get() = implementation(project(":features:dashboard:impl")) val DependencyHandler.DASHBOARD_API get() = api(project(":features:dashboard:api")) val DependencyHandler.ONBOARD get() = implementation(project(":features:onboard:impl")) val DependencyHandler.ONBOARD_API get() = api(project(":features:onboard:api")) val DependencyHandler.RECIPE_BUILDER get() = implementation(project(":features:recipe-builder:impl")) val DependencyHandler.RECIPE_BUILDER_API get() = api(project(":features:recipe-builder:api")) val DependencyHandler.SEARCH get() = implementation(project(":features:search:impl")) val DependencyHandler.SEARCH_API get() = api(project(":features:search:api")) val DependencyHandler.SIGN_OUT get() = implementation(project(":features:signout:impl")) val DependencyHandler.SIGN_OUT_API get() = api(project(":features:signout:api")) val DependencyHandler.USER_PROFILE get() = implementation(project(":features:user-profile:impl")) val DependencyHandler.USER_PROFILE_API get() = api(project(":features:user-profile:api")) val DependencyHandler.WELCOME get() = implementation(project(":features:welcome:impl")) val DependencyHandler.WELCOME_API get() = api(project(":features:welcome:api")) //Library val DependencyHandler.FRAMEWORK get() = implementation(project(":library:framework")) val DependencyHandler.ANALYTICS get() = implementation(project(":library:analytics")) val DependencyHandler.COIL get() = implementation(CoilLibs.COIL) fun DependencyHandler.addCoreDependencies() { implementation(CoreLibs.CORE_KTX) implementation(CoreLibs.LIFE_RUNTIME) } fun DependencyHandler.addJetpackComposeDependencies(){ implementation(ComposeLibs.ACTIVITY_COMPOSE) implementation(platform(ComposeLibs.COMPOSE_BOM)) implementation(ComposeLibs.COMPOSE_UI) implementation(ComposeLibs.COMPOSE_UI_GRAPHICS) implementation(ComposeLibs.COMPOSE_TOOLING_PREVIEW) implementation(ComposeLibs.COMPOSE_MATERIAL3) implementation(ComposeLibs.MATERIAL) implementation(ComposeLibs.COMPOSE_CONSTRAINT_LAYOUT) implementation(ComposeLibs.COMPOSE_FOUNDATION) debugImplementation(ComposeLibs.DEBUG_COMPOSE_UI_TOOLING) debugImplementation(ComposeLibs.DEBUG_COMPOSE_UI_MANIFEST) } fun DependencyHandler.addTestDependencies(){ testImplementation(TestingLibs.JUNIT) testImplementation(TestingLibs.JUNIT_EXT) testImplementation(TestingLibs.ESPRESSO) testImplementation(TestingLibs.COMPOSE_UI_TEST) } fun DependencyHandler.addHiltDependencies() { implementation(HiltLibs.HILT) implementation(HiltLibs.HILT_NAVIGATION) kapt(HiltLibs.HILT_COMPILER) } fun DependencyHandler.addDaggerDependencies() { implementation(DaggerLibs.DAGGER2) kapt(DaggerLibs.DAGGER2_COMPILER) } fun DependencyHandler.addCoroutineDependencies(){ implementation(CoroutineLibs.COROUTINES) implementation(CoroutineLibs.COROUTINES_ANDROID) implementation(CoroutineLibs.COROUTINES_VIEWMODEL) implementation(CoroutineLibs.COROUTINES_GOOGLE_PLAY) } fun DependencyHandler.addFirebaseDependencies(){ implementation(platform(FirebaseLibs.FIREBASE_BOM)) implementation(FirebaseLibs.FIREBASE_AUTHENTICATION) implementation(FirebaseLibs.FIREBASE_ANALYTICS) implementation(FirebaseLibs.FIREBASE_CRASHALYTICS) implementation(FirebaseLibs.FIREBASE_FIRESTORE) implementation(FirebaseLibs.GOOGLE_PLAY_AUTH) implementation(FirebaseLibs.LIB_PHONE_NUMBER) } fun DependencyHandler.addNavigationDependencies(){ api(NavigationLibs.COMPOSE_NAVIGATION) api(NavigationLibs.NAVIGATION_RUNTIME) } fun DependencyHandler.addFeatureDependencies(){ AUTHENTICATION DASHBOARD ONBOARD USER_PROFILE WELCOME SIGN_OUT SEARCH RECIPE_BUILDER } fun DependencyHandler.addFeatureAPIDependencies(){ AUTHENTICATION_API DASHBOARD_API ONBOARD_API USER_PROFILE_API WELCOME_API SIGN_OUT_API SEARCH_API RECIPE_BUILDER_API } fun DependencyHandler.addMedia3Dependencies(){ api(ExoPlayerLibs.EXO_PLAYER) api(ExoPlayerLibs.EXO_PLAYER_UI) } fun DependencyHandler.addNetworkDependencies(){ api(NetworkLibs.RETROFIT) api(NetworkLibs.RETROFIT_MOSHI) api(NetworkLibs.MOSHI) api(NetworkLibs.MOSHI_KOTLIN) kapt(NetworkLibs.MOSHI_CODEGEN) api(NetworkLibs.RETROFIT_COROUTINES) api(NetworkLibs.OKHTTP) api(NetworkLibs.OKHTTP_INTERCEPTOR) } fun DependencyHandler.addSerializationLib(){ api(SerializationLibs.KOTLINX_SERIALIZATION) } fun DependencyHandler.addRoomLib(){ api(RoomLibs.ROOM_RUNTIME) api(RoomLibs.ROOM_KTX) api(RoomLibs.GSON) kapt(RoomLibs.ROOM_COMPILER) }
body-balance/buildSrc/src/main/kotlin/DependencyHandlerExtensions.kt
3425408963
package config private object Version { const val CORE_KTX = "1.12.0" const val LIFECYCLE_RUNTIME = "2.6.2" const val ACTIVITY_COMPOSE = "1.8.1" const val COMPOSE_BOM = "2023.03.00" const val COMPOSE_NAVIGATION = "2.7.5" const val COMPOSE_FOUNDATION = "1.5.1" const val COMPOSE_CONSTRAINT_LAYOUT = "1.0.1" const val JUNIT = "4.13.2" const val JUNIT_EXT = "1.1.5" const val ESPRESSO = "3.5.1" const val HILT = "2.44" const val HILT_NAVIGATION = "1.1.0" const val DAGGER2 = "2.44" const val COROUTINES = "1.7.3" const val COROUTINES_VIEWMODEL = "2.6.2" const val FIREBASE_BOM = "32.6.0" const val EXO_PLAYER = "1.2.0" const val GOOGLE_PLAY_AUTH = "20.7.0" const val LIB_PHONE_NUMBER = "8.12.39" const val COIL = "2.2.13" const val RETROFIT = "2.9.0" const val RETROFIT_COROUTINES = "0.9.2" const val OKHTTP = "4.9.0" const val MOSHI = "1.14.0" const val KOTLINX_SERIALIZATION = "1.2.1" const val ROOM = "2.6.1" const val GSON = "2.8.6" } object CoreLibs{ const val CORE_KTX = "androidx.core:core-ktx:${Version.CORE_KTX}" const val LIFE_RUNTIME = "androidx.lifecycle:lifecycle-runtime-ktx:${Version.LIFECYCLE_RUNTIME}" } object ComposeLibs{ const val ACTIVITY_COMPOSE = "androidx.activity:activity-compose:${Version.ACTIVITY_COMPOSE}" const val COMPOSE_BOM = "androidx.compose:compose-bom:${Version.COMPOSE_BOM}" const val COMPOSE_UI = "androidx.compose.ui:ui" const val COMPOSE_UI_GRAPHICS = "androidx.compose.ui:ui-graphics" const val COMPOSE_TOOLING_PREVIEW = "androidx.compose.ui:ui-tooling-preview" const val COMPOSE_MATERIAL3 = "androidx.compose.material3:material3:1.1.2" const val DEBUG_COMPOSE_UI_TOOLING = "androidx.compose.ui:ui-tooling" const val DEBUG_COMPOSE_UI_MANIFEST = "androidx.compose.ui:ui-test-manifest" const val COMPOSE_CONSTRAINT_LAYOUT = "androidx.constraintlayout:constraintlayout-compose:${Version.COMPOSE_CONSTRAINT_LAYOUT}" const val MATERIAL = "com.google.android.material:material:1.4.0" const val COMPOSE_FOUNDATION = "androidx.compose.foundation:foundation-layout-android:${Version.COMPOSE_FOUNDATION}" } object NavigationLibs{ const val COMPOSE_NAVIGATION = "androidx.navigation:navigation-compose:${Version.COMPOSE_NAVIGATION}" const val NAVIGATION_RUNTIME = "androidx.navigation:navigation-runtime-ktx:${Version.COMPOSE_NAVIGATION}" } object TestingLibs{ const val JUNIT = "junit:junit:${Version.JUNIT}" const val JUNIT_EXT = "androidx.test.ext:junit:${Version.JUNIT_EXT}" const val ESPRESSO = "androidx.test.espresso:espresso-core:${Version.ESPRESSO}" const val COMPOSE_UI_TEST = "androidx.compose.ui:ui-test-junit4" } object HiltLibs{ const val HILT = "com.google.dagger:hilt-android:${Version.HILT}" const val HILT_COMPILER = "com.google.dagger:hilt-android-compiler:${Version.HILT}" const val HILT_NAVIGATION = "androidx.hilt:hilt-navigation-compose:${Version.HILT_NAVIGATION}" } object DaggerLibs{ const val DAGGER2 = "com.google.dagger:dagger:${Version.DAGGER2}" const val DAGGER2_COMPILER = "com.google.dagger:dagger-compiler:${Version.DAGGER2}" } object CoroutineLibs{ const val COROUTINES = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Version.COROUTINES}" const val COROUTINES_ANDROID = "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Version.COROUTINES}" const val COROUTINES_VIEWMODEL = "androidx.lifecycle:lifecycle-viewmodel-ktx:${Version.COROUTINES_VIEWMODEL}" const val COROUTINES_GOOGLE_PLAY = "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:${Version.COROUTINES}" } object FirebaseLibs{ const val FIREBASE_BOM = "com.google.firebase:firebase-bom:${Version.FIREBASE_BOM}" const val FIREBASE_ANALYTICS = "com.google.firebase:firebase-analytics" const val FIREBASE_CRASHALYTICS = "com.google.firebase:firebase-crashlytics" const val FIREBASE_FIRESTORE = "com.google.firebase:firebase-firestore" const val FIREBASE_AUTHENTICATION = "com.google.firebase:firebase-auth" const val GOOGLE_PLAY_AUTH = "com.google.android.gms:play-services-auth:${Version.GOOGLE_PLAY_AUTH}" const val LIB_PHONE_NUMBER = "com.googlecode.libphonenumber:libphonenumber:${Version.LIB_PHONE_NUMBER}" } object ExoPlayerLibs{ const val EXO_PLAYER = "androidx.media3:media3-exoplayer:${Version.EXO_PLAYER}" const val EXO_PLAYER_UI = "androidx.media3:media3-ui:${Version.EXO_PLAYER}" } object CoilLibs{ const val COIL = "com.github.skydoves:landscapist-coil:${Version.COIL}" } object NetworkLibs{ const val RETROFIT = "com.squareup.retrofit2:retrofit:${Version.RETROFIT}" const val RETROFIT_MOSHI = "com.squareup.retrofit2:converter-moshi:${Version.RETROFIT}" const val MOSHI_KOTLIN = "com.squareup.moshi:moshi-kotlin:${Version.MOSHI}" const val MOSHI = "com.squareup.moshi:moshi:${Version.MOSHI}" const val MOSHI_CODEGEN = "com.squareup.moshi:moshi-kotlin-codegen:${Version.MOSHI}" const val RETROFIT_COROUTINES = "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:${Version.RETROFIT_COROUTINES}" const val OKHTTP = "com.squareup.okhttp3:okhttp:${Version.OKHTTP}" const val OKHTTP_INTERCEPTOR = "com.squareup.okhttp3:logging-interceptor:${Version.OKHTTP}" } object SerializationLibs{ const val KOTLINX_SERIALIZATION = "org.jetbrains.kotlinx:kotlinx-serialization-json:${Version.KOTLINX_SERIALIZATION}" } object RoomLibs{ const val GSON = "com.google.code.gson:gson:${Version.GSON}" const val ROOM_RUNTIME = "androidx.room:room-runtime:${Version.ROOM}" const val ROOM_COMPILER = "androidx.room:room-compiler:${Version.ROOM}" const val ROOM_KTX = "androidx.room:room-ktx:${Version.ROOM}" }
body-balance/buildSrc/src/main/kotlin/config/Libs.kt
2410162960
package config import org.gradle.api.JavaVersion object Configs { private const val versionMajor = 1 private const val versionMinor = 0 private const val versionPatch = 0 private const val versionQualifier = "alpha1" private fun generateVersionCode(): Int { return versionMajor * 10000 + versionMinor * 100 + versionPatch } private fun generateVersionName(): String { return "$versionMajor.$versionMinor.$versionPatch" } const val Id = "com.fitness.bodybalance" val VersionCode = generateVersionCode() val VersionName = generateVersionName() const val CompileSdk = 34 const val TargetSdk = CompileSdk const val MinSdk = 26 const val AndroidJunitRunner = "androidx.test.runner.AndroidJUnitRunner" val SourceCompatibility = JavaVersion.VERSION_17 val TargetCompatibility = JavaVersion.VERSION_17 const val JvmTarget = "17" const val KotlinCompilerExtensionVersion = "1.4.2" val FreeCompilerArgs = listOf( "-Xjvm-default=all", "-Xopt-in=kotlin.RequiresOptIn", "-Xopt-in=kotlin.Experimental", "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi", "-Xopt-in=kotlinx.coroutines.InternalCoroutinesApi", "-Xopt-in=kotlinx.coroutines.FlowPreview", "-Xopt-in=androidx.compose.material.ExperimentalMaterialApi", "-Xopt-in=com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi", "-Xopt-in=androidx.compose.animation.ExperimentalAnimationApi" ) val FreeCoroutineCompilerArgs = listOf( "-Xjvm-default=all", "-Xopt-in=kotlin.RequiresOptIn", "-Xopt-in=kotlin.Experimental", "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi", "-Xopt-in=kotlinx.coroutines.InternalCoroutinesApi", "-Xopt-in=kotlinx.coroutines.FlowPreview" ) }
body-balance/buildSrc/src/main/kotlin/config/Config.kt
3752658729
package com.fitness.data.repository.auth import auth.PhoneAuthState import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks import com.google.firebase.FirebaseException import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.PhoneAuthCredential import com.google.firebase.auth.PhoneAuthOptions import com.google.firebase.auth.PhoneAuthProvider import com.google.firebase.auth.UserProfileChangeRequest import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.Flow import java.util.concurrent.TimeUnit import javax.inject.Inject class AuthRepositoryImpl @Inject constructor(private val firebase: FirebaseAuth) : AuthRepository { override suspend fun signInWithEmail(email: String, password: String): Task<AuthResult> = firebase.signInWithEmailAndPassword(email, password) override suspend fun sendVerificationCode(phoneNumber: String): Flow<PhoneAuthState> = callbackFlow { val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(credential: PhoneAuthCredential) {} override fun onVerificationFailed(e: FirebaseException) { trySend(PhoneAuthState.Error(e)) close(e) } override fun onCodeSent(verificationId: String, token: PhoneAuthProvider.ForceResendingToken) { trySend(PhoneAuthState.CodeSent(verificationId)) } } val options = PhoneAuthOptions.newBuilder(firebase) .setPhoneNumber(phoneNumber) .setTimeout(60L, TimeUnit.SECONDS) .setCallbacks(callbacks) .build() PhoneAuthProvider.verifyPhoneNumber(options) awaitClose { } } override suspend fun verifyPhoneNumberWithCode(verificationId: String, code: String): Task<AuthResult> { val credential = PhoneAuthProvider.getCredential(verificationId, code) return firebase.signInWithCredential(credential) } override suspend fun signUpWithEmail( firstname: String, lastname: String, email: String, password: String ): Task<AuthResult> = firebase.createUserWithEmailAndPassword(email, password) .onSuccessTask { authResult -> val profileUpdateTask = authResult?.user?.let { val profileUpdate = UserProfileChangeRequest.Builder() .setDisplayName("$firstname $lastname") .build() it.updateProfile(profileUpdate) } if (profileUpdateTask != null) { Tasks.whenAllComplete(profileUpdateTask).continueWithTask { Tasks.forResult(authResult) } } else { Tasks.forResult(authResult) } } override suspend fun sendPasswordResetEmail(email: String): Task<Unit> = firebase.sendPasswordResetEmail(email) .onSuccessTask { Tasks.forResult(Unit) } override suspend fun signOut(): Unit = firebase.signOut() }
body-balance/data/impl/src/main/kotlin/com/fitness/data/repository/auth/AuthRepositoryImpl.kt
2536119619
package com.fitness.data.repository.user import cache.firestore import com.fitness.data.model.cache.metrics.UserBodyMetricsCache import com.fitness.data.model.cache.metrics.UserRecommendedMacrosCache import com.fitness.data.model.cache.user.UserBasicGoalsInfoCache import com.fitness.data.model.cache.user.UserBasicInfoCache import com.fitness.data.model.cache.user.UserBasicNutritionInfoCache import com.fitness.data.model.cache.user.UserCache import com.fitness.data.model.cache.user.UserBasicFitnessLevelCache import com.fitness.data.model.cache.user.UserPreferencesCache import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestore import state.DataState import javax.inject.Inject class UserRepositoryImpl @Inject constructor( private val firebaseAuth: FirebaseAuth, private val firestore: FirebaseFirestore ) : UserRepository { private companion object { 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" const val USER_BODY_METRICS: String = "USER_BODY_METRICS" const val USER_RECOMMENDED_MACROS: String = "USER_RECOMMENDED_MACROS" const val USER_PREFERENCES_FIELD: String = "USER_GOALS_INFO" } override suspend fun getCurrentUserId(): Task<String?> = Tasks.forResult(firebaseAuth.currentUser?.uid) override suspend fun createUser(user: UserCache): DataState<Unit> = firestore { firestore.collection(USER) .document(user.id) .set(user) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun readUser(id: String): DataState<DocumentSnapshot> = firestore { firestore.collection(USER) .document(id) .get() } override suspend fun updateUser(id: String, map: Map<String, Any>): DataState<Unit> = firestore { firestore.collection(USER) .document(id) .update(map) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun deleteUser(id: String): DataState<Unit> = firestore { firestore.collection(USER) .document(id) .delete() .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun updateUserPreferences(id: String, preferences: UserPreferencesCache): DataState<Unit> = firestore { firestore.collection(USER) .document(id) .update(mapOf(USER_PREFERENCES_FIELD to preferences)) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun updateUserBodyMetrics(id: String, metrics: UserBodyMetricsCache): DataState<Unit> = firestore { firestore.collection(USER) .document(id) .update(mapOf(USER_BODY_METRICS to metrics)) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun updateUserRecommendedMetrics(id: String, macros: UserRecommendedMacrosCache): DataState<Unit> = firestore { firestore.collection(USER) .document(id) .update(mapOf(USER_RECOMMENDED_MACROS to macros)) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun createUserBasicInfo(info: UserBasicInfoCache): DataState<Unit> = firestore { firestore.collection(USER_BASIC_INFO) .document(info.userId) .set(info) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun readUserBasicInfo(id: String): DataState<DocumentSnapshot> = firestore { firestore.collection(USER_BASIC_INFO) .document(id) .get() } override suspend fun updateUserBasicInfo(id: String, map: Map<String, Any>): DataState<Unit> = firestore { firestore.collection(USER_BASIC_INFO) .document(id) .update(map) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun deleteUserBasicInfo(id: String): DataState<Unit> = firestore { firestore.collection(USER_BASIC_INFO) .document(id) .delete() .onSuccessTask{ Tasks.forResult(Unit) } } override suspend fun createBasicFitnessInfo(info: UserBasicFitnessLevelCache): DataState<Unit> = firestore { firestore.collection(USER_BASIC_FITNESS_INFO) .document(info.userId) .set(info) .onSuccessTask{ Tasks.forResult(Unit) } } override suspend fun readBasicFitnessInfo(id: String): DataState<DocumentSnapshot> = firestore { firestore.collection(USER_BASIC_FITNESS_INFO) .document(id) .get() } override suspend fun updateBasicFitnessInfo(id: String, map: Map<String, Any>): DataState<Unit> = firestore { firestore.collection(USER_BASIC_FITNESS_INFO) .document(id) .update(map) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun deleteBasicFitnessInfo(id: String): DataState<Unit> = firestore { firestore.collection(USER_BASIC_FITNESS_INFO) .document(id) .delete() .onSuccessTask{ Tasks.forResult(Unit) } } override suspend fun createBasicNutritionInfo(info: UserBasicNutritionInfoCache): DataState<Unit> = firestore { firestore.collection(USER_NUTRITIONAL_INFO) .document(info.userId) .set(info) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun readBasicNutritionInfo(id: String): DataState<DocumentSnapshot> = firestore { firestore.collection(USER_NUTRITIONAL_INFO) .document(id) .get() } override suspend fun updateBasicNutritionInfo(id: String, map: Map<String, Any>): DataState<Unit> = firestore { firestore.collection(USER_NUTRITIONAL_INFO) .document(id) .update(map) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun deleteBasicNutritionInfo(id: String): DataState<Unit> = firestore { firestore.collection(USER_NUTRITIONAL_INFO) .document(id) .delete() .onSuccessTask{ Tasks.forResult(Unit) } } override suspend fun createUserBasicGoalsInfo(info: UserBasicGoalsInfoCache): DataState<Unit> = firestore { firestore.collection(USER_GOALS_INFO) .document(info.userId) .set(info) .onSuccessTask{ Tasks.forResult(Unit) } } override suspend fun readUserBasicGoalsInfo(id: String): DataState<DocumentSnapshot> = firestore { firestore.collection(USER_GOALS_INFO) .document(id) .get() } override suspend fun updateUserBasicGoalsInfo(id: String, map: Map<String, Any>): DataState<Unit> = firestore { firestore.collection(USER_NUTRITIONAL_INFO) .document(id) .update(map) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun deleteUserBasicGoalsInfo(id: String): DataState<Unit> = firestore { firestore.collection(USER_GOALS_INFO) .document(id) .delete() .onSuccessTask{ Tasks.forResult(Unit) } } }
body-balance/data/impl/src/main/kotlin/com/fitness/data/repository/user/UserRepositoryImpl.kt
1812721797
package com.fitness.data.repository.edamam import com.fitness.data.model.network.edamam.NutrientsResponse import com.fitness.data.network.EdamamNutritionService import javax.inject.Inject class EdamamNutritionRepositoryImpl @Inject constructor( private val service: EdamamNutritionService ): EdamamNutritionRepository { override suspend fun getFoodNutrients(): NutrientsResponse = service.getFoodNutrients() }
body-balance/data/impl/src/main/kotlin/com/fitness/data/repository/edamam/EdamamNutritionRepositoryImpl.kt
3198963679
package com.fitness.data.repository.edamam import com.fitness.data.extensions.toIngredientEntity import com.fitness.data.model.cache.nutrition.IngredientEntity import com.fitness.data.model.network.edamam.food.FoodDataDto import com.fitness.data.model.network.edamam.params.IngredientBrandParams import com.fitness.data.model.network.edamam.params.IngredientSearchParams import com.fitness.data.network.EdamamFoodService import javax.inject.Inject class EdamamFoodRepositoryImpl @Inject constructor( private val service: EdamamFoodService ) : EdamamFoodRepository { override suspend fun getAllFood(): List<IngredientEntity> = service.getAllFood().hints?.toIngredientEntity() ?: emptyList() override suspend fun getFoodByIngredient(params: IngredientSearchParams): List<IngredientEntity> = service.getFoodByIngredient( ingredient = params.ingredient, category = params.category, calories = params.calories, health = params.health ).hints?.toIngredientEntity() ?: emptyList() override suspend fun getFoodByBrand(params: IngredientBrandParams): List<IngredientEntity> = TODO("Not yet implemented") override suspend fun getFoodByUpc(upc: String): List<IngredientEntity> = TODO("Not yet implemented") } fun List<FoodDataDto>.toIngredientEntity(): List<IngredientEntity> = mapNotNull { it.food?.toIngredientEntity(it.measures) }
body-balance/data/impl/src/main/kotlin/com/fitness/data/repository/edamam/EdamamFoodRepositoryImpl.kt
2376667422
package com.fitness.data.repository.edamam import com.fitness.data.cache.RecipeCache import com.fitness.data.cache.RecipeDao import com.fitness.data.cache.RecipeFreshnessThreshold import com.fitness.data.cache.deserializeRecipeEntity import com.fitness.data.cache.serializeRecipeEntity import com.fitness.data.model.network.edamam.RecipeResponse import com.fitness.data.model.network.edamam.params.RecipeSearchParams import com.fitness.data.model.network.edamam.shared.PaginationDto import com.fitness.data.model.network.edamam.recipe.RecipeDto import com.fitness.data.network.EdamamRecipeService import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject class EdamamRecipeRepositoryImpl @Inject constructor( private val cache: RecipeDao, private val service: EdamamRecipeService ) : EdamamRecipeRepository { private var pagination: PaginationDto? = null override suspend fun fetchRecipes(params: RecipeSearchParams): List<RecipeDto> = coroutineScope{ val local = getResultsFromCache() val currentTime = System.currentTimeMillis() val isFresh = local.run { isNotEmpty() && all { currentTime - it.created <= RecipeFreshnessThreshold } } return@coroutineScope if (isFresh) { local.map { deserializeRecipeEntity(it.json) } } else { [email protected](params) .hits?.mapNotNull { it.recipe }?.also { launch { clearAll() cacheAutoSearchResults(it) } } ?: emptyList() } } override suspend fun search(params: RecipeSearchParams): List<RecipeDto> = this.fetchRecipesFromBackend(params).run { pagination = links hits?.let { val recipes = it.mapNotNull { hit -> hit.recipe } recipes } ?: emptyList() } private suspend fun fetchRecipesFromBackend(params: RecipeSearchParams): RecipeResponse = service.getRecipes( type = params.type, query = params.query, ingredients = params.ingredients, diet = params.diet, health = params.health, cuisineType = params.cuisineType, mealType = params.mealType, dishType = params.dishType, calories = params.calories, time = params.time, imageSize = params.imageSize, glycemicIndex = params.glycemicIndex, excluded = params.excluded, random = params.random, co2EmissionsClass = params.co2EmissionsClass, tag = params.tag, language = params.language ) override suspend fun fetchRecipesByUri( type: String, uri: List<String>, language: String?, ): List<RecipeDto> = TODO() override suspend fun fetchRecipesById( type: String, id: String, language: String?, ): List<RecipeDto> = TODO() private suspend fun getResultsFromCache(): List<RecipeCache> = withContext(IO) { cache.getAll() } private suspend fun cacheAutoSearchResults(recipes: List<RecipeDto>) = withContext(IO) { recipes.forEach { val recipeCache = RecipeCache( created = System.currentTimeMillis(), json = serializeRecipeEntity(it) ) cache.insertAll(recipeCache) } } private suspend fun clearAll() = withContext(IO) { cache.clearAll() } private suspend fun delete(recipe: RecipeCache) = withContext(IO) { cache.delete(recipe) } }
body-balance/data/impl/src/main/kotlin/com/fitness/data/repository/edamam/EdamamRecipeRepositoryImpl.kt
4195034005
package com.fitness.data.repository.edamam import com.fitness.data.network.EdamamAutoCompleteService import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks import javax.inject.Inject class EdamamAutoCompleteRepositoryImpl @Inject constructor(private val service: EdamamAutoCompleteService): EdamamAutoCompleteRepository { override suspend fun autoComplete(q: String, limit: Int): Task<List<String>> = Tasks.forResult(service.autoComplete(q, limit)) }
body-balance/data/impl/src/main/kotlin/com/fitness/data/repository/edamam/EdamamAutoCompleteRepositoryImpl.kt
2494346119
package com.fitness.data.repository.nutrition import cache.firestore import com.fitness.data.model.cache.nutrition.NutritionEntity import com.google.android.gms.tasks.Tasks import com.google.firebase.firestore.FirebaseFirestore import state.DataState class NutritionRecordRepositoryImpl(private val firestore: FirebaseFirestore): NutritionRecordRepository { private companion object { const val NUTRITION_RECORD: String = "NUTRITION_RECORD" } override suspend fun createNutritionRecord(nutrition: NutritionEntity) : DataState<Unit> = firestore { firestore.collection(NUTRITION_RECORD) .document(nutrition.recordId) .set(nutrition) .onSuccessTask { Tasks.forResult(Unit) } } override suspend fun getEditableNutritionRecord(userId: String): DataState<List<NutritionEntity>> = firestore { firestore.collection(NUTRITION_RECORD) .whereEqualTo("userId", userId) .get() .onSuccessTask { Tasks.forResult(it.toObjects(NutritionEntity::class.java)) } } }
body-balance/data/impl/src/main/kotlin/com/fitness/data/repository/nutrition/NutritionRecordRepositoryImpl.kt
2286466800
package com.fitness.data.di import android.app.Application import androidx.room.Room import com.fitness.data.cache.LocalCache import com.fitness.data.cache.RecipeDao import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class LocalCacheModule { @Provides @Singleton fun provideLocalDB(application: Application): LocalCache = Room.databaseBuilder(application, LocalCache::class.java, "local-cache") .fallbackToDestructiveMigration() .build() @Provides @Singleton fun provideRecipeDao(cache: LocalCache): RecipeDao = cache.recipeDao() }
body-balance/data/impl/src/main/kotlin/com/fitness/data/di/LocalCacheModule.kt
975651202
package com.fitness.data.di import com.fitness.data.cache.RecipeDao import com.fitness.data.network.EdamamAutoCompleteService import com.fitness.data.network.EdamamFoodService import com.fitness.data.network.EdamamNutritionService import com.fitness.data.network.EdamamRecipeService import com.fitness.data.repository.auth.AuthRepositoryImpl import com.fitness.data.repository.user.UserRepositoryImpl import com.fitness.data.repository.auth.AuthRepository import com.fitness.data.repository.edamam.EdamamAutoCompleteRepository import com.fitness.data.repository.edamam.EdamamAutoCompleteRepositoryImpl import com.fitness.data.repository.edamam.EdamamFoodRepository import com.fitness.data.repository.edamam.EdamamFoodRepositoryImpl import com.fitness.data.repository.edamam.EdamamNutritionRepository import com.fitness.data.repository.edamam.EdamamNutritionRepositoryImpl import com.fitness.data.repository.edamam.EdamamRecipeRepository import com.fitness.data.repository.edamam.EdamamRecipeRepositoryImpl import com.fitness.data.repository.nutrition.NutritionRecordRepository import com.fitness.data.repository.nutrition.NutritionRecordRepositoryImpl import com.fitness.data.repository.user.UserRepository import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class RepositoryModule { @Provides @Singleton fun provideAuthRepository(firebaseAuth: FirebaseAuth): AuthRepository = AuthRepositoryImpl(firebaseAuth) @Provides @Singleton fun provideUserRepository(firebaseAuth: FirebaseAuth, firestore: FirebaseFirestore): UserRepository = UserRepositoryImpl(firebaseAuth, firestore) @Provides @Singleton fun provideEdamamAutoCompleteRepository(service: EdamamAutoCompleteService): EdamamAutoCompleteRepository = EdamamAutoCompleteRepositoryImpl(service = service) @Provides @Singleton fun provideEdamamFoodRepository(service: EdamamFoodService): EdamamFoodRepository = EdamamFoodRepositoryImpl(service = service) @Provides @Singleton fun provideEdamamNutritionRepository(service: EdamamNutritionService): EdamamNutritionRepository = EdamamNutritionRepositoryImpl(service = service) @Provides @Singleton fun provideEdamamRecipeRepository(recipeDao: RecipeDao, service: EdamamRecipeService): EdamamRecipeRepository = EdamamRecipeRepositoryImpl(cache = recipeDao, service = service) @Provides @Singleton fun provideNutritionRecordRepository(firestore: FirebaseFirestore): NutritionRecordRepository = NutritionRecordRepositoryImpl(firestore = firestore) }
body-balance/data/impl/src/main/kotlin/com/fitness/data/di/RepositoryModule.kt
2701704534
package com.fitness.data.di import android.content.Context import com.fitness.data.network.EdamamAutoCompleteService import com.fitness.data.network.EdamamFoodService import com.fitness.data.network.EdamamNutritionService import com.fitness.data.network.EdamamRecipeService import com.squareup.moshi.Moshi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import network.createHttpLoggingInterceptor import network.createMoshi import network.createOkHttpClient import network.createRetrofitWithMoshi import network.nutrition.NutritionInterceptor import network.nutrition.createNutritionInterceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import javax.inject.Named import javax.inject.Singleton private const val EDAMAM = "edamam-auto-complete" @Module @InstallIn(SingletonComponent::class) class RemoteModule { @Provides @Singleton @Named(value = EDAMAM) fun provideEdamamBaseUrl(): String = "https://api.edamam.com/" @Provides @Singleton fun provideMoshi(): Moshi = createMoshi() @Provides @Singleton fun provideNutritionInterceptor(): NutritionInterceptor = createNutritionInterceptor() @Provides @Singleton fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor = createHttpLoggingInterceptor(true) @Provides @Singleton fun provideOkHttpClient( @ApplicationContext context: Context, nutritionInterceptor: NutritionInterceptor, httpLoggingInterceptor: HttpLoggingInterceptor ) = createOkHttpClient(context = context, isCache = true, nutritionInterceptor, httpLoggingInterceptor) @Provides @Singleton fun provideAutoCompleteService( @Named(value = EDAMAM) baseUrl: String, moshi: Moshi, okHttpClient: OkHttpClient ): EdamamAutoCompleteService = createRetrofitWithMoshi(baseUrl = baseUrl, okHttpClient = okHttpClient, moshi = moshi) @Provides @Singleton fun provideFoodDatabaseService( @Named(value = EDAMAM) baseUrl: String, moshi: Moshi, okHttpClient: OkHttpClient ): EdamamFoodService = createRetrofitWithMoshi(baseUrl = baseUrl, okHttpClient = okHttpClient, moshi = moshi) @Provides @Singleton fun provideNutritionService( @Named(value = EDAMAM) baseUrl: String, moshi: Moshi, okHttpClient: OkHttpClient ): EdamamNutritionService = createRetrofitWithMoshi(baseUrl = baseUrl, okHttpClient = okHttpClient, moshi = moshi) @Provides @Singleton fun provideRecipeService( @Named(value = EDAMAM) baseUrl: String, moshi: Moshi, okHttpClient: OkHttpClient ): EdamamRecipeService = createRetrofitWithMoshi(baseUrl = baseUrl, okHttpClient = okHttpClient, moshi = moshi) }
body-balance/data/impl/src/main/kotlin/com/fitness/data/di/RemoteModule.kt
525913948
package com.fitness.data.cache import androidx.room.Database import androidx.room.RoomDatabase @Database( entities = [RecipeCache::class], version = 2 ) abstract class LocalCache : RoomDatabase() { abstract fun recipeDao(): RecipeDao }
body-balance/data/impl/src/main/kotlin/com/fitness/data/cache/LocalCache.kt
3300759112
package com.fitness.data.cache import com.fitness.data.model.network.edamam.recipe.RecipeDto import com.google.gson.Gson const val RecipeFreshnessThreshold = 86_400_000 fun serializeRecipeEntity(recipe: RecipeDto): String { val gson = Gson() return gson.toJson(recipe) } fun deserializeRecipeEntity(recipe: String): RecipeDto { val gson = Gson() return gson.fromJson(recipe, RecipeDto::class.java) }
body-balance/data/impl/src/main/kotlin/com/fitness/data/cache/LocalCacheUtil.kt
3563798431
package com.fitness.data.network import com.fitness.data.model.network.edamam.RecipeResponse import network.nutrition.Nutrition import network.nutrition.NutritionSource.RECIPE import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface EdamamRecipeService { @Nutrition(RECIPE) @GET(BASE_ENDPOINT) suspend fun getRecipes( @Query(TYPE_PARAM) type: String, @Query(QUERY_PARAM) query: String, @Query(INGREDIENTS_PARAM) ingredients: String?, @Query(DIET_PARAM) diet: List<String>?, @Query(HEALTH_PARAM) health: List<String>?, @Query(CUISINE_TYPE_PARAM) cuisineType: List<String>?, @Query(MEAL_TYPE_PARAM) mealType: List<String>?, @Query(DISH_TYPE_PARAM) dishType: List<String>?, @Query(CALORIES_PARAM) calories: String?, @Query(TIME_PARAM) time: String?, @Query(IMAGE_SIZE_PARAM) imageSize: List<String>?, @Query(GLYCEMIC_INDEX_PARAM) glycemicIndex: String?, @Query(EXCLUDED_PARAM) excluded: List<String>?, @Query(RANDOM_PARAM) random: String?, @Query(C02_EMISSION_PARAM) co2EmissionsClass: String?, @Query(TAG_PARAM) tag: List<String>?, @Query(ACCEPT_LANGUAGE_PARAM) language: String?, ): RecipeResponse @Nutrition(RECIPE) @GET("$BASE_ENDPOINT/$URI_ENDPOINT") suspend fun getRecipesByUri( @Query(TYPE_PARAM) type: String, @Query(URI_PARAM) uri: List<String>, @Query(ACCEPT_LANGUAGE_PARAM) language: String?, ): RecipeResponse @Nutrition(RECIPE) @GET("$BASE_ENDPOINT/{$ID_ENDPOINT}") suspend fun getRecipesById( @Query(TYPE_PARAM) type: String, @Path(ID_ENDPOINT) id: String, @Query(ACCEPT_LANGUAGE_PARAM) language: String?, ): RecipeResponse companion object { const val BASE_ENDPOINT = "api/recipes/v2" const val URI_ENDPOINT = "by-uri" const val ID_ENDPOINT = "id" const val URI_PARAM = "uri" const val TYPE_PARAM = "type" const val QUERY_PARAM = "q" const val INGREDIENTS_PARAM = "ingr" const val DIET_PARAM = "diet" const val HEALTH_PARAM = "health" const val CUISINE_TYPE_PARAM = "cuisineType" const val MEAL_TYPE_PARAM = "mealType" const val DISH_TYPE_PARAM = "dishType" const val CALORIES_PARAM = "calories" const val TIME_PARAM = "time" const val IMAGE_SIZE_PARAM = "imageSize" const val GLYCEMIC_INDEX_PARAM = "glycemicIndex" const val EXCLUDED_PARAM = "excluded" const val RANDOM_PARAM = "random" const val C02_EMISSION_PARAM = "co2EmissionsClass" const val TAG_PARAM = "tag" const val ACCEPT_LANGUAGE_PARAM = "Accept-Language" } }
body-balance/data/impl/src/main/kotlin/com/fitness/data/network/EdamamRecipeService.kt
706008344
package com.fitness.data.network import com.fitness.data.model.network.edamam.NutrientsResponse import network.nutrition.Nutrition import network.nutrition.NutritionSource import retrofit2.http.POST interface EdamamNutritionService { @Nutrition(NutritionSource.NUTRITION) @POST(NUTRIENTS_ENDPOINT) suspend fun getFoodNutrients(): NutrientsResponse companion object{ const val NUTRIENTS_ENDPOINT = "nutrients" const val INGREDIENTS_PARAM = "ingredients" const val QUANTITY_PARAM = "quantity" const val MEASUREMENT_URI_PARAM = "measureURI" const val QUALIFIERS_PARAM = "qualifiers" const val FOOD_ID_PARAM = "foodId" } }
body-balance/data/impl/src/main/kotlin/com/fitness/data/network/EdamamNutritionService.kt
3044578988
package com.fitness.data.network import retrofit2.http.GET import retrofit2.http.Query interface EdamamAutoCompleteService { @GET(AUTO_COMPLETE_ENDPOINT) suspend fun autoComplete(@Query(QUERY_PARAM) q: String, @Query(LIMIT_PARAM) limit: Int?) : List<String> companion object{ const val AUTO_COMPLETE_ENDPOINT = "auto-complete" const val QUERY_PARAM = "q" const val LIMIT_PARAM = "limit" } }
body-balance/data/impl/src/main/kotlin/com/fitness/data/network/EdamamAutoCompleteService.kt
2659923743
package com.fitness.data.network import com.fitness.data.model.network.edamam.FoodResponse import network.nutrition.Nutrition import network.nutrition.NutritionSource import retrofit2.http.GET import retrofit2.http.Query interface EdamamFoodService { @Nutrition(NutritionSource.FOOD) @GET(PARSER_ENDPOINT) suspend fun getAllFood(): FoodResponse @Nutrition(NutritionSource.FOOD) @GET(PARSER_ENDPOINT) suspend fun getFoodByIngredient( @Query(INGREDIENTS_PARAM) ingredient: String, @Query(HEALTH_PARAM) health: String?, @Query(CALORIES_PARAM) calories: String?, @Query(CATEGORY_PARAM) category: String?, ): FoodResponse @Nutrition(NutritionSource.FOOD) @GET(PARSER_ENDPOINT) suspend fun getFoodByBrand( @Query(BRAND_PARAM) brand: String, @Query(HEALTH_PARAM) health: String?, @Query(CALORIES_PARAM) calories: String?, @Query(CATEGORY_PARAM) category: String?, ): FoodResponse @Nutrition(NutritionSource.FOOD) @GET(PARSER_ENDPOINT) suspend fun getFoodByUpc(@Query(UPC_PARAM) upc: String): FoodResponse companion object { const val PARSER_ENDPOINT = "api/food-database/v2/parser" const val INGREDIENTS_PARAM = "ingr" const val BRAND_PARAM = "brand" const val UPC_PARAM = "upc" const val HEALTH_PARAM = "health" const val CALORIES_PARAM = "calories" const val CATEGORY_PARAM = "category" } }
body-balance/data/impl/src/main/kotlin/com/fitness/data/network/EdamamFoodService.kt
2804243081
package com.fitness.data.repository.auth import auth.PhoneAuthState import com.google.android.gms.tasks.Task import com.google.firebase.auth.AuthResult import kotlinx.coroutines.flow.Flow interface AuthRepository { suspend fun signInWithEmail(email: String, password: String): Task<AuthResult> suspend fun sendVerificationCode(phoneNumber: String): Flow<PhoneAuthState> suspend fun verifyPhoneNumberWithCode(verificationId: String, code: String): Task<AuthResult> suspend fun signUpWithEmail(firstname:String, lastname:String, email: String, password: String): Task<AuthResult> suspend fun sendPasswordResetEmail(email: String): Task<Unit> suspend fun signOut(): Unit }
body-balance/data/api/src/main/kotlin/com/fitness/data/repository/auth/AuthRepository.kt
936874858
package com.fitness.data.repository.user import com.fitness.data.model.cache.metrics.UserBodyMetricsCache import com.fitness.data.model.cache.metrics.UserRecommendedMacrosCache import com.fitness.data.model.cache.user.UserBasicGoalsInfoCache import com.fitness.data.model.cache.user.UserBasicInfoCache import com.fitness.data.model.cache.user.UserBasicNutritionInfoCache import com.fitness.data.model.cache.user.UserCache import com.fitness.data.model.cache.user.UserBasicFitnessLevelCache import com.fitness.data.model.cache.user.UserPreferencesCache import com.google.android.gms.tasks.Task import com.google.firebase.firestore.DocumentSnapshot import state.DataState interface UserRepository { suspend fun getCurrentUserId(): Task<String?> suspend fun createUser(user: UserCache): DataState<Unit> suspend fun readUser(id: String): DataState<DocumentSnapshot> suspend fun updateUser(id: String, map: Map<String, Any>): DataState<Unit> suspend fun deleteUser(id: String): DataState<Unit> suspend fun updateUserPreferences(id: String, preferences: UserPreferencesCache): DataState<Unit> suspend fun updateUserBodyMetrics(id: String, metrics: UserBodyMetricsCache): DataState<Unit> suspend fun updateUserRecommendedMetrics(id: String, macros: UserRecommendedMacrosCache): DataState<Unit> suspend fun createUserBasicInfo(info: UserBasicInfoCache): DataState<Unit> suspend fun readUserBasicInfo(id: String): DataState<DocumentSnapshot> suspend fun updateUserBasicInfo(id: String, map: Map<String, Any>): DataState<Unit> suspend fun deleteUserBasicInfo(id: String): DataState<Unit> suspend fun createBasicFitnessInfo(info: UserBasicFitnessLevelCache): DataState<Unit> suspend fun readBasicFitnessInfo(id: String): DataState<DocumentSnapshot> suspend fun updateBasicFitnessInfo(id: String, map: Map<String, Any>): DataState<Unit> suspend fun deleteBasicFitnessInfo(id: String): DataState<Unit> suspend fun createBasicNutritionInfo(info: UserBasicNutritionInfoCache): DataState<Unit> suspend fun readBasicNutritionInfo(id: String): DataState<DocumentSnapshot> suspend fun updateBasicNutritionInfo(id: String, map: Map<String, Any>): DataState<Unit> suspend fun deleteBasicNutritionInfo(id: String): DataState<Unit> suspend fun createUserBasicGoalsInfo(info: UserBasicGoalsInfoCache): DataState<Unit> suspend fun readUserBasicGoalsInfo(id: String): DataState<DocumentSnapshot> suspend fun updateUserBasicGoalsInfo(id: String, map: Map<String, Any>): DataState<Unit> suspend fun deleteUserBasicGoalsInfo(id: String): DataState<Unit> }
body-balance/data/api/src/main/kotlin/com/fitness/data/repository/user/UserRepository.kt
1351616180
package com.fitness.data.repository.edamam import com.google.android.gms.tasks.Task interface EdamamAutoCompleteRepository{ suspend fun autoComplete(q: String, limit: Int = 5): Task<List<String>> }
body-balance/data/api/src/main/kotlin/com/fitness/data/repository/edamam/EdamamAutoCompleteRepository.kt
1251395643
package com.fitness.data.repository.edamam import com.fitness.data.model.cache.nutrition.IngredientEntity import com.fitness.data.model.network.edamam.food.FoodDto import com.fitness.data.model.network.edamam.params.IngredientBrandParams import com.fitness.data.model.network.edamam.params.IngredientSearchParams import com.fitness.data.model.network.edamam.recipe.IngredientDto interface EdamamFoodRepository { suspend fun getAllFood(): List<IngredientEntity> suspend fun getFoodByIngredient(params: IngredientSearchParams): List<IngredientEntity> suspend fun getFoodByBrand(params: IngredientBrandParams): List<IngredientEntity> suspend fun getFoodByUpc(upc: String): List<IngredientEntity> }
body-balance/data/api/src/main/kotlin/com/fitness/data/repository/edamam/EdamamFoodRepository.kt
1214952247
package com.fitness.data.repository.edamam import com.fitness.data.model.network.edamam.params.RecipeSearchParams import com.fitness.data.model.network.edamam.recipe.RecipeDto interface EdamamRecipeRepository { suspend fun search(params: RecipeSearchParams): List<RecipeDto> suspend fun fetchRecipes(params: RecipeSearchParams): List<RecipeDto> suspend fun fetchRecipesByUri( type: String = "any", uri: List<String>, language: String? = null, ): List<RecipeDto> suspend fun fetchRecipesById( type: String = "any", id: String, language: String? = null, ): List<RecipeDto> }
body-balance/data/api/src/main/kotlin/com/fitness/data/repository/edamam/EdamamRecipeRepository.kt
3744207483
package com.fitness.data.repository.edamam import com.fitness.data.model.network.edamam.NutrientsResponse interface EdamamNutritionRepository { suspend fun getFoodNutrients(): NutrientsResponse }
body-balance/data/api/src/main/kotlin/com/fitness/data/repository/edamam/EdamamNutritionRepository.kt
2972436862
package com.fitness.data.repository.nutrition import com.fitness.data.model.cache.nutrition.NutritionEntity import state.DataState interface NutritionRecordRepository { suspend fun createNutritionRecord(nutrition: NutritionEntity): DataState<Unit> suspend fun getEditableNutritionRecord(userId: String): DataState<List<NutritionEntity>> }
body-balance/data/api/src/main/kotlin/com/fitness/data/repository/nutrition/NutritionRecordRepository.kt
274769730
package com.fitness.data.cache import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query @Dao interface RecipeDao { @Query("SELECT * FROM RecipeCache") suspend fun getAll(): List<RecipeCache> @Insert suspend fun insertAll(vararg recipes: RecipeCache) @Delete suspend fun delete(recipe: RecipeCache) @Query("DELETE FROM RecipeCache") suspend fun clearAll() }
body-balance/data/api/src/main/kotlin/com/fitness/data/cache/RecipeDao.kt
3537670849
package com.fitness.data.cache import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class RecipeCache(@PrimaryKey(autoGenerate = true) val id: Int? = null, val created: Long, val json: String)
body-balance/data/api/src/main/kotlin/com/fitness/data/cache/RecipeCache.kt
464263046
package com.fitness.data.util object TotalNutrientsKeys { const val KEY_CALCIUM = "ca" const val KEY_CARBOHYDRATES = "chocdf" const val KEY_NET_CARBS = "chocdfnet" const val KEY_CHOLESTEROL = "chole" const val KEY_ENERGY = "enerckcal" const val KEY_MONOUNSATURATED_FATS = "fams" const val KEY_POLYUNSATURATED_FATS = "fapu" const val KEY_SATURATED_FATS = "fasat" const val KEY_TOTAL_FAT = "fat" const val KEY_TRANS_FAT = "fatrn" const val KEY_IRON = "fe" const val KEY_FIBER = "fibtg" const val KEY_FOLIC_ACID = "folac" const val KEY_FOLATE_DFE = "foldfe" const val KEY_FOOD_FOLATE = "folfd" const val KEY_POTASSIUM = "k" const val KEY_MAGNESIUM = "mg" const val KEY_SODIUM = "na" const val KEY_NIACIN = "nia" const val KEY_PHOSPHORUS = "p" const val KEY_PROTEIN = "procnt" const val KEY_RIBOFLAVIN = "ribf" const val KEY_SUGARS = "sugar" const val KEY_ADDED_SUGARS = "sugaradded" const val KEY_THIAMIN = "thia" const val KEY_VITAMIN_E = "tocpaha" const val KEY_VITAMIN_A = "vitarAE" const val KEY_VITAMIN_B12 = "vitb12" const val KEY_VITAMIN_B6 = "vitb6a" const val KEY_VITAMIN_C = "vitc" const val KEY_VITAMIN_D = "vitd" const val KEY_VITAMIN_K1 = "vitk1" const val KEY_WATER = "water" const val KEY_ZINC = "zn" }
body-balance/data/api/src/main/kotlin/com/fitness/data/util/TotalNutrientsKeys.kt
1524115027
package com.fitness.data.extensions import enums.ECuisineType import enums.EDietaryRestrictions import enums.EHealthLabel import enums.safeEnumValueOf @JvmName("toEnumNameFromEDietaryRestrictionsList") fun List<EDietaryRestrictions>.toEnumName(): List<String> = mapNotNull { it.name } @JvmName("toEnumNameFromEHealthLabelList") fun List<EHealthLabel>.toEnumName(): List<String> = mapNotNull { it.name } @JvmName("toEnumNameFromECuisineTypeList") fun List<ECuisineType>.toEnumName(): List<String> = mapNotNull { it.name } fun List<EHealthLabel>.toApiParamFromEHealthLabel(): List<String> = mapNotNull { it.apiParameter } fun List<ECuisineType>.toApiParamFromECuisineType(): List<String> = mapNotNull { it.apiParameter } fun List<String>.toDietaryRestrictions(): List<EDietaryRestrictions> = mapNotNull { safeEnumValueOf<EDietaryRestrictions>(it) } fun List<String>.toHealthLabel(): List<EHealthLabel> = mapNotNull { safeEnumValueOf<EHealthLabel>(it) } fun List<String>.toCuisineType(): List<ECuisineType> = mapNotNull { safeEnumValueOf<ECuisineType>(it) }
body-balance/data/api/src/main/kotlin/com/fitness/data/extensions/UserExtensions.kt
3674586860
package com.fitness.data.extensions import cache.generateUniqueId import com.fitness.data.model.cache.nutrition.IngredientEntity import com.fitness.data.model.cache.nutrition.MeasureEntity import com.fitness.data.model.cache.nutrition.NutrientEntity import com.fitness.data.model.cache.nutrition.QualifiedEntity import com.fitness.data.model.cache.nutrition.QualifierEntity import com.fitness.data.model.cache.nutrition.RecipeEntity import com.fitness.data.model.network.edamam.food.FoodDto import com.fitness.data.model.network.edamam.food.MeasureDto import com.fitness.data.model.network.edamam.food.NutrientsDto import com.fitness.data.model.network.edamam.NutrientsResponse import com.fitness.data.model.network.edamam.food.QualifiedDto import com.fitness.data.model.network.edamam.food.QualifierDto import com.fitness.data.model.network.edamam.recipe.IngredientDto import com.fitness.data.model.network.edamam.recipe.RecipeDto import com.fitness.data.model.network.edamam.shared.TotalNutrientsDto import com.fitness.data.util.TotalNutrientsKeys fun RecipeDto.toRecipeEntity(userId: String): RecipeEntity = RecipeEntity( calories = calories, cautions = cautions, cuisineType = cuisineType, dietLabels = dietLabels, dishType = dishType, healthLabels = healthLabels, standardImage = image, large = images?.large?.url, regular = images?.regular?.url, small = images?.small?.url, thumbnail = images?.thumbnail?.url, ingredientLines = ingredientLines, label = label, mealType = mealType, shareAs = shareAs, source = source, tags = tags, totalTime = totalTime, totalWeight = totalWeight, recipeUri = uri, recipeUrl = url, yield = yield, ingredients = ingredients?.map { it.toIngredientEntity() }, nutrients = totalNutrients?.toTotalNutrientsEntity(), recipeId = generateUniqueId("$userId-$uri"), ) fun IngredientDto.toIngredientEntity(): IngredientEntity = IngredientEntity( foodId = foodId, name = food, categoryName = foodCategory, image = image, measureName = measure, quantity = quantity, detailed = text, weight = weight, ) fun TotalNutrientsDto.toTotalNutrientsEntity(): Map<String, NutrientEntity> = mapOf( TotalNutrientsKeys.KEY_CALCIUM to NutrientEntity(ca?.label ?: "", ca?.quantity ?: 0.0, ca?.unit ?: ""), TotalNutrientsKeys.KEY_CARBOHYDRATES to NutrientEntity(chocdf?.label ?: "", chocdf?.quantity ?: 0.0, chocdf?.unit ?: ""), TotalNutrientsKeys.KEY_NET_CARBS to NutrientEntity(chocdfnet?.label ?: "", chocdfnet?.quantity ?: 0.0, chocdfnet?.unit ?: ""), TotalNutrientsKeys.KEY_CHOLESTEROL to NutrientEntity(chole?.label ?: "", chole?.quantity ?: 0.0, chole?.unit ?: ""), TotalNutrientsKeys.KEY_ENERGY to NutrientEntity(enerckcal?.label ?: "", enerckcal?.quantity ?: 0.0, enerckcal?.unit ?: ""), TotalNutrientsKeys.KEY_MONOUNSATURATED_FATS to NutrientEntity(fams?.label ?: "", fams?.quantity ?: 0.0, fams?.unit ?: ""), TotalNutrientsKeys.KEY_POLYUNSATURATED_FATS to NutrientEntity(fapu?.label ?: "", fapu?.quantity ?: 0.0, fapu?.unit ?: ""), TotalNutrientsKeys.KEY_SATURATED_FATS to NutrientEntity(fasat?.label ?: "", fasat?.quantity ?: 0.0, fasat?.unit ?: ""), TotalNutrientsKeys.KEY_TOTAL_FAT to NutrientEntity(fat?.label ?: "", fat?.quantity ?: 0.0, fat?.unit ?: ""), TotalNutrientsKeys.KEY_TRANS_FAT to NutrientEntity(fatrn?.label ?: "", fatrn?.quantity ?: 0.0, fatrn?.unit ?: ""), TotalNutrientsKeys.KEY_IRON to NutrientEntity(fe?.label ?: "", fe?.quantity ?: 0.0, fe?.unit ?: ""), TotalNutrientsKeys.KEY_FIBER to NutrientEntity(fibtg?.label ?: "", fibtg?.quantity ?: 0.0, fibtg?.unit ?: ""), TotalNutrientsKeys.KEY_FOLIC_ACID to NutrientEntity(folac?.label ?: "", folac?.quantity ?: 0.0, folac?.unit ?: ""), TotalNutrientsKeys.KEY_FOLATE_DFE to NutrientEntity(foldfe?.label ?: "", foldfe?.quantity ?: 0.0, foldfe?.unit ?: ""), TotalNutrientsKeys.KEY_FOOD_FOLATE to NutrientEntity(folfd?.label ?: "", folfd?.quantity ?: 0.0, folfd?.unit ?: ""), TotalNutrientsKeys.KEY_POTASSIUM to NutrientEntity(k?.label ?: "", k?.quantity ?: 0.0, k?.unit ?: ""), TotalNutrientsKeys.KEY_MAGNESIUM to NutrientEntity(mg?.label ?: "", mg?.quantity ?: 0.0, mg?.unit ?: ""), TotalNutrientsKeys.KEY_SODIUM to NutrientEntity(na?.label ?: "", na?.quantity ?: 0.0, na?.unit ?: ""), TotalNutrientsKeys.KEY_NIACIN to NutrientEntity(nia?.label ?: "", nia?.quantity ?: 0.0, nia?.unit ?: ""), TotalNutrientsKeys.KEY_PHOSPHORUS to NutrientEntity(p?.label ?: "", p?.quantity ?: 0.0, p?.unit ?: ""), TotalNutrientsKeys.KEY_PROTEIN to NutrientEntity(procnt?.label ?: "", procnt?.quantity ?: 0.0, procnt?.unit ?: ""), TotalNutrientsKeys.KEY_RIBOFLAVIN to NutrientEntity(ribf?.label ?: "", ribf?.quantity ?: 0.0, ribf?.unit ?: ""), TotalNutrientsKeys.KEY_SUGARS to NutrientEntity(sugar?.label ?: "", sugar?.quantity ?: 0.0, sugar?.unit ?: ""), TotalNutrientsKeys.KEY_ADDED_SUGARS to NutrientEntity(sugaradded?.label ?: "", sugaradded?.quantity ?: 0.0, sugaradded?.unit ?: ""), TotalNutrientsKeys.KEY_THIAMIN to NutrientEntity(thia?.label ?: "", thia?.quantity ?: 0.0, thia?.unit ?: ""), TotalNutrientsKeys.KEY_VITAMIN_E to NutrientEntity(tocpaha?.label ?: "", tocpaha?.quantity ?: 0.0, tocpaha?.unit ?: ""), TotalNutrientsKeys.KEY_VITAMIN_A to NutrientEntity(vitarAE?.label ?: "", vitarAE?.quantity ?: 0.0, vitarAE?.unit ?: ""), TotalNutrientsKeys.KEY_VITAMIN_B12 to NutrientEntity(vitb12?.label ?: "", vitb12?.quantity ?: 0.0, vitb12?.unit ?: ""), TotalNutrientsKeys.KEY_VITAMIN_B6 to NutrientEntity(vitb6a?.label ?: "", vitb6a?.quantity ?: 0.0, vitb6a?.unit ?: ""), TotalNutrientsKeys.KEY_VITAMIN_C to NutrientEntity(vitc?.label ?: "", vitc?.quantity ?: 0.0, vitc?.unit ?: ""), TotalNutrientsKeys.KEY_VITAMIN_D to NutrientEntity(vitd?.label ?: "", vitd?.quantity ?: 0.0, vitd?.unit ?: ""), TotalNutrientsKeys.KEY_VITAMIN_K1 to NutrientEntity(vitk1?.label ?: "", vitk1?.quantity ?: 0.0, vitk1?.unit ?: ""), TotalNutrientsKeys.KEY_WATER to NutrientEntity(water?.label ?: "", water?.quantity ?: 0.0, water?.unit ?: ""), TotalNutrientsKeys.KEY_ZINC to NutrientEntity(zn?.label ?: "", zn?.quantity ?: 0.0, zn?.unit ?: "") ) fun FoodDto.toIngredientEntity(measures: List<MeasureDto?>?): IngredientEntity = IngredientEntity( name = label, image = image, foodId = foodId, category = category, categoryName = categoryLabel, measures = measures?.mapNotNull { it?.toMeasureEntity() }, nutrients = nutrients?.toTotalNutrientsEntity(), ) fun MeasureDto.toMeasureEntity(): MeasureEntity = MeasureEntity( label = this.label, qualified = this.qualified?.mapNotNull { it?.toEntity() }, uri = this.uri, weight = this.weight ) fun QualifiedDto.toEntity(): QualifiedEntity = QualifiedEntity( qualifiers = this.qualifiers?.mapNotNull { it?.toEntity() }, weight = this.weight ) fun QualifierDto.toEntity(): QualifierEntity { return QualifierEntity( label = this.label, uri = this.uri ) } fun NutrientsDto.toTotalNutrientsEntity(): Map<String, NutrientEntity> = mapOf( TotalNutrientsKeys.KEY_CARBOHYDRATES to NutrientEntity(TotalNutrientsKeys.KEY_CARBOHYDRATES, chocdf ?: 0.0, ""), TotalNutrientsKeys.KEY_ENERGY to NutrientEntity(TotalNutrientsKeys.KEY_ENERGY, enerckcal ?: 0.0, ""), TotalNutrientsKeys.KEY_TOTAL_FAT to NutrientEntity(TotalNutrientsKeys.KEY_TOTAL_FAT, fat ?: 0.0, ""), TotalNutrientsKeys.KEY_FIBER to NutrientEntity(TotalNutrientsKeys.KEY_FIBER, fibtg ?: 0.0, ""), TotalNutrientsKeys.KEY_PROTEIN to NutrientEntity(TotalNutrientsKeys.KEY_PROTEIN, procnt ?: 0.0, "") ) fun IngredientEntity.updateSelf(nutrients: NutrientsResponse?): IngredientEntity = copy( cautions = nutrients?.cautions, dietLabels = nutrients?.dietLabels, healthLabels = nutrients?.healthLabels, nutrients = nutrients?.totalNutrients?.toTotalNutrientsEntity(), weight = nutrients?.totalWeight, totalWeight = nutrients?.totalWeight )
body-balance/data/api/src/main/kotlin/com/fitness/data/extensions/NutritionDataExtensions.kt
1456977366
package com.fitness.data.model.cache.metrics data class UserBodyMetricsCache ( val userId: String, val bodyMassIndex: Double, val bodyFatPercentage: Double, val basalMetabolicRate: Double )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/metrics/UserBodyMetricsCache.kt
1011347202
package com.fitness.data.model.cache.metrics data class UserRecommendedMacrosCache ( val userId: String, val fat: Double, val protein: Double, val calories: Double, val totalDailyEnergyExpenditure: Double, val carbohydrates: Double, val fiber: Double )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/metrics/UserRecommendedMacrosCache.kt
1573888166
package com.fitness.data.model.cache.user data class UserBasicNutritionInfoCache( val userId: String = "", val restrictions: List<String> = emptyList(), val healthLabels: List<String> = emptyList(), val healthLabelsApi: List<String> = emptyList(), val cuisineType: List<String> = emptyList(), val cuisineTypeApi: List<String> = emptyList(), val lastUpdated: Long = 0L, )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/user/UserBasicNutritionInfoCache.kt
1645641182
package com.fitness.data.model.cache.user import enums.EFitnessInterest import enums.EPhysicalActivityLevel data class UserBasicFitnessLevelCache( val userId: String, val level: EPhysicalActivityLevel, val habits: List<EFitnessInterest>, val lastUpdated: Long, )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/user/UserBasicFitnessLevelCache.kt
897622430
package com.fitness.data.model.cache.user data class UserCache( val id: String = "", val displayName: String? = "", val email: String? = "", val phoneNumber: String? = "", val profilePictureUrl: String? = "", val isTermAndPrivacyAccepted: Boolean = false, val lastUpdated: Long = 0L, val isNewUser: Boolean = false, val userPreferences:UserPreferencesCache? = null )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/user/UserCache.kt
331965838
package com.fitness.data.model.cache.user import enums.EGender import enums.ELengthUnit import enums.EMassUnit import enums.SystemOfMeasurement data class UserBasicInfoCache( val userId: String = "", val age: Int = 0, val gender: EGender = EGender.MALE, val height: Double = 0.0, val weight: Double = 0.0, val waist: Double = 0.0, val lastUpdated: Long = 1L, )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/user/UserBasicInfoCache.kt
1791948363
package com.fitness.data.model.cache.user import enums.SystemOfMeasurement data class UserPreferencesCache(val systemOfMeasurement: SystemOfMeasurement = SystemOfMeasurement.METRIC)
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/user/UserPreferencesCache.kt
600931553
package com.fitness.data.model.cache.user import enums.EGoals data class UserBasicGoalsInfoCache( val userId: String, val goals: List<EGoals>, val lastUpdated: Long, )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/user/UserBasicGoalsInfoCache.kt
4025373830
package com.fitness.data.model.cache.nutrition data class QualifiedEntity( val qualifiers: List<QualifierEntity>? = null, val weight: Double? = null )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/nutrition/QualifiedEntity.kt
971535605
package com.fitness.data.model.cache.nutrition data class RecipeEntity( val recipeId: String = "", val calories: Double? = null, val cautions: List<String>? = null, val cuisineType: List<String>? = null, val dietLabels: List<String>? = null, val dishType: List<String>? = null, val healthLabels: List<String>? = null, val standardImage: String? = null, val large: String? = null, val regular: String? = null, val small: String? = null, val thumbnail: String? = null, val ingredientLines: List<String>? = null, val instructionLines: List<String>? = null, val label: String? = null, val mealType: List<String>? = null, val shareAs: String? = null, val source: String? = null, val tags: List<String>? = null, val totalTime: Double? = null, val totalWeight: Double? = null, val recipeUri: String? = null, val recipeUrl: String? = null, val yield: Double? = null, val ingredients: List<IngredientEntity>? = null, val nutrients: Map<String, NutrientEntity>? = null )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/nutrition/RecipeEntity.kt
89307356
package com.fitness.data.model.cache.nutrition data class NutrientEntity( val label: String = "", val quantity: Double = 0.0, val unit: String = "" )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/nutrition/NutrientEntity.kt
3737437864
package com.fitness.data.model.cache.nutrition import enums.EMealType data class NutritionEntity( val recordId: String = "", val userId: String = "", val dateTime: String = "", val mealType: EMealType = EMealType.BREAKFAST, val recipe: RecipeEntity = RecipeEntity(""), )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/nutrition/NutritionEntity.kt
3012103041
package com.fitness.data.model.cache.nutrition data class QualifierEntity( val label: String? = null, val uri: String? = null )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/nutrition/QualifierEntity.kt
2972113792
package com.fitness.data.model.cache.nutrition data class IngredientEntity( val name: String? = null, val foodId: String? = null, val image: String? = null, val quantity: Double? = null, val detailed: String? = null, val weight: Double? = null, val uri: String? = null, val category: String? = null, val categoryName: String? = null, val cautions: List<String>? = null, val dietLabels: List<String>? = null, val healthLabels: List<String>? = null, val totalWeight: Double? = null, val qualifiedUri: String? = null, // The qualified uri that corresponds with the name for selected qualifier. Value determined based on what qualified name user chooses. val qualifiedName: String? = null, // if available represents teh different states the ingredient can be in which affect the final weight. For instance cheese can be sliced, shredded, melted etc val qualifiedWeight: Double? = null, // The qualified weight for selected qualifier. Value determined based on what qualifier the user chooses. val measureUri: String? = null, // The measure uri that corresponds with the name (cup, tablespoon, etc) for selected measure. Value determined based on what measure name user chooses. val measureName: String? = null, // The measure name (cup, tablespoon, etc) for selected measure. Value determined by user. val measureWeight: Double? = null, // The measure weight for selected measure. Value determined based on what measure name user chooses. val measures: List<MeasureEntity>? = null, val nutrients: Map<String, NutrientEntity>? = null )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/nutrition/IngredientEntity.kt
576697504
package com.fitness.data.model.cache.nutrition data class MeasureEntity( val label: String? = null, val qualified: List<QualifiedEntity>? = null, val uri: String? = null, val weight: Double? = null )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/cache/nutrition/MeasureEntity.kt
365480617
package com.fitness.data.model.network.edamam import com.fitness.data.model.network.edamam.recipe.HitDto import com.fitness.data.model.network.edamam.shared.PaginationDto import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class RecipeResponse( val hits: List<HitDto>?, @Json(name = "_links") val links: PaginationDto? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/RecipeResponse.kt
2167731569
package com.fitness.data.model.network.edamam import com.fitness.data.model.network.edamam.shared.TotalNutrientsDto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class NutrientsResponse( val calories: Int? = null, val cautions: List<String>? = null, val dietLabels: List<String>? = null, val healthLabels: List<String>? = null, val totalNutrients: TotalNutrientsDto? = null, val totalWeight: Double? = null, val uri: String? = null )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/NutrientsResponse.kt
154218741
package com.fitness.data.model.network.edamam import com.fitness.data.model.network.edamam.food.FoodDataDto import com.fitness.data.model.network.edamam.shared.PaginationDto import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class FoodResponse( val hints: List<FoodDataDto>? = listOf(), @Json(name = "_links") val links: PaginationDto ? = null, )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/FoodResponse.kt
1649365156
package com.fitness.data.model.network.edamam.recipe import com.fitness.data.model.network.edamam.shared.TotalDailyDto import com.fitness.data.model.network.edamam.shared.TotalNutrientsDto import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class RecipeDto( val calories: Double?, val cautions: List<String>?, val co2EmissionsClass: String?, val cuisineType: List<String>?, val dietLabels: List<String>?, val digest: List<DigestDto>?, val dishType: List<String>?, val healthLabels: List<String>?, val image: String?, val images: ImagesDto?, val ingredientLines: List<String>?, val ingredients: List<IngredientDto>?, val label: String?, val mealType: List<String>?, val shareAs: String?, val source: String?, val tags: List<String>?, val totalDaily: TotalDailyDto?, val totalNutrients: TotalNutrientsDto?, val totalTime: Double?, val totalWeight: Double?, val uri: String?, val url: String?, val yield: Double? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/recipe/RecipeDto.kt
3875891539
package com.fitness.data.model.network.edamam.recipe import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class DigestDto( val daily: Double?, val hasRDI: Boolean?, val label: String?, val schemaOrgTag: String?, val sub: List<SubDto>?, val tag: String?, val total: Double?, val unit: String? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/recipe/DigestDto.kt
1134582588
package com.fitness.data.model.network.edamam.recipe import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class SubDto( val daily: Double?, val hasRDI: Boolean?, val label: String?, val schemaOrgTag: String?, val tag: String?, val total: Double?, val unit: String? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/recipe/SubDto.kt
4121803727
package com.fitness.data.model.network.edamam.recipe data class ImageMetaDataDto( val height: Int?, val url: String?, val width: Int? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/recipe/ImageMetaDataDto.kt
2038527327
package com.fitness.data.model.network.edamam.recipe import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class HitDto( val recipe: RecipeDto? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/recipe/HitDto.kt
2442651596
package com.fitness.data.model.network.edamam.recipe import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class IngredientDto( val food: String?, val foodCategory: String?, val foodId: String?, val image: String?, val measure: String?, val quantity: Double?, val text: String?, val weight: Double? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/recipe/IngredientDto.kt
1163035455
package com.fitness.data.model.network.edamam.recipe import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class ImagesDto( @Json(name = "LARGE") val large: ImageMetaDataDto?, @Json(name = "REGULAR") val regular: ImageMetaDataDto?, @Json(name = "SMALL") val small: ImageMetaDataDto?, @Json(name = "THUMBNAIL") val thumbnail: ImageMetaDataDto? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/recipe/ImagesDto.kt
597857695
package com.fitness.data.model.network.edamam.shared import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class TotalNutrientsDto( @Json(name = "CA") val ca: NutrientsMetaDataDto?, @Json(name = "CHOCDF") val chocdf: NutrientsMetaDataDto?, @Json(name = "CHOCDF.net") val chocdfnet: NutrientsMetaDataDto?, @Json(name = "CHOLE") val chole: NutrientsMetaDataDto?, @Json(name = "ENERC_KCAL") val enerckcal: NutrientsMetaDataDto?, @Json(name = "FAMS") val fams: NutrientsMetaDataDto?, @Json(name = "FAPU") val fapu: NutrientsMetaDataDto?, @Json(name = "FASAT") val fasat: NutrientsMetaDataDto?, @Json(name = "FAT") val fat: NutrientsMetaDataDto?, @Json(name = "FATRN") val fatrn: NutrientsMetaDataDto?, @Json(name = "FE") val fe: NutrientsMetaDataDto?, @Json(name = "FIBTG") val fibtg: NutrientsMetaDataDto?, @Json(name = "FOLAC") val folac: NutrientsMetaDataDto?, @Json(name = "FOLDFE") val foldfe: NutrientsMetaDataDto?, @Json(name = "FOLFD") val folfd: NutrientsMetaDataDto?, @Json(name = "K") val k: NutrientsMetaDataDto?, @Json(name = "MG") val mg: NutrientsMetaDataDto?, @Json(name = "NA") val na: NutrientsMetaDataDto?, @Json(name = "NIA") val nia: NutrientsMetaDataDto?, @Json(name = "P") val p: NutrientsMetaDataDto?, @Json(name = "PROCNT") val procnt: NutrientsMetaDataDto?, @Json(name = "RIBF") val ribf: NutrientsMetaDataDto?, @Json(name = "SUGAR") val sugar: NutrientsMetaDataDto?, @Json(name = "SUGAR.added") val sugaradded: NutrientsMetaDataDto?, @Json(name = "THIA") val thia: NutrientsMetaDataDto?, @Json(name = "TOCPHA") val tocpaha: NutrientsMetaDataDto?, @Json(name = "VITA_RAE") val vitarAE: NutrientsMetaDataDto?, @Json(name = "VITB12") val vitb12: NutrientsMetaDataDto?, @Json(name = "VITB6A") val vitb6a: NutrientsMetaDataDto?, @Json(name = "VITC") val vitc: NutrientsMetaDataDto?, @Json(name = "VITD") val vitd: NutrientsMetaDataDto?, @Json(name = "VITK1") val vitk1: NutrientsMetaDataDto?, @Json(name = "WATER") val water: NutrientsMetaDataDto?, @Json(name = "ZN") val zn: NutrientsMetaDataDto?, )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/shared/TotalNutrientsDto.kt
3074087046
package com.fitness.data.model.network.edamam.shared import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class NextDto( val href: String?, val title: String? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/shared/NextDto.kt
1678617312
package com.fitness.data.model.network.edamam.shared import android.os.Parcelable import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import kotlinx.parcelize.Parcelize @Parcelize @JsonClass(generateAdapter = true) data class NutrientsMetaDataDto( @Json(name = "label") val label: String?, @Json(name = "quantity") val quantity: Double?, @Json(name = "unit") val unit: String? ) : Parcelable
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/shared/NutrientsMetaDataDto.kt
3181356020
package com.fitness.data.model.network.edamam.shared import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class PaginationDto( val next: NextDto? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/shared/PaginationDto.kt
2580206707
package com.fitness.data.model.network.edamam.shared import com.fitness.data.model.network.edamam.shared.NutrientsMetaDataDto import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class TotalDailyDto( @Json(name = "CA") val ca: NutrientsMetaDataDto?, @Json(name = "CHOCDF") val chocdf: NutrientsMetaDataDto?, @Json(name = "CHOLE") val chole: NutrientsMetaDataDto?, @Json(name = "ENERC_KCAL") val enerckcal: NutrientsMetaDataDto?, @Json(name = "FASAT") val fasat: NutrientsMetaDataDto?, @Json(name = "FAT") val fat: NutrientsMetaDataDto?, @Json(name = "FE") val fe: NutrientsMetaDataDto?, @Json(name = "FIBTG") val fibtg: NutrientsMetaDataDto?, @Json(name = "FOLDFE") val foldfe: NutrientsMetaDataDto?, @Json(name = "K") val k: NutrientsMetaDataDto?, @Json(name = "MG") val mg: NutrientsMetaDataDto?, @Json(name = "NA") val na: NutrientsMetaDataDto?, @Json(name = "NIA") val nia: NutrientsMetaDataDto?, @Json(name = "P") val p: NutrientsMetaDataDto?, @Json(name = "PROCNT") val procnt: NutrientsMetaDataDto?, @Json(name = "RIBF") val ribf: NutrientsMetaDataDto?, @Json(name = "THIA") val thia: NutrientsMetaDataDto?, @Json(name = "TOCPHA") val tocpaha: NutrientsMetaDataDto?, @Json(name = "VITA_RAE") val vitarae: NutrientsMetaDataDto?, @Json(name = "VITB12") val vitb12: NutrientsMetaDataDto?, @Json(name = "VITB6A") val vitb6a: NutrientsMetaDataDto?, @Json(name = "VITC") val vitc: NutrientsMetaDataDto?, @Json(name = "VITD") val vitd: NutrientsMetaDataDto?, @Json(name = "VITK1") val vitk1: NutrientsMetaDataDto?, @Json(name = "ZN") val zn: NutrientsMetaDataDto? )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/shared/TotalDailyDto.kt
1545225314
package com.fitness.data.model.network.edamam.params data class IngredientBrandParams( val brand: String, val health: String? = null, val calories: String? = null, val category: String? = null, )
body-balance/data/api/src/main/kotlin/com/fitness/data/model/network/edamam/params/IngredientBrandParams.kt
930962279