Modern Apps git

← Modern-Apps.git

calculator: keypad rework, unit converter and viewmodel updates

Commit
3ac70cc9050db2137f7fbc6a8eb84766c7ea9568
Author
vayun-mathur <[email protected]>
When
2026-09-27 18:15 UTC (2 months ago)
Parents
61b1752

Diff

calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt b/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.ktindex b9c239f846..64a707615a 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt@@ -106,6 +106,11 @@ fun Navigation(viewModel: CalculatorViewModel, unitsRequest: Int = 0) {     ) {         entry<Route.Calculator>(metadata = SiblingPage()) { CalculatorPage(viewModel) }         entry<Route.Graph>(metadata = SiblingPage()) { GraphPage(viewModel) }-        entry<Route.Units>(metadata = SiblingPage()) { UnitConverterPage(viewModel) }+        entry<Route.Units>(metadata = SiblingPage()) {+            UnitConverterPage(viewModel) { epochSeconds ->+                viewModel.insertInstant(epochSeconds)+                backStack.reset(Route.Calculator)+            }+        }     } }
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.ktindex cea70e063c..ebee040189 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.kt@@ -40,6 +40,7 @@ import com.vayunmathur.library.ui.Tab import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import java.time.Instant+import java.time.LocalDate import java.time.ZoneId import java.time.ZoneOffset @@ -88,6 +89,15 @@ internal fun combineDateTimeSeconds(utcDateMillis: Long, hour: Int, minute: Int)     Instant.ofEpochMilli(utcDateMillis).atZone(ZoneOffset.UTC).toLocalDate()         .atTime(hour, minute).atZone(ZoneId.systemDefault()).toEpochSecond() +/**+ * A time-of-day picked with no date: today at that local time. Kept absolute (an instant)+ * rather than a duration so 2 AM never casts to 2 hours — `5 AM + 2 AM` errors, matching the+ * engine's rule that two instants only subtract.+ */+internal fun todayAtTimeSeconds(hour: Int, minute: Int): Long =+    LocalDate.now(ZoneId.systemDefault()).atTime(hour, minute)+        .atZone(ZoneId.systemDefault()).toEpochSecond()+ @OptIn(ExperimentalLayoutApi::class) @Composable internal fun UnitPickerSheet(
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.ktindex 66bcbe5401..cad0309ef0 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt@@ -3,6 +3,8 @@ package com.vayunmathur.calculator.ui import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope@@ -23,16 +25,12 @@ import com.vayunmathur.calculator.util.CalculatorActions import com.vayunmathur.calculator.util.CalculatorUiState import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.ButtonDefaults-import com.vayunmathur.library.ui.ButtonGroup+import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text  internal enum class KeyEmphasis { Digit, Operator, Primary, Function, Toggle } -/** Which date/time picker (if any) is currently open. `DtDate`/`DtTime` are the two steps of- * the combined date-and-time flow. */-internal enum class CalculatorPicker { None, Date, Time, DtDate, DtTime }- /**  * A keypad key. [second]/[secondPress] give an alternate label+action shown when the  * "2nd" modifier is active (e.g. sin → sin⁻¹). [weight] lets a key span extra columns.@@ -144,21 +142,6 @@ internal fun buildCalculatorRows(angleMode: AngleMode): List<List<Key>> {     ) } -/** A keypad button that opens a picker (styled like a Function key, but driven by screen state- * rather than a [CalculatorActions] call, so it can toggle a dialog). */-@Composable-internal fun RowScope.PickerKey(label: String, onClick: () -> Unit) {-    Button(-        onClick = onClick,-        modifier = Modifier.weight(1f).height(50.dp).padding(2.dp),-        shape = MaterialTheme.shapes.largeIncreased,-        colors = ButtonDefaults.textButtonColors(),-        contentPadding = PaddingValues(0.dp),-    ) {-        Text(label, fontSize = if (label.length >= 4) 13.sp else 18.sp, maxLines = 1)-    }-}- /** The readout column: extracted so the compact (stacked) and expanded (side-by-side)  * layouts share one implementation. */ @Composable@@ -190,29 +173,39 @@ internal fun DisplayColumn(state: CalculatorUiState, actions: CalculatorActions,             color = MaterialTheme.colorScheme.onSurfaceVariant,         )         if (state.unitOptions.isNotEmpty()) {-            Row(-                Modifier.fillMaxWidth().padding(top = 8.dp),-                horizontalArrangement = Arrangement.spacedBy(8.dp),-                verticalAlignment = Alignment.CenterVertically,-            ) {-                Text(-                    stringResource(R.string.convert_to),-                    fontSize = 12.sp,-                    color = MaterialTheme.colorScheme.onSurfaceVariant,+            // A wrapping row of filter chips rather than a ButtonGroup: the group is a+            // single-row control whose measure policy throws IllegalArgumentException+            // (maxWidth < minWidth) when the options overflow the available width, which+            // crashes the app as soon as a unit-bearing result is previewed. Chips wrap+            // to a second line instead and tolerate the narrow display column on both+            // compact and expanded layouts.+            UnitOptionsRow(state, actions)+        }+    }+}++/** The keypad column: extracted so the compact (stacked) and expanded (side-by-side)+ * layouts share one implementation. */+@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun UnitOptionsRow(state: CalculatorUiState, actions: CalculatorActions) {+    Column(Modifier.fillMaxWidth().padding(top = 8.dp)) {+        Text(+            stringResource(R.string.convert_to),+            fontSize = 12.sp,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        FlowRow(+            Modifier.fillMaxWidth().padding(top = 4.dp),+            horizontalArrangement = Arrangement.spacedBy(8.dp),+            verticalArrangement = Arrangement.spacedBy(4.dp),+        ) {+            state.unitOptions.forEach { unit ->+                FilterChip(+                    selected = unit == state.selectedUnit,+                    onClick = { actions.selectOutputUnit(unit.token) },+                    label = { Text(unit.symbol) },                 )-                // A ButtonGroup rather than a scrolling row of chips: picking the output-                // unit is one choice, so the options should read as one control. The group-                // moves anything that does not fit into its overflow menu, which is easier-                // to find than a chip scrolled off the right edge.-                ButtonGroup(Modifier.weight(1f)) {-                    state.unitOptions.forEach { unit ->-                        toggleableItem(-                            checked = unit == state.selectedUnit,-                            label = unit.symbol,-                            onCheckedChange = { actions.selectOutputUnit(unit.token) },-                        )-                    }-                }             }         }     }@@ -226,16 +219,9 @@ internal fun KeypadColumn(     actions: CalculatorActions,     second: Boolean,     onToggleSecond: () -> Unit,-    picker: CalculatorPicker,-    onPickerChange: (CalculatorPicker) -> Unit,     modifier: Modifier = Modifier, ) {     Column(modifier.padding(4.dp)) {-        Row(Modifier.fillMaxWidth()) {-            PickerKey(stringResource(R.string.key_date)) { onPickerChange(CalculatorPicker.Date) }-            PickerKey(stringResource(R.string.key_time)) { onPickerChange(CalculatorPicker.Time) }-            PickerKey(stringResource(R.string.key_datetime)) { onPickerChange(CalculatorPicker.DtDate) }-        }         rows.forEach { row ->             Row(Modifier.fillMaxWidth()) {                 row.forEach { key -> KeyButton(key, actions, second) { onToggleSecond() } }
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.ktindex 56a1426731..2453a9d68e 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt@@ -52,9 +52,6 @@ fun CalculatorScreen(     var showHistory by remember { mutableStateOf(initialShowHistory) }     var second by remember { mutableStateOf(initialSecond) }     var showUnitPicker by remember { mutableStateOf(initialShowUnitPicker) }-    var picker by remember { mutableStateOf(CalculatorPicker.None) }-    // The date chosen in the first step of the combined date-and-time flow (UTC midnight millis).-    var dtDateMillis by remember { mutableStateOf<Long?>(null) }      val rows: List<List<Key>> = remember(state.angleMode) { buildCalculatorRows(state.angleMode) } @@ -74,37 +71,17 @@ fun CalculatorScreen(             Row(Modifier.fillMaxSize().padding(padding).padding(16.dp)) {                 DisplayColumn(state, actions, Modifier.weight(1f).fillMaxSize())                 VerticalDivider()-                KeypadColumn(rows, actions, second, { second = !second }, picker, { picker = it }, Modifier.weight(1f).widthIn(max = 560.dp).fillMaxSize())+                KeypadColumn(rows, actions, second, { second = !second }, Modifier.weight(1f).widthIn(max = 560.dp).fillMaxSize())             }         } else {             Column(Modifier.fillMaxSize().padding(padding)) {                 DisplayColumn(state, actions, Modifier.fillMaxWidth().weight(1f))                 HorizontalDivider()-                KeypadColumn(rows, actions, second, { second = !second }, picker, { picker = it }, Modifier.fillMaxWidth())+                KeypadColumn(rows, actions, second, { second = !second }, Modifier.fillMaxWidth())             }         }     }      if (showHistory) HistoryDialog(state.history, actions) { showHistory = false }     if (showUnitPicker) UnitPickerSheet(state, actions) { showUnitPicker = false }--    when (picker) {-        CalculatorPicker.Date -> DatePickerModal(onDismiss = { picker = CalculatorPicker.None }) { millis ->-            actions.insertInstant(localMidnightSeconds(millis))-            picker = CalculatorPicker.None-        }-        CalculatorPicker.DtDate -> DatePickerModal(onDismiss = { picker = CalculatorPicker.None }) { millis ->-            dtDateMillis = millis-            picker = CalculatorPicker.DtTime-        }-        CalculatorPicker.Time -> TimePickerModal(onDismiss = { picker = CalculatorPicker.None }) { hour, minute ->-            actions.insertDuration((hour * 3600 + minute * 60).toLong())-            picker = CalculatorPicker.None-        }-        CalculatorPicker.DtTime -> TimePickerModal(onDismiss = { picker = CalculatorPicker.None }) { hour, minute ->-            dtDateMillis?.let { actions.insertInstant(combineDateTimeSeconds(it, hour, minute)) }-            picker = CalculatorPicker.None-        }-        CalculatorPicker.None -> {}-    } }
calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.ktindex e39eb5c677..4a22644ee4 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.kt@@ -50,17 +50,26 @@ import com.vayunmathur.library.ui.appBarScrollBehavior  /** Binds [CalculatorViewModel] to the stateless [UnitConverterScreen]. */ @Composable-fun UnitConverterPage(viewModel: CalculatorViewModel) {-    UnitConverterScreen(state = viewModel.unitConverterUiState, actions = viewModel)+fun UnitConverterPage(viewModel: CalculatorViewModel, onPickInstant: (Long) -> Unit = {}) {+    UnitConverterScreen(state = viewModel.unitConverterUiState, actions = viewModel, onPickInstant = onPickInstant) }  /**  * The units tab: a plain from/to converter with no equations. The twenty-odd categories are picked  * from a single collapsed dropdown, which keeps the converter itself the focus of the screen.+ * The Absolute-time section is picker-only: date, time and date-and-time items that insert an+ * instant into the keypad input (via [onPickInstant], which also navigates back to Calculator).  * Stateless so it can be rendered from a `@Preview` — see `src/screenshotTest`.  */ @Composable-fun UnitConverterScreen(state: UnitConverterUiState, actions: UnitConverterActions) {+fun UnitConverterScreen(+    state: UnitConverterUiState,+    actions: UnitConverterActions,+    onPickInstant: (Long) -> Unit = {},+) {+    var picker by remember { mutableStateOf(AbsoluteTimePicker.None) }+    // The date chosen in the first step of the combined date-and-time flow (UTC midnight millis).+    var dtDateMillis by remember { mutableStateOf<Long?>(null) }     AppScaffold(         title = stringResource(R.string.units),         alignment = AppBarAlignment.Center,@@ -82,7 +91,12 @@ fun UnitConverterScreen(state: UnitConverterUiState, actions: UnitConverterActio                 modifier = Modifier.fillMaxWidth().padding(horizontal = Spacing.lg, vertical = Spacing.xs),             )             if (category != null) {-                if (state.isCurrencyCategory && category.units.isEmpty()) {+                if (state.isAbsoluteTimeCategory) {+                    AbsoluteTimeSection(+                        onPick = { picker = it },+                        modifier = Modifier.fillMaxWidth().padding(Spacing.lg),+                    )+                } else if (state.isCurrencyCategory && category.units.isEmpty()) {                     CurrencyStatus(                         loading = state.currencyLoading,                         error = state.currencyError,@@ -142,6 +156,54 @@ fun UnitConverterScreen(state: UnitConverterUiState, actions: UnitConverterActio         }         }     }++    when (picker) {+        AbsoluteTimePicker.Date -> DatePickerModal(onDismiss = { picker = AbsoluteTimePicker.None }) { millis ->+            onPickInstant(localMidnightSeconds(millis))+            picker = AbsoluteTimePicker.None+        }+        AbsoluteTimePicker.DtDate -> DatePickerModal(onDismiss = { picker = AbsoluteTimePicker.None }) { millis ->+            dtDateMillis = millis+            picker = AbsoluteTimePicker.DtTime+        }+        // Time-of-day with no date: today at that time, kept absolute so 2 AM never casts+        // to 2 hours — `5 AM + 2 AM` errors like any other instant + instant.+        AbsoluteTimePicker.Time -> TimePickerModal(onDismiss = { picker = AbsoluteTimePicker.None }) { hour, minute ->+            onPickInstant(todayAtTimeSeconds(hour, minute))+            picker = AbsoluteTimePicker.None+        }+        AbsoluteTimePicker.DtTime -> TimePickerModal(onDismiss = { picker = AbsoluteTimePicker.None }) { hour, minute ->+            dtDateMillis?.let { onPickInstant(combineDateTimeSeconds(it, hour, minute)) }+            picker = AbsoluteTimePicker.None+        }+        AbsoluteTimePicker.None -> {}+    }+}++/** Which absolute-time picker (if any) is currently open. `DtDate`/`DtTime` are the two steps+ * of the combined date-and-time flow. */+internal enum class AbsoluteTimePicker { None, Date, Time, DtDate, DtTime }++/**+ * The Absolute-time section: three full-width picker items (date, time, date & time) instead of+ * a from/to converter form. Each inserts an `#<epoch>` instant into the keypad input.+ */+@Composable+private fun AbsoluteTimeSection(onPick: (AbsoluteTimePicker) -> Unit, modifier: Modifier = Modifier) {+    Column(modifier, verticalArrangement = Arrangement.spacedBy(Spacing.md)) {+        OutlinedButton(+            onClick = { onPick(AbsoluteTimePicker.Date) },+            modifier = Modifier.fillMaxWidth(),+        ) { Text(stringResource(R.string.key_date), modifier = Modifier.weight(1f), textAlign = TextAlign.Start) }+        OutlinedButton(+            onClick = { onPick(AbsoluteTimePicker.Time) },+            modifier = Modifier.fillMaxWidth(),+        ) { Text(stringResource(R.string.key_time), modifier = Modifier.weight(1f), textAlign = TextAlign.Start) }+        OutlinedButton(+            onClick = { onPick(AbsoluteTimePicker.DtDate) },+            modifier = Modifier.fillMaxWidth(),+        ) { Text(stringResource(R.string.key_datetime), modifier = Modifier.weight(1f), textAlign = TextAlign.Start) }+    } }  /**
calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.ktindex b6a24fdaad..97c5521cf1 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt@@ -106,8 +106,6 @@ interface CalculatorActions {     fun append(text: String) {}     /** Insert an absolute date/datetime (epoch seconds) chosen from a picker. */     fun insertInstant(epochSeconds: Long) {}-    /** Insert a duration in seconds (e.g. a time-of-day) chosen from a picker. */-    fun insertDuration(seconds: Long) {}     fun clear() {}     fun backspace() {}     fun evaluate() {}@@ -164,6 +162,8 @@ data class UnitConverterUiState(     val currencyError: String? = null,     /** True once the selected category is the live Currency tab. */     val isCurrencyCategory: Boolean = false,+    /** True once the selected category is the Absolute-time picker section. */+    val isAbsoluteTimeCategory: Boolean = false, )  /** Unit-converter callbacks. Same no-op-default arrangement as [CalculatorActions]. */
calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.ktindex 666fd83372..86d234d6a6 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt@@ -115,19 +115,6 @@ class CalculatorViewModel(application: Application) :      override fun insertInstant(epochSeconds: Long) = append("#$epochSeconds") -    /** Insert a duration (e.g. a picked time of day) as a re-parsable `(Hh+Mmin+Ss)` group. */-    override fun insertDuration(seconds: Long) {-        val h = seconds / 3600-        val m = (seconds % 3600) / 60-        val s = seconds % 60-        val parts = buildList {-            if (h != 0L) add("${h}h")-            if (m != 0L) add("${m}min")-            if (s != 0L) add("${s}s")-        }-        append(if (parts.isEmpty()) "0s" else "(" + parts.joinToString("+") + ")")-    }-     override fun backspace() {         if (input.isNotEmpty()) updateInput(input.dropLast(1))     }@@ -290,9 +277,18 @@ class CalculatorViewModel(application: Application) :      */     private val lastUnits = mutableMapOf<String, Pair<String, String>>() -    /** Static physical-unit categories plus the (possibly still-empty) live Currency tab. */+    /** Static physical-unit categories, the Absolute-time picker section (right after Time),+     * plus the (possibly still-empty) live Currency tab. Absolute time is a picker section, not a+     * unit category: it is kept out of UnitRegistry so the parser, output selector and widget never+     * see it — the converter screen renders it as date/time pickers instead of a from/to form. */     private val converterCategories: List<UnitCategory>-        get() = UnitRegistry.categories + (currencyCategory ?: EMPTY_CURRENCY_CATEGORY)+        get() {+            val static = UnitRegistry.categories.toMutableList()+            val timeIndex = static.indexOfFirst { it.name == TIME_CATEGORY_NAME }+            static.add(if (timeIndex >= 0) timeIndex + 1 else static.size, ABSOLUTE_TIME_CATEGORY)+            static.add(currencyCategory ?: EMPTY_CURRENCY_CATEGORY)+            return static+        }      private val currencyIndex: Int get() = converterCategories.lastIndex @@ -300,16 +296,19 @@ class CalculatorViewModel(application: Application) :         get() {             val categories = converterCategories             val index = converterCategoryIndex.coerceIn(categories.indices)+            val category = categories[index]+            val isAbsoluteTime = category.name == ABSOLUTE_TIME_CATEGORY_NAME             return UnitConverterUiState(                 categories = categories,                 selectedCategoryIndex = index,                 fromToken = converterFromToken,                 toToken = converterToToken,                 inputText = converterValueText,-                outputText = convert(categories[index]),+                outputText = if (isAbsoluteTime) "" else convert(category),                 currencyLoading = currencyLoading,                 currencyError = currencyError,                 isCurrencyCategory = index == currencyIndex,+                isAbsoluteTimeCategory = isAbsoluteTime,             )         } @@ -324,9 +323,13 @@ class CalculatorViewModel(application: Application) :         val categories = converterCategories         if (index !in categories.indices) return         converterCategoryIndex = index-        applyRememberedUnits(categories[index])-        persist(KEY_UNITS_CATEGORY, categories[index].name)-        refreshUnitsWidget()+        val category = categories[index]+        // Absolute time has no from/to pair to remember — it is three pickers, not a conversion.+        if (category.name != ABSOLUTE_TIME_CATEGORY_NAME) {+            applyRememberedUnits(category)+            persist(KEY_UNITS_CATEGORY, category.name)+            refreshUnitsWidget()+        }     }      /**@@ -354,7 +357,10 @@ class CalculatorViewModel(application: Application) :      private fun rememberUnits() {         val categories = converterCategories-        val name = categories[converterCategoryIndex.coerceIn(categories.indices)].name+        val category = categories[converterCategoryIndex.coerceIn(categories.indices)]+        // Absolute time and Currency have no from/to pair to remember.+        if (category.name == ABSOLUTE_TIME_CATEGORY_NAME || category.units.isEmpty()) return+        val name = category.name         lastUnits[name] = converterFromToken to converterToToken         persist(unitsFromKey(name), converterFromToken)         persist(unitsToKey(name), converterToToken)@@ -383,7 +389,9 @@ class CalculatorViewModel(application: Application) :     override fun setConverterInput(text: String) { converterValueText = text }     override fun swapUnits() {         val categories = converterCategories-        val swappedInput = convert(categories[converterCategoryIndex.coerceIn(categories.indices)])+        val category = categories[converterCategoryIndex.coerceIn(categories.indices)]+        if (category.name == ABSOLUTE_TIME_CATEGORY_NAME || category.units.isEmpty()) return+        val swappedInput = convert(category)         val from = converterFromToken         converterFromToken = converterToToken         converterToToken = from@@ -430,12 +438,14 @@ class CalculatorViewModel(application: Application) :     private fun restoreConverterSelection() {         viewModelScope.launch {             val name = dataStore.getStringAwait(KEY_UNITS_CATEGORY) ?: return@launch-            val from = dataStore.getStringAwait(unitsFromKey(name))-            val to = dataStore.getStringAwait(unitsToKey(name))-            if (from != null && to != null) lastUnits.putIfAbsent(name, from to to)+            // Absolute time is never persisted as the selected category; fall back to Time.+            val resolvedName = if (name == ABSOLUTE_TIME_CATEGORY_NAME) TIME_CATEGORY_NAME else name+            val from = dataStore.getStringAwait(unitsFromKey(resolvedName))+            val to = dataStore.getStringAwait(unitsToKey(resolvedName))+            if (from != null && to != null) lastUnits.putIfAbsent(resolvedName, from to to)              val categories = converterCategories-            val index = categories.indexOfFirst { it.name == name }+            val index = categories.indexOfFirst { it.name == resolvedName }             if (index < 0) return@launch             converterCategoryIndex = index             // Currency has no units until rates arrive; loadCurrencyRates applies them then.@@ -484,6 +494,25 @@ class CalculatorViewModel(application: Application) :         private val EMPTY_CURRENCY_CATEGORY =             UnitCategory("Currency", emptyList(), inEquations = false) +        /**+         * The name of the built-in Time category the Absolute-time section follows. Matched by+         * name (rather than position) because the registry owns the ordering.+         */+        internal const val TIME_CATEGORY_NAME = "Time"++        /** Name of the Absolute-time picker section appended after [TIME_CATEGORY_NAME]. */+        internal const val ABSOLUTE_TIME_CATEGORY_NAME = "Absolute time"++        /**+         * The Absolute-time picker section: date, time-of-day and combined pickers that insert+         * `#<epoch>` instants into the keypad input. Empty units mark it as picker-only — the+         * converter screen renders pickers instead of a from/to form, and `convert` is never+         * called on it. Kept out of [UnitRegistry] so the parser, output selector and widget+         * never see it.+         */+        internal val ABSOLUTE_TIME_CATEGORY =+            UnitCategory(ABSOLUTE_TIME_CATEGORY_NAME, emptyList(), inEquations = false)+         // Not private: the units widget reads these same preferences, and a second copy of the         // key names is a copy that can drift.         internal const val KEY_UNITS_CATEGORY = "calculator_units_category"
calculator/src/test/java/com/vayunmathur/calculator/util/DateExpressionTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/DateExpressionTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/DateExpressionTest.ktindex d53e5c7415..631f345ee9 100644--- a/calculator/src/test/java/com/vayunmathur/calculator/util/DateExpressionTest.kt+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/DateExpressionTest.kt@@ -5,6 +5,9 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue+import java.time.Instant+import java.time.ZoneId+import com.vayunmathur.calculator.ui.todayAtTimeSeconds  /** Covers the date/datetime support added to the expression engine: the `#<epoch>` literal and  * the instant arithmetic rules (instant−instant=duration, instant±duration=instant). */@@ -60,4 +63,33 @@ class DateExpressionTest {     fun addingAScalarToADateIsRejected() {         assertFailsWith<ExpressionError> { q("#1000000 + 5") }     }++    @Test+    fun addingTwoTimesOfDayIsRejected() {+        // The time picker inserts an instant (today at H:M), not a duration, so 5 AM + 2 AM+        // errors like any other instant + instant rather than returning 7 AM.+        val fiveAm = "#${todayAtTimeSeconds(5, 0)}"+        val twoAm = "#${todayAtTimeSeconds(2, 0)}"+        assertFailsWith<ExpressionError> { q("$fiveAm + $twoAm") }+    }++    @Test+    fun subtractingTwoTimesOfDayGivesADuration() {+        val fiveAm = "#${todayAtTimeSeconds(5, 0)}"+        val twoAm = "#${todayAtTimeSeconds(2, 0)}"+        val result = q("$fiveAm - $twoAm")+        assertEquals(Dimension.TIME, result.dimension)+        assertFalse(result.instant, "a difference of two times is a duration, not an instant")+        assertEquals(3 * 3600.0, result.value, 1e-9)+    }++    @Test+    fun timeOfDayIsAnInstantOnTheCurrentDay() {+        val epoch = todayAtTimeSeconds(14, 30)+        val result = q("#$epoch")+        assertTrue(result.instant)+        val zoned = Instant.ofEpochSecond(epoch).atZone(ZoneId.systemDefault())+        assertEquals(14, zoned.hour)+        assertEquals(30, zoned.minute)+    } }