content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package ch.epfl.skysync.models.flight import ch.epfl.skysync.models.calendar.TimeSlot import java.time.LocalDate interface Flight { val nPassengers: Int val team: Team val flightType: FlightType val balloon: Balloon? // might not yet be defined on flight creation val basket: Basket? // might not yet be defined on flight creation val date: LocalDate val timeSlot: TimeSlot val vehicles: List<Vehicle> val id: String /** @return the status of the flight */ fun getFlightStatus(): FlightStatus }
skysync/app/src/main/java/ch/epfl/skysync/models/flight/Flight.kt
810084085
package ch.epfl.skysync.models.flight enum class FlightColor { RED, BLUE, ORANGE, YELLOW, PINK, NO_COLOR }
skysync/app/src/main/java/ch/epfl/skysync/models/flight/FlightColor.kt
452221560
package ch.epfl.skysync.models.message import ch.epfl.skysync.models.UNSET_ID import java.util.Date /** * Represents a message * * @param userId The ID of the user who sent the message * @param date Date at which the message was sent * @param content The content of the message */ data class Message( val id: String = UNSET_ID, val userId: String, val date: Date, val content: String, )
skysync/app/src/main/java/ch/epfl/skysync/models/message/Message.kt
1445909029
package ch.epfl.skysync.models.message import ch.epfl.skysync.models.UNSET_ID /** * Represents a message group * * @param userIds The list of IDs of the users in the group, this can be useful to add/remove users * to/from the group * @param messages A list of messages sent in the group */ data class MessageGroup( val id: String = UNSET_ID, val userIds: Set<String> = setOf(), val messages: List<Message> = listOf() )
skysync/app/src/main/java/ch/epfl/skysync/models/message/MessageGroup.kt
457291538
package ch.epfl.skysync.models.user import ch.epfl.skysync.models.UNSET_ID import ch.epfl.skysync.models.calendar.AvailabilityCalendar import ch.epfl.skysync.models.calendar.FlightGroupCalendar import ch.epfl.skysync.models.flight.RoleType data class Crew( override val id: String = UNSET_ID, override val firstname: String, override val lastname: String, override val availabilities: AvailabilityCalendar, override val assignedFlights: FlightGroupCalendar, override val roleTypes: Set<RoleType> = setOf(RoleType.CREW), ) : User { override fun addRoleType(roleType: RoleType): Crew { return this.copy(roleTypes = roleTypes + roleType) } }
skysync/app/src/main/java/ch/epfl/skysync/models/user/Crew.kt
2508064919
package ch.epfl.skysync.models.user import ch.epfl.skysync.models.UNSET_ID import ch.epfl.skysync.models.calendar.AvailabilityCalendar import ch.epfl.skysync.models.calendar.FlightGroupCalendar import ch.epfl.skysync.models.flight.RoleType data class Admin( override val id: String = UNSET_ID, override val firstname: String, override val lastname: String, override val availabilities: AvailabilityCalendar, override val assignedFlights: FlightGroupCalendar, override val roleTypes: Set<RoleType> = setOf(), ) : User { override fun addRoleType(roleType: RoleType): Admin { return this.copy(roleTypes = roleTypes + roleType) } }
skysync/app/src/main/java/ch/epfl/skysync/models/user/Admin.kt
2438407485
package ch.epfl.skysync.models.user import ch.epfl.skysync.models.UNSET_ID import ch.epfl.skysync.models.calendar.AvailabilityCalendar import ch.epfl.skysync.models.calendar.FlightGroupCalendar import ch.epfl.skysync.models.flight.BalloonQualification import ch.epfl.skysync.models.flight.RoleType data class Pilot( override val id: String = UNSET_ID, override val firstname: String, override val lastname: String, override val availabilities: AvailabilityCalendar, override val assignedFlights: FlightGroupCalendar, override val roleTypes: Set<RoleType> = setOf(RoleType.CREW, RoleType.PILOT), val qualification: BalloonQualification, ) : User { override fun addRoleType(roleType: RoleType): Pilot { return this.copy(roleTypes = roleTypes + roleType) } }
skysync/app/src/main/java/ch/epfl/skysync/models/user/Pilot.kt
3540072600
package ch.epfl.skysync.models.user import ch.epfl.skysync.models.calendar.AvailabilityCalendar import ch.epfl.skysync.models.calendar.FlightGroupCalendar import ch.epfl.skysync.models.flight.RoleType interface User { val id: String val firstname: String val lastname: String val availabilities: AvailabilityCalendar val assignedFlights: FlightGroupCalendar val roleTypes: Set<RoleType> fun addRoleType(roleType: RoleType): User fun canAssumeRole(roleType: RoleType): Boolean { return roleTypes.contains(roleType) } }
skysync/app/src/main/java/ch/epfl/skysync/models/user/User.kt
2770458578
package ch.epfl.skysync.models // Only define a global constant to be used as default value for models id field // when creating a new instance of the model in the database. // Do not opt for a hierarchical data class pattern with an parent `IdentifiableModel` class // as kotlin doesn't support inheritance in data class well: // https://stackoverflow.com/questions/26444145/extend-data-class-in-kotlin /** * Used for an ID that has not yet been generated * * This should only be used when adding a new item to a database. */ const val UNSET_ID = "__unset_id__"
skysync/app/src/main/java/ch/epfl/skysync/models/UnsetId.kt
3147174141
package ch.epfl.skysync.screens import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import ch.epfl.skysync.components.forms.FlightForm import ch.epfl.skysync.models.flight.PlannedFlight import ch.epfl.skysync.models.flight.RoleType import ch.epfl.skysync.navigation.Route import ch.epfl.skysync.viewmodel.FlightsViewModel @Composable fun ModifyFlightScreen( navController: NavHostController, viewModel: FlightsViewModel, flightId: String ) { val allFlightTypes by viewModel.currentFlightTypes.collectAsStateWithLifecycle() val allBalloons by viewModel.currentBalloons.collectAsStateWithLifecycle() val allBaskets by viewModel.currentBaskets.collectAsStateWithLifecycle() val allVehicles by viewModel.currentVehicles.collectAsStateWithLifecycle() val flightToModify by viewModel.getFlight(flightId).collectAsStateWithLifecycle() val allRoleTypes = RoleType.entries FlightForm( currentFlight = flightToModify, navController = navController, title = "Modify Flight", modifyMode = true, allFlightTypes = allFlightTypes, allRoleTypes = allRoleTypes, allVehicles = allVehicles, allBalloons = allBalloons, allBaskets = allBaskets, flightAction = { flight: PlannedFlight -> viewModel.modifyFlight(flight) navController.navigate(Route.HOME) }) }
skysync/app/src/main/java/ch/epfl/skysync/screens/ModifyFlight.kt
3811657902
package ch.epfl.skysync.screens import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import ch.epfl.skysync.components.CustomTopAppBar import ch.epfl.skysync.components.forms.TitledDropDownMenu import ch.epfl.skysync.components.forms.TitledInputTextField import ch.epfl.skysync.models.calendar.AvailabilityCalendar import ch.epfl.skysync.models.calendar.FlightGroupCalendar import ch.epfl.skysync.models.flight.BalloonQualification import ch.epfl.skysync.models.user.Admin import ch.epfl.skysync.models.user.Crew import ch.epfl.skysync.models.user.Pilot import ch.epfl.skysync.models.user.User import ch.epfl.skysync.ui.theme.lightOrange @Composable fun AddUserScreen(navController: NavController) { val title = "Add User" val allRoles = listOf("Admin", "Pilot", "Crew") val allBalloons = listOf(BalloonQualification.MEDIUM, BalloonQualification.LARGE, BalloonQualification.SMALL) Scaffold( modifier = Modifier.fillMaxSize(), topBar = { CustomTopAppBar(navController = navController, title = title) }) { padding -> val defaultPadding = 16.dp var roleValue by remember { mutableStateOf("") } var roleError by remember { mutableStateOf(false) } var firstNameValue by remember { mutableStateOf("") } var firstNameError by remember { mutableStateOf(false) } var lastNameValue by remember { mutableStateOf("") } var lastNameError by remember { mutableStateOf(false) } var emailValue by remember { mutableStateOf("") } var emailError by remember { mutableStateOf(false) } var balloonQualificationValue: BalloonQualification? by remember { mutableStateOf(null) } var balloonQualificationError by remember { mutableStateOf(false) } var isError by remember { mutableStateOf(false) } Column(Modifier.fillMaxSize().padding(padding)) { LazyColumn(modifier = Modifier.fillMaxSize().weight(1f).testTag("$title Lazy Column")) { item { TitledDropDownMenu( defaultPadding = defaultPadding, title = "Role", value = roleValue, onclickMenu = { roleValue = it }, items = allRoles, isError = roleError, messageError = if (roleError) "Select a role" else "") } item { TitledInputTextField( padding = defaultPadding, title = "First Name", value = firstNameValue, onValueChange = { firstNameValue = it }, isError = firstNameError, messageError = if (firstNameError) "Enter a first name" else "") } item { TitledInputTextField( padding = defaultPadding, title = "Last Name", value = lastNameValue, onValueChange = { lastNameValue = it }, isError = lastNameError, messageError = if (lastNameError) "Enter a last name" else "") } item { TitledInputTextField( padding = defaultPadding, title = "E-mail", value = emailValue, onValueChange = { emailValue = it }, isError = emailError, messageError = if (emailError) "Invalid email" else "", keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)) } if (roleValue === "Pilot") { item { TitledDropDownMenu( defaultPadding = defaultPadding, title = "Balloon Qualification", value = balloonQualificationValue, onclickMenu = { balloonQualificationValue = it }, items = allBalloons, isError = balloonQualificationError, messageError = if (balloonQualificationError) "Select a balloon type" else "", showString = { it?.name?.lowercase() ?: "Choose a balloon qualification" }) } } } Button( onClick = { emailError = !validateEmail(emailValue) firstNameError = textInputValidation(firstNameValue) lastNameError = textInputValidation(lastNameValue) roleError = textInputValidation(roleValue) balloonQualificationError = if (roleValue === "Pilot") dropDownInputValidation(balloonQualificationValue) else false isError = inputValidation( roleError, firstNameError, lastNameError, emailError, balloonQualificationError) if (!isError) { val user: User when (roleValue) { "Admin" -> { user = Admin( firstname = firstNameValue, lastname = lastNameValue, assignedFlights = FlightGroupCalendar(), availabilities = AvailabilityCalendar()) } "Pilot" -> { user = Pilot( firstname = firstNameValue, lastname = lastNameValue, assignedFlights = FlightGroupCalendar(), availabilities = AvailabilityCalendar(), qualification = balloonQualificationValue!!) } "Crew" -> { user = Crew( firstname = firstNameValue, lastname = lastNameValue, assignedFlights = FlightGroupCalendar(), availabilities = AvailabilityCalendar()) } } // TODO: Add user to the database navController.popBackStack() } }, modifier = Modifier.fillMaxWidth().padding(defaultPadding).testTag("$title Button"), colors = ButtonDefaults.buttonColors(containerColor = lightOrange)) { Text(title) } } } } fun validateEmail(email: String): Boolean { return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() } fun textInputValidation(name: String): Boolean { return name.isEmpty() } fun <T> dropDownInputValidation(value: T): Boolean { return value === null } fun inputValidation(vararg errors: Boolean): Boolean { return errors.any { it } } @Preview @Composable fun AddUserScreenPreview() { val navController = rememberNavController() AddUserScreen(navController = navController) }
skysync/app/src/main/java/ch/epfl/skysync/screens/AddUser.kt
1789200722
package ch.epfl.skysync.screens import android.util.Log import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavHostController import androidx.navigation.compose.currentBackStackEntryAsState import ch.epfl.skysync.components.AvailabilityCalendar import ch.epfl.skysync.components.FlightCalendar import ch.epfl.skysync.navigation.BottomBar import ch.epfl.skysync.navigation.Route import ch.epfl.skysync.ui.theme.lightGray import ch.epfl.skysync.viewmodel.CalendarViewModel @Composable fun CalendarScreen( navController: NavHostController, calendarType: String, viewModel: CalendarViewModel ) { val tabs = mapOf(Route.FLIGHT_CALENDAR to 0, Route.AVAILABILITY_CALENDAR to 1) val navBackStackEntry by navController.currentBackStackEntryAsState() val currentDestination = navBackStackEntry?.destination Scaffold( modifier = Modifier.fillMaxSize(), topBar = { CalendarTopBar(tab = calendarType, tabs = tabs) { route -> navController.navigate(route) { if (currentDestination?.route != route) { navController.navigate(route) { popUpTo(navController.graph.findStartDestination().id) launchSingleTop = true } } } } }, bottomBar = { BottomBar(navController) }) { padding -> val uiState by viewModel.uiState.collectAsStateWithLifecycle() if (calendarType == Route.AVAILABILITY_CALENDAR) { val availabilityCalendar = uiState.availabilityCalendar AvailabilityCalendar( padding = padding, getAvailabilityStatus = { date, time -> availabilityCalendar.getAvailabilityStatus(date, time) }, nextAvailabilityStatus = { date, time -> availabilityCalendar.nextAvailabilityStatus(date, time) }, onSave = { viewModel.saveAvailabilities() }, onCancel = { Log.d("TO BE IMPLEMENTED", "Cancel in Availabilities") }) } else if (calendarType == Route.FLIGHT_CALENDAR) { val flightCalendar = uiState.flightGroupCalendar FlightCalendar( padding = padding, getFirstFlightByDate = { date, time -> flightCalendar.getFirstFlightByDate(date, time) }, onFlightClick = { selectedFlight -> navController.navigate(Route.FLIGHT_DETAILS + "/${selectedFlight}") }) } } } @Composable fun CalendarTopBar(tab: String, tabs: Map<String, Int>, onclick: (String) -> Unit) { val tabIndex = tabs[tab] if (tabIndex != null) { TabRow(selectedTabIndex = tabIndex, containerColor = lightGray) { tabs.forEach { (route, index) -> Tab( modifier = Modifier.padding(8.dp).testTag(route), text = { Text(text = route) }, selected = tabIndex == index, onClick = { onclick(route) }) } } } }
skysync/app/src/main/java/ch/epfl/skysync/screens/Calendar.kt
858623789
package ch.epfl.skysync.screens import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import ch.epfl.skysync.components.GroupChat import ch.epfl.skysync.components.GroupDetail import ch.epfl.skysync.navigation.BottomBar import ch.epfl.skysync.navigation.Route @Composable fun ChatScreen(navController: NavHostController) { Scaffold( modifier = Modifier.fillMaxSize().testTag("ChatScreenScaffold"), bottomBar = { BottomBar(navController) }, floatingActionButton = // TODO delete the button. It is just there for preview purposes { FloatingActionButton(onClick = { navController.navigate(Route.ADD_USER) }) { Icons.Default.Add } }) { padding -> val groupList = List(10) { GroupDetail( groupName = "Group $it", groupImage = null, lastMessage = "Hello", lastMessageTime = "12:00") } GroupChat( groupList = groupList, onClick = { selectedGroup -> navController.navigate(Route.TEXT + "/${selectedGroup}") }, paddingValues = padding) } } @Composable @Preview fun Preview() { val navController = rememberNavController() ChatScreen(navController = navController) }
skysync/app/src/main/java/ch/epfl/skysync/screens/Chat.kt
893592279
package ch.epfl.skysync.screens.flightDetail import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import ch.epfl.skysync.navigation.BottomBar import ch.epfl.skysync.navigation.Route import ch.epfl.skysync.viewmodel.FlightsViewModel @Composable fun FlightDetailScreen( navController: NavHostController, flightId: String, viewModel: FlightsViewModel ) { val flight by viewModel.getFlight(flightId).collectAsStateWithLifecycle() Scaffold(modifier = Modifier.fillMaxSize(), bottomBar = { BottomBar(navController) }) { padding -> FlightDetailUi( backClick = { navController.popBackStack() }, deleteClick = { viewModel.deleteFlight(flightId) navController.navigate(Route.HOME) }, editClick = { navController.navigate(Route.MODIFY_FLIGHT + "/${flightId}") }, confirmClick = { navController.navigate(Route.CONFIRM_FLIGHT + "/${flightId}") }, padding = padding, flight = flight, flightId = flightId, ) } } // @Composable // @Preview // fun FlightDetailScreenPreview() { // val navController = rememberNavController() // val viewModel = UserViewModel.createViewModel(firebaseUser = null) // FlightDetailScreen(navController = navController, flightId = "1", viewModel = viewModel) // }
skysync/app/src/main/java/ch/epfl/skysync/screens/flightDetail/FlightDetailsScreen.kt
1860280288
package ch.epfl.skysync.screens.flightDetail import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Divider 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.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import ch.epfl.skysync.components.Header import ch.epfl.skysync.components.LoadingComponent import ch.epfl.skysync.models.flight.Flight import ch.epfl.skysync.models.flight.Team import ch.epfl.skysync.models.flight.Vehicle /** * FlightDetailUi is a Composable function that displays the UI for flight details. It consists of a * header, body, and bottom section with action buttons. * * @param backClick Callback function invoked when the back button is clicked. * @param deleteClick Callback function invoked when the delete button is clicked. * @param editClick Callback function invoked when the edit button is clicked. * @param confirmClick Callback function invoked when the confirm button is clicked. * @param padding PaddingValues to apply to the content. * @param flight The flight details to display. */ @Composable fun FlightDetailUi( backClick: () -> Unit, deleteClick: (flightId: String) -> Unit, editClick: (flightId: String) -> Unit, confirmClick: (flightId: String) -> Unit, padding: PaddingValues, flight: Flight?, flightId: String ) { Column( modifier = Modifier.fillMaxSize().background(Color.White), ) { Header(backClick = backClick, title = "Flight Detail") Box(modifier = Modifier.fillMaxHeight().padding(padding)) { if (flight == null) { LoadingComponent(isLoading = true, onRefresh = {}) {} } else { FlightDetailBody(flight, padding) } FlightDetailBottom(flightId, deleteClick, editClick, confirmClick) } } } /** * FlightdetailBody is a Composable function that displays the body of the flight detail screen. * * @param flight The flight details to display. * @param padding PaddingValues to apply to the content. */ @Composable fun FlightDetailBody(flight: Flight, padding: PaddingValues) { Column(modifier = Modifier.fillMaxWidth().fillMaxHeight(0.9f).padding(padding)) { Spacer(modifier = Modifier.fillMaxHeight(0.05f)) Row() { Column( modifier = Modifier.fillMaxWidth(0.7f), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Text( text = flight.flightType.name, color = Color.Black, fontSize = 20.sp, fontWeight = FontWeight.Bold) Text( text = flight.nPassengers.toString() + " Pax", fontSize = 20.sp, color = Color.Black, fontWeight = FontWeight.Bold) } Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Text( flight.date.toString(), fontSize = 15.sp, color = Color.Black, ) Text( flight.timeSlot.name, color = Color.Black, fontSize = 15.sp, ) } } Row { Column( modifier = Modifier.fillMaxWidth(0.5f), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { TextBar(textLeft = "Balloon", textRight = flight.balloon?.name ?: "None") } Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { TextBar(textLeft = "Basket", textRight = flight.basket?.name ?: "None") } } ScrollableBoxWithButton("Team") { TeamRolesList(team = flight.team) } ScrollableBoxWithButton("Vehicles") { VehicleListText(vehicle = flight.vehicles) } } } /** * FlightDetailBottom is a Composable function that displays the bottom section of the flight detail * screen. * * @param DeleteClick Callback function invoked when the delete button is clicked. * @param EditClick Callback function invoked when the edit button is clicked. * @param ConfirmClick Callback function invoked when the confirm button is clicked. * @param padding PaddingValues to apply to the content. */ @Composable fun FlightDetailBottom( flightId: String, DeleteClick: (flightId: String) -> Unit, EditClick: (flightId: String) -> Unit, ConfirmClick: (flightId: String) -> Unit, ) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { ClickButton( text = "Delete", onClick = { DeleteClick(flightId) }, modifier = Modifier.fillMaxWidth(0.3f).testTag("DeleteButton"), color = Color.Red) ClickButton( text = "Edit", onClick = { EditClick(flightId) }, modifier = Modifier.fillMaxWidth(3 / 7f).testTag("EditButton"), color = Color.Yellow) ClickButton( text = "Confirm", onClick = { ConfirmClick(flightId) }, modifier = Modifier.fillMaxWidth(0.7f).testTag("ConfirmButton"), color = Color.Green) } } } /** * Composable function to create a custom clickable button. * * @param text The text to be displayed on the button. * @param onClick The lambda function to be executed when the button is clicked. * @param modifier The modifier for the button layout. * @param color The color for the button background. */ @Composable fun ClickButton(text: String, onClick: () -> Unit, modifier: Modifier, color: Color) { Button( onClick = onClick, modifier = modifier, colors = ButtonDefaults.buttonColors(containerColor = color)) { Text(text = text, color = Color.Black, overflow = TextOverflow.Clip) } } /** * TextBar is a Composable function that displays a row with two text elements separated by a * divider. * * @param textLeft The text to display on the left side. * @param textRight The text to display on the right side. */ @Composable fun TextBar(textLeft: String, textRight: String) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) { Column( modifier = Modifier.fillMaxWidth(0.5f), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Text(text = textLeft, color = Color.Black, fontSize = 15.sp) } Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Text( text = textRight, fontSize = 15.sp, color = Color.Black, modifier = Modifier.testTag(textLeft + textRight)) } } Spacer(modifier = Modifier.height(8.dp)) Divider(color = Color.Black, thickness = 1.dp) Spacer(modifier = Modifier.height(8.dp)) } /** * TeamRolesList is a Composable function that displays a list of team roles. * * @param team The team containing the roles to display. */ @Composable fun TeamRolesList(team: Team) { if (team.roles.isEmpty()) { Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Text(text = "No team member", color = Color.Black) } } else { LazyColumn(modifier = Modifier.testTag("TeamList").fillMaxHeight(0.5f)) { itemsIndexed(team.roles) { index, role -> val firstname = role.assignedUser?.firstname ?: "" val lastname = role.assignedUser?.lastname ?: "" val name = "$firstname $lastname" TextBar(textLeft = "Member $index: ${role.roleType.name}", textRight = name) } } } } /** * VehicleListText is a Composable function that displays a list of vehicles. * * @param vehicle The list of vehicles to display. */ @Composable fun VehicleListText(vehicle: List<Vehicle>) { if (vehicle.indices.isEmpty()) { Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Text( text = "No vehicle", color = Color.Black, ) } } else { LazyColumn(modifier = Modifier.testTag("VehicleList")) { itemsIndexed(vehicle) { index, car -> TextBar(textLeft = "Vehicle $index", textRight = car.name) } } } } /** * ScrollableBoxWithButton is a Composable function that displays a button that, when clicked, * toggles the visibility of a content area. * * @param name The text to display on the button. * @param content The content to be displayed when the button is clicked. */ @Composable fun ScrollableBoxWithButton(name: String, content: @Composable () -> Unit) { var expanded by remember { mutableStateOf(false) } Column { Button( onClick = { expanded = !expanded }, modifier = Modifier.fillMaxWidth(), colors = ButtonDefaults.buttonColors(containerColor = Color.Gray)) { Text(text = name, color = Color.White) } if (expanded) { content() } } }
skysync/app/src/main/java/ch/epfl/skysync/screens/flightDetail/FlightDetailUi.kt
3152046318
package ch.epfl.skysync.screens import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.navigation.NavHostController import ch.epfl.skysync.components.ChatMessage import ch.epfl.skysync.components.ChatText import ch.epfl.skysync.components.MessageType import ch.epfl.skysync.navigation.BottomBar @Composable fun TextScreen(navController: NavHostController, groupName: String) { val hardCoded = listOf( ChatMessage("Sender", MessageType.RECEIVED, null, "Message", "11:11"), ChatMessage("me", MessageType.SENT, null, "Message", "12:12"), ) Scaffold( modifier = Modifier.fillMaxSize().testTag("ChatScreenScaffold"), bottomBar = { BottomBar(navController) }) { padding -> ChatText( groupName = groupName, messages = hardCoded, onBack = { navController.popBackStack() }, onSend = { /*TODO*/}, paddingValues = padding) } }
skysync/app/src/main/java/ch/epfl/skysync/screens/TextScreen.kt
1787207955
package ch.epfl.skysync.screens import android.content.Intent import androidx.activity.result.ActivityResultLauncher 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.padding import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon 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.platform.testTag import androidx.compose.ui.unit.dp import com.firebase.ui.auth.AuthUI @OptIn(ExperimentalMaterial3Api::class) @Composable fun LoginScreen(signInLauncher: ActivityResultLauncher<Intent>) { val providers = listOf( // Google sign-in AuthUI.IdpConfig.GoogleBuilder().build()) val signInIntent = AuthUI.getInstance().createSignInIntentBuilder().setAvailableProviders(providers).build() Surface(modifier = Modifier.fillMaxSize()) { Column( modifier = Modifier.fillMaxSize().padding(16.dp).testTag("LoginScreen"), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { Button( modifier = Modifier.testTag("LoginButton"), onClick = { signInLauncher.launch(signInIntent) }) { Icon(imageVector = Icons.Default.Check, contentDescription = null) Spacer(modifier = Modifier.width(8.dp)) Text("Sign in with Google") } Text(text = "You need to log in") } } }
skysync/app/src/main/java/ch/epfl/skysync/screens/LoginScreen.kt
1443393837
package ch.epfl.skysync.screens import android.annotation.SuppressLint import android.util.Log import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.FabPosition import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import ch.epfl.skysync.components.LoadingComponent import ch.epfl.skysync.models.flight.Flight import ch.epfl.skysync.navigation.BottomBar import ch.epfl.skysync.navigation.Route import ch.epfl.skysync.ui.theme.lightOrange import ch.epfl.skysync.viewmodel.FlightsViewModel import java.time.format.DateTimeFormatter import java.util.Locale @Composable fun UpcomingFlights(flights: List<Flight>?, onFlightClick: (String) -> Unit) { Column(modifier = Modifier.fillMaxSize().padding(16.dp)) { Text( text = "Upcoming flights", style = MaterialTheme.typography.headlineMedium.copy(fontWeight = FontWeight.Bold), modifier = Modifier.background( color = lightOrange, shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)) .fillMaxWidth() .padding(16.dp), color = Color.White, textAlign = TextAlign.Center) Spacer(modifier = Modifier.height(16.dp)) if (flights == null) { LoadingComponent(isLoading = true, onRefresh = { /*TODO*/}) {} } else if (flights.isEmpty()) { // Handle case when no upcoming flights Box( modifier = Modifier.fillMaxWidth().fillMaxHeight(0.3f), contentAlignment = Alignment.Center) { Text( text = "No upcoming flights", style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold), color = Color.Black) } } else { // Display the flights in a LazyColumn if the list is not empty LazyColumn { items(flights) { flight -> FlightRow(flight, onFlightClick) } } } } } @Composable fun FlightRow(flight: Flight, onFlightClick: (String) -> Unit) { // Card for an individual flight, clickable to navigate to details Card( modifier = Modifier.fillMaxWidth() .clickable { onFlightClick(flight.id) } .padding(vertical = 4.dp) .testTag("flightCard"), elevation = CardDefaults.cardElevation(defaultElevation = 1.dp), ) { Surface(modifier = Modifier.fillMaxWidth(), color = flight.getFlightStatus().displayColor) { Row( modifier = Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start) { Text( text = flight.date.format( DateTimeFormatter.ofPattern("E\ndd").withLocale(Locale.ENGLISH)), style = MaterialTheme.typography.titleMedium, modifier = Modifier.alignByBaseline(), color = Color.Black) // Spacer for horizontal separation Spacer(modifier = Modifier.width(16.dp)) // Column for flight details Column(modifier = Modifier.weight(0.7f).padding(start = 16.dp)) { // Text for flight type and passenger count Text( text = "${flight.flightType.name} - ${flight.nPassengers} pax", fontWeight = FontWeight.Bold, color = Color.Black) // Text for flight time slot Text(text = flight.timeSlot.toString(), color = Color.Gray) } Text( text = flight.getFlightStatus().toString(), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.alignByBaseline(), color = Color.Gray) } } } } // Scaffold wrapper for the Home Screen @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun HomeScreen(navController: NavHostController, viewModel: FlightsViewModel) { val currentFlights by viewModel.currentFlights.collectAsStateWithLifecycle() Scaffold( modifier = Modifier.fillMaxSize(), bottomBar = { BottomBar(navController) }, floatingActionButton = { // Define the FloatingActionButton to create a flight FloatingActionButton( modifier = Modifier.testTag("addFlightButton"), onClick = { navController.navigate(Route.ADD_FLIGHT) { launchSingleTop = true } }, containerColor = lightOrange) { Icon(imageVector = Icons.Default.Add, contentDescription = "Add", tint = Color.White) } }, floatingActionButtonPosition = FabPosition.End, ) { padding -> UpcomingFlights(currentFlights) { selectedFlight -> // Here is where you'd navigate to a new screen. For now, just log a message. val some = viewModel Log.d("HomeScreen", "Navigating to FlightDetails with id $selectedFlight") navController.navigate(Route.FLIGHT_DETAILS + "/${selectedFlight}") // Example navigation call: navController.navigate("FlightDetails.id") } } } // Preview provider for the Home Screen // @Composable // @Preview // fun HomeScreenPreview() { // // Preview navigation controller // val navController = rememberNavController() // // Preview of Home Screen // HomeScreen(navController = navController) // }
skysync/app/src/main/java/ch/epfl/skysync/screens/Home.kt
469605550
package ch.epfl.skysync.screens import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import ch.epfl.skysync.components.forms.FlightForm import ch.epfl.skysync.models.flight.PlannedFlight import ch.epfl.skysync.models.flight.RoleType import ch.epfl.skysync.navigation.Route import ch.epfl.skysync.viewmodel.FlightsViewModel @Composable fun AddFlightScreen(navController: NavHostController, viewModel: FlightsViewModel) { val allFlightTypes by viewModel.currentFlightTypes.collectAsStateWithLifecycle() val allBalloons by viewModel.currentBalloons.collectAsStateWithLifecycle() val allBaskets by viewModel.currentBaskets.collectAsStateWithLifecycle() val allVehicles by viewModel.currentVehicles.collectAsStateWithLifecycle() val allRoleTypes = RoleType.entries FlightForm( currentFlight = null, navController = navController, modifyMode = false, title = "Add Flight", allFlightTypes = allFlightTypes, allRoleTypes = allRoleTypes, allVehicles = allVehicles, allBalloons = allBalloons, allBaskets = allBaskets, flightAction = { flight: PlannedFlight -> viewModel.addFlight(flight) navController.navigate(Route.HOME) }) }
skysync/app/src/main/java/ch/epfl/skysync/screens/AddFlight.kt
2119649085
package ch.epfl.skysync.screens import androidx.compose.runtime.Composable import androidx.navigation.NavController import ch.epfl.skysync.components.confirmation import ch.epfl.skysync.models.calendar.TimeSlot import ch.epfl.skysync.models.flight.Balloon import ch.epfl.skysync.models.flight.BalloonQualification import ch.epfl.skysync.models.flight.Basket import ch.epfl.skysync.models.flight.FlightType import ch.epfl.skysync.models.flight.PlannedFlight import ch.epfl.skysync.models.flight.Role import ch.epfl.skysync.models.flight.RoleType import ch.epfl.skysync.models.flight.Team import ch.epfl.skysync.models.flight.Vehicle import ch.epfl.skysync.navigation.Route import ch.epfl.skysync.viewmodel.FlightsViewModel import java.time.LocalDate @Composable fun confirmationScreenHardCoded(navController: NavController) { val dummy = PlannedFlight( "1234", 3, FlightType.DISCOVERY, Team(listOf(Role(RoleType.CREW))), Balloon("Balloon Name", BalloonQualification.LARGE, "Ballon Name"), Basket("Basket Name", true, "1234"), LocalDate.now().plusDays(3), TimeSlot.PM, listOf(Vehicle("Peugeot 308", "1234"))) confirmation(dummy) { navController.navigate(Route.MAIN) } } @Composable fun confirmationScreen(navCtr: NavController, flightId: String, vm: FlightsViewModel) { confirmationScreenHardCoded(navController = navCtr) }
skysync/app/src/main/java/ch/epfl/skysync/screens/ConfirmFlightScreen.kt
3004617392
package ch.epfl.skysync.screens import android.util.Log import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.LocationOn import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect 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.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import ch.epfl.skysync.components.LoadingComponent import ch.epfl.skysync.components.Timer import ch.epfl.skysync.navigation.BottomBar import ch.epfl.skysync.ui.theme.lightOrange import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.location.LocationServices import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.maps.android.compose.GoogleMap import com.google.maps.android.compose.Marker import com.google.maps.android.compose.rememberCameraPositionState import com.google.maps.android.compose.rememberMarkerState /** * This composable function renders a screen with a map that shows the user's current location. It * requests and checks location permissions, updates location in real-time, and handles permissions * denial. * * @param navController Navigation controller for navigating between composables. */ @OptIn(ExperimentalPermissionsApi::class) @Composable fun FlightScreen(navController: NavHostController) { // Access to the application context. val context = LocalContext.current // Manages the state of location permissions. val locationPermission = rememberPermissionState(android.Manifest.permission.ACCESS_FINE_LOCATION) // Provides access to the Fused Location Provider API. val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context) // State holding the current location initialized to Lausanne as default value. var location by remember { mutableStateOf(LatLng(46.516, 6.63282)) } // Remembers and controls the camera position state for the map. val cameraPositionState = rememberCameraPositionState { position = CameraPosition.fromLatLngZoom(location, 13f) } // Manages the state of the map marker. val markerState = rememberMarkerState(position = location) var speed by remember { mutableStateOf(0f) } // Speed in meters/second var altitude by remember { mutableStateOf(0.0) } // Altitude in meters var bearing by remember { mutableStateOf(0f) } // Direction in degrees var verticalSpeed by remember { mutableStateOf(0.0) } // Vertical speed in meters/second var previousAltitude by remember { mutableStateOf<Double?>(null) } var previousTime by remember { mutableStateOf<Long?>(null) } // DisposableEffect to handle location updates and permissions. DisposableEffect(locationPermission) { // Defines the location request parameters. val locationRequest = LocationRequest.create().apply { interval = 5000 // Interval for location updates. fastestInterval = 2000 // Fastest interval for location updates. } // Callback to receive location updates val locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { locationResult.lastLocation?.let { val newLocation = LatLng(it.latitude, it.longitude) cameraPositionState.position = CameraPosition.fromLatLngZoom(newLocation, 13f) location = newLocation markerState.position = newLocation speed = it.speed // Update speed bearing = it.bearing // Update Bearing val currentTime = System.currentTimeMillis() previousAltitude?.let { prevAlt -> verticalSpeed = if (previousTime != null) { (it.altitude - prevAlt) / ((currentTime - previousTime!!) / 1000.0) } else { 0.0 } } altitude = it.altitude previousAltitude = it.altitude previousTime = currentTime } } } // Requests location updates if permission is granted. if (locationPermission.status.isGranted) { try { fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null) } catch (e: SecurityException) { // Exception handling if the permission was rejected. Log.e("FlightScreen", "Failed to request location updates", e) } } else { locationPermission.launchPermissionRequest() // Request permission if not granted } // Cleanup function to stop receiving location updates when the composable is disposed. onDispose { fusedLocationClient.removeLocationUpdates(locationCallback) } } Scaffold( modifier = Modifier.fillMaxSize(), floatingActionButton = { // Floating action button to center the map on the current location. if (locationPermission.status.isGranted) { Box( modifier = Modifier.fillMaxSize().padding(start = 32.dp, bottom = 88.dp, top = 100.dp), contentAlignment = Alignment.BottomStart) { Timer(Modifier.align(Alignment.TopEnd).testTag("Timer")) Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) { FloatingActionButton( onClick = { // Moves the camera to the current location when clicked. location ?.let { CameraUpdateFactory.newLatLngZoom(it, 13f) } ?.let { cameraPositionState.move(it) } }, containerColor = lightOrange) { Icon(Icons.Default.LocationOn, contentDescription = "Locate Me") } FloatingActionButton( onClick = { // Here is where you'd navigate to a new screen. For now, just log a // message. Log.d( "FlightScreen", "FloatingActionButton clicked. Implement navigation here.") // Example navigation call: navController.navigate("FlightInfos") }, containerColor = lightOrange) { Icon( imageVector = Icons.Default.Info, contentDescription = "Flight infos", tint = Color.White) } } } } }, bottomBar = { BottomBar(navController) }) { padding -> if (locationPermission.status.isGranted && location == null) { LoadingComponent(isLoading = true, onRefresh = {}, content = {}) } // Renders the Google Map or a permission request message based on the permission status. if (locationPermission.status.isGranted && location != null) { GoogleMap( modifier = Modifier.fillMaxSize().padding(padding).testTag("Map"), cameraPositionState = cameraPositionState) { Marker(state = markerState, title = "Your Location", snippet = "You are here") } Text( text = "X Speed: $speed m/s\nY Speed: $verticalSpeed m/s\nAltitude: $altitude m\nBearing: $bearing °", style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(top = 16.dp, start = 12.dp, end = 12.dp) .background(color = Color.White, shape = RoundedCornerShape(8.dp)) .padding(6.dp)) } if (!locationPermission.status.isGranted) { // Displays a message if location permission is denied. Box( modifier = Modifier.fillMaxSize().padding(16.dp), contentAlignment = Alignment.Center) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Text("Access to location is required to use this feature.") Text("Please enable location permissions in settings.") } } } } } @Composable @Preview fun FlightScreenPreview() { val navController = rememberNavController() FlightScreen(navController = navController) }
skysync/app/src/main/java/ch/epfl/skysync/screens/Flight.kt
3597386321
package ch.epfl.skysync.components import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material.Text import androidx.compose.material3.Divider 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.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import ch.epfl.skysync.models.calendar.TimeSlot import ch.epfl.skysync.ui.theme.* import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.Locale /** * Function to calculate the start date of the week for the given date. * * @param date The input LocalDate for which the start date of the week is to be calculated. * @return The start date of the week containing the input date. */ fun getStartOfWeek(date: LocalDate): LocalDate { return date.minusDays(date.dayOfWeek.value.toLong() - 1) } /** * Composable function to display a calendar with a week view * * @param modifier The modifier * @param isDraft Indicates if the [AvailabilityCalendar] is being modified * @param tile The composable rendered for each tile */ @OptIn(ExperimentalFoundationApi::class) @Composable fun ModularCalendar( modifier: Modifier, isDraft: Boolean, tile: @Composable (date: LocalDate, time: TimeSlot) -> Unit ) { val pagerState = rememberPagerState(initialPage = 20, pageCount = { 52 }) var currentWeekStartDate by remember { mutableStateOf(getStartOfWeek(LocalDate.now())) } var previousPage by remember { mutableIntStateOf(pagerState.currentPage) } var initLaunchEffect = true LaunchedEffect(pagerState) { // Collect from the a snapshotFlow reading the currentPage snapshotFlow { pagerState.currentPage } .collect { page -> if (initLaunchEffect) { initLaunchEffect = false } else { currentWeekStartDate = if (page > previousPage) { currentWeekStartDate.plusWeeks(1) } else { currentWeekStartDate.minusWeeks(1) } previousPage = page } } } HorizontalPager(state = pagerState, modifier = modifier.testTag("HorizontalPager")) { WeekView(isDraft, currentWeekStartDate, tile) } } /** * Composable function to display a week view with a [tile] for each day and time slot. * * @param startOfWeek The start date of the week to be displayed. * @param tile The composable rendering each tile */ @Composable fun WeekView( isDraft: Boolean, startOfWeek: LocalDate, tile: @Composable (date: LocalDate, time: TimeSlot) -> Unit ) { val weekDays = (0..6).map { startOfWeek.plusDays(it.toLong()) } Column { Row( modifier = Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.CenterVertically) { val textColor = if (isDraft) Color.Black else Color.White mapOf("Draft" to textColor, "AM" to Color.Black, "PM" to Color.Black).forEach { (text, color) -> Text( text = text, modifier = Modifier.fillMaxWidth().weight(1f), fontSize = 16.sp, color = color, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center) } } weekDays.forEach { day -> Row( modifier = Modifier.fillMaxSize().weight(2f), verticalAlignment = Alignment.CenterVertically, ) { Column( modifier = Modifier.fillMaxHeight().fillMaxWidth(0.3f).background(Color.White), verticalArrangement = Arrangement.Center, ) { Text( text = day.format(DateTimeFormatter.ofPattern("EEE", Locale.getDefault())), fontSize = 16.sp, color = Color.Black, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center) Text( text = day.format(DateTimeFormatter.ofPattern("MM/dd", Locale.getDefault())), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = Color.Black, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center) } tile(day, TimeSlot.AM) tile(day, TimeSlot.PM) } Divider(color = Color.Black, thickness = 1.dp) } } } @Preview @Composable fun CalendarPreview() { ModularCalendar(Modifier, true) { date, time -> println(date) println(time) } }
skysync/app/src/main/java/ch/epfl/skysync/components/ModularCalendar.kt
3950937839
package ch.epfl.skysync.components.forms import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.OutlinedTextField 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.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.Dp @OptIn(ExperimentalMaterial3Api::class) @Composable fun <T> CustomDropDownMenu( defaultPadding: Dp, title: String, value: T, onclickMenu: (T) -> Unit, items: List<T>, showString: (T) -> String = { it.toString() }, isError: Boolean = false, messageError: String = "", ) { var expanded by remember { mutableStateOf(false) } Column { ExposedDropdownMenuBox( modifier = Modifier.fillMaxWidth() .padding(horizontal = defaultPadding) .clickable(onClick = { expanded = true }) .testTag("$title Menu"), expanded = expanded, onExpandedChange = { expanded = !expanded }) { OutlinedTextField( value = showString(value), modifier = Modifier.fillMaxWidth().menuAnchor(), readOnly = true, onValueChange = {}, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, isError = isError, supportingText = { if (isError) Text(messageError) }) } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, ) { items.withIndex().forEach { (id, item) -> DropdownMenuItem( modifier = Modifier.fillMaxWidth().padding(horizontal = defaultPadding).testTag("$title $id"), onClick = { onclickMenu(item) expanded = false }, text = { Text(showString(item)) }, contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding) } } } }
skysync/app/src/main/java/ch/epfl/skysync/components/forms/CustomDropDownMenu.kt
21829589
package ch.epfl.skysync.components.forms import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp @Composable fun <T> TitledDropDownMenu( defaultPadding: Dp, title: String, value: T, onclickMenu: (T) -> Unit, items: List<T>, showString: (T) -> String = { it.toString() }, isError: Boolean = false, messageError: String = "" ) { Text( modifier = Modifier.fillMaxWidth().padding(horizontal = defaultPadding), text = title, style = MaterialTheme.typography.headlineSmall) CustomDropDownMenu( defaultPadding = defaultPadding, title = title, value = value, onclickMenu = onclickMenu, items = items, showString = showString, isError = isError, messageError = messageError) }
skysync/app/src/main/java/ch/epfl/skysync/components/forms/TitledDropDownMenu.kt
2142637105
package ch.epfl.skysync.components.forms import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box 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.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun <T> SearchBarCustom( query: String, onQueryChange: (String) -> Unit, onSearch: (String) -> Unit, active: Boolean, onActiveChange: (Boolean) -> Unit, onElementClick: (T) -> Unit, propositions: List<T>, showProposition: (T) -> String, placeholder: String = "Search" ) { val focusRequester = remember { FocusRequester() } var height by remember { mutableStateOf(90.dp) } val animatedHeight by animateDpAsState(targetValue = height, label = "") val keyboardController = LocalSoftwareKeyboardController.current LaunchedEffect(active) { height = if (active) 300.dp else 90.dp } Column(modifier = Modifier.fillMaxWidth().height(animatedHeight).padding(16.dp)) { OutlinedTextField( value = query, onValueChange = onQueryChange, modifier = Modifier.fillMaxWidth() .focusRequester(focusRequester) .onFocusChanged { focusState -> onActiveChange(focusState.isFocused) } .testTag("Search Bar Input"), singleLine = true, placeholder = { Text(text = placeholder) }, keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Search), keyboardActions = KeyboardActions( onSearch = { onSearch(query) keyboardController?.hide() focusRequester.freeFocus() })) Spacer(modifier = Modifier.height(16.dp)) if (active) { LazyColumn(modifier = Modifier.fillMaxSize().weight(1f).testTag("Search Propositions")) { items(propositions) { proposition -> Box(modifier = Modifier.fillMaxWidth().clickable { onElementClick(proposition) }) { Spacer(modifier = Modifier.height(16.dp)) Text( text = showProposition(proposition), modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp, horizontal = 16.dp)) } } } } } } @Preview @Composable fun SearchBarCustomPreview() { var active by remember { mutableStateOf(false) } var query by remember { mutableStateOf("") } SearchBarCustom( query = query, onQueryChange = { query = it }, onSearch = { active = false }, active = active, onActiveChange = { active = it }, onElementClick = { query = it }, propositions = listOf( "Proposition 1", "Proposition 2", "Proposition 3", "Proposition 4", "Proposition 5", "Proposition 6", "Proposition 7", "Proposition 8", "Proposition 9", "Proposition 10", "Proposition 11", "Proposition 12", "Proposition 13", "Proposition 14", "Proposition 15"), showProposition = { it }) }
skysync/app/src/main/java/ch/epfl/skysync/components/forms/SearchBarCustom.kt
2337781174
package ch.epfl.skysync.components.forms import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.Dp @Composable fun TitledInputTextField( padding: Dp, title: String, value: String, onValueChange: (String) -> Unit, isError: Boolean = false, messageError: String = "", keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default ) { Text( modifier = Modifier.fillMaxWidth().padding(horizontal = padding), text = title, style = MaterialTheme.typography.headlineSmall) OutlinedTextField( value = value, modifier = Modifier.fillMaxWidth().padding(horizontal = padding).testTag(title), onValueChange = onValueChange, isError = isError, supportingText = { if (isError) Text(messageError) }, singleLine = true, keyboardOptions = keyboardOptions, keyboardActions = keyboardActions) }
skysync/app/src/main/java/ch/epfl/skysync/components/forms/TitledInputTextField.kt
2042487217
package ch.epfl.skysync.components.forms import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.DatePicker import androidx.compose.material3.DatePickerDialog import androidx.compose.material3.DatePickerState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.rememberDatePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf 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.platform.testTag import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import ch.epfl.skysync.components.CustomTopAppBar import ch.epfl.skysync.models.UNSET_ID import ch.epfl.skysync.models.calendar.TimeSlot import ch.epfl.skysync.models.flight.BASE_ROLES import ch.epfl.skysync.models.flight.Balloon import ch.epfl.skysync.models.flight.Basket import ch.epfl.skysync.models.flight.Flight import ch.epfl.skysync.models.flight.FlightType import ch.epfl.skysync.models.flight.PlannedFlight import ch.epfl.skysync.models.flight.Role import ch.epfl.skysync.models.flight.RoleType import ch.epfl.skysync.models.flight.Team import ch.epfl.skysync.models.flight.Vehicle import java.time.Instant import java.time.LocalDate import java.time.ZoneId import java.util.Calendar @OptIn(ExperimentalMaterial3Api::class) @Composable fun FlightForm( navController: NavHostController, currentFlight: Flight?, modifyMode: Boolean, title: String, allFlightTypes: List<FlightType>, allRoleTypes: List<RoleType>, allVehicles: List<Vehicle>, allBalloons: List<Balloon>, allBaskets: List<Basket>, flightAction: (PlannedFlight) -> Unit, ) { Scaffold(modifier = Modifier.fillMaxSize(), topBar = { CustomTopAppBar(navController, title) }) { padding -> if (currentFlight == null && modifyMode) { Text("Flight is loading...") } else { Column { val defaultPadding = 16.dp val smallPadding = 8.dp var nbPassengersValue by remember { mutableStateOf(currentFlight?.nPassengers?.toString() ?: "") } var nbPassengersValueError by remember { mutableStateOf(false) } var openDatePicker by remember { mutableStateOf(false) } var dateValue by remember { mutableStateOf(currentFlight?.date ?: LocalDate.now()) } var flightTypeValue: FlightType? by remember { mutableStateOf(currentFlight?.flightType) } var flightTypeValueError by remember { mutableStateOf(false) } val vehicle: Vehicle? by remember { mutableStateOf(null) } val listVehiclesValue = remember { mutableStateListOf(*currentFlight?.vehicles?.toTypedArray() ?: emptyArray()) } var addVehicle by remember { mutableStateOf(listVehiclesValue.isEmpty()) } var timeSlotValue: TimeSlot by remember { mutableStateOf(currentFlight?.timeSlot ?: TimeSlot.AM) } var balloonValue: Balloon? by remember { mutableStateOf(currentFlight?.balloon) } var basketValue: Basket? by remember { mutableStateOf(currentFlight?.basket) } val crewMembers = remember { mutableStateListOf( *currentFlight?.team?.roles?.toTypedArray() ?: Role.initRoles(BASE_ROLES).toTypedArray()) } val specialRoles: MutableList<Role> = remember { mutableStateListOf() } var showAddMemberDialog by remember { mutableStateOf(false) } var addNewRole: RoleType? by remember { mutableStateOf(null) } var addNewRoleError by remember { mutableStateOf(false) } var expandedAddNewRole by remember { mutableStateOf(false) } var addNewUserQuery: String by remember { mutableStateOf("") } val lazyListState = rememberLazyListState() var isError by remember { mutableStateOf(false) } // Scroll to the first field with an error LaunchedEffect(isError) { if (nbPassengersValueError) { lazyListState.animateScrollToItem(0) } else if (flightTypeValueError) { lazyListState.animateScrollToItem(3) } } LazyColumn( modifier = Modifier.padding(padding).weight(1f).testTag("Flight Lazy Column"), state = lazyListState, verticalArrangement = Arrangement.SpaceBetween) { // Field getting the number of passengers. Only number can be entered item { TitledInputTextField( padding = defaultPadding, title = "Number of passengers", value = nbPassengersValue, onValueChange = { value -> nbPassengersValue = value.filter { it.isDigit() } }, isError = nbPassengersValueError, messageError = if (nbPassengersValueError) "Please enter a valid number" else "", keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), ) } // The date field is a clickable field that opens a date picker item { val today = Calendar.getInstance().timeInMillis val datePickerState = rememberDatePickerState(initialSelectedDateMillis = today) DatePickerField( dateValue = dateValue, defaultPadding = defaultPadding, openDatePicker = openDatePicker, onclickConfirm = { openDatePicker = false Calendar.getInstance().apply { timeInMillis = datePickerState.selectedDateMillis!! dateValue = Instant.ofEpochMilli(timeInMillis) .atZone(ZoneId.of("GMT")) .toLocalDate() } }, onclickDismiss = { openDatePicker = false }, onclickField = { openDatePicker = true }, datePickerState = datePickerState, today = today) } // Drop down menu for the time slot. Only AM and PM are available item { val timeSlotTitle = "Time Slot" TitledDropDownMenu( defaultPadding = defaultPadding, title = timeSlotTitle, value = timeSlotValue, onclickMenu = { item -> timeSlotValue = item }, items = TimeSlot.entries) } // Drop down menu for the flight type item { val flightTypeTitle = "Flight Type" TitledDropDownMenu( defaultPadding = defaultPadding, title = flightTypeTitle, value = flightTypeValue, onclickMenu = { item -> flightTypeValue = item }, items = allFlightTypes, showString = { it?.name ?: "Choose the flightType" }, isError = flightTypeValueError, messageError = "Please choose a flight type") } // Section to add the crew members item { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Text( modifier = Modifier.padding(horizontal = defaultPadding), text = "Team", style = MaterialTheme.typography.headlineSmall, ) IconButton( modifier = Modifier.padding(horizontal = defaultPadding) .testTag("Add Crew Button"), onClick = { showAddMemberDialog = true }, ) { Icon(Icons.Default.Add, contentDescription = "Add Crew Member") } } // Dialog to add a new crew member and its corresponding field if (showAddMemberDialog) { AlertDialog( onDismissRequest = { showAddMemberDialog = false }, title = { Text("Add Crew Member") }, text = { Column { CustomDropDownMenu( defaultPadding = defaultPadding, title = "Role Type", value = addNewRole, onclickMenu = { item -> addNewRole = item }, items = allRoleTypes, showString = { it?.name ?: "Choose a role" }, ) // TODO: Handle correctly the user for now it is just a text field OutlinedTextField( modifier = Modifier.fillMaxWidth() .padding(defaultPadding) .testTag("User Dialog Field"), value = addNewUserQuery, onValueChange = { addNewUserQuery = it }, placeholder = { Text("User") }, singleLine = true) } }, confirmButton = { Button( onClick = { addNewRoleError = addNewRole == null if (!addNewRoleError) { crewMembers.add(Role(addNewRole!!)) showAddMemberDialog = false } }) { Text("Add") } }, dismissButton = { Button(onClick = { showAddMemberDialog = false }) { Text("Cancel") } }) } } crewMembers.withIndex().forEach() { (id, role) -> item { RoleField(defaultPadding, smallPadding, role, id, crewMembers) } } if (flightTypeValue != null) { flightTypeValue!!.specialRoles.withIndex().forEach { (id, roleType) -> item { RoleField( defaultPadding, smallPadding, Role(roleType), id, specialRoles, "Special") } } } // Drop down menu for the vehicle item { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Text( modifier = Modifier.padding(horizontal = defaultPadding), text = "Vehicles", style = MaterialTheme.typography.headlineSmall) IconButton( modifier = Modifier.padding(horizontal = defaultPadding) .testTag("Add Vehicle Button"), onClick = { if (listVehiclesValue.size < allVehicles.size) { addVehicle = true } }, ) { Icon(Icons.Default.Add, contentDescription = "Add Vehicle") } } } listVehiclesValue.withIndex().forEach() { (idList, car) -> item { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { CustomDropDownMenu( defaultPadding = defaultPadding, title = "Vehicle $idList", value = car, onclickMenu = { item -> listVehiclesValue[idList] = item }, items = allVehicles, showString = { it.name }) IconButton( modifier = Modifier.testTag("Delete Vehicle $idList Button"), onClick = { listVehiclesValue.removeAt(idList) if (listVehiclesValue.isEmpty()) { addVehicle = true } }, ) { Icon(Icons.Default.Delete, contentDescription = "Delete Vehicle $idList") } } } } if (addVehicle) { item { val id = listVehiclesValue.size Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { CustomDropDownMenu( defaultPadding = defaultPadding, title = "Vehicle $id", value = vehicle, onclickMenu = { item -> addVehicle = false listVehiclesValue.add(item!!) }, items = allVehicles, showString = { it?.name ?: "Choose a vehicle" }) IconButton( modifier = Modifier.testTag("Delete Vehicle $id Button"), onClick = { listVehiclesValue.removeAt(id) if (listVehiclesValue.isEmpty()) { addVehicle = true } }, ) { Icon(Icons.Default.Delete, contentDescription = "Delete Vehicle $id") } } } } // Drop down menu for the balloon item { val balloonTitle = "Balloon" TitledDropDownMenu( defaultPadding = defaultPadding, title = balloonTitle, value = balloonValue, onclickMenu = { item -> balloonValue = item }, items = allBalloons, showString = { it?.name ?: "Choose the balloon" }) } // Drop down menu for the basket item { val basketTitle = "Basket" TitledDropDownMenu( defaultPadding = defaultPadding, title = basketTitle, value = basketValue, onclickMenu = { item -> basketValue = item }, items = allBaskets, showString = { it?.name ?: "Choose the basket" }) } } // Button to add the flight to the list of flights Button( modifier = Modifier.fillMaxWidth().padding(defaultPadding).testTag("$title Button"), onClick = { nbPassengersValueError = nbPassengerInputValidation(nbPassengersValue) flightTypeValueError = flightTypeInputValidation(flightTypeValue) isError = inputValidation(nbPassengersValueError, flightTypeValueError) if (!isError) { val vehicles: List<Vehicle> = if (vehicle == null) emptyList() else listOf(vehicle!!) val allRoles = crewMembers.toList() + specialRoles val team = Team(allRoles) val newFlight = PlannedFlight( nPassengers = nbPassengersValue.toInt(), date = dateValue, flightType = flightTypeValue!!, timeSlot = timeSlotValue, balloon = balloonValue, basket = basketValue, vehicles = vehicles, team = team, id = currentFlight?.id ?: UNSET_ID) flightAction(newFlight) } }) { Text(title) } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun DatePickerField( dateValue: LocalDate, defaultPadding: Dp, openDatePicker: Boolean, onclickConfirm: () -> Unit, onclickDismiss: () -> Unit, onclickField: () -> Unit, datePickerState: DatePickerState, today: Long ) { Text( modifier = Modifier.padding(horizontal = defaultPadding), text = "Date", style = MaterialTheme.typography.headlineSmall) if (openDatePicker) { DatePickerDialog( onDismissRequest = {}, confirmButton = { TextButton(onClick = onclickConfirm) { Text("OK") } }, dismissButton = { TextButton(onClick = onclickDismiss) { Text("Cancel") } }) { // The date picker is only available for the current date and later val todayDate = Instant.ofEpochMilli(today) .atZone(ZoneId.of("GMT")) .toLocalDate() .atStartOfDay(ZoneId.of("GMT")) .toInstant() .toEpochMilli() DatePicker(state = datePickerState, dateValidator = { it >= todayDate }) } } OutlinedTextField( modifier = Modifier.fillMaxWidth() .padding(defaultPadding) .clickable(onClick = onclickField) .testTag("Date Field"), enabled = false, value = String.format( "%02d/%02d/%04d", dateValue.dayOfMonth, dateValue.monthValue, dateValue.year), onValueChange = {}) } fun nbPassengerInputValidation(nbPassengersValue: String): Boolean { return nbPassengersValue.isEmpty() || nbPassengersValue.toInt() <= 0 } fun flightTypeInputValidation(flightTypeValue: FlightType?): Boolean { return flightTypeValue == null } fun inputValidation(nbPassengersValueError: Boolean, flightTypeValueError: Boolean): Boolean { return nbPassengersValueError || flightTypeValueError } @Composable fun RoleField( defaultPadding: Dp, smallPadding: Dp, role: Role, id: Int, crewMembers: MutableList<Role>, specialName: String = "" ) { var query by remember { mutableStateOf("") } Text(modifier = Modifier.padding(horizontal = defaultPadding), text = role.roleType.name) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { OutlinedTextField( modifier = Modifier.fillMaxWidth() .padding(horizontal = defaultPadding, vertical = smallPadding) .weight(1f) .testTag("$specialName User $id"), value = query, onValueChange = { query = it }, placeholder = { Text("User ${id + 1}") }, singleLine = true) IconButton(onClick = { crewMembers.removeAt(id) }) { Icon( modifier = Modifier.testTag("Delete $specialName Crew Member $id"), imageVector = Icons.Default.Delete, contentDescription = "Delete $specialName Crew Member") } } } @Composable @Preview fun FlightFormPreview() { val navController = rememberNavController() val currentFlight = PlannedFlight( nPassengers = 1, date = LocalDate.now(), flightType = FlightType.PREMIUM, timeSlot = TimeSlot.AM, vehicles = listOf(), balloon = null, basket = null, id = "testId") FlightForm( navController = navController, currentFlight, modifyMode = false, "Flight Form", emptyList(), emptyList(), emptyList(), emptyList(), emptyList(), flightAction = {}) }
skysync/app/src/main/java/ch/epfl/skysync/components/forms/FlightForm.kt
3862769119
package ch.epfl.skysync.components import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import ch.epfl.skysync.models.calendar.AvailabilityStatus import ch.epfl.skysync.models.calendar.TimeSlot import ch.epfl.skysync.ui.theme.* import java.time.LocalDate // Define custom colors to represent availability status // These colors are used to indicate availability status in the UI // Custom color for indicating availability status as "OK" (e.g., available) val customGreen = Color(0xffaaee7b) // Custom color for indicating availability status as "MAYBE" (e.g., partially available) val customBlue = Color(0xff9ae0f0) // Custom color for indicating availability status as "NO" (e.g., not available) val customRed = Color(0xfff05959) // Custom color for indicating an empty or unknown availability status val customEmpty = Color(0xfff0f0f0) /** * Maps availability status to a corresponding color. * * @param status The availability status to be mapped. * @return The color representing the availability status. */ fun availabilityToColor(status: AvailabilityStatus): Color { val availabilityToColorMap = mapOf( AvailabilityStatus.OK to customGreen, AvailabilityStatus.MAYBE to customBlue, AvailabilityStatus.NO to customRed) return availabilityToColorMap.getOrDefault(status, customEmpty) } /** * Composable function to display a colored tile indicating availability status. * * @param date The date of the tile * @param time The time slot of the tile * @param availabilityStatus The availability status of the tile * @param onClick Callback called when clicking on the tile */ @Composable fun AvailabilityTile( date: LocalDate, time: TimeSlot, availabilityStatus: AvailabilityStatus, onClick: () -> Unit ) { val weight = if (time == TimeSlot.AM) 0.5f else 1f val testTag = date.toString() + time.toString() Box( modifier = Modifier.fillMaxHeight() .fillMaxWidth(weight) .testTag(testTag) .background( color = availabilityToColor(availabilityStatus), shape = RoundedCornerShape(0.dp)) .clickable { onClick() }) {} } /** * Composable function to display buttons for saving or canceling availabilities. * * @param isDraft Indicates if the [AvailabilityCalendar] is being modified * @param onSave Callback called when clicking on the save button, should save the * * [AvailabilityCalendar] to the database * * @param onCancel Callback called when clicking on the cancel button, should reset the * * [AvailabilityCalendar] to its original state */ @Composable fun SaveCancelButton( isDraft: Boolean, onSave: () -> Unit, onCancel: () -> Unit, ) { Row( modifier = Modifier.padding(8.dp), ) { Button( onClick = onCancel, enabled = isDraft, colors = ButtonDefaults.buttonColors(containerColor = darkOrange), shape = RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp), modifier = Modifier.weight(1f).testTag("CancelButton"), ) { Text(text = "Cancel", fontSize = 12.sp, overflow = TextOverflow.Clip) } Button( onClick = onSave, enabled = isDraft, shape = RoundedCornerShape(topEnd = 10.dp, bottomEnd = 10.dp), modifier = Modifier.weight(1f).testTag("SaveButton"), ) { Text( text = "Save", fontSize = 12.sp, overflow = TextOverflow.Clip, ) } } } /** * Composable function to display a calendar with the user's availabilities for each date and time * slot. * * @param padding The padding of the surrounding Scafffold * @param getAvailabilityStatus Callback that returns the [AvailabilityStatus] for a specific date * and time slot * @param nextAvailabilityStatus Callback called when clicking on an tile, returns the next * [AvailabilityStatus], should also update the [AvailabilityCalendar] * @param onSave Callback called when clicking on the save button, should save the * [AvailabilityCalendar] to the database * @param onCancel Callback called when clicking on the cancel button, should reset the * [AvailabilityCalendar] to its original state */ @Composable fun AvailabilityCalendar( padding: PaddingValues, getAvailabilityStatus: (LocalDate, TimeSlot) -> AvailabilityStatus, nextAvailabilityStatus: (LocalDate, TimeSlot) -> AvailabilityStatus, onSave: () -> Unit, onCancel: () -> Unit ) { var isDraft by remember { mutableStateOf(false) } Column(modifier = Modifier.padding(padding)) { ModularCalendar(modifier = Modifier.weight(1f), isDraft = isDraft) { date, time -> // at the moment the Calendar is a mutable class // thus the reference of the Calendar stay the same on updates // -> it does not trigger a recompose. To trigger the recompose // we have to store the availability status in a state and update // it each time the result of getAvailabilityStatus change // which is a bit hacky and should be a temporary solution val availabilityStatus = getAvailabilityStatus(date, time) var status by remember { mutableStateOf(availabilityStatus) } if (status != availabilityStatus) { status = availabilityStatus } AvailabilityTile(date = date, time = time, availabilityStatus = status) { status = nextAvailabilityStatus(date, time) isDraft = true } } SaveCancelButton( isDraft = isDraft, onSave = { onSave() isDraft = false }) { onCancel() isDraft = false } } }
skysync/app/src/main/java/ch/epfl/skysync/components/AvailabilityCalendar.kt
1610706049
package ch.epfl.skysync.components import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import ch.epfl.skysync.ui.theme.lightOrange /** * Composable function representing a back button with an arrow icon and text. * * @param backClick Callback function to be invoked when the back button is clicked. */ @Composable fun Backbutton(backClick: () -> Unit) { IconButton(onClick = backClick, modifier = Modifier.fillMaxWidth(0.2f).testTag("BackButton")) { Row(verticalAlignment = Alignment.CenterVertically) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back", tint = lightOrange) Text(text = "Back", color = lightOrange) } } }
skysync/app/src/main/java/ch/epfl/skysync/components/BackButton.kt
1417863321
package ch.epfl.skysync.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.sp /** * Composable function representing a header with a back button and title. * * @param BackClick Callback function to be invoked when the back button is clicked. * @param title Title text to be displayed in the header. */ @Composable fun Header(backClick: () -> Unit, title: String) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, ) { Backbutton(backClick) Column( modifier = Modifier.fillMaxWidth(0.75f), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Text( text = title, color = Color.Black, fontSize = 30.sp, modifier = Modifier.testTag("HeaderTitle")) } } }
skysync/app/src/main/java/ch/epfl/skysync/components/Header.kt
362576951
package ch.epfl.skysync.components import androidx.compose.material3.Snackbar import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.receiveAsFlow // Singleton object to manage snackbar messages. object SnackbarManager { // Using a Channel to handle message passing; conflated to drop old messages if new ones arrive // before they are displayed. private val messageChannel = Channel<String>(Channel.CONFLATED) // Function to enqueue a message to the snackbar. Messages are sent to the channel. fun showMessage(message: String) { messageChannel.trySend(message) } // Exposes the internal channel as a Flow to be collected by the composable layer. val messagesFlow = messageChannel.receiveAsFlow() } // Composable function that hosts a Snackbar. It listens for messages from the SnackbarManager. @Composable fun GlobalSnackbarHost() { // Remember a SnackbarHostState which controls the snackbar queue. val snackbarHostState = remember { SnackbarHostState() } val snackbarManager = SnackbarManager // LaunchedEffect to listen to messages from SnackbarManager and show them as they arrive. LaunchedEffect(snackbarManager) { snackbarManager.messagesFlow.collect { message -> snackbarHostState.showSnackbar(message) } } // The actual SnackbarHost that will display the snackbars. SnackbarHost( hostState = snackbarHostState, snackbar = { snackbarData -> Snackbar(snackbarData = snackbarData) }) } // Preview of how the snackbar system works within a Scaffold. Useful for seeing the behavior in the // design tool. // @Preview(showBackground = true) // @Composable // fun SnackbarPreview() { // MaterialTheme { // Scaffold(snackbarHost = { GlobalSnackbarHost() }) { innerPadding -> // Box( // contentAlignment = Alignment.Center) { // // An effect to send a test message when the Preview is launched. // LaunchedEffect(Unit) { SnackbarManager.showMessage("Preview: Error in database") } // } // } // } // }
skysync/app/src/main/java/ch/epfl/skysync/components/Snackbar.kt
3529084424
package ch.epfl.skysync.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.dp import ch.epfl.skysync.ui.theme.lightOrange import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState /** * A reusable loading component that displays a progress indicator when content is being loaded. It * also supports a pull-to-refresh mechanism to reload content. The progress indicator is displayed * over the content as an overlay when data is loading or during a refresh action. * * @param isLoading Boolean state indicating whether the data is currently loading. The progress * indicator is shown on top of the content when true. * @param onRefresh Function to be invoked when a refresh is triggered by the user. This allows * external specification of the reload behavior, enhancing the component's reusability. * @param content A composable that defines the content to be displayed when not loading. This * content will be displayed beneath the progress indicator during loading operations. */ @Composable fun LoadingComponent( isLoading: Boolean, onRefresh: () -> Unit, // Added onRefresh as a parameter to handle reload logic , content: @Composable () -> Unit ) { // The SwipeRefresh component is used to wrap the content. It provides pull-to-refresh // functionality. SwipeRefresh( state = rememberSwipeRefreshState(isLoading), onRefresh = onRefresh, // Use the passed onRefresh function here modifier = Modifier.testTag("SwipeRefreshLayout"), indicator = { state, trigger -> // This ensures the CircularProgressIndicator is part of the layer but does not obscure // content layout if (state.isRefreshing) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator( modifier = Modifier.size(50.dp).testTag("ProgressIndicator"), color = lightOrange) } } }) { content() } // Display the CircularProgressIndicator centered on top of the content when isLoading is // true if (isLoading) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator( modifier = Modifier.size(50.dp).testTag("LoadingIndicator"), color = lightOrange) } } } /** * Preview of the LoadingComponent. This preview function helps visualize how the LoadingComponent * will look in the UI. */ // @Preview(showBackground = true) // @Composable // fun LoadingContentPreview() { // Surface(modifier = Modifier.fillMaxSize()) { // Instantiate the LoadingComponent with a simple Text inside. // LoadingComponent( // isLoading = true, // onRefresh = { /* Define what happens on refresh here, e.g., viewModel.loadData() */}, // content = { // Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { // Text("Content goes here", style = MaterialTheme.typography.bodyLarge) // } // }) // } // }
skysync/app/src/main/java/ch/epfl/skysync/components/Loading.kt
4176887135
package ch.epfl.skysync.components import androidx.compose.foundation.layout.* 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.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.ButtonDefaults import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import ch.epfl.skysync.models.flight.FlightColor import ch.epfl.skysync.models.flight.FlightType import ch.epfl.skysync.models.flight.PlannedFlight import ch.epfl.skysync.models.flight.Vehicle import ch.epfl.skysync.screens.flightDetail.ClickButton import ch.epfl.skysync.ui.theme.lightOrange import java.time.LocalDate import java.time.LocalTime import java.time.format.DateTimeFormatter /** * Composable function to display a confirmation screen for a planned flight. * * @param plannedFlight The planned flight for which the confirmation screen is displayed. */ @Composable fun confirmation(plannedFlight: PlannedFlight, confirmClick: () -> Unit) { val id: String = plannedFlight.id val nPassengers: Int = plannedFlight.nPassengers val flightType: FlightType = plannedFlight.flightType val teamRoles = plannedFlight.team.roles val balloon = plannedFlight.balloon val basket = plannedFlight.basket val date: LocalDate = plannedFlight.date val timeSlot = plannedFlight.timeSlot val vehicles: List<Vehicle> = plannedFlight.vehicles var remarks: List<String> = emptyList() var Teamcolor = FlightColor.NO_COLOR var meetupTimeTeam = LocalTime.now() var departureTimeTeam = meetupTimeTeam.plusHours(1) var meetupTimePassenger = departureTimeTeam.plusHours(1) var meetupLocationPassenger = "Nancy" val fontSize = 17.sp LazyColumn(Modifier.testTag("LazyList")) { item { Text( modifier = Modifier.fillMaxWidth().padding(top = 18.dp, bottom = 25.dp), text = "Confirmation of Flight $id", fontSize = 24.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center) Text( modifier = Modifier.fillMaxWidth().padding(bottom = 12.dp), text = "Informations to confirm", fontSize = 20.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center) elementShow("Passengers nb", "$nPassengers", fontSize) elementShow("Flight type", flightType.name, fontSize) teamRoles.withIndex().forEach() { (i, role) -> elementShow("Teammate" + " " + (i + 1).toString(), role.roleType.name, fontSize) } if (balloon != null) { elementShow("Balloon", balloon.name, fontSize) } if (basket != null) { elementShow("Basket", basket.name, fontSize) } elementShow( "Date", (date.dayOfMonth.toString() + " " + date.month.toString() + " $timeSlot").lowercase(), fontSize) vehicles.withIndex().forEach() { (i, vehicle) -> elementShow("Vehicle" + " " + (i + 1).toString(), vehicle.name, fontSize) } Text( modifier = Modifier.fillMaxWidth().padding(top = 12.dp, bottom = 16.dp), text = "Informations to enter", fontSize = 20.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center) // color choosing: var selectedOption by remember { mutableStateOf<String?>(null) } val options = listOf("RED", "BLUE", "ORANGE", "YELLOW", "PINK", "NO_COLOR") Row() { Column(Modifier.fillMaxWidth(0.5f)) { Spacer(modifier = Modifier.height(5.dp)) Text( modifier = Modifier.fillMaxWidth(), text = "Team Color", fontSize = fontSize, textAlign = TextAlign.Center) } Column( Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { OptionSelector( options = options, onOptionSelected = { option -> selectedOption = option }, 65.dp) } } // meetup time : Text( modifier = Modifier.fillMaxWidth(), text = "MeetUp time", fontSize = fontSize, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center) var selectedTime by remember { mutableStateOf<LocalTime?>(null) } Column( modifier = Modifier.padding(2.dp), ) { TimePicker({ time -> selectedTime = time }, LocalTime.now(), 65.dp, "MeetUp") selectedTime?.let { time -> Text( text = "Selected Time: ${time.format(DateTimeFormatter.ofPattern("HH:mm"))}", fontSize = 16.sp) } } // departure Time Team : Text( modifier = Modifier.fillMaxWidth(), text = "Departure Time (For Team)", fontSize = fontSize, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center) var selectedTime1 by remember { mutableStateOf<LocalTime?>(null) } Column( modifier = Modifier.padding(2.dp), ) { TimePicker({ time -> selectedTime1 = time }, meetupTimePassenger, 65.dp, "Departure") selectedTime1?.let { time -> Text( text = "Selected Time: ${time.format(DateTimeFormatter.ofPattern("HH:mm"))}", fontSize = 16.sp) } } // meetUp Time for passengers : Text( modifier = Modifier.fillMaxWidth(), text = "MeetUp (passengers)", fontSize = fontSize, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center) var selectedTime2 by remember { mutableStateOf<LocalTime?>(null) } Column( modifier = Modifier.padding(2.dp), ) { TimePicker({ time -> selectedTime2 = time }, meetupTimeTeam, 65.dp, "MeetUp pass.") selectedTime2?.let { time -> Text( text = "Selected Time: ${time.format(DateTimeFormatter.ofPattern("HH:mm"))}", fontSize = 16.sp) } } // meetUp location: var location: String = meetupLocationPassenger val keyboardController = LocalSoftwareKeyboardController.current Column( modifier = Modifier.padding(2.dp), ) { AddElementComposable( title = "MeetUp Location", remarksList = { -> listOf(location) }, onAddRemark = { remark -> location = remark (keyboardController)?.hide() }) } // remark adding var remarkList: List<String> = remarks Column( modifier = Modifier.padding(2.dp), ) { AddElementComposable( remarksList = { -> remarkList }, onAddRemark = { remark -> if (remark != "") { remarkList += (remark) } }) } Box(modifier = Modifier.fillMaxWidth().padding(2.dp), contentAlignment = Alignment.Center) { ClickButton( text = "Confirm", onClick = { confirmClick() }, modifier = Modifier.fillMaxWidth(0.7f).testTag("ConfirmThisFlightButton"), color = Color.Green) } } } } /** * Composable function to display two text elements side by side. * * @param left The text to display on the left side. * @param right The text to display on the right side. * @param fontSize The font size of the text elements. */ @Composable fun elementShow(left: String, right: String, fontSize: TextUnit) { Row(Modifier.padding(top = 7.dp, bottom = 7.dp)) { Text( text = left, modifier = Modifier.fillMaxWidth(0.5f), fontSize = fontSize, textAlign = TextAlign.Center) Text( text = right, modifier = Modifier.fillMaxWidth(), fontSize = fontSize, textAlign = TextAlign.Center) } } /** * Composable function to create a time picker for selecting hours and minutes. * * @param onTimeSelected A lambda function to handle when a time is selected. Accepts a LocalTime * parameter representing the selected time. * @param baseTime The initial time displayed in the time picker. * @param height The height of the time picker. * @param testTag A tag used for testing purposes. */ @Composable fun TimePicker( onTimeSelected: (LocalTime) -> Unit, baseTime: LocalTime, height: Dp, testTag: String ) { val startHour = baseTime.hour val startMinute = baseTime.minute var hours by remember { mutableStateOf(startHour) } var minutes by remember { mutableStateOf(startMinute) } val keyboardController = LocalSoftwareKeyboardController.current Column(modifier = Modifier.padding(8.dp).height(height), horizontalAlignment = Alignment.Start) { Row(horizontalArrangement = Arrangement.Start) { OutlinedTextField( modifier = Modifier.fillMaxWidth(0.3f).testTag(testTag + "/Hours"), value = if (hours == -1) { "" } else { hours.toString() }, onValueChange = { hours = it.toIntOrNull() ?: -1 }, label = { Text("Hours") }, keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Next), keyboardActions = KeyboardActions( onNext = { // Move focus to the next TextField or perform any action })) Spacer(modifier = Modifier.width(16.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(0.45f).testTag(testTag + "/Minutes"), value = if (minutes == -1) { "" } else { minutes.toString() }, onValueChange = { minutes = it.toIntOrNull() ?: -1 }, label = { Text("Minutes") }, keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done), keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() })) Spacer(modifier = Modifier.width(16.dp)) Button( modifier = Modifier.fillMaxWidth(1f).testTag(testTag + "/SetTime"), colors = ButtonDefaults.buttonColors(backgroundColor = lightOrange), onClick = { if (hours !in 0..23 || minutes !in 0..59) { return@Button } if (minutes !in 0..59) { return@Button } val time = LocalTime.of(hours, minutes) keyboardController?.hide() onTimeSelected(time) }, ) { Text(text = "Set Time") } } } } /** * Composable function to create a dropdown menu for selecting an option from a list. * * @param options The list of options to display in the dropdown menu. * @param onOptionSelected A lambda function to handle when an option is selected. Accepts a string * parameter representing the selected option. * @param height The height of the dropdown menu. */ @Composable fun OptionSelector(options: List<String>, onOptionSelected: (String) -> Unit, height: Dp) { var expanded by remember { mutableStateOf(false) } var selectedIndex by remember { mutableStateOf(0) } var selectedOption by remember { mutableStateOf<String?>(null) } var selected by remember { mutableStateOf("Select Option") } Column( modifier = Modifier.fillMaxWidth().height(height), horizontalAlignment = Alignment.CenterHorizontally) { OutlinedButton(onClick = { expanded = true }) { Text(text = selected) } DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { options.forEachIndexed { index, option -> DropdownMenuItem( onClick = { selectedIndex = index selectedOption = option expanded = false onOptionSelected(option) }, modifier = Modifier.padding(vertical = 1.dp).testTag(option)) { Text(text = option) } } } selectedOption?.let { selected = it } } } /** * Composable function to create an element with a text input field, a button to add the input as a * remark, and a list of remarks. * * @param title The title of the element. Defaults to "Remark". * @param remarksList A lambda function that provides the list of remarks. * @param onAddRemark A lambda function to handle adding a remark. Accepts a string parameter * representing the remark to add. */ @Composable fun AddElementComposable( title: String = "Remark", remarksList: () -> List<String>, onAddRemark: (String) -> Unit ) { var remarkText by remember { mutableStateOf("") } Column( modifier = Modifier.padding(0.dp).fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { TextField( value = remarkText, onValueChange = { remarkText = it }, label = { Text("Enter " + title) }, keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done), keyboardActions = KeyboardActions( onDone = { onAddRemark(remarkText) remarkText = "" }), modifier = Modifier.fillMaxWidth().padding(bottom = 0.dp)) Button( onClick = { onAddRemark(remarkText) remarkText = "" }, colors = ButtonDefaults.buttonColors(backgroundColor = lightOrange)) { Text("Add " + title) } Column { remarksList().forEach { remark -> if (remark != "") { Text(text = remark) } } } } }
skysync/app/src/main/java/ch/epfl/skysync/components/ConfirmFlightUI.kt
562447760
package ch.epfl.skysync.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.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.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import ch.epfl.skysync.ui.theme.lightOrange import kotlinx.coroutines.delay @Composable fun Timer(modifier: Modifier) { var timer by remember { mutableIntStateOf(0) } var isRunning by remember { mutableStateOf(false) } Box( modifier = modifier.testTag("Timer"), contentAlignment = androidx.compose.ui.Alignment.Center) { Column(horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally) { Text( modifier = Modifier.testTag("Timer Value"), text = timer.formatTime(), style = MaterialTheme.typography.headlineMedium) if (isRunning) { Button( modifier = Modifier.testTag("Reset Button"), onClick = { isRunning = !isRunning timer = 0 }) { Text(text = "Reset") } } else { Button( modifier = Modifier.testTag("Start Button"), onClick = { isRunning = !isRunning }, colors = ButtonDefaults.buttonColors(containerColor = lightOrange)) { Text(text = "Start") } } if (isRunning) { LaunchedEffect(key1 = isRunning) { while (isRunning) { delay(1000) timer++ } } } } } } // Format the time in HH:MM:SS format from seconds fun Int.formatTime(): String { val hours = this / 3600 val minutes = (this % 3600) / 60 val remainingSeconds = this % 60 return String.format("%02d:%02d:%02d", hours, minutes, remainingSeconds) } @Preview @Composable fun TimerPreview() { Timer(Modifier.padding(16.dp)) }
skysync/app/src/main/java/ch/epfl/skysync/components/Timer.kt
3252226835
package ch.epfl.skysync.components import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight 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.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.Send import androidx.compose.material.icons.filled.Send import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import ch.epfl.skysync.ui.theme.lightOrange enum class MessageType { SENT, RECEIVED, } data class ChatMessage( val sender: String, val messageType: MessageType, val profilePicture: ImageVector?, val message: String, val time: String ) /** * Composable function representing a chat screen. * * @param groupName Name of the group or chat. * @param msgList List of chat messages with sender information, message content, and timestamp. * @param backClick Callback function to be invoked when the back button is clicked. * @param sendClick Callback function to be invoked when a message is sent. * @param paddingValues Padding values to be applied to the chat screen. */ @Composable fun ChatText( groupName: String, messages: List<ChatMessage>, onBack: () -> Unit, onSend: (String) -> Unit, paddingValues: PaddingValues ) { Column(modifier = Modifier.fillMaxSize().padding(paddingValues)) { Header(backClick = onBack, title = groupName) Spacer(modifier = Modifier.size(1.dp)) ChatTextBody(messages) ChatInput(onSend) } } /** * Composable function representing the body of a chat screen, displaying chat bubbles. * * @param msgList List of chat messages with sender name, sender profile picture, message content, * and timestamp. */ @Composable fun ChatTextBody(messages: List<ChatMessage>) { val lazyListState = rememberLazyListState() LazyColumn(Modifier.fillMaxHeight(0.875f).testTag("ChatTextBody"), state = lazyListState) { items(messages.size) { index -> ChatBubble(message = messages[index], index = "$index") } } LaunchedEffect(Unit) { lazyListState.scrollToItem(messages.size - 1) } } /** * Composable function representing a chat bubble. * * @param message The message. * @param index The index of the chat bubble. */ @Composable fun ChatBubble(message: ChatMessage, index: String) { var isMyMessage = false val image = message.profilePicture val messageContent = message.message val time = message.time if (message.messageType == MessageType.SENT) { isMyMessage = true } val backgroundColor = if (isMyMessage) Color(0xFFDCF8C6) else Color.White val contentColor = Color.Black val shape = when (isMyMessage) { false -> { RoundedCornerShape(topStart = 8.dp, topEnd = 8.dp, bottomEnd = 8.dp, bottomStart = 0.dp) } true -> { RoundedCornerShape(topStart = 8.dp, topEnd = 8.dp, bottomEnd = 0.dp, bottomStart = 8.dp) } } Row( modifier = Modifier.padding(8.dp).fillMaxWidth(), horizontalArrangement = if (isMyMessage) Arrangement.End else Arrangement.Start, verticalAlignment = Alignment.Bottom) { if (!isMyMessage) { if (image != null) { Box(modifier = Modifier.fillMaxWidth(0.125f).size(30.dp)) { Image(imageVector = image, contentDescription = "Image of Sender") } } else { Box( modifier = Modifier.fillMaxWidth(0.075f) .size(30.dp) .background(color = Color.LightGray, shape = CircleShape)) {} } Spacer(modifier = Modifier.size(2.dp)) } Column( modifier = Modifier.background(color = backgroundColor, shape = shape).padding(8.dp)) { Row { Text( text = messageContent, color = contentColor, modifier = Modifier.padding(bottom = 2.dp).testTag("ChatBubbleMessage$index")) Spacer(modifier = Modifier.size(4.dp)) Text( text = time, color = Color.Gray, fontSize = 9.sp, modifier = Modifier.align(Alignment.Bottom).testTag("ChatBubbleTime$index")) } } } } /** * Composable function representing an input field for typing and sending messages. * * @param onSend Callback function to be invoked when a message is sent. It takes the message as a * parameter. */ @Composable fun ChatInput(onSend: (String) -> Unit) { var text by remember { mutableStateOf("") } val keyboardController = LocalSoftwareKeyboardController.current Row( modifier = Modifier.fillMaxWidth().padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { OutlinedTextField( value = text, onValueChange = { text = it }, label = { Text("Type a message") }, colors = OutlinedTextFieldDefaults.colors( focusedBorderColor = Color.DarkGray, focusedLabelColor = Color.DarkGray), singleLine = true, keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Send), keyboardActions = KeyboardActions( onSend = { onSend(text) text = "" keyboardController?.hide() }), modifier = Modifier.weight(1f).testTag("ChatInput")) IconButton( onClick = { onSend(text) text = "" }, modifier = Modifier.padding(start = 8.dp) .background(lightOrange, CircleShape) .testTag("SendButton")) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send", tint = Color.White) } } }
skysync/app/src/main/java/ch/epfl/skysync/components/ChatText.kt
3202643499
package ch.epfl.skysync.components import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.navigation.NavController @OptIn(ExperimentalMaterial3Api::class) @Composable fun CustomTopAppBar(navController: NavController, title: String) { TopAppBar( title = { Text(text = title, style = MaterialTheme.typography.headlineMedium) }, navigationIcon = { IconButton(onClick = { navController.popBackStack() }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") } }) }
skysync/app/src/main/java/ch/epfl/skysync/components/CustomTopAppBar.kt
4188551316
package ch.epfl.skysync.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.platform.testTag 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.sp import ch.epfl.skysync.models.calendar.TimeSlot import ch.epfl.skysync.models.flight.Flight import ch.epfl.skysync.ui.theme.* import java.time.LocalDate /** * Composable function to display flight information based on a given date and time slot. * * @param date The date of the tile * @param time The time slot of the tile * @param flight The flight at this tile, if any * @param onClick Callback called when clicking on the tile */ @Composable fun FlightTile(date: LocalDate, time: TimeSlot, flight: Flight?, onClick: () -> Unit) { val testTag = date.toString() + time.toString() val weight = if (time == TimeSlot.AM) 0.5f else 1f if (flight != null) { Button( onClick = { onClick() }, shape = RectangleShape, modifier = Modifier.fillMaxHeight().fillMaxWidth(weight).testTag(testTag), colors = ButtonDefaults.buttonColors(containerColor = Color.Cyan)) { Text( text = flight.flightType.name, fontSize = 12.sp, color = Color.Black, overflow = TextOverflow.Clip, maxLines = 1, modifier = Modifier.width(120.dp), textAlign = TextAlign.Center) } } else { Box( modifier = Modifier.background(lightGray).fillMaxHeight().fillMaxWidth(weight).testTag(testTag), contentAlignment = Alignment.Center) {} } } /** * Composable function to display a calendar with flight information for each date and time slot. * * @param padding The padding of the surrounding Scaffold * @param getFirstFlightByDate Callback that returns the first [Flight] (if any) for a specific date * and time slot * @param onFlightClick Callback called when clicking on a tile with a flight */ @Composable fun FlightCalendar( padding: PaddingValues, getFirstFlightByDate: (LocalDate, TimeSlot) -> Flight?, onFlightClick: (Flight) -> Unit ) { Column(modifier = Modifier.padding(padding)) { ModularCalendar(modifier = Modifier, isDraft = false) { date, time -> val flight = getFirstFlightByDate(date, time) FlightTile( date = date, time = time, flight = flight, ) { onFlightClick(flight!!) } } } }
skysync/app/src/main/java/ch/epfl/skysync/components/FlightCalendar.kt
1240485815
package ch.epfl.skysync.components 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.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight 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.lazy.LazyColumn import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults 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.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import ch.epfl.skysync.ui.theme.lightGray import ch.epfl.skysync.ui.theme.lightOrange data class GroupDetail( val groupName: String, val groupImage: ImageVector?, val lastMessage: String, val lastMessageTime: String ) /** * Composable function to display a group chat UI. * * @param groupList A list of quadruples representing group data containing group name, image, last * message, and last message time. * @param onClick Callback triggered when a group is clicked. * @param paddingValues Padding values for the column. */ @Composable fun GroupChat( groupList: List<GroupDetail>, onClick: (String) -> Unit, paddingValues: PaddingValues ) { var searchQuery by remember { mutableStateOf("") } Column(modifier = Modifier.fillMaxSize().padding(paddingValues)) { GroupChatTopBar() Spacer(modifier = Modifier.fillMaxHeight(0.02f)) OutlinedTextField( value = searchQuery, onValueChange = { searchQuery = it }, label = { Text("Search") }, colors = OutlinedTextFieldDefaults.colors( focusedBorderColor = lightOrange, focusedLabelColor = lightOrange), modifier = Modifier.fillMaxWidth().testTag("Search"), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done)) val filteredGroups = groupList.filter { it.groupName.contains(searchQuery, ignoreCase = true) } Spacer(modifier = Modifier.fillMaxHeight(0.05f)) GroupChatBody(groupList = filteredGroups, onClick = onClick) } } /** Composable function to display the top bar of the group chat UI. */ @Composable fun GroupChatTopBar() { Column { Box( modifier = Modifier.fillMaxWidth().fillMaxHeight(0.05f), contentAlignment = Alignment.Center, ) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center) { Text( text = "Messages", fontWeight = FontWeight.Bold, fontSize = 22.sp, ) } } } } /** * Composable function to display a group card in the group chat UI. * * @param group The name of the group. * @param onClick Callback triggered when the group card is clicked. * @param groupImage The image associated with the group. Can be null if no image is available. * @param lastMsg The last message in the group. * @param lastMsgTime The time of the last message. * @param testTag A tag used for testing purposes. */ @Composable fun GroupCard( group: String, onClick: (String) -> Unit, groupImage: ImageVector?, lastMsg: String, lastMsgTime: String, testTag: String ) { Card( modifier = Modifier.clickable(onClick = { onClick(group) }).fillMaxWidth().testTag(testTag), shape = RectangleShape, colors = CardDefaults.cardColors( containerColor = lightGray, )) { Row { if (groupImage != null) { Box(modifier = Modifier.fillMaxWidth(0.125f).size(50.dp)) { Image(imageVector = groupImage, contentDescription = "Group Image") } } else { Box( modifier = Modifier.fillMaxWidth(0.125f) .size(50.dp) .background(color = Color.LightGray)) {} } Spacer(modifier = Modifier.size(10.dp)) Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.SpaceBetween) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text( text = group, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = Color.Black) Text( text = lastMsgTime, color = Color.Gray, style = MaterialTheme.typography.bodyMedium, ) } Text( text = lastMsg, color = Color.Black, style = MaterialTheme.typography.bodyMedium) } } } } /** * Composable function to display the body of the group chat UI. * * @param Groups List of quadruples representing group data containing group name, image, last * message, and last message time. * @param onClick Callback triggered when a group card is clicked. */ @Composable fun GroupChatBody(groupList: List<GroupDetail>, onClick: (String) -> Unit) { LazyColumn(modifier = Modifier.testTag("GroupChatBody")) { items(groupList.size) { index -> GroupCard( group = groupList[index].groupName, onClick = onClick, groupImage = groupList[index].groupImage, lastMsg = groupList[index].lastMessage, lastMsgTime = groupList[index].lastMessageTime, testTag = "GroupCard$index") Spacer(modifier = Modifier.size(1.dp)) } } } // @Composable // @Preview // fun GroupChatPreview() { // val image: ImageVector? = null // val groups = listOf(Quadruple("Group 1", image, "Last message", "Last message time"), // Quadruple("Group 2",image, "Last message", "Last message time"), // Quadruple("Group 3",image,"Last message", "Last message time") // ) // GroupChat(GroupsImageLastmsgLastmsgtime = groups, onClick = {}, paddingValues = // PaddingValues(0.dp)) // }
skysync/app/src/main/java/ch/epfl/skysync/components/GroupChat.kt
1333039045
package dsp_club.technodar_sel import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dsp_club.technodar_sel", appContext.packageName) } }
Technodar-SEL/app/src/androidTest/java/dsp_club/technodar_sel/ExampleInstrumentedTest.kt
823737072
package dsp_club.technodar_sel import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Technodar-SEL/app/src/test/java/dsp_club/technodar_sel/ExampleUnitTest.kt
1793163571
package dsp_club.technodar_sel.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is home Fragment" } val text: LiveData<String> = _text }
Technodar-SEL/app/src/main/java/dsp_club/technodar_sel/ui/home/HomeViewModel.kt
1312988649
package dsp_club.technodar_sel.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import dsp_club.technodar_sel.databinding.FragmentHomeBinding class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java) _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textHome homeViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
Technodar-SEL/app/src/main/java/dsp_club/technodar_sel/ui/home/HomeFragment.kt
609989806
package dsp_club.technodar_sel.ui.dashboard import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import dsp_club.technodar_sel.databinding.FragmentDashboardBinding class DashboardFragment : Fragment() { private var _binding: FragmentDashboardBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java) _binding = FragmentDashboardBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textDashboard dashboardViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
Technodar-SEL/app/src/main/java/dsp_club/technodar_sel/ui/dashboard/DashboardFragment.kt
3672611169
package dsp_club.technodar_sel.ui.dashboard import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class DashboardViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is dashboard Fragment" } val text: LiveData<String> = _text }
Technodar-SEL/app/src/main/java/dsp_club/technodar_sel/ui/dashboard/DashboardViewModel.kt
592498839
package dsp_club.technodar_sel.ui.notifications import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class NotificationsViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is notifications Fragment" } val text: LiveData<String> = _text }
Technodar-SEL/app/src/main/java/dsp_club/technodar_sel/ui/notifications/NotificationsViewModel.kt
3381604241
package dsp_club.technodar_sel.ui.notifications import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import dsp_club.technodar_sel.databinding.FragmentNotificationsBinding class NotificationsFragment : Fragment() { private var _binding: FragmentNotificationsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val notificationsViewModel = ViewModelProvider(this).get(NotificationsViewModel::class.java) _binding = FragmentNotificationsBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textNotifications notificationsViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
Technodar-SEL/app/src/main/java/dsp_club/technodar_sel/ui/notifications/NotificationsFragment.kt
1454816854
package dsp_club.technodar_sel import android.os.Bundle import com.google.android.material.bottomnavigation.BottomNavigationView import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import dsp_club.technodar_sel.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navView: BottomNavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_activity_main) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val appBarConfiguration = AppBarConfiguration( setOf( R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications ) ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } }
Technodar-SEL/app/src/main/java/dsp_club/technodar_sel/MainActivity.kt
1734188814
package com.example.daggerhiltpractice import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.daggerhiltpractice", appContext.packageName) } }
Dagger-Hilt-Practice/app/src/androidTest/java/com/example/daggerhiltpractice/ExampleInstrumentedTest.kt
1029031911
package com.example.daggerhiltpractice import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Dagger-Hilt-Practice/app/src/test/java/com/example/daggerhiltpractice/ExampleUnitTest.kt
2689698869
package com.example.daggerhiltpractice import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MyApplication :Application(){ }
Dagger-Hilt-Practice/app/src/main/java/com/example/daggerhiltpractice/MyApplication.kt
1451826265
package com.example.daggerhiltpractice import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
Dagger-Hilt-Practice/app/src/main/java/com/example/daggerhiltpractice/MainActivity.kt
3583004356
import java.io.File import kotlin.math.abs lateinit var rootDir: String //set via command line argument var minTimeBetweenBatteries: Int = 30 //can be changed via command line argument /** * Walks through all folders of the [rootDir]. For each model folder, [evalAlgorithm] will be called. and the results are put into a list. * Prints the list at the end, ordered by number of errors (the best algorithms will be printed first) */ fun main(args: Array<String>) { rootDir = args[0] if (args.size >= 2) minTimeBetweenBatteries = args[1].toInt() val results = mutableListOf<Pair<String, Int>>() File(rootDir).walk().forEach { if (it.isModelFolder()) { val result = Pair(it.path, evalAlgorithm(it)) results.add(result) } } results.sortBy { abs(it.second) } results.forEach { println("Errors: ${it.second} Algo: ${it.first.removePrefix(rootDir)}") } } /** * true for folders named "bayes" and "default" */ private fun File.isModelFolder() : Boolean { return isDirectory && (name == "bayes" || name == "default") } /** * evaluates the algorithm * @return the number of false positives + false negatives */ private fun evalAlgorithm(dir: File): Int { var errorCounter = 0 dir.walk().forEach { if (it.isFile && it.extension == "txt") { if (it.name.contains("SSG_montage2")) return@forEach val errors = countErrorsInFile(it) errorCounter += errors } } return errorCounter } /** * counts occurrences of the "words" model and "video" in the file. * Excludes too frequent battery occurrences in the model based on [minTimeBetweenBatteries] * @return the difference between numbers of batteries in model and in video (after excluding too frequent occurrences of model batteries) */ private fun countErrorsInFile(file: File): Int { val text = file.readText() val modelTimes = readStartAndEndTimesModel(text) var counterOfBatteriesToExclude = 0 for (i in 1..<modelTimes.size) { if ((modelTimes[i].first - modelTimes[i - 1].second) < minTimeBetweenBatteries) { counterOfBatteriesToExclude++ } } val batteriesInModel = countWordOccurrencesInString(text, "Model") - counterOfBatteriesToExclude val batteriesInVideo = countWordOccurrencesInString(text, "Video") var errors = batteriesInModel - batteriesInVideo if (errors < 1) errors *= 2 return abs(errors) } /** * @return pair.first: startNumber, pair.second: endNumber */ private fun readStartAndEndTimesModel(string: String): List<Pair<Int, Int>> { val list = mutableListOf<Pair<Int, Int>>() string.lines().forEach { if (it.contains("Video")) return@forEach val (startNumber, endNumber) = getNumbersFromString(it) if (startNumber != null && endNumber != null) { list.add(Pair(startNumber, endNumber)) } } return list } /** * reads a pair of two Integers if they are in a string */ private fun getNumbersFromString(input: String): Pair<Int?, Int?> { val regex = Regex("\\d+") val matches = regex.findAll(input) val numbers = matches.map { it.value.toInt() }.toList() return when (numbers.size) { 2 -> Pair(numbers[0], numbers[1]) else -> Pair(null, null) } } /** * counts times a word is contained in a string */ private fun countWordOccurrencesInString(str: String, word: String): Int { var count = 0 var startIndex = 0 while (startIndex < str.length) { val index = str.indexOf(word, startIndex) if (index >= 0) { count++ startIndex = index + word.length } else { break } } return count }
DigiMBAuswertung/src/main/kotlin/Main.kt
2380943175
package com.karizal.ads_channel_startio import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
ads-channel-startio/ads/channel_startio/src/test/java/com/karizal/ads_channel_startio/ExampleUnitTest.kt
177079005
package com.karizal.ads_channel_startio import android.app.Application import com.startapp.sdk.adsbase.StartAppAd import com.startapp.sdk.adsbase.StartAppSDK object StartIOConst { fun init(application: Application, data: StartIOData) { StartAppSDK.init(application, data.app_id, false) StartAppSDK.enableReturnAds(false) StartAppAd.disableAutoInterstitial() StartAppAd.disableSplash() } }
ads-channel-startio/ads/channel_startio/src/main/java/com/karizal/ads_channel_startio/StartIOConst.kt
1631159982
package com.karizal.ads_channel_startio import android.app.Activity import com.karizal.ads_base.AdsBaseConst import com.karizal.ads_base.contract.InterstitialContract import com.startapp.sdk.adsbase.Ad import com.startapp.sdk.adsbase.StartAppAd import com.startapp.sdk.adsbase.adlisteners.AdDisplayListener import com.startapp.sdk.adsbase.adlisteners.AdEventListener class StartIOInterstitial(private val data: StartIOData) : InterstitialContract { override val name: String = AdsBaseConst.startio override var isDebug: Boolean = false override var activity: Activity? = null override var onInitializeOK: (name: String) -> Unit = {} override var onInitializeError: (name: String) -> Unit = {} private var interstitial: StartAppAd? = null private var onHide: () -> Unit = {} private var onFailure: (Activity) -> Unit = {} private val listenerOnLoad = object : AdEventListener { override fun onReceiveAd(ad: Ad) { onInitializeOK.invoke(name) } override fun onFailedToReceiveAd(ad: Ad?) { onInitializeError.invoke(name) } } private val listenerOnDisplay = object : AdDisplayListener { override fun adHidden(ad: Ad?) { interstitial?.close() onHide.invoke() activity?.let { initialize(it, isDebug, onInitializeOK, onInitializeError) } } override fun adDisplayed(ad: Ad?) { } override fun adClicked(ad: Ad?) { } override fun adNotDisplayed(ad: Ad?) { activity?.let { onFailure.invoke(it) } } } override fun initialize( activity: Activity, isDebug: Boolean, onInitializeOK: (name: String) -> Unit, onInitializeError: (name: String) -> Unit ) { super.initialize(activity, isDebug, onInitializeOK, onInitializeError) interstitial = StartAppAd(activity) interstitial?.loadAd(listenerOnLoad) } override fun show( activity: Activity, possibleToShow: (channel: String) -> Boolean, onHide: () -> Unit, onFailure: (activity: Activity) -> Unit ) { if (possibleToShow.invoke(name).not()) { return onFailure.invoke(activity) } this.onHide = onHide this.onFailure = onFailure if (interstitial?.isReady == true) { interstitial?.showAd(listenerOnDisplay) } else { onFailure.invoke(activity) } } }
ads-channel-startio/ads/channel_startio/src/main/java/com/karizal/ads_channel_startio/StartIOInterstitial.kt
2476298971
package com.karizal.ads_channel_startio import com.karizal.ads_base.data.BasicAdsData class StartIOData( val app_id: String ) : BasicAdsData(name = "startio")
ads-channel-startio/ads/channel_startio/src/main/java/com/karizal/ads_channel_startio/StartIOData.kt
2070802685
package com.karizal.ads_channel_startio import android.app.Activity import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.RelativeLayout import androidx.core.view.allViews import com.karizal.ads_base.AdsBaseConst import com.karizal.ads_base.contract.BannerContract import com.startapp.sdk.ads.banner.Banner import com.startapp.sdk.ads.banner.BannerListener import com.startapp.sdk.adsbase.StartAppAd import com.startapp.sdk.adsbase.StartAppSDK class StartIOBanner( private val data: StartIOData ) : BannerContract { override val name: String = AdsBaseConst.startio override var isDebug: Boolean = false override var activity: Activity? = null override fun initialize(activity: Activity, isDebug: Boolean) { super.initialize(activity, isDebug) StartAppSDK.init(activity, data.app_id, false) StartAppSDK.enableReturnAds(false) StartAppAd.disableAutoInterstitial() StartAppAd.disableSplash() if (isDebug) { StartAppSDK.setTestAdsEnabled(true); } } override fun fetch( container: ViewGroup, preparing: () -> Unit, possibleToLoad: () -> Boolean, onSuccessLoaded: (channel: String) -> Unit, onFailedLoaded: () -> Unit ) { activity ?: return prepareContainerView(container) preparing.invoke() val banner = Banner(activity, object : BannerListener { override fun onReceiveAd(p0: View?) { val view = container.allViews.first() view.layoutParams = FrameLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT, ) onSuccessLoaded.invoke(name) Log.i([email protected](), "StartIO.banner.onReceiveAd") } override fun onFailedToReceiveAd(p0: View?) { Log.i([email protected](), "StartIO.banner.onFailedToReceiveAd") } override fun onImpression(p0: View?) { Log.i([email protected](), "StartIO.banner.onImpression") } override fun onClick(p0: View?) { Log.i([email protected](), "StartIO.banner.onClick") } }) val bannerParameters = RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT ) bannerParameters.addRule(RelativeLayout.CENTER_HORIZONTAL) bannerParameters.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) if (possibleToLoad.invoke()) { container.removeAllViewsInLayout() container.addView(banner, bannerParameters) banner.loadAd() } } }
ads-channel-startio/ads/channel_startio/src/main/java/com/karizal/ads_channel_startio/StartIOBanner.kt
1124776165
package com.karizal.ads_channel_startio_sample import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
ads-channel-startio/app/src/test/java/com/karizal/ads_channel_startio_sample/ExampleUnitTest.kt
1906954418
package com.karizal.ads_channel_startio_sample import android.app.Application import com.karizal.ads_channel_startio.StartIOConst class App: Application() { override fun onCreate() { super.onCreate() StartIOConst.init(this, Const.data) } }
ads-channel-startio/app/src/main/java/com/karizal/ads_channel_startio_sample/App.kt
3018264205
package com.karizal.ads_channel_startio_sample import android.os.Bundle import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.karizal.ads_base.AdsBaseConst import com.karizal.ads_base.unit.BaseUnitBanner import com.karizal.ads_base.unit.BaseUnitInterstitial import com.karizal.ads_channel_startio.StartIOBanner import com.karizal.ads_channel_startio.StartIOInterstitial class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // interstitial val btnInterstitial = findViewById<Button>(R.id.btn_interstitial) val interstitialAds = BaseUnitInterstitial( isEnabled = true, isDebug = true, key = this::class.java.simpleName, arrayOf( StartIOInterstitial(Const.data), // other channel ) ) interstitialAds.onCreate(this) btnInterstitial.setOnClickListener { interstitialAds.showForce(this, onHide = { Toast.makeText(this, "Hide Ads", Toast.LENGTH_SHORT).show() }) } // banner unit BaseUnitBanner.init( activity = this, R.id.ads_banner, isDebug = true, // enable test mode StartIOBanner(Const.data), // other channels forceAdsChannel = AdsBaseConst.startio ) } }
ads-channel-startio/app/src/main/java/com/karizal/ads_channel_startio_sample/MainActivity.kt
3982064152
package com.karizal.ads_channel_startio_sample import com.karizal.ads_channel_startio.StartIOData object Const { val data = StartIOData("207718184" ) }
ads-channel-startio/app/src/main/java/com/karizal/ads_channel_startio_sample/Const.kt
2724617650
package com.rtjh.vto import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.rtjh.vto", appContext.packageName) } }
VTO/app/src/androidTest/java/com/rtjh/vto/ExampleInstrumentedTest.kt
789110177
package com.rtjh.vto import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
VTO/app/src/test/java/com/rtjh/vto/ExampleUnitTest.kt
2912111600
package com.rtjh.vto.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is home Fragment" } val text: LiveData<String> = _text }
VTO/app/src/main/java/com/rtjh/vto/ui/home/HomeViewModel.kt
180942573
package com.rtjh.vto.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.bin.david.form.core.SmartTable import com.rtjh.vto.R import com.rtjh.vto.adapter.TableAdapter import com.rtjh.vto.databinding.FragmentHomeBinding import com.rtjh.vto.model.SchedulingInfoDataModel class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater : LayoutInflater, container : ViewGroup?, savedInstanceState : Bundle? ) : View { ViewModelProvider(this)[HomeViewModel::class.java] _binding = FragmentHomeBinding.inflate(inflater, container, false) val smartTable: SmartTable<SchedulingInfoDataModel> = binding.schedulingInfoLl.findViewById( R.id.scheduling_info_table) val tableAdapter = TableAdapter(binding.root.context) tableAdapter.setupTable(smartTable) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
VTO/app/src/main/java/com/rtjh/vto/ui/home/HomeFragment.kt
3250964863
package com.rtjh.vto.ui.dashboard import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.rtjh.vto.databinding.ControlAirConditionModuleBinding import com.rtjh.vto.databinding.FragmentDashboardBinding import com.rtjh.vto.helper.AirConditionStatusHelper class DashboardFragment : Fragment() { private var _binding: FragmentDashboardBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! private lateinit var airConditionStatusHelper: AirConditionStatusHelper override fun onCreateView( inflater : LayoutInflater, container : ViewGroup?, savedInstanceState : Bundle? ) : View { _binding = FragmentDashboardBinding.inflate(inflater, container, false) val controlAirConditionBinding = ControlAirConditionModuleBinding.bind(binding.airConditionLl) airConditionStatusHelper = AirConditionStatusHelper(controlAirConditionBinding) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
VTO/app/src/main/java/com/rtjh/vto/ui/dashboard/DashboardFragment.kt
885519405
package com.rtjh.vto.ui.dashboard import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class DashboardViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is dashboard Fragment" } val text: LiveData<String> = _text }
VTO/app/src/main/java/com/rtjh/vto/ui/dashboard/DashboardViewModel.kt
3281637006
package com.rtjh.vto.ui.notifications import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class NotificationsViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is notifications Fragment" } val text: LiveData<String> = _text }
VTO/app/src/main/java/com/rtjh/vto/ui/notifications/NotificationsViewModel.kt
438481841
package com.rtjh.vto.ui.notifications import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.rtjh.vto.databinding.FragmentNotificationsBinding class NotificationsFragment : Fragment() { private var _binding: FragmentNotificationsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater : LayoutInflater, container : ViewGroup?, savedInstanceState : Bundle? ) : View { val notificationsViewModel = ViewModelProvider(this).get(NotificationsViewModel::class.java) _binding = FragmentNotificationsBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
VTO/app/src/main/java/com/rtjh/vto/ui/notifications/NotificationsFragment.kt
3021439083
package com.rtjh.vto import android.os.Bundle import android.view.WindowInsets import androidx.appcompat.app.AppCompatActivity import com.rtjh.vto.databinding.ActivityMainBinding import com.rtjh.vto.databinding.CustomBottomNavigationBinding import com.rtjh.vto.helper.BottomNavigationHelper class MainActivity : AppCompatActivity() { private lateinit var binding : ActivityMainBinding private lateinit var customBottomNavigationBinding : CustomBottomNavigationBinding private lateinit var bottomNavigationHelper : BottomNavigationHelper override fun onCreate(savedInstanceState : Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) customBottomNavigationBinding = CustomBottomNavigationBinding.bind(binding.navView) setContentView(binding.root) bottomNavigationHelper = BottomNavigationHelper(this, customBottomNavigationBinding) val navController = bottomNavigationHelper.getNavController(supportFragmentManager) navController?.let { bottomNavigationHelper.setNavClickListener(it) } // 在 Activity 的 onCreate 方法中添加以下代码 val controller = window.insetsController controller?.hide(WindowInsets.Type.statusBars()) } }
VTO/app/src/main/java/com/rtjh/vto/MainActivity.kt
818503286
package com.rtjh.vto.utils class TypeUtils { companion object{ fun isNum(value: String?): Boolean { try { value !!.toDouble() } catch (e: Exception) { return false } return true } } }
VTO/app/src/main/java/com/rtjh/vto/utils/TypeUtils.kt
3640452427
package com.rtjh.vto.adapter import android.annotation.SuppressLint import android.content.Context import android.graphics.Color import androidx.core.content.ContextCompat import com.bin.david.form.core.SmartTable import com.bin.david.form.data.column.Column import com.bin.david.form.data.format.bg.IBackgroundFormat import com.bin.david.form.data.format.grid.IGridFormat import com.bin.david.form.data.style.FontStyle import com.bin.david.form.data.style.LineStyle import com.bin.david.form.data.table.TableData import com.rtjh.vto.R import com.rtjh.vto.model.SchedulingInfoDataModel class TableAdapter(private val context : Context) { @SuppressLint("ResourceAsColor") fun setupTable(smartTable : SmartTable<SchedulingInfoDataModel>) { // 创建列 val surgeryNameColumn = Column<String>("手术名称", "surgeryName") val patientColumn = Column<String>("患者", "patient") val surgeonColumn = Column<String>("主刀医生", "surgeon") val nurseColumn = Column<String>("责任护士", "nurse") val surgeryTimeColumn = Column<String>("手术时间", "surgeryTime") val surgeryStatusColumn = Column<String>("手术状态", "surgeryStatus") // 设置表格数据 val dataList : List<SchedulingInfoDataModel> = listOf( SchedulingInfoDataModel("手术1", "患者A", "医生1", "护士1", "2023-01-01", "手术中"), SchedulingInfoDataModel("手术2", "患者B", "医生2", "护士2", "2023-01-01", "手术中"), SchedulingInfoDataModel("手术3", "患者C", "医生1", "护士3", "2023-01-01", "手术中"), SchedulingInfoDataModel("手术4", "患者D", "医生2", "护士3", "2023-01-01", "手术中"), SchedulingInfoDataModel("手术5", "患者E", "医生1", "护士2", "2023-01-01", "手术中"), SchedulingInfoDataModel("手术6", "患者F", "医生2", "护士1", "2023-01-01", "手术中"), SchedulingInfoDataModel("手术7", "患者F", "医生2", "护士1", "2023-01-01", "手术中"), ) // 设置表格数据 val tableData = TableData( "", dataList, surgeryNameColumn, patientColumn, surgeonColumn, nurseColumn, surgeryTimeColumn, surgeryStatusColumn ) val config = smartTable.config config.isShowTableTitle = false config.isShowXSequence = false config.isShowYSequence = false config.columnTitleStyle = FontStyle().setTextSize(24) .setTextColor(R.color.black) config.columnTitleBackground = IBackgroundFormat{canvas, rect, paint -> paint.color = ContextCompat.getColor(context, R.color.table_title_bg_color) canvas.drawRect(rect, paint) } config.contentStyle = FontStyle().setTextSize(24) .setTextColor(R.color.black) config.contentBackground = IBackgroundFormat{canvas, rect, paint -> paint.color = ContextCompat.getColor(context, R.color.table_content_bg_color) canvas.drawRect(rect, paint) } LineStyle.setDefaultLineColor(Color.parseColor("#FFFFFF")) LineStyle.setDefaultLineSize(0.toFloat()) smartTable.tableData = tableData } }
VTO/app/src/main/java/com/rtjh/vto/adapter/TableAdapter.kt
460898207
package com.rtjh.vto.model data class SchedulingInfoDataModel( val surgeryName: String, val patient: String, val surgeon: String, val nurse: String, val surgeryTime: String, val surgeryStatus: String )
VTO/app/src/main/java/com/rtjh/vto/model/SchedulingInfoDataModel.kt
2491597721
package com.rtjh.vto.view import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.graphics.Typeface import android.os.Handler import android.util.AttributeSet import android.view.View import androidx.core.content.ContextCompat import com.rtjh.vto.R import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class ConcaveShapeView(context : Context, attrs : AttributeSet? = null) : View(context, attrs) { private val concaveColor = ContextCompat.getColor(context, R.color.top_module_bg_color) private val concaveHeight = resources.getDimension(R.dimen.concave_height) private val concaveWidth = resources.getDimension(R.dimen.concave_width) private val viewHeight = resources.getDimension(R.dimen.top_module_height) - 30 private val viewWidth = 1080 private val paint = Paint(Paint.ANTI_ALIAS_FLAG) private val companyName = "Your Company" private val centerText = "OR.56" private val handler = Handler() private val updateTimeRunnable = object : Runnable{ override fun run() { invalidate() handler.postDelayed(this, 1000) } } override fun onAttachedToWindow() { super.onAttachedToWindow() handler.post(updateTimeRunnable) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() handler.removeCallbacks(updateTimeRunnable) } init { paint.color = concaveColor } @SuppressLint("DrawAllocation") override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val path = Path() // 左上角 path.moveTo(0f, 0f) // 左下角 path.lineTo(0f, viewHeight) // 绘制直线到居中位置 path.lineTo((viewWidth - concaveWidth) / 2f, viewHeight) // 开始绘制凹陷 path.lineTo((viewWidth - concaveWidth) / 2f, viewHeight) val controlPoint1X = (viewWidth - concaveWidth) / 2f val controlPoint1Y = viewHeight + concaveHeight / 2f val controlPoint2X = (viewWidth + concaveWidth) / 2f val controlPoint2Y = viewHeight + concaveHeight / 2f path.cubicTo(controlPoint1X, controlPoint1Y, controlPoint2X, controlPoint2Y, (viewWidth + concaveWidth) / 2, viewHeight) // 向右下方绘制矩形 path.lineTo((viewWidth + concaveWidth) / 2, viewHeight + concaveHeight) path.lineTo((viewWidth + concaveWidth) / 2, viewHeight) // 向右上方绘制凹陷 path.lineTo(viewWidth.toFloat(), viewHeight) path.lineTo(viewWidth.toFloat(),0f) canvas.drawPath(path, paint) // 绘制公司名称 val textPaint = Paint(Paint.ANTI_ALIAS_FLAG) textPaint.color = ContextCompat.getColor(context, R.color.top_module_text_color) textPaint.textSize = resources.getDimension(R.dimen.home_time_zh_text_size) canvas.drawText(companyName, 20f, viewHeight / 2f, textPaint) // 中间文字画笔 val centerTextPaint = Paint(Paint.ANTI_ALIAS_FLAG) centerTextPaint.color = ContextCompat.getColor(context, R.color.top_module_text_color) centerTextPaint.textSize = resources.getDimension(R.dimen.top_module_text_size) centerTextPaint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) // 绘制中间文字 "OR56" val centerTextWidth = centerTextPaint.measureText(centerText) val centerTextHeight = centerTextPaint.fontMetrics.bottom - centerTextPaint.fontMetrics.top val centerTextBaseline = viewHeight + (concaveHeight - centerTextHeight) / 2 - centerTextPaint.fontMetrics.bottom canvas.drawText(centerText, (viewWidth - centerTextWidth) / 2, centerTextBaseline, centerTextPaint) // 绘制右侧当地时间(包含年月日时分秒) val timeFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()) val currentTime = timeFormat.format(Date()) canvas.drawText(currentTime, viewWidth - 320f, viewHeight / 2f + 10, textPaint) } }
VTO/app/src/main/java/com/rtjh/vto/view/ConcaveShapeView.kt
1367617417
package com.rtjh.vto.view import android.content.Context import android.graphics.drawable.ColorDrawable import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.OvalShape import android.util.AttributeSet import android.view.View import com.rtjh.vto.R class ColoredDotView @JvmOverloads constructor( context : Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { init { if (attrs != null) { val a = context.obtainStyledAttributes(attrs, R.styleable.ColoredDotView) val dotColor = a.getColor(R.styleable.ColoredDotView_dotColor, 0) a.recycle() // 设置圆点颜色 setDotColor(dotColor) } } private fun setDotColor(color: Int) { val ovalShape = OvalShape() val shapeDrawable = ShapeDrawable(ovalShape) shapeDrawable.paint.color = color background = shapeDrawable } }
VTO/app/src/main/java/com/rtjh/vto/view/ColoredDotView.kt
3742991234
package com.rtjh.vto.view import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.LinearGradient import android.graphics.Matrix import android.graphics.Paint import android.graphics.Point import android.graphics.RectF import android.graphics.SweepGradient import android.graphics.Typeface import android.graphics.drawable.Drawable import android.text.TextPaint import android.util.AttributeSet import android.util.Log import android.view.View import com.rtjh.vto.R import com.rtjh.vto.utils.TypeUtils.Companion.isNum import java.text.DecimalFormat class CircleProgressView(context : Context?, attrs : AttributeSet?) : View(context, attrs) { // 是否开启抗锯齿 private var antiAlias : Boolean = true // 圆心位置 private lateinit var centerPosition : Point // 半径 private var radius : Float? = null // 声明边界矩形 private var mRectF : RectF? = null // 声明背景圆画笔 private lateinit var mBgCirPaint : Paint // 画笔 private var mBgCirColor : Int? = null // 颜色 private var mBgCirWidth : Float = 15f // 圆环背景宽度 // 声明进度圆画笔 private lateinit var mCirPaint : Paint // 画笔 private var mCirColor : Int? = null // 颜色 private var mCirWidth : Float = 15f // 主圆的宽度 // 绘制的起始角度和滑过角度(默认从顶部开始绘制,绘制360度) private var mStartAngle : Float = -90f private var mSweepAngle : Float = 360f // 动画时间 private var mAnimTime : Int = 1000 // 属性动画 private var mAnimator : ValueAnimator? = null // 动画进度 private var mAnimPercent : Float = 0f // 进度值 private var mValue : String? = null // 最大值(默认100) private var mMaxValue : Float = 100f // 绘制数值 private lateinit var mValuePaint : TextPaint private var mValueSize : Float? = null private var mValueColor : Int? = null // 绘制进度的后缀-默认为百分号 private var mUnit : CharSequence? = R.string.celsius.toString() // 绘制描述 private var mHint : CharSequence? = null private lateinit var mHintPaint : TextPaint private var mHintSize : Float? = null private var mHintColor : Int? = null // 颜色渐变 private var isGradient : Boolean? = null private var mGradientColors : IntArray? = intArrayOf(Color.RED, Color.GRAY, Color.BLUE) private var mGradientColor : Int? = null private var mSweepGradient : SweepGradient? = null // 阴影 private var mShadowColor : Int? = null private var mShadowSize : Float? = null private var mShadowIsShow : Boolean = false // 保留的小数位数(默认两位) private var mDigit : Int = 2 // 是否需要动画(默认需要动画) private var isAnim : Boolean = true // 图标渲染 private var mHintDrawable : Drawable? = null // 图标单位 private var mHintText : String? = null init { try { setLayerType(LAYER_TYPE_SOFTWARE, null) mAnimPercent = 0f centerPosition = Point()// 初始化圆心属性 mRectF = RectF() mAnimator = ValueAnimator()// 初始化属性动画 initAttrs(attrs, context)//初始化属性 Log.d("CircleProgressView", "Attempting to instantiate CircleProgressView") initPaint()//初始化画笔 } catch (e : Exception) { // 捕捉任何异常 Log.e("CircleProgressView", "Error during instantiation: ${e.localizedMessage}") } } /** * 初始化属性 */ private fun initAttrs(attrs : AttributeSet?, context : Context?) { val typeArray = context !!.obtainStyledAttributes(attrs, R.styleable.CircleProgressView) isAnim = typeArray.getBoolean(R.styleable.CircleProgressView_isanim, true) mDigit = typeArray.getInt(R.styleable.CircleProgressView_digit, 2) mBgCirColor = typeArray.getColor(R.styleable.CircleProgressView_mBgCirColor, Color.GRAY) mBgCirWidth = typeArray.getDimension(R.styleable.CircleProgressView_mBgCirWidth, 15f) mCirColor = typeArray.getColor(R.styleable.CircleProgressView_mCirColor, Color.YELLOW) mCirWidth = typeArray.getDimension(R.styleable.CircleProgressView_mCirWidth, 15f) mAnimTime = typeArray.getInt(R.styleable.CircleProgressView_animTime, 1000) mValue = typeArray.getString(R.styleable.CircleProgressView_value) mMaxValue = typeArray.getFloat(R.styleable.CircleProgressView_maxvalue, 100f) mStartAngle = typeArray.getFloat(R.styleable.CircleProgressView_startAngle, 270f) mSweepAngle = typeArray.getFloat(R.styleable.CircleProgressView_sweepAngle, 360f) mValueSize = typeArray.getDimension(R.styleable.CircleProgressView_valueSize, 15f) mValueColor = typeArray.getColor(R.styleable.CircleProgressView_valueColor, Color.BLACK) mHintDrawable = typeArray.getDrawable(R.styleable.CircleProgressView_hintDrawable) mHintText = typeArray.getString(R.styleable.CircleProgressView_hintText) mHint = typeArray.getString(R.styleable.CircleProgressView_hint) mHintSize = typeArray.getDimension(R.styleable.CircleProgressView_hintSize, 15f) mHintColor = typeArray.getColor(R.styleable.CircleProgressView_hintColor, Color.GRAY) mUnit = typeArray.getString(R.styleable.CircleProgressView_unit) mShadowColor = typeArray.getColor(R.styleable.CircleProgressView_shadowColor, Color.BLACK) mShadowIsShow = typeArray.getBoolean(R.styleable.CircleProgressView_shadowShow, false) mShadowSize = typeArray.getFloat(R.styleable.CircleProgressView_shadowSize, 8f) isGradient = typeArray.getBoolean(R.styleable.CircleProgressView_isGradient, false) mGradientColor = typeArray.getResourceId(R.styleable.CircleProgressView_gradient, 0) if (mGradientColor != 0) { mGradientColors = resources.getIntArray(mGradientColor !!) } typeArray.recycle() } /** * 初始化画笔 */ private fun initPaint() { // 圆画笔(主圆的画笔设置) mCirPaint = Paint() mCirPaint.isAntiAlias = antiAlias // 是否开启抗锯齿 mCirPaint.style = Paint.Style.STROKE // 画笔样式 mCirPaint.strokeWidth = mCirWidth // 画笔宽度 mCirPaint.strokeCap = Paint.Cap.ROUND // 笔刷样式(圆角的效果) mCirPaint.color = mCirColor !!// 画笔颜色 // 背景圆画笔(一般和主圆一样大或者小于主圆的宽度) mBgCirPaint = Paint() mBgCirPaint.isAntiAlias = antiAlias mBgCirPaint.style = Paint.Style.STROKE mBgCirPaint.strokeWidth = mBgCirWidth mBgCirPaint.strokeCap = Paint.Cap.ROUND mBgCirPaint.color = mBgCirColor !! // 初始化主题文字的字体画笔 mValuePaint = TextPaint() mValuePaint.isAntiAlias = antiAlias mValuePaint.textSize = mValueSize !! // 字体大小 mValuePaint.color = mValueColor !! // 字体颜色 mValuePaint.textAlign = Paint.Align.CENTER // 从中间向两边绘制,不需要再次计算文字 //初始化提示文本的字体画笔 mHintPaint = TextPaint() mHintPaint.isAntiAlias = antiAlias mHintPaint.textSize = mHintSize !! mHintPaint.color = mHintColor !! mHintPaint.textAlign = Paint.Align.CENTER mHintPaint.typeface = Typeface.DEFAULT_BOLD } /** * 设置圆形和矩阵的大小,设置圆心位置 */ override fun onSizeChanged(w : Int, h : Int, oldw : Int, oldh : Int) { super.onSizeChanged(w, h, oldw, oldh) // 圆心位置 centerPosition.x = w / 2 centerPosition.y = h / 2 // 半径 val maxCirWidth = mCirWidth.coerceAtLeast(mBgCirWidth) val minWidth = (w - paddingLeft - paddingRight - 2 * maxCirWidth).coerceAtMost(h - paddingBottom - paddingTop - 2 * maxCirWidth) radius = minWidth / 2 //矩阵坐标 mRectF !!.left = centerPosition.x - radius !! - maxCirWidth / 2 mRectF !!.top = centerPosition.y - radius !! - maxCirWidth / 2 mRectF !!.right = centerPosition.x + radius !! + maxCirWidth / 2 mRectF !!.bottom = centerPosition.y + radius !! + maxCirWidth / 2 if (isGradient !!) { setupGradientCircle() // 设置圆环画笔颜色渐变 } } /** * 核心方法-绘制文本与圆环 */ override fun onDraw(canvas : Canvas) { super.onDraw(canvas) drawIcon(canvas) drawCircle(canvas) } /** * 绘制中心的文本 */ private fun drawIcon(canvas : Canvas) { mValue?.let { it -> val intValue = it.toIntOrNull() if (intValue != null) { // 计算主值文本的基线 val textBaseline = (centerPosition.y + mValuePaint.textSize / 4f) + 10 // 计算主值文本的X坐标,使其向左移动 val valueTextX = centerPosition.x.toFloat() - mValuePaint.measureText(intValue.toString()) * 0.1f // 绘制主值文本 mValuePaint.isFakeBoldText = true canvas.drawText( intValue.toString(), valueTextX, textBaseline, mValuePaint ) // 绘制单位文本 mUnit?.let { // 设置单位文本的字体大小 val unitTextSize = mValuePaint.textSize * 0.4f mValuePaint.textSize = unitTextSize // 计算单位文本的位置 val unitTextBaseline = textBaseline - mValuePaint.descent() - unitTextSize val unitTextX = valueTextX + mValuePaint.measureText(intValue.toString()) * 2f // 绘制单位文本 canvas.drawText( it.toString(), unitTextX, unitTextBaseline, mValuePaint ) // 恢复主值文本的字体大小 mValuePaint.textSize = mValueSize!! } } } } /** * 使用渐变色画圆 */ private fun setupGradientCircle() { if (mGradientColors != null && mGradientColors!!.size >= 2) { // 计算渐变中每个颜色在渐变过程中的位置 val colorPositions = FloatArray(mGradientColors!!.size) // 计算等差数列,确保 endColor 在最后 val step = 1.0f / (mGradientColors!!.size - 1) for (i in mGradientColors!!.indices) { colorPositions[i] = i * step } // 最后一个颜色的位置设为 1,以确保达到 mValue 时显示终止颜色 colorPositions[mGradientColors!!.size - 1] = 1f // 创建具有多个颜色的扫描渐变 mSweepGradient = SweepGradient( centerPosition.x.toFloat(), centerPosition.y.toFloat(), mGradientColors!!, colorPositions ) // 设置渐变的起始和结束位置 val matrix = Matrix() val adjustedStartAngle = mStartAngle - 9f matrix.setRotate(adjustedStartAngle, centerPosition.x.toFloat(), centerPosition.y.toFloat()) mSweepGradient!!.setLocalMatrix(matrix) // 应用扫描渐变 mCirPaint.shader = mSweepGradient // 重绘视图 postInvalidate() } } /** * 画圆(主要的圆) */ private fun drawCircle(canvas : Canvas?) { canvas?.save() if (mShadowIsShow) { mCirPaint.setShadowLayer(mShadowSize !!, 0f, 0f, mShadowColor !!) // 设置阴影 } if (isGradient == true) { mCirPaint.shader = mSweepGradient } // 画背景圆 canvas?.drawArc(mRectF !!, mStartAngle, mSweepAngle, false, mBgCirPaint) // 画圆 canvas?.drawArc(mRectF !!, mStartAngle, mSweepAngle * mAnimPercent, false, mCirPaint) canvas?.restore() } /** * 设置当前需要展示的值 */ fun setValue(value : String, maxValue : Float) : CircleProgressView { if (isNum(value)) { mValue = value mMaxValue = maxValue //当前的进度和最大的进度,去做动画的绘制 val start = mAnimPercent val end = value.toFloat() / maxValue startAnim(start, end, mAnimTime) if (isGradient == true){ // 更新渐变 setupGradientCircle() } } else { mValue = value } return this } /** * 执行属性动画 */ private fun startAnim(start : Float, end : Float, animTime : Int) { mAnimator = ValueAnimator.ofFloat(start, end) mAnimator?.duration = animTime.toLong() mAnimator?.addUpdateListener { // 得到当前的动画进度并赋值 mAnimPercent = it.animatedValue as Float // 根据当前的动画得到当前的值 val decimalFormat = DecimalFormat("#.#") mValue = decimalFormat.format(mAnimPercent * mMaxValue) // 不停的重绘当前的值-表现出动画效果 postInvalidate() } mAnimator?.start() } /** * 设置动画时长 */ fun setAnimTIme(animTime : Int) : CircleProgressView { this.mAnimTime = animTime invalidate() return this } /** * 是否渐变色 * */ fun setIsGradient(isGradient : Boolean) : CircleProgressView { this.isGradient = isGradient invalidate() return this } /** * 设置渐变色 * */ fun setGradientColors(gradientColors : IntArray) : CircleProgressView { mGradientColors = gradientColors setupGradientCircle() return this } /** * 是否显示阴影 * */ fun setShadowEnable(enable : Boolean) : CircleProgressView { mShadowIsShow = enable invalidate() return this } /** * 内部工具类 */ private class CircleUtil { companion object { /** * 将double格式化为指定小数位的String,不足小数位用0补全 * * @param v 需要格式化的数字 * @param scale 小数点后保留几位 * @return */ fun roundByScale(v : Double, scale : Int) : String { if (scale < 0) { throw IllegalArgumentException("参数错误,必须设置大于0的数字") } if (scale == 0) { return DecimalFormat("0").format(v) } var formatStr = "0." for (i in 0 until scale) { formatStr += "0" } return DecimalFormat(formatStr).format(v) } fun dip2px(context : Context, dpValue : Float) : Int { val scale = context.resources.displayMetrics.density return (dpValue * scale + 0.5f).toInt() } fun dp2px(context : Context, dpValue : Float) : Int { return dip2px(context, dpValue) } fun px2dip(context : Context, pxValue : Float) : Int { val scale = context.resources.displayMetrics.density return (pxValue / scale + 0.5f).toInt() } fun px2sp(context : Context, pxValue : Float) : Int { val fontScale = context.resources.displayMetrics.scaledDensity return (pxValue / fontScale + 0.5f).toInt() } fun sp2px(context : Context, spValue : Float) : Int { val fontScale = context.resources.displayMetrics.scaledDensity return (spValue * fontScale + 0.5f).toInt() } } } }
VTO/app/src/main/java/com/rtjh/vto/view/CircleProgressView.kt
4117753383
package com.rtjh.vto.helper import android.content.Context import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import androidx.fragment.app.FragmentManager import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import com.rtjh.vto.R import com.rtjh.vto.databinding.CustomBottomNavigationBinding class BottomNavigationHelper(private val context: Context, private val binding: CustomBottomNavigationBinding) { private val navHome = binding.navigationHome private val navControl = binding.navigationControl private val navSetting = binding.navigationSetting fun setNavClickListener(navController: NavController) { setMenuItemActive(navHome, R.drawable.icon_home_active) navHome.setOnClickListener { navigateAndSetState(navController, R.id.navigation_home, navHome, R.drawable.icon_home_active) } navControl.setOnClickListener { navigateAndSetState(navController, R.id.navigation_control, navControl, R.drawable.icon_control_active) } navSetting.setOnClickListener { navigateAndSetState(navController, R.id.navigation_setting, navSetting, R.drawable.icon_setting_active) } } fun getNavController(fragmentManager: FragmentManager): NavController? { val navHostFragment = fragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as? NavHostFragment return navHostFragment?.navController } private fun navigateAndSetState(navController: NavController, destinationId: Int, navView: LinearLayout, activeIconResId: Int) { // 在导航前,先将其他项置为未激活状态 setMenuItemInactive(navHome, R.drawable.icon_home) setMenuItemInactive(navControl, R.drawable.icon_control) setMenuItemInactive(navSetting, R.drawable.icon_setting) // 导航到目标页面 navController.navigate(destinationId) // 设置当前项为激活状态 setMenuItemActive(navView, activeIconResId) } private fun setMenuItemActive(navView: LinearLayout, activeIconResId: Int) { // 设置激活状态下的背景图标和文字颜色 val activeIconDrawable = ContextCompat.getDrawable(context, activeIconResId) val activeTextColor = ContextCompat.getColor(context, R.color.menu_active_color) // 设置图标 val iconImageView = navView.getChildAt(0) as ImageView iconImageView.setImageDrawable(activeIconDrawable) // 设置文字颜色 val textView = navView.getChildAt(1) as TextView textView.setTextColor(activeTextColor) } private fun setMenuItemInactive(navView: LinearLayout, inactiveIconResId: Int) { // 设置未激活状态下的背景图标和文字颜色 val inactiveIconDrawable = ContextCompat.getDrawable(context, inactiveIconResId) val inactiveTextColor = ContextCompat.getColor(context, R.color.menu_text_default_color) // 设置图标 val iconImageView = navView.getChildAt(0) as ImageView iconImageView.setImageDrawable(inactiveIconDrawable) // 设置文字颜色 val textView = navView.getChildAt(1) as TextView textView.setTextColor(inactiveTextColor) } }
VTO/app/src/main/java/com/rtjh/vto/helper/BottomNavigationHelper.kt
2019397874
package com.rtjh.vto.helper import androidx.core.content.ContextCompat import com.rtjh.vto.R import com.rtjh.vto.databinding.ControlAirConditionModuleBinding class AirConditionStatusHelper(binding: ControlAirConditionModuleBinding) { private val context = binding.root.context private val temCircleView = binding.tempCircle private val temStartColor = ContextCompat.getColor(context, R.color.tem_circle_start_color) private val temEndColor = ContextCompat.getColor(context,R.color.tem_circle_end_color) private val humCircleView = binding.humCircle private val humStartColor = ContextCompat.getColor(context,R.color.hum_circle_start_color) private val humEndColor = ContextCompat.getColor(context, R.color.hum_circle_end_color) private val dpCircleView = binding.differentPressureCircle private val dpStartColor = ContextCompat.getColor(context, R.color.d_p_circle_start_color) private val dpEndColor = ContextCompat.getColor(context, R.color.d_p_circle_end_color) init { initTemCircle() initHumCircle() initDpCircle() } private fun initTemCircle(){ temCircleView.setIsGradient(true) temCircleView.setGradientColors(intArrayOf(temStartColor,temEndColor)) temCircleView.setValue("15",30f) } private fun initHumCircle(){ humCircleView.setIsGradient(true) humCircleView.setGradientColors(intArrayOf(humStartColor, humEndColor)) humCircleView.setValue("40",70f) } private fun initDpCircle(){ dpCircleView.setIsGradient(true) dpCircleView.setGradientColors(intArrayOf(dpStartColor,dpEndColor)) dpCircleView.setValue("50", 80f) } }
VTO/app/src/main/java/com/rtjh/vto/helper/AirConditionStatusHelper.kt
1447121323
package com.example.myapplication import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.myapplication", appContext.packageName) } }
CourseRepo/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
package com.example.myapplication import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
CourseRepo/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
package com.example.myapplication.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) val yellow = Color(0xFFF4CE14) object LittleLemonColor { val green = Color(0xFF495E57) val yellow = Color(0xFFF4CE14) val orange = Color(0xFFEE9972) val pink = Color(0XFFDBDABB) val cloud = Color(0xFFEDEFEE) val charcoal = Color(0xFF333333) }
CourseRepo/app/src/main/java/com/example/myapplication/ui/theme/Color.kt
1188429596
package com.example.myapplication.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = yellow, secondary = yellow, tertiary = yellow ) private val LightColorScheme = lightColorScheme( primary = yellow, secondary = yellow, tertiary = yellow ) @Composable fun LittleLemonTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CourseRepo/app/src/main/java/com/example/myapplication/ui/theme/Theme.kt
1426374066
package com.example.myapplication.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
CourseRepo/app/src/main/java/com/example/myapplication/ui/theme/Type.kt
3481532690
@file:OptIn(DelicateCoroutinesApi::class, ExperimentalGlideComposeApi::class) package com.example.myapplication import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewmodel.compose.viewModel import coil.compose.AsyncImage import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi import com.bumptech.glide.integration.compose.GlideImage import com.example.myapplication.course.MenuCoursera import com.example.myapplication.models.ContactsViewModel import com.example.myapplication.models.ImageViewModel import com.example.myapplication.screens.SecondActivity import com.example.myapplication.ui.theme.LittleLemonTheme import com.example.myapplication.utils.RetrofitInstance import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import retrofit2.HttpException import java.io.IOException const val TAG = "Coursera" class MainActivity : ComponentActivity() { private var fact = mutableStateOf(MenuCoursera()) private val viewModel by viewModels<ImageViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LittleLemonTheme { // val viewModel = viewModel<ContactsViewModel>( // factory = object : ViewModelProvider.Factory { // override fun <T : ViewModel> create(modelClass: Class<T>): T { // return ContactsViewModel() as T // } // } // ) Surface ( color = Color.White ) { // sendRequest() // MyUI(fact = fact, onImageClick = { viewModel.changeBackgroundColor() }) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { viewModel.uri?.let { AsyncImage(model = viewModel.uri, contentDescription = null) } Button(onClick = { // Intent(Intent.ACTION_MAIN).also { // it.`package` = "com.google.android.youtube" // try { // startActivity(it) // } catch (e: ActivityNotFoundException) { // e.printStackTrace() // } // } val intent = Intent(Intent.ACTION_SEND).apply { type="text/plain" putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]")) putExtra(Intent.EXTRA_SUBJECT, "This is my subject") putExtra(Intent.EXTRA_TEXT, "This is the content of my email") } if(intent.resolveActivity(packageManager) != null) { startActivity(intent) } }) { Text(text = "Move to another activity") } } } } } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent?.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) } else { intent?.getParcelableExtra(Intent.EXTRA_STREAM) } viewModel.updateUri(uri) } private fun sendRequest() { GlobalScope.launch(Dispatchers.IO) { val response = try { RetrofitInstance.api.getRandomFact() }catch (e: HttpException){ Toast.makeText(applicationContext, "http error: ${e.message}", Toast.LENGTH_SHORT).show() return@launch }catch (e: IOException){ Toast.makeText(applicationContext, "app error: ${e.message}", Toast.LENGTH_SHORT).show() return@launch } if (response.isSuccessful && response.body() != null) { withContext(Dispatchers.Main) { fact.value = response.body() !! } } } } } @OptIn(ExperimentalGlideComposeApi::class) @Composable fun ImageShowcase (onImageClick: () -> Unit){ GlideImage(modifier = Modifier.clickable { onImageClick() }, model = "data:image/jpeg;base64,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", contentDescription = "") } @Composable fun MyUI(fact: MutableState<MenuCoursera>, modifier: Modifier = Modifier, onImageClick: () -> Unit) { val menuText = fact.value?.Salads?.menu.toString() ?: "Loading..." val words = java.lang.String(menuText).split(", ").map { it.trim() }.toMutableList() for (word in words.indices) { if (word == 0) { words[word] = words[word].drop(1) } else if (word == words.lastIndex) { words[word] = words[word].dropLast(1) } } Column(modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center, ) { words.forEach {word-> Text(text = word, fontSize = 26.sp, fontWeight = FontWeight.Bold, lineHeight = 40.sp) } ImageShowcase(onImageClick = onImageClick) Button(onClick = { onImageClick() }) { Text(text = "Change Background") } } }
CourseRepo/app/src/main/java/com/example/myapplication/MainActivity.kt
2777367069
package com.example.myapplication.course data class MenuCoursera( val Appetizers: Appetizers = Appetizers(menu = listOf()), val Dessert: Dessert = Dessert(menu = listOf()), val Drinks: Drinks = Drinks(menu = listOf()), var Salads: Salads = Salads(menu = listOf()) )
CourseRepo/app/src/main/java/com/example/myapplication/course/MenuCoursera.kt
3776264521
package com.example.myapplication.course data class Salads( val menu: List<String> )
CourseRepo/app/src/main/java/com/example/myapplication/course/Salads.kt
2308962484
package com.example.myapplication.course data class Dessert( val menu: List<String> )
CourseRepo/app/src/main/java/com/example/myapplication/course/Dessert.kt
1345181238
package com.example.myapplication.course data class Drinks( val menu: List<String> )
CourseRepo/app/src/main/java/com/example/myapplication/course/Drinks.kt
4051010556
package com.example.myapplication.course data class Appetizers( val menu: List<String> )
CourseRepo/app/src/main/java/com/example/myapplication/course/Appetizers.kt
2466472939
package com.example.myapplication.utils import com.example.myapplication.data.ApiInterface import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.create object RetrofitInstance { val api: ApiInterface by lazy { Retrofit.Builder() .baseUrl(Util.Base) .addConverterFactory(GsonConverterFactory.create()) .build() .create(ApiInterface::class.java) } }
CourseRepo/app/src/main/java/com/example/myapplication/utils/RetfrofitInstance.kt
2424169646
package com.example.myapplication.utils object Util { const val Base = "https://raw.githubusercontent.com/Meta-Mobile-Developer-PC/Working-With-Data-API/main/" }
CourseRepo/app/src/main/java/com/example/myapplication/utils/Util.kt
2374945113
package com.example.myapplication.models import android.net.Uri import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel class ImageViewModel: ViewModel() { var uri: Uri? by mutableStateOf(null) private set fun updateUri (uri: Uri?) { this.uri = uri } }
CourseRepo/app/src/main/java/com/example/myapplication/models/ImageViewModel.kt
1868302218
package com.example.myapplication.models import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.lifecycle.ViewModel class ContactsViewModel: ViewModel() { var backgroundColor by mutableStateOf(Color.White) private set fun changeBackgroundColor () { backgroundColor = Color.Red } }
CourseRepo/app/src/main/java/com/example/myapplication/models/ContactsViewModel.kt
1965428749
package com.example.myapplication.screens import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Divider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.myapplication.R import com.example.myapplication.data.Categories import com.example.myapplication.data.Dish import com.example.myapplication.data.DishRepository import com.example.myapplication.ui.theme.LittleLemonColor @Composable fun LowerPanel (navController: NavController) { Column { WeeklySpecial() MenuListScreen(navController = navController) } } @Composable fun WeeklySpecial () { Card (modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(Color.White)) { Text( text = stringResource(id = R.string.week_spec), fontWeight = FontWeight.Bold, color = LittleLemonColor.charcoal, fontSize = 26.sp, modifier = Modifier .padding(8.dp) ) } } @Composable fun MenuCategory(category: String) { Button( onClick = { /*TODO*/ }, colors = ButtonDefaults.buttonColors(Color.LightGray), shape = RoundedCornerShape(40.dp), modifier = Modifier.padding(5.dp) ) { Text(text = category, color = Color.Black) } } @Composable fun MenuListScreen(navController: NavController) { Column { LazyRow { items(Categories) { category -> MenuCategory(category) } } Divider( modifier = Modifier.padding(8.dp), color = LittleLemonColor.yellow, thickness = 1.dp ) LazyColumn { items(DishRepository.dishes) { Dish -> MenuDish(Dish, navController) } } } } @Composable fun MenuDish(Dish: Dish, navController: NavController) { Card ( colors = CardDefaults.cardColors(Color.White), modifier = Modifier.clickable { navController.navigate("DishDetails/${Dish.id}") } ) { Row(modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { Column { Text(text = Dish.name, color = LittleLemonColor.charcoal, fontSize = 18.sp, fontWeight = FontWeight.Bold) Text( text = Dish.description, color = LittleLemonColor.green, modifier = Modifier .padding(vertical = 5.dp) .fillMaxWidth(.75f) ) Text( text = Dish.price.toString(), color = LittleLemonColor.green, fontWeight = FontWeight.Bold ) } Image( painter = painterResource(id = Dish.imageResource), contentDescription = Dish.name, ) } } }
CourseRepo/app/src/main/java/com/example/myapplication/screens/LowerPanel.kt
3885212690
package com.example.myapplication.screens import android.widget.Toast import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add 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.Text 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.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.myapplication.R @Composable fun ItemOrder ( count: Int, onIncrement: () -> Unit, onDecrement: () -> Unit ) { val context = LocalContext.current Column ( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { Card (colors = CardDefaults.cardColors(Color.White)) { Column { Text( text = stringResource(id = R.string.greek_salad), fontSize = 30.sp, modifier = Modifier.padding(start = 20.dp, top = 20.dp), fontWeight = FontWeight.Bold ) Row ( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { IconButton(onClick = { if (count == 0) { return@IconButton } else { onDecrement() } }) { //using to decrease number of dishes Canvas( modifier = Modifier.size(15.dp), onDraw = { drawLine( color = Color.Black, start = Offset(0f, size.height / 2f), end = Offset(size.width, size.height / 2f), strokeWidth = 5f ) } ) } Text( text = "$count", fontSize = 28.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(8.dp) ) IconButton(onClick = {onIncrement()}) { //using to increase number of dishes Icon( imageVector = Icons.Default.Add, contentDescription = "Add" ) } } Button( onClick = { if (count == 0) { Toast.makeText(context, "No Items to be Added", Toast.LENGTH_SHORT).show() } else { Toast.makeText(context, "Successfully Added $count Items", Toast.LENGTH_SHORT).show() } }, modifier = Modifier .padding(start = 20.dp, end = 20.dp, bottom = 20.dp) .fillMaxWidth(), shape = RoundedCornerShape(10.dp) ) { Text(text = "Add") } } } } }
CourseRepo/app/src/main/java/com/example/myapplication/screens/ItemOrder.kt
2955534072
package com.example.myapplication.screens import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import com.example.myapplication.screens.BottomBar @Composable fun Settings(selectedIndex: MutableState<Int>, navController: NavHostController) { Scaffold (bottomBar = { BottomBar(selectedIndex = selectedIndex, navController) }) { paddingValues -> Box( modifier = Modifier .fillMaxSize() .padding(paddingValues), contentAlignment = Alignment.Center ){ Text(text = "Settings Screen", fontSize = 48.sp) } } }
CourseRepo/app/src/main/java/com/example/myapplication/screens/Settings.kt
379783364
package com.example.myapplication.screens import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.outlined.Email import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.Badge import androidx.compose.material3.BadgedBox import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.navigation.NavController @OptIn(ExperimentalMaterial3Api::class) @Composable fun BottomBar(selectedIndex: MutableState<Int>, navController: NavController){ val bottomBarItems = listOf( BottomNavigationItem( title = "Home", selectedIcon = Icons.Filled.Home, unselectedIcon = Icons.Outlined.Home ), BottomNavigationItem( title = "News", selectedIcon = Icons.Filled.Email, unselectedIcon = Icons.Outlined.Email, badgeCount = 45 ), BottomNavigationItem( title = "Settings", selectedIcon = Icons.Filled.Settings, unselectedIcon = Icons.Outlined.Settings, hasNews = true ) ) NavigationBar { bottomBarItems.forEachIndexed { index, item -> NavigationBarItem( selected = selectedIndex.value == index, onClick = { selectedIndex.value = index navController.navigate(item.title) }, label = { Text(text = item.title) }, icon = { BadgedBox( badge = { if (item.badgeCount != null && index != selectedIndex.value){ Badge { Text(text = item.badgeCount.toString()) } } else if (item.hasNews && index != selectedIndex.value) { Badge () } }) { Icon( imageVector = if (index == selectedIndex.value){ item.selectedIcon }else { item.selectedIcon }, contentDescription = item.title ) } }) } } }
CourseRepo/app/src/main/java/com/example/myapplication/screens/BottomBar.kt
1884128983
package com.example.myapplication.screens import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import com.example.myapplication.R @Composable fun News(selectedIndex: MutableState<Int>, navController: NavHostController) { Scaffold (bottomBar = { BottomBar(selectedIndex = selectedIndex, navController) }) { paddingValues -> LazyGrid(modifier = Modifier.padding(paddingValues = paddingValues)) } } @Composable fun LazyGrid (modifier: Modifier){ LazyVerticalGrid(columns = GridCells.Adaptive(140.dp)){ items(1000){ MyGridCell() } } } @Composable fun MyGridCell() { Card( elevation = CardDefaults.cardElevation(20.dp), modifier = Modifier.padding(8.dp) ) { Box( modifier = Modifier .padding(8.dp) .fillMaxSize() ) { Image( painter = painterResource(id = R.drawable.greeksalad), contentDescription = "Greek Salad", contentScale = ContentScale.FillWidth, modifier = Modifier.fillMaxWidth() ) Text( text = "Greek Salad", fontSize = 18.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Start, modifier = Modifier .fillMaxWidth() .background(Color.White) .align(Alignment.TopStart) ) Text( text = "$12.99", fontSize = 18.sp, fontWeight = FontWeight.Bold, modifier = Modifier .background(Color.White) .padding(start = 4.dp, end = 4.dp) .align(Alignment.BottomEnd) ) } } }
CourseRepo/app/src/main/java/com/example/myapplication/screens/News.kt
3480520212
@file:OptIn(ExperimentalMaterial3Api::class) package com.example.myapplication.screens import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.outlined.Email import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.Info import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.example.myapplication.data.DishDetails import com.example.myapplication.R import com.example.myapplication.data.Dashboard import com.example.myapplication.data.Details import com.example.myapplication.data.Menu import com.example.myapplication.data.NavigationItem import kotlinx.coroutines.launch @Composable fun MyNavCourseFF () { val navController = rememberNavController() NavHost(navController = navController, startDestination = Dashboard.route) { composable(Dashboard.route) { // DashboardScreenCourse(navController) } composable(Details.route) { // DetailsScreenCourse() } composable( Menu.route + "/{${Menu.argOrderNo}}", arguments = listOf( navArgument(Menu.argOrderNo) { type = NavType.IntType} )) { // MenuScreen(it.arguments?.getInt(Menu.argOrderNo)) } } } data class BottomNavigationItem ( val title: String, val selectedIcon: ImageVector, val unselectedIcon: ImageVector, val hasNews: Boolean = false, var badgeCount: Int? = null) sealed class Screen(val route:String) { object Login: Screen("Login") object Home: Screen("Home") object News: Screen("News") object Settings: Screen("Settings") object DishDetails: Screen("DishDetails") } private fun currentDestination(navController: NavController): String? { return navController.currentBackStackEntry?.destination?.route } @Composable fun MyNav() { val navController = rememberNavController() val selectedIndex = rememberSaveable { mutableStateOf(0) } val bottomBarItems = listOf( BottomNavigationItem( title = "Home", selectedIcon = Icons.Filled.Home, unselectedIcon = Icons.Outlined.Home ), BottomNavigationItem( title = "News", selectedIcon = Icons.Filled.Email, unselectedIcon = Icons.Outlined.Email, badgeCount = 45 ), BottomNavigationItem( title = "Settings", selectedIcon = Icons.Filled.Settings, unselectedIcon = Icons.Outlined.Settings, hasNews = true ) ) val topBarItems = listOf( NavigationItem( title = "Menu", selectedIcon = Icons.Filled.Home, unselectedIcon = Icons.Outlined.Home ), NavigationItem( title = "Urgent", selectedIcon = Icons.Filled.Info, unselectedIcon = Icons.Outlined.Info ), NavigationItem( title = "Settings", selectedIcon = Icons.Filled.Settings, unselectedIcon = Icons.Outlined.Settings ) ) val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) val selectedItemIndex by rememberSaveable { mutableStateOf(0) } val scope = rememberCoroutineScope() Scaffold( bottomBar = { if (bottomBarItems.any { it.title == currentDestination(navController) }) { BottomBar(navController = navController, selectedIndex = selectedIndex) } }, topBar = { if (bottomBarItems.any { it.title == currentDestination(navController) }){ Row ( modifier = Modifier .fillMaxWidth() .background(Color.White), verticalAlignment = Alignment.CenterVertically, ) { IconButton(onClick = { scope.launch { drawerState.open() } } ) { Icon( imageVector = Icons.Default.Menu, contentDescription = "Menu Button", Modifier.size(24.dp) ) } Image( painter = painterResource(id = R.drawable.littlelemonimgtxt_nobg), contentDescription = "Little Lemon Logo", modifier = Modifier .fillMaxWidth(0.85F) .padding(horizontal = 20.dp) .height(40.dp) ) IconButton(onClick = { /*TODO*/ }) { Image( painter = painterResource(id = R.drawable.ic_basket), contentDescription = "Cart", modifier = Modifier.size(24.dp) ) } } } } ) { it NavHost(navController = navController, startDestination = Screen.Login.route) { composable(Screen.Login.route) { LoginScreen(navController) } composable(Screen.Home.route) { HomeScreen(selectedIndex, navController) } composable(Screen.News.route) { News(selectedIndex, navController) } composable(Screen.Settings.route) { Settings(selectedIndex, navController) } composable(Screen.DishDetails.route + "/{id}") { backStackEntry -> val arguments = requireNotNull(backStackEntry.arguments) val dishId = arguments.getInt("id") DishDetails(dishId, selectedIndex, navController) } } } }
CourseRepo/app/src/main/java/com/example/myapplication/screens/Navigation.kt
3797122820
package com.example.myapplication.screens import android.os.Bundle import android.os.PersistableBundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Text import androidx.compose.ui.Modifier import androidx.compose.ui.unit.sp class SecondActivity: ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Text(text = "Second Activity", modifier = Modifier.fillMaxSize(), fontSize = 40.sp) } } }
CourseRepo/app/src/main/java/com/example/myapplication/screens/SecondActivity.kt
1220722789