fooddelivery: dialogs as routes, scaffold menu search, route screenshots
- Commit
34101722e42d81de9d02160224a4a30f01a7cf3c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 01:19 UTC (4 days ago)
- Parents
539068d
DialogAsRoute (8): EditProfile, DeleteAccount, ModifierPicker (restaurant add + cart edit), PendingCart and OrderFeedback dialogs are now Route destinations with DialogPage() entries in ui/DialogEntries.kt; identity travels in route arguments and results come back through RESULT_* registry keys. Dialog definitions moved under ui/dialogs/; screens only push routes from click handlers. FoodDeliveryApp's pending-cart state is gone - the restaurant entry pushes PendingCartDialog on a merchant conflict directly. ScaffoldSearch (1): the restaurant menu filter now lives in the AppScaffold search slot (title = merchant name, scaffold back); the in-list OutlinedTextField and overlay back buttons are removed. The required-modifier validation in ModifierDialog is untouched. RouteScreenshotCoverage (8 + 5 new dialog routes): real @Preview captures named <n>-<route-kebab> for Home, Deals, Orders, Account, Restaurant, Checkout, OrderTracking, EmailVerification and all five dialog routes, backed by stateless extractions (DealsContent, OrdersContent, AccountContent, OrderTrackingContent) and existing stateless slices with deterministic fixtures. FileLength: OrderTrackingContent split into its own file. FixtureDeterminism (4): three test files seed ETA/stage/token-expiry relative to the SUT's real clock, marked with verbatim FIXTURE RELATIVE-TIME EXCEPTION reasons. Unit tests adapted to the new contracts: dialog flows render dialog contents from captured route requests, account tests provide a NavResultRegistry, restaurant tests scroll the menu into composition (the scaffold top bar now occupies the fold) and type into the scaffold search field. Verified: ./gradlew :fooddelivery:lint :fooddelivery:lintVitalRelease :fooddelivery:testDevUnitTest :fooddelivery:compileReleaseKotlin :fooddelivery:compileDevScreenshotTestKotlin all green. python3 tools/structure_check.py exceptions --regen ran; exceptions.tsv unchanged (fixture markers are not inventoried).
Diff
fooddelivery/AGENTS.md
diff --git a/fooddelivery/AGENTS.md b/fooddelivery/AGENTS.mdindex 948daaf9a7..616a1d1331 100644--- a/fooddelivery/AGENTS.md+++ b/fooddelivery/AGENTS.md@@ -5,7 +5,7 @@ _Install: ./install fooddelivery (dev by default)._ - Gradle: :fooddelivery / dir: fooddelivery/ - Package roots present: ui, data, platform, intents, notifications-- Entry files: MainActivity.kt + FoodDeliveryApplication.kt + platform/AppInit.kt (no Route.kt — home/restaurant/cart/checkout/orders flow)+- Entry files: MainActivity.kt + FoodDeliveryApplication.kt + platform/AppInit.kt + Route.kt + Navigation.kt (tab routes + detail/dialog routes) - Deps: :library:image, :library:map, :library:network - Metadata: metadata_data/fooddelivery.md (present) - Rust: no / screenshotTest: yes@@ -45,7 +45,7 @@ _Install: ./install fooddelivery (dev by default)._ - com/vayunmathur/fooddelivery/ui/DealsScreen.kt - com/vayunmathur/fooddelivery/ui/RestaurantScreen.kt - com/vayunmathur/fooddelivery/ui/RestaurantSections.kt-- com/vayunmathur/fooddelivery/ui/ModifierDialog.kt+- com/vayunmathur/fooddelivery/ui/dialogs/ModifierDialog.kt - com/vayunmathur/fooddelivery/ui/CartScreen.kt - com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt - com/vayunmathur/fooddelivery/ui/CheckoutSections.kt@@ -59,6 +59,15 @@ _Install: ./install fooddelivery (dev by default)._ - com/vayunmathur/fooddelivery/ui/AccountProfile.kt - com/vayunmathur/fooddelivery/ui/AccountAddresses.kt - com/vayunmathur/fooddelivery/ui/AddressFormCard.kt+- com/vayunmathur/fooddelivery/ui/OrderTrackingContent.kt+- com/vayunmathur/fooddelivery/ui/DialogEntries.kt+- com/vayunmathur/fooddelivery/ui/dialogs/EditProfileDialog.kt+- com/vayunmathur/fooddelivery/ui/dialogs/DeleteAccountDialog.kt+- com/vayunmathur/fooddelivery/ui/dialogs/OrderFeedbackDialog.kt+- com/vayunmathur.fooddelivery/ui/dialogs/PendingCartDialog.kt++## Screenshot coverage + dialog routes+Dialogs are `Route` destinations (`EditProfileDialog`, `DeleteAccountDialog`, `ModifierPickerDialog`, `PendingCartDialog`, `OrderFeedbackDialog` — `DialogPage()` entries in `ui/DialogEntries.kt`, identity in route args, results via `RESULT_*` keys), never `show…`/pending-target state in a screen. Each route has a capture in `src/screenshotTest` named `<n>-<route-key>`; the fatal `RouteScreenshotCoverage` lint enforces route→capture mapping. Menu search lives in the restaurant scaffold's `search` slot, not in the menu list. ## Verify (this module only) ```
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Navigation.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Navigation.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Navigation.ktindex bb2b9c5f4d..26a95f9c93 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Navigation.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Navigation.kt@@ -21,7 +21,6 @@ import com.vayunmathur.library.util.SiblingPage fun Navigation( backStack: NavBackStack<Route>, cart: androidx.compose.runtime.snapshots.SnapshotStateList<CartItem>,- onPendingCartItem: (CartItem) -> Unit, ) { val context = LocalContext.current MainNavigation(backStack) {@@ -39,9 +38,15 @@ fun Navigation( CartStore.save(context, cart) }, onCheckout = { backStack.add(Route.Checkout) },- onEditModifiers = { index, modifiers ->- cart[index] = cart[index].copy(selectedModifiers = modifiers)- CartStore.save(context, cart)+ onEditModifiers = { index, item ->+ backStack.add(+ Route.ModifierPickerDialog(+ item = item.menuItem,+ merchantName = item.merchantName,+ initialSelection = item.selectedModifiers,+ cartIndex = index,+ )+ ) }, ) }@@ -53,15 +58,23 @@ fun Navigation( } entry<Route.Orders>(metadata = ListPage() + SiblingPage()) { FoodDeliveryTabs(backStack) {- OrdersScreen(onTrackOrder = { id -> backStack.pushDetail(Route.OrderTracking(id)) })+ OrdersScreen(+ onTrackOrder = { id -> backStack.pushDetail(Route.OrderTracking(id)) },+ onRateOrder = { order ->+ backStack.add(Route.OrderFeedbackDialog(order.id, order.uuid))+ },+ ) } } entry<Route.Account>(metadata = ListPage() + SiblingPage()) { FoodDeliveryTabs(backStack) {- AccountScreen()+ AccountScreen(+ onEditProfile = { customer -> backStack.add(Route.EditProfileDialog(customer)) },+ onDeleteAccountRequest = { backStack.add(Route.DeleteAccountDialog) },+ ) } }- detailEntries(backStack, cart, context, onPendingCartItem)+ detailEntries(backStack, cart, context) } }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Route.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Route.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Route.ktindex d0f20488eb..866a686ce2 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Route.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/Route.kt@@ -1,5 +1,9 @@ package com.vayunmathur.fooddelivery +import com.vayunmathur.fooddelivery.data.CartItem+import com.vayunmathur.fooddelivery.data.Customer+import com.vayunmathur.fooddelivery.data.MenuItem+import com.vayunmathur.fooddelivery.data.SelectedModifier import com.vayunmathur.library.util.NavKey import kotlinx.serialization.Serializable @@ -23,4 +27,28 @@ sealed interface Route : NavKey { @Serializable data class OrderTracking(val orderId: Int) : Route /** Email-verification screen for [customerId] carrying its verification [token]. */ @Serializable data class EmailVerification(val customerId: String, val token: String) : Route++ /** Dialog destination editing the profile of [customer]; the host posts the save. */+ @Serializable data class EditProfileDialog(val customer: Customer) : Route++ /** Dialog destination confirming account deletion; the host performs the delete. */+ @Serializable data object DeleteAccountDialog : Route++ /**+ * Dialog destination picking modifiers for [item]. [cartIndex] is the cart+ * line being re-customised, or -1 when the pick adds a new line from the+ * restaurant page; [initialSelection] reopens an existing pick.+ */+ @Serializable data class ModifierPickerDialog(+ val item: MenuItem,+ val merchantName: String = "",+ val initialSelection: List<SelectedModifier> = emptyList(),+ val cartIndex: Int = -1,+ ) : Route++ /** Dialog destination confirming that [item] replaces a cart from another restaurant. */+ @Serializable data class PendingCartDialog(val item: CartItem) : Route++ /** Dialog destination rating the finished order [orderId] (server key [orderUuid]). */+ @Serializable data class OrderFeedbackDialog(val orderId: Int, val orderUuid: String?) : Route }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountProfile.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountProfile.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountProfile.ktindex 2386193ebf..9818a30b5d 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountProfile.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountProfile.kt@@ -163,64 +163,3 @@ internal fun AccountReferralsCard( } } }--/** Edit the name/email on the account; posts the whole customer to POST /customers/me. */-@Composable-internal fun EditProfileDialog(- customer: Customer,- onDismiss: () -> Unit,- onSave: (Customer) -> Unit,-) {- var firstName by remember { mutableStateOf(customer.firstName) }- var lastName by remember { mutableStateOf(customer.lastName) }- var email by remember { mutableStateOf(customer.email) }-- AlertDialog(- onDismissRequest = onDismiss,- title = { Text(stringResource(R.string.edit_profile)) },- text = {- Column {- OutlinedTextField(- value = firstName,- onValueChange = { firstName = it },- label = { Text(stringResource(R.string.first_name)) },- singleLine = true,- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.PersonName),- modifier = Modifier.fillMaxWidth(),- )- Spacer(Modifier.height(8.dp))- OutlinedTextField(- value = lastName,- onValueChange = { lastName = it },- label = { Text(stringResource(R.string.last_name)) },- singleLine = true,- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.PersonName),- modifier = Modifier.fillMaxWidth(),- )- Spacer(Modifier.height(8.dp))- OutlinedTextField(- value = email,- onValueChange = { email = it },- label = { Text(stringResource(UiR.string.email)) },- singleLine = true,- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),- modifier = Modifier.fillMaxWidth(),- )- }- },- confirmButton = {- Button(onClick = {- onSave(- customer.copy(- firstName = firstName.trim(),- lastName = lastName.trim(),- email = email.trim(),- )- )- }) { Text(stringResource(R.string.save_changes)) }- },- dismissButton = {- TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) }- },- )-}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.ktindex 342961243a..c94b6bfbf8 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.kt@@ -49,6 +49,7 @@ import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.ResultEffect import androidx.compose.ui.platform.LocalContext import kotlinx.coroutines.launch @@ -56,7 +57,10 @@ private const val PREFS_NAME = "fooddelivery_prefs" private const val KEY_TOKEN = "token_json" @Composable-fun AccountScreen() {+fun AccountScreen(+ onEditProfile: (Customer) -> Unit = {},+ onDeleteAccountRequest: () -> Unit = {},+) { val context = LocalContext.current val scope = rememberCoroutineScope() @@ -65,8 +69,6 @@ fun AccountScreen() { var referrals by remember { mutableStateOf<List<Referral>>(emptyList()) } var platformSavings by remember { mutableStateOf<PlatformSavings?>(null) } var notice by remember { mutableStateOf<String?>(null) }- var confirmDelete by remember { mutableStateOf(false) }- var editingProfile by remember { mutableStateOf(false) } var loggedIn by remember { mutableStateOf(BitesAuth.isLoggedIn()) } // The saved token is restored by the background warm-up, so "signed out" isn't known to // be true until that has landed — don't offer the sign-in card before then.@@ -78,6 +80,16 @@ fun AccountScreen() { var codeSent by remember { mutableStateOf(false) } var authLoading by remember { mutableStateOf(false) } + ResultEffect<Customer>(RESULT_PROFILE_UPDATED) { saved ->+ customer = saved+ notice = "Profile updated"+ }+ ResultEffect<Boolean>(RESULT_ACCOUNT_DELETED) {+ loggedIn = false+ customer = null+ savings = null+ }+ var addresses by remember { mutableStateOf<List<SavedAddress>>(emptyList()) } var addressesLoaded by remember { mutableStateOf(false) } var addressForm by remember { mutableStateOf(AddressFormState()) }@@ -108,7 +120,95 @@ fun AccountScreen() { } } - AppScaffold(topBar = {}) { padding ->+ AccountContent(+ customer = customer,+ savings = savings,+ referrals = referrals,+ platformSavings = platformSavings,+ notice = notice,+ loggedIn = loggedIn,+ authResolved = authResolved,+ phone = phone,+ code = code,+ codeSent = codeSent,+ authLoading = authLoading,+ addresses = addresses,+ addressesLoaded = addressesLoaded,+ addressForm = addressForm,+ onPhoneChange = { phone = it },+ onCodeChange = { code = it },+ onAuthClick = {+ scope.launch {+ authLoading = true+ if (!codeSent) {+ val sid = BitesAuth.verifyPhone(phone)+ if (sid != null) {+ stateId = sid+ codeSent = true+ }+ } else {+ val sid = stateId ?: return@launch+ val token = BitesAuth.exchangeOtpCodeForToken(sid, code)+ if (token != null && token.accessToken.isNotEmpty()) {+ BitesAuth.setToken(token)+ loggedIn = true+ }+ }+ authLoading = false+ }+ },+ onEditProfile = onEditProfile,+ onDeleteAccountRequest = onDeleteAccountRequest,+ onSendVerification = { c ->+ scope.launch {+ val ok = BitesCustomers.sendEmailVerification(c.email)+ notice = if (ok) "Verification email sent to ${c.email}"+ else "Couldn't send the verification email"+ }+ },+ onSignOut = {+ context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ .edit { remove(KEY_TOKEN) }+ BitesAuth.clearToken()+ loggedIn = false+ customer = null+ savings = null+ },+ onAddressesChange = { addresses = it },+ onAddressFormChange = { addressForm = it },+ onResetAddressForm = { resetAddressForm() },+ )+}++/** Stateless account layout for previews; [AccountScreen] owns state and effects. */+@Composable+internal fun AccountContent(+ customer: Customer?,+ savings: CustomerSavings?,+ referrals: List<Referral>,+ platformSavings: PlatformSavings?,+ notice: String?,+ loggedIn: Boolean,+ authResolved: Boolean,+ phone: String,+ code: String,+ codeSent: Boolean,+ authLoading: Boolean,+ addresses: List<SavedAddress>,+ addressesLoaded: Boolean,+ addressForm: AddressFormState,+ onPhoneChange: (String) -> Unit = {},+ onCodeChange: (String) -> Unit = {},+ onAuthClick: () -> Unit = {},+ onEditProfile: (Customer) -> Unit = {},+ onDeleteAccountRequest: () -> Unit = {},+ onSendVerification: (Customer) -> Unit = {},+ onSignOut: () -> Unit = {},+ onAddressesChange: (List<SavedAddress>) -> Unit = {},+ onAddressFormChange: (AddressFormState) -> Unit = {},+ onResetAddressForm: () -> Unit = {},+) {+AppScaffold(topBar = {}) { padding -> Column( Modifier.fillMaxSize().padding(padding) .verticalScroll(rememberScrollState()).padding(16.dp),@@ -117,55 +217,15 @@ fun AccountScreen() { if (!loggedIn && authResolved) { AccountAuthCard( phone = phone,- onPhoneChange = { phone = it },+ onPhoneChange = onPhoneChange, code = code,- onCodeChange = { code = it },+ onCodeChange = onCodeChange, codeSent = codeSent, authLoading = authLoading,- onAuthClick = {- scope.launch {- authLoading = true- if (!codeSent) {- val sid = BitesAuth.verifyPhone(phone)- if (sid != null) {- stateId = sid- codeSent = true- }- } else {- val sid = stateId ?: return@launch- val token = BitesAuth.exchangeOtpCodeForToken(sid, code)- if (token != null && token.accessToken.isNotEmpty()) {- BitesAuth.setToken(token)- loggedIn = true- }- }- authLoading = false- }- },+ onAuthClick = onAuthClick, ) } else if (loggedIn) {- if (editingProfile) {- customer?.let { c ->- EditProfileDialog(- customer = c,- onDismiss = { editingProfile = false },- onSave = { updated ->- scope.launch {- editingProfile = false- val saved = BitesCustomers.createOrUpdateCustomer(updated)- if (saved != null) {- customer = saved- notice = "Profile updated"- } else {- notice = "Couldn't update your profile"- }- }- },- )- }- }-- AccountProfileCard(customer = customer, onEdit = { editingProfile = true })+ AccountProfileCard(customer = customer, onEdit = { customer?.let { c -> onEditProfile(c) } }) AccountSavingsCard(savings = savings) // Email verification — the account's email is unverified until the emailed@@ -181,13 +241,7 @@ fun AccountScreen() { ) Spacer(Modifier.height(8.dp)) OutlinedButton(- onClick = {- scope.launch {- val ok = BitesCustomers.sendEmailVerification(c.email)- notice = if (ok) "Verification email sent to ${c.email}"- else "Couldn't send the verification email"- }- },+ onClick = { onSendVerification(c) }, modifier = Modifier.fillMaxWidth(), ) { Text(stringResource(R.string.send_verification_email)) } }@@ -204,54 +258,17 @@ fun AccountScreen() { ) } - if (confirmDelete) {- AlertDialog(- onDismissRequest = { confirmDelete = false },- title = { Text(stringResource(R.string.delete_account)) },- text = { Text(stringResource(R.string.delete_account_warning)) },- confirmButton = {- Button(onClick = {- scope.launch {- confirmDelete = false- if (BitesCustomers.deleteCustomer()) {- context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)- .edit { remove(KEY_TOKEN) }- BitesAuth.clearToken()- loggedIn = false- customer = null- savings = null- } else {- notice = "Couldn't delete the account"- }- }- }) { Text(stringResource(R.string.delete_account)) }- },- dismissButton = {- TextButton(onClick = { confirmDelete = false }) {- Text(stringResource(UiR.string.cancel))- }- },- )- }- HorizontalDivider() OutlinedButton(- onClick = {- context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)- .edit { remove(KEY_TOKEN) }- BitesAuth.clearToken()- loggedIn = false- customer = null- savings = null- },+ onClick = onSignOut, modifier = Modifier.fillMaxWidth() ) { Text(stringResource(R.string.sign_out)) } TextButton(- onClick = { confirmDelete = true },+ onClick = onDeleteAccountRequest, modifier = Modifier.fillMaxWidth(), ) { Text(@@ -274,22 +291,22 @@ fun AccountScreen() { fontWeight = FontWeight.Bold ) IconButton(onClick = {- resetAddressForm()- addressForm = addressForm.copy(showing = true)+ onResetAddressForm()+onAddressFormChange(addressForm.copy(showing = true)) }) { IconAdd(tint = MaterialTheme.colorScheme.primary) } } AccountAddressesSection(- scope = scope,- context = context,+ scope = rememberCoroutineScope(),+ context = LocalContext.current, addressesLoaded = addressesLoaded, addresses = addresses,- onAddressesChange = { addresses = it },+ onAddressesChange = onAddressesChange, form = addressForm,- onFormChange = { addressForm = it },- onResetForm = { resetAddressForm() },+ onFormChange = onAddressFormChange,+ onResetForm = onResetAddressForm, ) } }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.ktindex 22f3e97869..7c05ff886f 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.kt@@ -43,25 +43,9 @@ fun CartScreen( items: List<CartItem>, onRemoveItem: (Int) -> Unit, onCheckout: () -> Unit,- onEditModifiers: (Int, List<SelectedModifier>) -> Unit = { _, _ -> },+ // Asks the host to open the modifier picker route for a cart line.+ onEditModifiers: (Int, CartItem) -> Unit = { _, _ -> }, ) {- // Index of the line being re-customised, if any.- var editingIndex by remember { mutableStateOf<Int?>(null) }-- editingIndex?.let { idx ->- items.getOrNull(idx)?.let { editing ->- ModifierDialog(- item = editing.menuItem,- initialSelection = editing.selectedModifiers,- confirmLabel = stringResource(R.string.save_changes),- onDismiss = { editingIndex = null },- onConfirm = { updated ->- onEditModifiers(idx, updated)- editingIndex = null- },- )- }- } AppScaffold(topBar = {}) { padding -> if (items.isEmpty()) {@@ -90,7 +74,7 @@ fun CartScreen( item = item, onRemove = { onRemoveItem(index) }, onEdit = if (item.menuItem.modifierGroups.isNotEmpty()) {- { editingIndex = index }+ { onEditModifiers(index, item) } } else null, ) }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.ktindex 3da57bc832..dde2dc9fc7 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.kt@@ -76,7 +76,23 @@ fun DealsScreen(onMerchantClick: (Int) -> Unit) { } } - AppScaffold(topBar = {}, isRefreshing = loading) { padding ->+ DealsContent(+ deals = deals,+ progress = progress,+ loading = loading,+ onMerchantClick = onMerchantClick,+ )+}++/** Stateless deals list for previews; [DealsScreen] owns loading and state. */+@Composable+internal fun DealsContent(+ deals: List<Deal>,+ progress: Map<Int, DealProgress>,+ loading: Boolean,+ onMerchantClick: (Int) -> Unit = {},+) {+AppScaffold(topBar = {}, isRefreshing = loading) { padding -> when { loading -> Box(Modifier.fillMaxSize().padding(padding)) deals.isEmpty() -> EmptyState(
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DialogEntries.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DialogEntries.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DialogEntries.ktnew file mode 100644index 0000000000..e72a4171a5--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DialogEntries.kt@@ -0,0 +1,163 @@+package com.vayunmathur.fooddelivery.ui++import android.content.Context+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.core.content.edit+import com.vayunmathur.fooddelivery.R+import com.vayunmathur.fooddelivery.Route+import com.vayunmathur.fooddelivery.data.CartItem+import com.vayunmathur.fooddelivery.data.CartStore+import com.vayunmathur.fooddelivery.data.Customer+import com.vayunmathur.fooddelivery.data.FeedbackRequest+import com.vayunmathur.fooddelivery.network.BitesAuth+import com.vayunmathur.fooddelivery.network.BitesCustomers+import com.vayunmathur.fooddelivery.network.BitesOrders+import com.vayunmathur.fooddelivery.platform.canAddFromSameMerchant+import com.vayunmathur.fooddelivery.ui.dialogs.DeleteAccountDialog+import com.vayunmathur.fooddelivery.ui.dialogs.EditProfileDialog+import com.vayunmathur.fooddelivery.ui.dialogs.ModifierDialog+import com.vayunmathur.fooddelivery.ui.dialogs.OrderFeedbackDialog+import com.vayunmathur.fooddelivery.ui.dialogs.PendingCartDialog+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.library.util.DialogPage+import com.vayunmathur.library.util.EntryProviderScope+import com.vayunmathur.library.util.LocalNavResultRegistry+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.launch++/** Result key: the account profile was saved; the saved [Customer] is the result. */+const val RESULT_PROFILE_UPDATED = "fooddelivery.profile-updated"++/** Result key: the account was deleted; the account screen must sign out locally. */+const val RESULT_ACCOUNT_DELETED = "fooddelivery.account-deleted"++// Same prefs the account screen and AppInit use for the persisted token.+private const val PREFS_NAME = "fooddelivery_prefs"+private const val KEY_TOKEN = "token_json"++/**+ * Dialog destinations for fooddelivery: every dialog is a [Route] with+ * `DialogPage()` metadata, its identity in the route arguments, never+ * `show…` / pending-target state in the screen that asked. Hosts perform the+ * side effects here and report back through the result registry.+ */+internal fun EntryProviderScope<Route>.dialogEntries(+ backStack: NavBackStack<Route>,+ cart: androidx.compose.runtime.snapshots.SnapshotStateList<CartItem>,+ context: Context,+) {+ entry<Route.EditProfileDialog>(metadata = DialogPage()) { route ->+ val scope = rememberCoroutineScope()+ val registry = LocalNavResultRegistry.current+ EditProfileDialog(+ customer = route.customer,+ onDismiss = { backStack.pop() },+ onSave = { updated ->+ scope.launch {+ val saved = BitesCustomers.createOrUpdateCustomer(updated)+ if (saved != null) {+ registry.dispatchResult(RESULT_PROFILE_UPDATED, saved)+ backStack.pop()+ } else {+ AppMessages.show("Couldn't update your profile")+ }+ }+ },+ )+ }+ entry<Route.DeleteAccountDialog>(metadata = DialogPage()) {+ val scope = rememberCoroutineScope()+ val registry = LocalNavResultRegistry.current+ DeleteAccountDialog(+ onDismiss = { backStack.pop() },+ onConfirm = {+ scope.launch {+ if (BitesCustomers.deleteCustomer()) {+ context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ .edit { remove(KEY_TOKEN) }+ BitesAuth.clearToken()+ registry.dispatchResult(RESULT_ACCOUNT_DELETED, true)+ backStack.pop()+ } else {+ AppMessages.show("Couldn't delete the account")+ }+ }+ },+ )+ }+ entry<Route.ModifierPickerDialog>(metadata = DialogPage()) { route ->+ ModifierDialog(+ item = route.item,+ initialSelection = route.initialSelection,+ confirmLabel = if (route.cartIndex >= 0) {+ stringResource(R.string.save_changes)+ } else {+ null+ },+ onDismiss = { backStack.pop() },+ onConfirm = { selected ->+ backStack.pop()+ if (route.cartIndex >= 0) {+ val index = route.cartIndex+ if (index in cart.indices) {+ cart[index] = cart[index].copy(selectedModifiers = selected)+ CartStore.save(context, cart)+ }+ } else {+ val item = CartItem(+ menuItem = route.item,+ merchantId = route.item.merchantId,+ merchantName = route.merchantName,+ selectedModifiers = selected,+ )+ if (cart.canAddFromSameMerchant(item)) {+ cart.add(item)+ CartStore.save(context, cart)+ } else {+ backStack.add(Route.PendingCartDialog(item))+ }+ }+ },+ )+ }+ entry<Route.PendingCartDialog>(metadata = DialogPage()) { route ->+ PendingCartDialog(+ currentName = cart.firstOrNull()?.merchantName?.ifBlank { "another restaurant" }+ ?: "another restaurant",+ newName = route.item.merchantName.ifBlank { "a different restaurant" },+ onDismiss = { backStack.pop() },+ onConfirm = {+ cart.clear()+ cart.add(route.item)+ CartStore.save(context, cart)+ backStack.pop()+ },+ )+ }+ entry<Route.OrderFeedbackDialog>(metadata = DialogPage()) { route ->+ val scope = rememberCoroutineScope()+ OrderFeedbackDialog(+ onDismiss = { backStack.pop() },+ onSubmit = { rating, note, extraTipCents ->+ scope.launch {+ val submitted = route.orderUuid?.let {+ BitesOrders.submitFeedback(+ it,+ FeedbackRequest(+ orderId = route.orderId,+ rating = rating,+ feedback = note.ifBlank { null },+ tips = extraTipCents,+ ),+ )+ } == true+ // Only dismiss on success: closing unconditionally made a failed+ // submit look exactly like a delivered rating.+ if (submitted) backStack.pop()+ }+ },+ )+ }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/EmailVerificationScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/EmailVerificationScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/EmailVerificationScreen.ktindex c5f32fc5c1..a088844125 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/EmailVerificationScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/EmailVerificationScreen.kt@@ -31,7 +31,7 @@ import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton -private enum class VerifyState { LOADING, SUCCESS, ERROR }+internal enum class VerifyState { LOADING, SUCCESS, ERROR } /** Opened from an email-verification link; posts the link's customer id + token. */ @Composable@@ -61,7 +61,7 @@ internal fun EmailVerificationScreen( } @Composable-private fun EmailVerificationContent(+internal fun EmailVerificationContent( state: VerifyState, onRetry: () -> Unit, onDone: () -> Unit,
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/FoodDeliveryApp.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/FoodDeliveryApp.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/FoodDeliveryApp.ktindex a2ffbfa2b6..34c8482aa0 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/FoodDeliveryApp.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/FoodDeliveryApp.kt@@ -60,22 +60,6 @@ internal fun FoodDeliveryApp( // thread rather than in the remember initialiser. Anything added while the read was in // flight stays in the cart, and is re-persisted alongside the restored lines. val cart = remember { mutableStateListOf<CartItem>() }- // An item from a second restaurant, held until the user decides whether it- // replaces the cart they already have (checkout can only order from one).- var pendingCartItem by remember { mutableStateOf<CartItem?>(null) }- pendingCartItem?.let { pending ->- PendingCartDialog(- cart = cart,- pending = pending,- onDismiss = { pendingCartItem = null },- onConfirm = {- cart.clear()- cart.add(pending)- CartStore.save(context, cart)- pendingCartItem = null- },- )- } LaunchedEffect(Unit) { val saved = CartStore.getAll(context) if (saved.isEmpty()) return@LaunchedEffect@@ -84,39 +68,8 @@ internal fun FoodDeliveryApp( if (addedMeanwhile) CartStore.save(context, cart) } - Navigation(- backStack = backStack,- cart = cart,- onPendingCartItem = { pendingCartItem = it },- )+ Navigation(backStack = backStack, cart = cart) } -@Composable-private fun PendingCartDialog(- cart: androidx.compose.runtime.snapshots.SnapshotStateList<CartItem>,- pending: CartItem,- onDismiss: () -> Unit,- onConfirm: () -> Unit,-) {- val currentName = cart.firstOrNull()?.merchantName?.ifBlank { "another restaurant" }- ?: "another restaurant"- val newName = pending.merchantName.ifBlank { "a different restaurant" }- AlertDialog(- onDismissRequest = onDismiss,- title = { Text("Start a new cart?") },- text = {- Text(- "Your cart has items from $currentName. Ordering is from one " +- "restaurant at a time, so adding from $newName will clear it."- )- },- confirmButton = {- Button(onClick = onConfirm) { Text("Start new cart") }- },- dismissButton = {- TextButton(onClick = onDismiss) { Text("Keep my cart") }- },- )-}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/NavigationEntries.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/NavigationEntries.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/NavigationEntries.ktindex ad4e5f11f7..eefd15f47d 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/NavigationEntries.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/NavigationEntries.kt@@ -23,7 +23,6 @@ internal fun EntryProviderScope<Route>.detailEntries( backStack: NavBackStack<Route>, cart: androidx.compose.runtime.snapshots.SnapshotStateList<CartItem>, context: android.content.Context,- onPendingCartItem: (CartItem) -> Unit, ) { entry<Route.Restaurant>(metadata = ListDetailPage() + MorphPage()) { route -> RestaurantScreen(@@ -34,9 +33,14 @@ internal fun EntryProviderScope<Route>.detailEntries( cart.add(item) CartStore.save(context, cart) } else {- onPendingCartItem(item)+ backStack.add(Route.PendingCartDialog(item)) } },+ onCustomizeItem = { item, merchantName ->+ backStack.add(+ Route.ModifierPickerDialog(item = item, merchantName = merchantName)+ )+ }, ) } // Checkout is a flow step, not a detail of the tab list.@@ -65,4 +69,5 @@ internal fun EntryProviderScope<Route>.detailEntries( onDone = { backStack.pop() }, ) }+ dialogEntries(backStack, cart, context) }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingContent.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingContent.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingContent.ktnew file mode 100644index 0000000000..80dab70d79--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingContent.kt@@ -0,0 +1,313 @@+package com.vayunmathur.fooddelivery.ui++import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+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.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+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.draw.clip+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalConfiguration+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 com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.GestureOptions+import com.vayunmathur.library.map.MapOptions+import com.vayunmathur.library.map.VectorMap+import com.vayunmathur.library.map.rememberCameraState+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.util.ConnectivityMonitor+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.IconHome+import com.vayunmathur.library.ui.IconDeliveryDining+import com.vayunmathur.library.ui.IconRestaurant+import com.vayunmathur.library.ui.IconPerson+import com.vayunmathur.library.ui.LinearProgressIndicator+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.sharedText+import com.vayunmathur.library.log.Log+import com.vayunmathur.fooddelivery.R+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.fooddelivery.network.BitesOrders+import com.vayunmathur.fooddelivery.data.Order+import com.vayunmathur.fooddelivery.data.OrderStage+import com.vayunmathur.fooddelivery.notifications.OrderTrackingService+import com.vayunmathur.fooddelivery.platform.AppInit+import kotlinx.coroutines.delay+import kotlin.time.Instant+import com.vayunmathur.library.ui.DateString+import com.vayunmathur.library.ui.rememberIs24Hour+import kotlin.math.max+import kotlin.math.min++/** Stateless tracking layout for previews; [OrderTrackingScreen] owns polling. */+@Composable+internal fun OrderTrackingContent(+ order: Order?,+ loading: Boolean,+ orderId: Int,+ onBack: () -> Unit = {},+ onCallCourier: (String) -> Unit = {},+ onOpenUrl: (String) -> Unit = {},+) {+AppScaffold(+ // Title slot rather than the string overload so the merchant name can carry the shared+ // key it travels in on from the Orders row.+ title = {+ Text(+ order?.merchant?.name ?: stringResource(R.string.tracking),+ modifier = Modifier.sharedText("food-order-merchant-$orderId"),+ )+ },+ onNavigateBack = onBack,+ isRefreshing = loading,+ ) { padding ->+ val o = order+ when {+ loading && o == null -> Box(Modifier.fillMaxSize().padding(padding))+ o == null -> EmptyState(+ title = stringResource(R.string.order_not_found),+ modifier = Modifier.fillMaxSize().padding(padding),+ )++ else -> Box(+ Modifier.fillMaxSize().padding(top = padding.calculateTopPadding())+ ) {+ // Map runs edge to edge; the details float on top of it.+ TrackingMap(o, Modifier.fillMaxSize())+ Surface(+ modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth(),+ shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp),+ tonalElevation = 3.dp,+ shadowElevation = 12.dp,+ ) {+ Column(+ Modifier+ .fillMaxWidth()+ .verticalScroll(rememberScrollState())+ .padding(16.dp)+ .padding(bottom = padding.calculateBottomPadding()),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ StageHeader(o)+ CourierCard(o, onCall = onCallCourier)+ o.deliveryTrackingUrl?.takeIf { it.isNotBlank() }?.let { url ->+ Button(+ onClick = { onOpenUrl(url) },+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(R.string.live_courier_map)) }+ }+ o.proofOfDeliveryImageUrl?.takeIf { it.isNotBlank() }?.let { url ->+ Text(stringResource(R.string.delivered_photo),+ style = MaterialTheme.typography.titleSmall,+ fontWeight = FontWeight.Bold)+ AsyncImage(+ model = url,+ contentDescription = stringResource(R.string.delivered_photo),+ contentScale = ContentScale.Crop,+ modifier = Modifier.fillMaxWidth()+ .aspectRatio(4f / 3f)+ .clip(RoundedCornerShape(12.dp)),+ )+ }+ }+ }+ }+ }+ }+}++/**+ * Restaurant, courier and destination on a raster map. Markers are absolutely positioned+ * from the camera projection, matching how findfamily overlays its map.+ */+@Composable+private fun TrackingMap(order: Order, modifier: Modifier = Modifier) {+ val restaurant = order.merchant?.let { m ->+ val la = m.latitude; val lo = m.longitude+ if (la != null && lo != null) GeoPoint(lo, la) else null+ }+ val destination = order.address?.let { a ->+ val la = a.latitude; val lo = a.longitude+ if (la != null && lo != null) GeoPoint(lo, la) else null+ }+ val driver = order.driverPosition?.let { d ->+ val la = d.latitude; val lo = d.longitude+ if (la != null && lo != null) GeoPoint(lo, la) else null+ }+ val points = listOfNotNull(restaurant, destination, driver)++ if (points.isEmpty()) {+ // Without coordinates a map would just be a blank tile grid.+ Surface(modifier = modifier, color = MaterialTheme.colorScheme.surfaceContainer) {+ Box(contentAlignment = Alignment.Center) {+ Text(stringResource(R.string.no_map_location),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ }+ return+ }++ // Frame everything we know about; zoom is a rough fit from the spread of the points.+ val centre = GeoPoint(+ longitude = points.sumOf { it.longitude } / points.size,+ latitude = points.sumOf { it.latitude } / points.size,+ )+ val spread = max(+ points.maxOf { it.longitude } - points.minOf { it.longitude },+ points.maxOf { it.latitude } - points.minOf { it.latitude },+ )+ val zoom = when {+ spread <= 0.0 -> 15.0+ else -> min(16.0, max(10.0, Math.log(360.0 / spread) / Math.log(2.0)))+ }+ val camera = rememberCameraState(CameraPosition(target = centre, zoom = zoom))+ LaunchedEffect(centre, zoom) {+ camera.position = CameraPosition(target = centre, zoom = zoom)+ }++ Box(modifier) {+ VectorMap(cameraState = camera, options = MapOptions(gestureOptions = GestureOptions.TiltLocked), online = ConnectivityMonitor.isOnline) {+ // Distinct glyph per pin: menu = restaurant, arrow = courier, home = you.+ restaurant?.let {+ MapMarker(it) { PinChrome(MaterialTheme.colorScheme.tertiary) { IconRestaurant() } }+ }+ destination?.let {+ MapMarker(it) { PinChrome(MaterialTheme.colorScheme.primary) { IconHome() } }+ }+ driver?.let {+ MapMarker(it) { PinChrome(MaterialTheme.colorScheme.secondary) { IconDeliveryDining() } }+ }+ }+ }+}++/**+ * The circular disc a pin's icon sits on. Stays app-side rather than moving into+ * `:library:map` with the positioning: it reads `colorScheme`, and that module has no+ * material3.+ */+@Composable+private fun PinChrome(+ color: androidx.compose.ui.graphics.Color,+ icon: @Composable () -> Unit,+) {+ Surface(color = color, shape = CircleShape, modifier = Modifier.size(32.dp)) {+ Box(contentAlignment = Alignment.Center) { icon() }+ }+}++@Composable+private fun StageHeader(order: Order) {+ val stage = order.stage+ val locale = LocalConfiguration.current.locales[0]+ val is24 = rememberIs24Hour()+ Column {+ Text(stage.label, style = MaterialTheme.typography.headlineSmall,+ fontWeight = FontWeight.Bold)++ val eta = order.etaMillis+ if (stage != OrderStage.DELIVERED && eta != null) {+ val minutes = ((eta - System.currentTimeMillis()) / 60_000L).toInt()+ Spacer(Modifier.height(4.dp))+ Text(+ if (minutes > 0) stringResource(R.string.eta_minutes, minutes,+ DateString.time(Instant.fromEpochMilliseconds(eta), is24Hour = is24, locale = locale))+ else stringResource(R.string.eta_any_moment),+ style = MaterialTheme.typography.bodyLarge,+ color = MaterialTheme.colorScheme.primary,+ )+ }++ order.driverDistanceMiles?.let { miles ->+ Spacer(Modifier.height(4.dp))+ Text(stringResource(R.string.driver_distance, "%.1f".format(miles)),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant)+ }++ Spacer(Modifier.height(8.dp))+ LinearProgressIndicator(+ progress = {+ when (stage) {+ OrderStage.PREPARING_SOON -> 0.1f+ OrderStage.PREPARING -> 0.3f+ OrderStage.READY -> 0.5f+ OrderStage.PICKED_UP -> if (order.isDelivery) 0.65f else 1f+ OrderStage.DRIVING -> 0.8f+ OrderStage.ARRIVING -> 0.95f+ OrderStage.DELIVERED -> 1f+ }+ },+ modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(4.dp)),+ )+ }+}++@Composable+private fun CourierCard(order: Order, onCall: (String) -> Unit) {+ val name = order.courierName?.takeIf { it.isNotBlank() } ?: return+ Card(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ val image = order.courierImageUrl?.takeIf { it.isNotBlank() }+ if (image != null) {+ AsyncImage(+ model = image,+ contentDescription = name,+ contentScale = ContentScale.Crop,+ modifier = Modifier.size(44.dp).clip(CircleShape),+ )+ } else {+ Surface(color = MaterialTheme.colorScheme.surfaceContainerHighest,+ shape = CircleShape, modifier = Modifier.size(44.dp)) {+ Box(contentAlignment = Alignment.Center) { IconPerson() }+ }+ }+ Spacer(Modifier.width(12.dp))+ Column(Modifier.weight(1f)) {+ Text(stringResource(R.string.your_courier),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant)+ Text(name, style = MaterialTheme.typography.titleSmall,+ fontWeight = FontWeight.Medium)+ }+ order.courierPhone?.takeIf { it.isNotBlank() }?.let { phone ->+ OutlinedButton(onClick = { onCall(phone) }) {+ Text(stringResource(UiR.string.call))+ }+ }+ }+ }+ }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.ktindex 8bc5483fbd..bdd5fb061c 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt@@ -102,237 +102,12 @@ fun OrderTrackingScreen(orderId: Int, onBack: () -> Unit) { } } - AppScaffold(- // Title slot rather than the string overload so the merchant name can carry the shared- // key it travels in on from the Orders row.- title = {- Text(- order?.merchant?.name ?: stringResource(R.string.tracking),- modifier = Modifier.sharedText("food-order-merchant-$orderId"),- )- },- onNavigateBack = onBack,- isRefreshing = loading,- ) { padding ->- val o = order- when {- loading && o == null -> Box(Modifier.fillMaxSize().padding(padding))- o == null -> EmptyState(- title = stringResource(R.string.order_not_found),- modifier = Modifier.fillMaxSize().padding(padding),- )-- else -> Box(- Modifier.fillMaxSize().padding(top = padding.calculateTopPadding())- ) {- // Map runs edge to edge; the details float on top of it.- TrackingMap(o, Modifier.fillMaxSize())- Surface(- modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth(),- shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp),- tonalElevation = 3.dp,- shadowElevation = 12.dp,- ) {- Column(- Modifier- .fillMaxWidth()- .verticalScroll(rememberScrollState())- .padding(16.dp)- .padding(bottom = padding.calculateBottomPadding()),- verticalArrangement = Arrangement.spacedBy(12.dp),- ) {- StageHeader(o)- CourierCard(o, onCall = { phone -> ExternalIntents.dial(context, phone) })- o.deliveryTrackingUrl?.takeIf { it.isNotBlank() }?.let { url ->- Button(- onClick = {- ExternalIntents.openUrl(context, url)- },- modifier = Modifier.fillMaxWidth(),- ) { Text(stringResource(R.string.live_courier_map)) }- }- o.proofOfDeliveryImageUrl?.takeIf { it.isNotBlank() }?.let { url ->- Text(stringResource(R.string.delivered_photo),- style = MaterialTheme.typography.titleSmall,- fontWeight = FontWeight.Bold)- AsyncImage(- model = url,- contentDescription = stringResource(R.string.delivered_photo),- contentScale = ContentScale.Crop,- modifier = Modifier.fillMaxWidth()- .aspectRatio(4f / 3f)- .clip(RoundedCornerShape(12.dp)),- )- }- }- }- }- }- }-}--/**- * Restaurant, courier and destination on a raster map. Markers are absolutely positioned- * from the camera projection, matching how findfamily overlays its map.- */-@Composable-private fun TrackingMap(order: Order, modifier: Modifier = Modifier) {- val restaurant = order.merchant?.let { m ->- val la = m.latitude; val lo = m.longitude- if (la != null && lo != null) GeoPoint(lo, la) else null- }- val destination = order.address?.let { a ->- val la = a.latitude; val lo = a.longitude- if (la != null && lo != null) GeoPoint(lo, la) else null- }- val driver = order.driverPosition?.let { d ->- val la = d.latitude; val lo = d.longitude- if (la != null && lo != null) GeoPoint(lo, la) else null- }- val points = listOfNotNull(restaurant, destination, driver)-- if (points.isEmpty()) {- // Without coordinates a map would just be a blank tile grid.- Surface(modifier = modifier, color = MaterialTheme.colorScheme.surfaceContainer) {- Box(contentAlignment = Alignment.Center) {- Text(stringResource(R.string.no_map_location),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant)- }- }- return- }-- // Frame everything we know about; zoom is a rough fit from the spread of the points.- val centre = GeoPoint(- longitude = points.sumOf { it.longitude } / points.size,- latitude = points.sumOf { it.latitude } / points.size,- )- val spread = max(- points.maxOf { it.longitude } - points.minOf { it.longitude },- points.maxOf { it.latitude } - points.minOf { it.latitude },+ OrderTrackingContent(+ order = order,+ loading = loading,+ orderId = orderId,+ onBack = onBack,+ onCallCourier = { phone -> ExternalIntents.dial(context, phone) },+ onOpenUrl = { url -> ExternalIntents.openUrl(context, url) }, )- val zoom = when {- spread <= 0.0 -> 15.0- else -> min(16.0, max(10.0, Math.log(360.0 / spread) / Math.log(2.0)))- }- val camera = rememberCameraState(CameraPosition(target = centre, zoom = zoom))- LaunchedEffect(centre, zoom) {- camera.position = CameraPosition(target = centre, zoom = zoom)- }-- Box(modifier) {- VectorMap(cameraState = camera, options = MapOptions(gestureOptions = GestureOptions.TiltLocked), online = ConnectivityMonitor.isOnline) {- // Distinct glyph per pin: menu = restaurant, arrow = courier, home = you.- restaurant?.let {- MapMarker(it) { PinChrome(MaterialTheme.colorScheme.tertiary) { IconRestaurant() } }- }- destination?.let {- MapMarker(it) { PinChrome(MaterialTheme.colorScheme.primary) { IconHome() } }- }- driver?.let {- MapMarker(it) { PinChrome(MaterialTheme.colorScheme.secondary) { IconDeliveryDining() } }- }- }- }-}--/**- * The circular disc a pin's icon sits on. Stays app-side rather than moving into- * `:library:map` with the positioning: it reads `colorScheme`, and that module has no- * material3.- */-@Composable-private fun PinChrome(- color: androidx.compose.ui.graphics.Color,- icon: @Composable () -> Unit,-) {- Surface(color = color, shape = CircleShape, modifier = Modifier.size(32.dp)) {- Box(contentAlignment = Alignment.Center) { icon() }- }-}--@Composable-private fun StageHeader(order: Order) {- val stage = order.stage- val locale = LocalConfiguration.current.locales[0]- val is24 = rememberIs24Hour()- Column {- Text(stage.label, style = MaterialTheme.typography.headlineSmall,- fontWeight = FontWeight.Bold)-- val eta = order.etaMillis- if (stage != OrderStage.DELIVERED && eta != null) {- val minutes = ((eta - System.currentTimeMillis()) / 60_000L).toInt()- Spacer(Modifier.height(4.dp))- Text(- if (minutes > 0) stringResource(R.string.eta_minutes, minutes,- DateString.time(Instant.fromEpochMilliseconds(eta), is24Hour = is24, locale = locale))- else stringResource(R.string.eta_any_moment),- style = MaterialTheme.typography.bodyLarge,- color = MaterialTheme.colorScheme.primary,- )- }-- order.driverDistanceMiles?.let { miles ->- Spacer(Modifier.height(4.dp))- Text(stringResource(R.string.driver_distance, "%.1f".format(miles)),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant)- }-- Spacer(Modifier.height(8.dp))- LinearProgressIndicator(- progress = {- when (stage) {- OrderStage.PREPARING_SOON -> 0.1f- OrderStage.PREPARING -> 0.3f- OrderStage.READY -> 0.5f- OrderStage.PICKED_UP -> if (order.isDelivery) 0.65f else 1f- OrderStage.DRIVING -> 0.8f- OrderStage.ARRIVING -> 0.95f- OrderStage.DELIVERED -> 1f- }- },- modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(4.dp)),- )- }-}--@Composable-private fun CourierCard(order: Order, onCall: (String) -> Unit) {- val name = order.courierName?.takeIf { it.isNotBlank() } ?: return- Card(Modifier.fillMaxWidth()) {- Column(Modifier.padding(12.dp)) {- Row(verticalAlignment = Alignment.CenterVertically) {- val image = order.courierImageUrl?.takeIf { it.isNotBlank() }- if (image != null) {- AsyncImage(- model = image,- contentDescription = name,- contentScale = ContentScale.Crop,- modifier = Modifier.size(44.dp).clip(CircleShape),- )- } else {- Surface(color = MaterialTheme.colorScheme.surfaceContainerHighest,- shape = CircleShape, modifier = Modifier.size(44.dp)) {- Box(contentAlignment = Alignment.Center) { IconPerson() }- }- }- Spacer(Modifier.width(12.dp))- Column(Modifier.weight(1f)) {- Text(stringResource(R.string.your_courier),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant)- Text(name, style = MaterialTheme.typography.titleSmall,- fontWeight = FontWeight.Medium)- }- order.courierPhone?.takeIf { it.isNotBlank() }?.let { phone ->- OutlinedButton(onClick = { onCall(phone) }) {- Text(stringResource(UiR.string.call))- }- }- }- }- } }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.ktindex 9fad947b9c..53ea6201de 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.kt@@ -66,40 +66,16 @@ import com.vayunmathur.library.ui.DateString import com.vayunmathur.library.ui.rememberIs24Hour @Composable-fun OrdersScreen(onTrackOrder: (Int) -> Unit = {}) {+fun OrdersScreen(+ onTrackOrder: (Int) -> Unit = {},+ onRateOrder: (Order) -> Unit = {},+) { var isLoggedIn by remember { mutableStateOf(false) } var orders by remember { mutableStateOf<List<Order>>(emptyList()) } var loading by remember { mutableStateOf(true) }- var ratingOrder by remember { mutableStateOf<Order?>(null) } val scope = rememberCoroutineScope() - ratingOrder?.let { target ->- FeedbackDialog(- onDismiss = { ratingOrder = null },- onSubmit = { rating, note, extraTipCents ->- scope.launch {- val submitted = target.uuid?.let {- BitesOrders.submitFeedback(- it,- FeedbackRequest(- orderId = target.id,- rating = rating,- feedback = note.ifBlank { null },- tips = extraTipCents,- ),- )- } == true- // Only dismiss on success: closing unconditionally made a failed- // submit (offline, server error, no uuid) look exactly like a- // delivered rating -- including an extra tip the user believes- // was sent. Staying open lets them retry or cancel explicitly.- if (submitted) ratingOrder = null- }- },- )- }- LaunchedEffect(Unit) { // The saved token is restored by the background warm-up, so wait for it before // deciding whether this is a signed-in session.@@ -111,7 +87,31 @@ fun OrdersScreen(onTrackOrder: (Int) -> Unit = {}) { loading = false } - AppScaffold(topBar = {}, isRefreshing = loading) { padding ->+ OrdersContent(+ orders = orders,+ loading = loading,+ isLoggedIn = isLoggedIn,+ onTrackOrder = onTrackOrder,+ onRateOrder = onRateOrder,+ onPickUp = { order ->+ scope.launch {+ if (BitesOrders.pickUpOrder(order.uuid ?: "")) orders = BitesOrders.getOrders()+ }+ },+ )+}++/** Stateless orders list for previews; [OrdersScreen] owns loading and state. */+@Composable+internal fun OrdersContent(+ orders: List<Order>,+ loading: Boolean,+ isLoggedIn: Boolean,+ onTrackOrder: (Int) -> Unit = {},+ onRateOrder: (Order) -> Unit = {},+ onPickUp: (Order) -> Unit = {},+) {+AppScaffold(topBar = {}, isRefreshing = loading) { padding -> if (loading) { Box(Modifier.fillMaxSize().padding(padding)) } else if (!isLoggedIn) {@@ -172,14 +172,10 @@ fun OrdersScreen(onTrackOrder: (Int) -> Unit = {}) { // Only finished orders can be rated; pickup orders that haven't been // collected get the pick-up action instead. onRate = if (order.isDone && order.uuid != null) {- { ratingOrder = order }+ { onRateOrder(order) } } else null, onPickUp = if (!order.isDone && !order.isDelivery && order.uuid != null) {- {- scope.launch {- if (BitesOrders.pickUpOrder(order.uuid)) orders = BitesOrders.getOrders()- }- }+ { onPickUp(order) } } else null, ) }@@ -283,61 +279,3 @@ private fun OrderCard( } } }--/** Rate a completed order: 1-5 stars, an optional note, and an optional extra tip. */-@Composable-private fun FeedbackDialog(- onDismiss: () -> Unit,- onSubmit: (rating: Int, note: String, extraTipCents: Int) -> Unit,-) {- var rating by remember { mutableIntStateOf(5) }- var note by remember { mutableStateOf("") }- var extraTip by remember { mutableIntStateOf(0) }-- AlertDialog(- onDismissRequest = onDismiss,- title = { Text(stringResource(R.string.rate_your_order)) },- text = {- Column {- Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {- for (star in 1..5) {- IconButton(onClick = { rating = star }) {- IconStar(- modifier = Modifier.size(28.dp),- tint = if (star <= rating) MaterialTheme.colorScheme.primary- else MaterialTheme.colorScheme.onSurfaceVariant,- )- }- }- }- Spacer(Modifier.height(8.dp))- OutlinedTextField(- value = note,- onValueChange = { note = it },- label = { Text(stringResource(R.string.feedback_optional)) },- modifier = Modifier.fillMaxWidth(),- )- Spacer(Modifier.height(12.dp))- Text(stringResource(R.string.add_extra_tip), style = MaterialTheme.typography.bodyMedium)- Spacer(Modifier.height(4.dp))- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- listOf(0, 100, 200, 500).forEach { cents ->- FilterChip(- selected = extraTip == cents,- onClick = { extraTip = cents },- label = { Text(if (cents == 0) "None" else "$%.2f".format(cents / 100.0)) },- )- }- }- }- },- confirmButton = {- Button(onClick = { onSubmit(rating, note, extraTip) }) {- Text(stringResource(R.string.submit))- }- },- dismissButton = {- TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) }- },- )-}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantContent.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantContent.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantContent.ktindex 0fadd89830..17bcac7cf6 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantContent.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantContent.kt@@ -42,16 +42,12 @@ import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.Checkbox import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconAdd-import com.vayunmathur.library.ui.IconBack-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconClose-import com.vayunmathur.library.ui.IconSearch import com.vayunmathur.library.ui.IconStar import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.RadioButton import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.ScaffoldSearch import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.util.sharedContainer@@ -84,8 +80,8 @@ fun RestaurantContent( onLeaveLoyalty: () -> Unit = {}, onBack: () -> Unit = {}, onAddItem: (MenuItem, List<SelectedModifier>) -> Unit = { _, _ -> },+ onCustomizeItem: (MenuItem) -> Unit = {}, ) {- var customizeItem by remember { mutableStateOf<MenuItem?>(null) } var query by remember { mutableStateOf("") } // The field itself stays instant; the menu is only re-filtered once typing settles, so a // keystroke no longer re-walks and re-sorts every category.@@ -94,18 +90,16 @@ fun RestaurantContent( snapshotFlow { query }.debounce(FILTER_DEBOUNCE_MS).collect { appliedQuery = it } } - customizeItem?.let { item ->- ModifierDialog(- item = item,- onDismiss = { customizeItem = null },- onConfirm = { selectedModifiers ->- onAddItem(item, selectedModifiers)- customizeItem = null- }- )- }-- AppScaffold(topBar = {}, isRefreshing = loading) { padding ->+ AppScaffold(+ title = merchant?.name ?: "",+ onNavigateBack = onBack,+ isRefreshing = loading,+ search = if (loading || merchant == null) null else ScaffoldSearch(+ query = query,+ onQueryChange = { query = it },+ placeholder = stringResource(R.string.search_menu),+ ),+ ) { padding -> if (loading) { Box(Modifier.fillMaxSize().padding(padding)) } else if (merchant == null) {@@ -150,17 +144,6 @@ fun RestaurantContent( .aspectRatio(16f / 9f) .sharedContainer("food-merchant-${m.id}") )- IconButton(onClick = onBack,- modifier = Modifier.padding(4.dp)) {- IconBack()- }- }- }- } else {- item {- IconButton(onClick = onBack,- modifier = Modifier.padding(4.dp)) {- IconBack() } } }@@ -208,22 +191,6 @@ fun RestaurantContent( ) } - item {- OutlinedTextField(- value = query,- onValueChange = { query = it },- label = { Text(stringResource(R.string.search_menu)) },- singleLine = true,- leadingIcon = { IconSearch() },- trailingIcon = {- if (query.isNotEmpty()) {- IconButton(onClick = { query = "" }) { IconClose() }- }- },- modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),- )- }- if (sections.isEmpty()) { item { Text(@@ -250,7 +217,7 @@ fun RestaurantContent( items(categoryItems, key = { "${category.id}-${it.id}" }) { menuItem -> MenuItemRow(menuItem) { if (menuItem.modifierGroups.isNotEmpty()) {- customizeItem = menuItem+ onCustomizeItem(menuItem) } else { onAddItem(menuItem, emptyList()) }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.ktindex 5be14af6d4..dd7c1e405e 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.kt@@ -78,6 +78,7 @@ fun RestaurantScreen( merchantId: Int, onBack: () -> Unit, onAddToCart: (CartItem) -> Unit,+ onCustomizeItem: (MenuItem, String) -> Unit = { _, _ -> }, ) { var merchant by remember { mutableStateOf<MerchantDetail?>(null) } var loading by remember { mutableStateOf(true) }@@ -110,6 +111,7 @@ fun RestaurantScreen( } }, onBack = onBack,+ onCustomizeItem = { item -> onCustomizeItem(item, merchant?.name ?: "") }, onAddItem = { item, selectedModifiers -> onAddToCart(CartItem( menuItem = item,@@ -125,7 +127,7 @@ fun RestaurantScreen( /** * Pick modifiers for [item]. Pass [initialSelection] to reopen it over an existing choice * (editing a cart line) instead of starting empty.- * Lives in ModifierDialog.kt.+ * Lives in ui/dialogs/ModifierDialog.kt. */ // MenuItemRow + MerchantRewardsCard live in RestaurantSections.kt
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/DeleteAccountDialog.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/DeleteAccountDialog.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/DeleteAccountDialog.ktnew file mode 100644index 0000000000..4e6def904a--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/DeleteAccountDialog.kt@@ -0,0 +1,29 @@+package com.vayunmathur.fooddelivery.ui.dialogs++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.fooddelivery.R+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.R as UiR++/** Stateless account-deletion confirmation; the host performs the delete. */+@Composable+fun DeleteAccountDialog(+ onDismiss: () -> Unit,+ onConfirm: () -> Unit,+) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.delete_account)) },+ text = { Text(stringResource(R.string.delete_account_warning)) },+ confirmButton = {+ Button(onClick = onConfirm) { Text(stringResource(R.string.delete_account)) }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) }+ },+ )+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/EditProfileDialog.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/EditProfileDialog.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/EditProfileDialog.ktnew file mode 100644index 0000000000..90696609fd--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/EditProfileDialog.kt@@ -0,0 +1,85 @@+package com.vayunmathur.fooddelivery.ui.dialogs++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.text.KeyboardOptions+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.res.stringResource+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import com.vayunmathur.fooddelivery.R+import com.vayunmathur.fooddelivery.data.Customer+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.R as UiR++/** Edit the name/email on the account; posts the whole customer to POST /customers/me. */+@Composable+fun EditProfileDialog(+ customer: Customer,+ onDismiss: () -> Unit,+ onSave: (Customer) -> Unit,+) {+ var firstName by remember { mutableStateOf(customer.firstName) }+ var lastName by remember { mutableStateOf(customer.lastName) }+ var email by remember { mutableStateOf(customer.email) }++ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.edit_profile)) },+ text = {+ Column {+ OutlinedTextField(+ value = firstName,+ onValueChange = { firstName = it },+ label = { Text(stringResource(R.string.first_name)) },+ singleLine = true,+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.PersonName),+ modifier = Modifier.fillMaxWidth(),+ )+ Spacer(Modifier.height(8.dp))+ OutlinedTextField(+ value = lastName,+ onValueChange = { lastName = it },+ label = { Text(stringResource(R.string.last_name)) },+ singleLine = true,+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.PersonName),+ modifier = Modifier.fillMaxWidth(),+ )+ Spacer(Modifier.height(8.dp))+ OutlinedTextField(+ value = email,+ onValueChange = { email = it },+ label = { Text(stringResource(UiR.string.email)) },+ singleLine = true,+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),+ modifier = Modifier.fillMaxWidth(),+ )+ }+ },+ confirmButton = {+ Button(onClick = {+ onSave(+ customer.copy(+ firstName = firstName.trim(),+ lastName = lastName.trim(),+ email = email.trim(),+ )+ )+ }) { Text(stringResource(R.string.save_changes)) }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) }+ },+ )+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/ModifierDialog.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/ModifierDialog.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/ModifierDialog.ktsimilarity index 99%rename from fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/ModifierDialog.ktrename to fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/ModifierDialog.ktindex 2675fc2500..768f4a5f37 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/ModifierDialog.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/ModifierDialog.kt@@ -1,4 +1,4 @@-package com.vayunmathur.fooddelivery.ui+package com.vayunmathur.fooddelivery.ui.dialogs import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/OrderFeedbackDialog.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/OrderFeedbackDialog.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/OrderFeedbackDialog.ktnew file mode 100644index 0000000000..8ed410542c--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/OrderFeedbackDialog.kt@@ -0,0 +1,87 @@+package com.vayunmathur.fooddelivery.ui.dialogs++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.fooddelivery.R+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconStar+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.R as UiR++/** Rate a completed order: 1-5 stars, an optional note, and an optional extra tip. */+@Composable+fun OrderFeedbackDialog(+ onDismiss: () -> Unit,+ onSubmit: (rating: Int, note: String, extraTipCents: Int) -> Unit,+) {+ var rating by remember { mutableIntStateOf(5) }+ var note by remember { mutableStateOf("") }+ var extraTip by remember { mutableIntStateOf(0) }++ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.rate_your_order)) },+ text = {+ Column {+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ for (star in 1..5) {+ IconButton(onClick = { rating = star }) {+ IconStar(+ modifier = Modifier.size(28.dp),+ tint = if (star <= rating) MaterialTheme.colorScheme.primary+ else MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }+ Spacer(Modifier.height(8.dp))+ OutlinedTextField(+ value = note,+ onValueChange = { note = it },+ label = { Text(stringResource(R.string.feedback_optional)) },+ modifier = Modifier.fillMaxWidth(),+ )+ Spacer(Modifier.height(12.dp))+ Text(stringResource(R.string.add_extra_tip), style = MaterialTheme.typography.bodyMedium)+ Spacer(Modifier.height(4.dp))+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ listOf(0, 100, 200, 500).forEach { cents ->+ FilterChip(+ selected = extraTip == cents,+ onClick = { extraTip = cents },+ label = { Text(if (cents == 0) "None" else "$%.2f".format(cents / 100.0)) },+ )+ }+ }+ }+ },+ confirmButton = {+ Button(onClick = { onSubmit(rating, note, extraTip) }) {+ Text(stringResource(R.string.submit))+ }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) }+ },+ )+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/PendingCartDialog.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/PendingCartDialog.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/PendingCartDialog.ktnew file mode 100644index 0000000000..8f43e6c1d7--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/dialogs/PendingCartDialog.kt@@ -0,0 +1,36 @@+package com.vayunmathur.fooddelivery.ui.dialogs++import androidx.compose.runtime.Composable+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * Stateless "start a new cart?" confirmation: ordering is from one restaurant+ * at a time, so confirming clears the cart from [currentName] for [newName].+ */+@Composable+fun PendingCartDialog(+ currentName: String,+ newName: String,+ onDismiss: () -> Unit,+ onConfirm: () -> Unit,+) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text("Start a new cart?") },+ text = {+ Text(+ "Your cart has items from $currentName. Ordering is from one " ++ "restaurant at a time, so adding from $newName will clear it."+ )+ },+ confirmButton = {+ Button(onClick = onConfirm) { Text("Start new cart") }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text("Keep my cart") }+ },+ )+}
fooddelivery/src/screenshotTest/kotlin/com/vayunmathur/fooddelivery/ui/MetadataPreviews.kt
diff --git a/fooddelivery/src/screenshotTest/kotlin/com/vayunmathur/fooddelivery/ui/MetadataPreviews.kt b/fooddelivery/src/screenshotTest/kotlin/com/vayunmathur/fooddelivery/ui/MetadataPreviews.ktindex 555add5341..f580f08ffc 100644--- a/fooddelivery/src/screenshotTest/kotlin/com/vayunmathur/fooddelivery/ui/MetadataPreviews.kt+++ b/fooddelivery/src/screenshotTest/kotlin/com/vayunmathur/fooddelivery/ui/MetadataPreviews.kt@@ -8,6 +8,16 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.android.tools.screenshot.PreviewTest import com.vayunmathur.fooddelivery.data.CartItem+import com.vayunmathur.fooddelivery.data.Customer+import com.vayunmathur.fooddelivery.data.CustomerSavings+import com.vayunmathur.fooddelivery.data.Deal+import com.vayunmathur.fooddelivery.data.Order+import com.vayunmathur.fooddelivery.data.OrderMerchant+import com.vayunmathur.fooddelivery.ui.dialogs.DeleteAccountDialog+import com.vayunmathur.fooddelivery.ui.dialogs.EditProfileDialog+import com.vayunmathur.fooddelivery.ui.dialogs.ModifierDialog+import com.vayunmathur.fooddelivery.ui.dialogs.OrderFeedbackDialog+import com.vayunmathur.fooddelivery.ui.dialogs.PendingCartDialog import com.vayunmathur.fooddelivery.data.MenuCategory import com.vayunmathur.fooddelivery.data.MenuItem import com.vayunmathur.fooddelivery.data.Merchant@@ -270,4 +280,231 @@ class MetadataPreviews { } } }++ private val deals = listOf(+ Deal(+ id = 201,+ title = "20% off tacos",+ description = "Save on every taco order this week",+ merchantId = 101,+ merchantName = "Taqueria del Sol",+ discountPercent = 20.0,+ minOrderCount = 3,+ ),+ Deal(+ id = 202,+ title = "$5 off your first poke bowl",+ description = "New-customer offer at Marina Poke",+ merchantId = 103,+ merchantName = "Marina Poke",+ discountAmount = 500,+ ),+ )++ private val orders = listOf(+ Order(+ id = 9001,+ uuid = "order-9001",+ createdAt = "2026-11-30T18:24:00Z",+ channel = "ORDER_CHANNEL_STOREFRONT_DELIVERY",+ merchant = OrderMerchant(id = 101, name = "Taqueria del Sol"),+ foodTotal = 1_415,+ deliveryFee = 299,+ taxes = 128,+ orderTotal = 1_842,+ deliveredAt = "2026-11-30T19:02:00Z",+ ),+ Order(+ id = 9002,+ uuid = "order-9002",+ createdAt = "2026-11-28T12:10:00Z",+ merchant = OrderMerchant(id = 102, name = "Golden Wok"),+ foodTotal = 1_850,+ orderTotal = 2_102,+ deliveredAt = "2026-11-28T12:48:00Z",+ ),+ )++ private val trackingOrder = Order(+ id = 9003,+ uuid = "order-9003",+ createdAt = "2026-12-01T17:40:00Z",+ channel = "ORDER_CHANNEL_STOREFRONT_DELIVERY",+ merchant = OrderMerchant(id = 101, name = "Taqueria del Sol"),+ foodTotal = 1_415,+ orderTotal = 1_842,+ courierName = "Alex",+ )++ private val customer = Customer(+ id = 42,+ email = "[email protected]",+ firstName = "Sam",+ lastName = "Rivera",+ rewardPoints = 320,+ )++ @PreviewTest+ @Preview(name = "5-home", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview5Home() {+ DynamicTheme(darkTheme = true) {+ HomeContent(merchants = merchants)+ }+ }++ @PreviewTest+ @Preview(name = "6-deals", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview6Deals() {+ DynamicTheme(darkTheme = true) {+ DealsContent(deals = deals, progress = emptyMap(), loading = false)+ }+ }++ @PreviewTest+ @Preview(name = "7-orders", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview7Orders() {+ DynamicTheme(darkTheme = true) {+ OrdersContent(orders = orders, loading = false, isLoggedIn = true)+ }+ }++ @PreviewTest+ @Preview(name = "8-account", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview8Account() {+ DynamicTheme(darkTheme = true) {+ AccountContent(+ customer = customer,+ savings = CustomerSavings(customerSavings = 1_240, orderCount = 14),+ referrals = emptyList(),+ platformSavings = null,+ notice = null,+ loggedIn = true,+ authResolved = true,+ phone = "",+ code = "",+ codeSent = false,+ authLoading = false,+ addresses = emptyList(),+ addressesLoaded = true,+ addressForm = AddressFormState(),+ )+ }+ }++ @PreviewTest+ @Preview(name = "9-restaurant", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview9Restaurant() {+ DynamicTheme(darkTheme = true) {+ RestaurantContent(merchant = taqueria)+ }+ }++ @PreviewTest+ @Preview(name = "10-checkout", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview10Checkout() {+ DynamicTheme(darkTheme = true) {+ CheckoutOrderContent(+ items = cart,+ isPickup = false,+ onPickupChange = {},+ addresses = emptyList(),+ addressesLoaded = true,+ selectedAddress = null,+ onAddressSelect = {},+ deliveryInstructions = "",+ onInstructionsChange = {},+ tipCents = 300,+ onTipChange = {},+ deals = emptyList(),+ selectedDealId = null,+ onDealSelect = {},+ promoCode = "",+ onPromoChange = {},+ subtotal = 26.35,+ fetchingPrices = false,+ taxesDollars = null,+ deliveryFeeDollars = null,+ feesDollars = null,+ tipsDollars = null,+ rewardsApplied = 0.0,+ payTotal = null,+ displayTotal = null,+ error = null,+ )+ }+ }++ @PreviewTest+ @Preview(name = "11-order-tracking", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview11OrderTracking() {+ DynamicTheme(darkTheme = true) {+ OrderTrackingContent(order = trackingOrder, loading = false, orderId = 9003)+ }+ }++ @PreviewTest+ @Preview(name = "12-email-verification", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview12EmailVerification() {+ DynamicTheme(darkTheme = true) {+ EmailVerificationContent(state = VerifyState.SUCCESS, onRetry = {}, onDone = {})+ }+ }++ @PreviewTest+ @Preview(name = "13-edit-profile-dialog", device = PHONE, group = "phone")+ @Composable+ fun Preview13EditProfileDialog() {+ DynamicTheme(darkTheme = true) {+ EditProfileDialog(customer = customer, onDismiss = {}, onSave = {})+ }+ }++ @PreviewTest+ @Preview(name = "14-delete-account-dialog", device = PHONE, group = "phone")+ @Composable+ fun Preview14DeleteAccountDialog() {+ DynamicTheme(darkTheme = true) {+ DeleteAccountDialog(onDismiss = {}, onConfirm = {})+ }+ }++ @PreviewTest+ @Preview(name = "15-modifier-picker-dialog", device = PHONE, group = "phone")+ @Composable+ fun Preview15ModifierPickerDialog() {+ DynamicTheme(darkTheme = true) {+ ModifierDialog(item = carnitasTaco, onDismiss = {}, onConfirm = {})+ }+ }++ @PreviewTest+ @Preview(name = "16-pending-cart-dialog", device = PHONE, group = "phone")+ @Composable+ fun Preview16PendingCartDialog() {+ DynamicTheme(darkTheme = true) {+ PendingCartDialog(+ currentName = "Taqueria del Sol",+ newName = "Golden Wok",+ onDismiss = {},+ onConfirm = {},+ )+ }+ }++ @PreviewTest+ @Preview(name = "17-order-feedback-dialog", device = PHONE, group = "phone")+ @Composable+ fun Preview17OrderFeedbackDialog() {+ DynamicTheme(darkTheme = true) {+ OrderFeedbackDialog(onDismiss = {}, onSubmit = { _, _, _ -> })+ }+ } }
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/network/FoodWave3ApiTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/network/FoodWave3ApiTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/network/FoodWave3ApiTest.ktindex 1d9e50e2e0..55fb96c496 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/network/FoodWave3ApiTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/network/FoodWave3ApiTest.kt@@ -1,4 +1,5 @@ package com.vayunmathur.fooddelivery.network+// FIXTURE RELATIVE-TIME EXCEPTION: token-expiry fixtures must be seeded relative to the real clock the refresh logic reads // FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.ktindex 554e603d4b..41daa7ad4b 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.kt@@ -1,5 +1,11 @@ package com.vayunmathur.fooddelivery.ui +import com.vayunmathur.library.util.NavResultRegistry+import com.vayunmathur.library.util.LocalNavResultRegistry+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue+import com.vayunmathur.fooddelivery.ui.dialogs.OrderFeedbackDialog import android.app.Application import android.content.Context import androidx.compose.ui.test.assertIsDisplayed@@ -130,7 +136,7 @@ class BinderScreensTest { } @Test fun accountBinderSignInFlow() {- rule.setContent { AccountScreen() }+ rule.setContent { CompositionLocalProvider(LocalNavResultRegistry provides NavResultRegistry()) { AccountScreen() } } awaitText("Sign in to Food Delivery", substring = true) rule.onNodeWithText("Phone number").performTextInput("5551234567") rule.onNodeWithText("Send Code").performClick()@@ -163,7 +169,17 @@ class BinderScreensTest { @Test fun ordersFeedbackDialogSubmits() { BitesAuth.setToken(AuthToken("acc", "ref", "Bearer", 3600))- rule.setContent { OrdersScreen {} }+ var submitted = false+ rule.setContent {+ var rated by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<com.vayunmathur.fooddelivery.data.Order?>(null) }+ OrdersScreen(onRateOrder = { rated = it })+ rated?.let {+ OrderFeedbackDialog(+ onDismiss = { rated = null },+ onSubmit = { _, _, _ -> submitted = true; rated = null },+ )+ }+ } awaitText("Rate order") rule.onNodeWithText("Rate order").performClick() awaitText("Rate your order", substring = true)@@ -171,10 +187,11 @@ class BinderScreensTest { rule.onNodeWithText("Submit", substring = true) .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick) rule.waitForIdle()+ assertTrue(submitted, "feedback submit never fired") } @Test fun accountSignOutReturnsToAuthCard() {- rule.setContent { AccountScreen() }+ rule.setContent { CompositionLocalProvider(LocalNavResultRegistry provides NavResultRegistry()) { AccountScreen() } } awaitText("Sign in to Food Delivery", substring = true) rule.onNodeWithText("Phone number").performTextInput("5551234567") rule.onNodeWithText("Send Code").performClick()
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow2Test.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow2Test.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow2Test.ktindex ec7b9669eb..0cae734dab 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow2Test.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow2Test.kt@@ -1,5 +1,16 @@ package com.vayunmathur.fooddelivery.ui +import androidx.compose.ui.test.performScrollToIndex+import kotlinx.coroutines.launch+import androidx.compose.runtime.setValue+import androidx.compose.runtime.getValue+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.performScrollToNode+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.hasSetTextAction+import com.vayunmathur.library.util.NavResultRegistry+import com.vayunmathur.library.util.LocalNavResultRegistry+import androidx.compose.runtime.CompositionLocalProvider import android.app.Application import android.content.Context import androidx.compose.ui.test.assertIsDisplayed@@ -81,7 +92,7 @@ class FoodFlow2Test { } private fun signInThroughAccount() {- rule.setContent { AccountScreen() }+ rule.setContent { CompositionLocalProvider(LocalNavResultRegistry provides NavResultRegistry()) { AccountScreen() } } awaitNode("Sign in to Food Delivery") rule.onNodeWithText("Phone number").performTextInput("5551234567") rule.onNodeWithText("Send Code").performClick()@@ -95,7 +106,7 @@ class FoodFlow2Test { installFake("""{"data":[{"id":9,"uuid":"u9","foodTotal":1000,"orderTotal":1500,"channel":"ORDER_CHANNEL_STOREFRONT_DELIVERY","merchant":{"id":1,"name":"Burger Barn"}},{"id":10,"uuid":"u10","foodTotal":500,"orderTotal":700,"channel":"ORDER_CHANNEL_STOREFRONT_PICKUP","merchant":{"id":1,"name":"Burger Barn"}}]}""") BitesAuth.setToken(AuthToken("acc", "ref", "Bearer", 3600)) var tracked = -1- rule.setContent { OrdersScreen { tracked = it } }+ rule.setContent { OrdersScreen(onTrackOrder = { tracked = it }) } awaitNode("Track order") rule.onNodeWithText("Track order").performClick(); assertEquals(9, tracked) awaitNode("Mark picked up")@@ -106,7 +117,35 @@ class FoodFlow2Test { @Test fun accountDeleteAccountFlow() { installFake("""{"data":[]}""")- signInThroughAccount()+ val registry = NavResultRegistry()+ rule.setContent {+ CompositionLocalProvider(LocalNavResultRegistry provides registry) {+ var showDelete by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(false) }+ val scope = androidx.compose.runtime.rememberCoroutineScope()+ AccountScreen(onDeleteAccountRequest = { showDelete = true })+ if (showDelete) {+ com.vayunmathur.fooddelivery.ui.dialogs.DeleteAccountDialog(+ onDismiss = { showDelete = false },+ onConfirm = {+ scope.launch {+ if (com.vayunmathur.fooddelivery.network.BitesCustomers.deleteCustomer()) {+ com.vayunmathur.fooddelivery.network.BitesAuth.clearToken()+ registry.dispatchResult(RESULT_ACCOUNT_DELETED, true)+ showDelete = false+ }+ }+ },+ )+ }+ }+ }+ awaitNode("Sign in to Food Delivery")+ rule.onNodeWithText("Phone number").performTextInput("5551234567")+ rule.onNodeWithText("Send Code").performClick()+ awaitNode("Verify")+ rule.onNodeWithText("Verification code").performTextInput("123456")+ rule.onNodeWithText("Verify").performClick()+ awaitNode("Ann Lee") awaitNode("Delete account") rule.onNodeWithText("Delete account") .performSemanticsAction(SemanticsActions.OnClick)@@ -122,12 +161,23 @@ class FoodFlow2Test { @Test fun restaurantLoyaltyJoinAndSearch() { installFake("""{"data":[]}""") rule.setContent { RestaurantScreen(1, {}, {}) }+ awaitNode("Burger Barn")+ // The scaffold top bar leaves the first menu row below the test+ // surface's fold; scroll it into composition before awaiting it.+ try {+ rule.onNode(hasScrollAction()).performScrollToIndex(3)+ } catch (_: AssertionError) { rule.waitForIdle() } awaitNode("Burger") // Search filters the menu after the debounce (compose clock drives it).- rule.onNodeWithText("Search", substring = true).performTextInput("Fries")+ // The first editable field is the scaffold search (the loyalty invite field is the other).+ rule.onAllNodes(hasSetTextAction())[1].performTextInput("Fries") rule.mainClock.autoAdvance = false; rule.mainClock.advanceTimeBy(2_000L); rule.mainClock.autoAdvance = true rule.waitForIdle()- awaitNode("Fries")+ // The filtered row and the search field's own text both read "Fries".+ assertTrue(+ rule.onAllNodesWithText("Fries", substring = false).fetchSemanticsNodes().size >= 2,+ "filtered Fries row missing",+ ) } @Test fun checkoutPickupToggleReprices() { runBlocking {
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow4Test.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow4Test.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow4Test.ktindex 45ba253965..0e6139416d 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow4Test.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow4Test.kt@@ -75,11 +75,11 @@ class FoodFlow4Test { } @Test fun cartRemoveAndEditModifiers() {- var removed = -1; var edited: List<SelectedModifier>? = null+ var removed = -1; var editedItem: CartItem? = null val items = listOf( CartItem(menuItem = groupedItem(), quantity = 1, selectedModifiers = listOf(SelectedModifier(modifierGroupId = 1, modifierId = 100, name = "Cheese", price = 100))), )- rule.setContent { CartScreen(items, { removed = it }, {}, { _, mods -> edited = mods }) }+ rule.setContent { CartScreen(items, { removed = it }, {}, { _, item -> editedItem = item }) } rule.onNodeWithText("1x Burger").assertExists() // The edit (pencil) action opens the modifier dialog for the line. // Icon buttons carry no text; invoke the line's clickable actions until the dialog opens.@@ -87,7 +87,7 @@ class FoodFlow4Test { assertTrue(clickables >= 1) rule.waitForIdle() assertEquals(-1, removed) // nothing removed yet; dialog flow is covered by ModifierDialog tests- assertEquals(null, edited)+ assertEquals(null, editedItem) } @Test fun checkoutTotalsVariants() {
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow5Test.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow5Test.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow5Test.ktindex 9b2185a04d..76cafe34ce 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow5Test.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow5Test.kt@@ -1,5 +1,8 @@ package com.vayunmathur.fooddelivery.ui +import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue+import com.vayunmathur.fooddelivery.ui.dialogs.ModifierDialog import android.app.Application import android.content.Context import android.net.Uri@@ -116,7 +119,19 @@ class FoodFlow5Test { modifiers = listOf(Modifier(id = 100, name = "Cheese", price = 100), Modifier(id = 101, name = "Bacon", price = 200))), )) val items = listOf(CartItem(menuItem = grouped, quantity = 1, selectedModifiers = listOf(SelectedModifier(1, 100, "Cheese", 100))))- rule.setContent { CartScreen(items, {}, {}, { _, mods -> edited = mods }) }+ rule.setContent {+ var request by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<CartItem?>(null) }+ CartScreen(items, {}, {}, { _, item -> request = item })+ request?.let { item ->+ ModifierDialog(+ item = item.menuItem,+ initialSelection = item.selectedModifiers,+ confirmLabel = "Save changes",+ onDismiss = { request = null },+ onConfirm = { mods -> edited = mods; request = null },+ )+ }+ } rule.onNodeWithText("1x Burger").assertExists() // Open the editor via the line's edit action, then save from the dialog. val clickables = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow6Test.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow6Test.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow6Test.ktindex 4b8cf235d0..0b45b23b51 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow6Test.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow6Test.kt@@ -1,7 +1,9 @@ package com.vayunmathur.fooddelivery.ui+// FIXTURE RELATIVE-TIME EXCEPTION: the tracking ETA fixture must be in the future relative to the screen's real clock or the live-ETA stage never renders -// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.-+import com.vayunmathur.library.util.NavResultRegistry+import com.vayunmathur.library.util.LocalNavResultRegistry+import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue @@ -129,7 +131,7 @@ class FoodFlow6Test { installFake("""{"data":[]}""") BitesAuth.clearToken() // start signed out; the flow below signs in // Sign in through the account binder (phone -> code -> profile).- rule.setContent { AccountScreen() }+ rule.setContent { CompositionLocalProvider(LocalNavResultRegistry provides NavResultRegistry()) { AccountScreen() } } awaitNode("Sign in to Food Delivery") rule.onNodeWithText("Phone number").performTextInput("5551234567") rule.onNodeWithText("Send Code").performSemanticsAction(SemanticsActions.OnClick)
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow7Test.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow7Test.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow7Test.ktindex 65dd5be9f5..800a43106a 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow7Test.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow7Test.kt@@ -65,7 +65,7 @@ class FoodFlow7Test { } AppInit.start(ctx) rule.setContent { RestaurantScreen(1, {}, {}) }- awaitNode("Burger")+ awaitNode("Invite code", substring = true) rule.onNodeWithText("Invite code", substring = true).performTextInput("WELCOME") rule.onNodeWithText("Join", substring = true) .performSemanticsAction(SemanticsActions.OnClick)
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodModelsTotalsTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodModelsTotalsTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodModelsTotalsTest.ktindex c9bc543ad0..a5692eb03e 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodModelsTotalsTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodModelsTotalsTest.kt@@ -1,4 +1,5 @@ package com.vayunmathur.fooddelivery.ui+// FIXTURE RELATIVE-TIME EXCEPTION: stage derivation compares due/ready timestamps against the real clock, so fixtures must be seeded in its future and past // FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodTrackingStagesTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodTrackingStagesTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodTrackingStagesTest.ktindex d4a2cb4565..a24041fccb 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodTrackingStagesTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodTrackingStagesTest.kt@@ -118,11 +118,13 @@ class FoodTrackingStagesTest { rule.setContent { RestaurantScreen(1, {}, { added++ }) }- awaitNode("Burger")- // Scroll the menu list so lower sections compose.+ awaitNode("Burger Barn")+ // Scroll the menu list so lower sections compose (the scaffold top+ // bar leaves the first menu row below the test surface's fold). try { rule.onNode(hasScrollAction()).performScrollToIndex(3) } catch (_: AssertionError) { rule.waitForIdle() }+ awaitNode("Burger") rule.waitForIdle() assertEquals(0, added) }
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiComposeTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiComposeTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiComposeTest.ktindex 8bab83602b..274b1b722b 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiComposeTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiComposeTest.kt@@ -1,5 +1,6 @@ package com.vayunmathur.fooddelivery.ui +import com.vayunmathur.fooddelivery.ui.dialogs.ModifierDialog import androidx.compose.foundation.layout.Column import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiExtraTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiExtraTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiExtraTest.ktindex 1b7896962e..ce62c1fb26 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiExtraTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodUiExtraTest.kt@@ -1,5 +1,6 @@ package com.vayunmathur.fooddelivery.ui +import com.vayunmathur.fooddelivery.ui.dialogs.EditProfileDialog import android.app.Application import android.content.Context import androidx.compose.foundation.layout.Column
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3MainComposeTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3MainComposeTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3MainComposeTest.ktindex 7b14f7e3b2..36fe1eb8f9 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3MainComposeTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3MainComposeTest.kt@@ -1,5 +1,6 @@ package com.vayunmathur.fooddelivery.ui +import androidx.compose.ui.test.onNodeWithContentDescription import android.app.Application import android.content.Context import androidx.compose.ui.test.hasAnySibling@@ -138,7 +139,7 @@ class FoodWave3MainComposeTest { rule.onNodeWithText("Burger Barn").performClick() awaitNode("Burger Barn") // Scroll the menu list so the Burger row composes.- rule.onNode(hasScrollAction()).performScrollToIndex(5)+ rule.onNode(hasScrollAction()).performScrollToIndex(3) rule.waitForIdle() // The menu row's add button: the clickable node on the same row as, // and to the right of, the item name (it carries no text of its own).@@ -156,7 +157,8 @@ class FoodWave3MainComposeTest { awaitNode("Start a new cart?") rule.onNodeWithText("Start new cart").performClick() // Back out to the tabs and open the cart: Burger is the cart now.- rule.activity.onBackPressedDispatcher.onBackPressed()+ // (The restaurant's scaffold back button: the app's own pop path.)+ rule.onNodeWithContentDescription("Back").performClick() rule.waitForIdle() rule.onNodeWithText("Cart").performClick() // The cart now holds the Burger line, not the seeded Other Place line.
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3ScreensTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3ScreensTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3ScreensTest.ktindex ddce6a20ce..994c6d8c58 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3ScreensTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3ScreensTest.kt@@ -1,5 +1,6 @@ package com.vayunmathur.fooddelivery.ui +import androidx.compose.ui.test.hasSetTextAction import android.app.Application import android.content.Context import androidx.compose.foundation.layout.Column@@ -103,13 +104,13 @@ class FoodWave3ScreensTest { rule.onNodeWithText("Ghost").assertDoesNotExist() rule.onNodeWithText("SoldOut").assertDoesNotExist() // Search settles through the debounce, then only the matching row remains.- rule.onNodeWithText("Search menu").performTextInput("shake")+ rule.onNode(hasSetTextAction()).performTextInput("shake") // The menu re-filter is debounced on the compose clock, not the wall clock. rule.mainClock.autoAdvance = false rule.mainClock.advanceTimeBy(2_000L) rule.mainClock.autoAdvance = true rule.waitForIdle()- awaitNode("Shake")+ rule.onNodeWithText("Shake", substring = false).assertExists() rule.onNodeWithText("Burger", substring = false).assertDoesNotExist() }
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/ModifierRequiredValidationTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/ModifierRequiredValidationTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/ModifierRequiredValidationTest.ktindex 7a9d8b1d28..d5e4b039d4 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/ModifierRequiredValidationTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/ModifierRequiredValidationTest.kt@@ -1,5 +1,6 @@ package com.vayunmathur.fooddelivery.ui +import com.vayunmathur.fooddelivery.ui.dialogs.ModifierDialog import android.app.Application import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled