Modern Apps git

← Modern-Apps.git

weather: fix remaining util/map imports and duplicate SelectedDateOrTime

Commit
01ed937d145a736ccb8c2bad0774eec8778a0e32
Author
vayun-mathur <[email protected]>
When
2026-08-15 19:05 UTC (3 months ago)
Parents
a76f70e

Diff

weather/src/main/java/com/vayunmathur/weather/domain/SelectedDateOrTime.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/domain/SelectedDateOrTime.kt b/weather/src/main/java/com/vayunmathur/weather/domain/SelectedDateOrTime.ktnew file mode 100644index 0000000000..96389d3ac1--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/domain/SelectedDateOrTime.kt@@ -0,0 +1,6 @@+package com.vayunmathur.weather.domain++sealed interface SelectedDateOrTime {+    data class Time(val isoTime: String) : SelectedDateOrTime+    data class Day(val isoDate: String) : SelectedDateOrTime+}
weather/src/main/java/com/vayunmathur/weather/platform/SystemUnits.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/platform/SystemUnits.kt b/weather/src/main/java/com/vayunmathur/weather/platform/SystemUnits.ktindex 99028f62ed..eab58c71a6 100644--- a/weather/src/main/java/com/vayunmathur/weather/platform/SystemUnits.kt+++ b/weather/src/main/java/com/vayunmathur/weather/platform/SystemUnits.kt@@ -1,74 +1,77 @@-package com.vayunmathur.weather.platform--import androidx.compose.runtime.Composable-import androidx.compose.runtime.remember-import androidx.compose.ui.platform.LocalConfiguration-import androidx.compose.ui.platform.LocalContext-import androidx.core.text.util.LocalePreferences-import java.util.Locale--/**- * Resolve the display units from the device's regional preferences (set- * via Android 14's *Settings → System → Languages → Regional preferences*,- * and inferred from the active locale on earlier versions). Reading via- * Compose's `LocalConfiguration` ensures we re-resolve on configuration- * changes when the user flips a setting at runtime.- *- * Temperature comes from [LocalePreferences.getTemperatureUnit].- *- * Wind speed (and any other distance-based units) comes from the- * **measurement system** preference, which Android writes to the active- * locale as the Unicode extension `-u-ms-{metric|ussystem|uksystem}`. We- * read it directly via [Locale.getUnicodeLocaleType] since the androidx- * helper doesn't expose it yet — falling back to the locale's country code- * (US/LR/MM → US system) for devices where the extension is absent.- */-@Composable-fun rememberTempUnit(): TemperatureUnit {-    LocalConfiguration.current-    return remember(LocalConfiguration.current) {-        when (LocalePreferences.getTemperatureUnit()) {-            LocalePreferences.TemperatureUnit.FAHRENHEIT -> TemperatureUnit.Fahrenheit-            else -> TemperatureUnit.Celsius-        }-    }-}--@Composable-fun rememberWindUnit(): WindUnit {-    LocalConfiguration.current-    return remember(LocalConfiguration.current) {-        if (isImperialMeasurementSystem(Locale.getDefault())) WindUnit.Mph else WindUnit.KmH-    }-}--@Composable-fun rememberPressureUnit(): PressureUnit {-    LocalConfiguration.current-    return remember(LocalConfiguration.current) {-        if (isImperialMeasurementSystem(Locale.getDefault())) PressureUnit.InHg else PressureUnit.Hpa-    }-}--@Composable-fun rememberUse24Hour(): Boolean {-    LocalConfiguration.current-    val context = LocalContext.current-    return remember(LocalConfiguration.current) {-        android.text.format.DateFormat.is24HourFormat(context)-    }-}--/**- * True when the locale opts into a non-metric measurement system, either- * via the explicit `-u-ms-…` Unicode extension that Android 14's regional- * preference sets, or by virtue of being one of the three remaining- * predominantly-imperial country codes.- */-private fun isImperialMeasurementSystem(locale: Locale): Boolean {-    val extension = locale.getUnicodeLocaleType("ms")-    if (extension != null) {-        return extension == "ussystem" || extension == "uksystem"-    }-    return locale.country in setOf("US", "LR", "MM")-}+package com.vayunmathur.weather.platform++import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalConfiguration+import androidx.compose.ui.platform.LocalContext+import androidx.core.text.util.LocalePreferences+import com.vayunmathur.weather.domain.PressureUnit+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.WindUnit+import java.util.Locale++/**+ * Resolve the display units from the device's regional preferences (set+ * via Android 14's *Settings → System → Languages → Regional preferences*,+ * and inferred from the active locale on earlier versions). Reading via+ * Compose's `LocalConfiguration` ensures we re-resolve on configuration+ * changes when the user flips a setting at runtime.+ *+ * Temperature comes from [LocalePreferences.getTemperatureUnit].+ *+ * Wind speed (and any other distance-based units) comes from the+ * **measurement system** preference, which Android writes to the active+ * locale as the Unicode extension `-u-ms-{metric|ussystem|uksystem}`. We+ * read it directly via [Locale.getUnicodeLocaleType] since the androidx+ * helper doesn't expose it yet — falling back to the locale's country code+ * (US/LR/MM → US system) for devices where the extension is absent.+ */+@Composable+fun rememberTempUnit(): TemperatureUnit {+    LocalConfiguration.current+    return remember(LocalConfiguration.current) {+        when (LocalePreferences.getTemperatureUnit()) {+            LocalePreferences.TemperatureUnit.FAHRENHEIT -> TemperatureUnit.Fahrenheit+            else -> TemperatureUnit.Celsius+        }+    }+}++@Composable+fun rememberWindUnit(): WindUnit {+    LocalConfiguration.current+    return remember(LocalConfiguration.current) {+        if (isImperialMeasurementSystem(Locale.getDefault())) WindUnit.Mph else WindUnit.KmH+    }+}++@Composable+fun rememberPressureUnit(): PressureUnit {+    LocalConfiguration.current+    return remember(LocalConfiguration.current) {+        if (isImperialMeasurementSystem(Locale.getDefault())) PressureUnit.InHg else PressureUnit.Hpa+    }+}++@Composable+fun rememberUse24Hour(): Boolean {+    LocalConfiguration.current+    val context = LocalContext.current+    return remember(LocalConfiguration.current) {+        android.text.format.DateFormat.is24HourFormat(context)+    }+}++/**+ * True when the locale opts into a non-metric measurement system, either+ * via the explicit `-u-ms-…` Unicode extension that Android 14's regional+ * preference sets, or by virtue of being one of the three remaining+ * predominantly-imperial country codes.+ */+private fun isImperialMeasurementSystem(locale: Locale): Boolean {+    val extension = locale.getUnicodeLocaleType("ms")+    if (extension != null) {+        return extension == "ussystem" || extension == "uksystem"+    }+    return locale.country in setOf("US", "LR", "MM")+}
weather/src/main/java/com/vayunmathur/weather/platform/WeatherUiContract.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherUiContract.kt b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherUiContract.ktindex 511275196b..1ba709cc37 100644--- a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherUiContract.kt+++ b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherUiContract.kt@@ -1,89 +1,92 @@-package com.vayunmathur.weather.platform--import androidx.compose.runtime.Composable-import com.vayunmathur.weather.data.SavedLocation-import com.vayunmathur.weather.domain.TemperatureUnit-import com.vayunmathur.weather.network.AirQualityCurrent-import com.vayunmathur.weather.network.ForecastResponse--/**- * The UI contract between [WeatherViewModel] and the screens.- *- * Screens take a state value plus an actions interface rather than the ViewModel itself,- * so they can be rendered by a `@Preview` — which is what the store listing images are- * generated from. It lives in `util` rather than `ui` so the dependency runs one way:- * `ui` depends on `util`, and the ViewModel implements the actions interface.- */--/**- * Display units and the 12/24-hour choice, resolved from the device's regional- * preferences by the binder rather than inside the screens. Hoisting them is what keeps a- * preview reproducible: the render machine's locale and clock setting no longer leak into- * the image.- */-data class DisplayUnits(-    val temperature: TemperatureUnit = TemperatureUnit.Celsius,-    val wind: WindUnit = WindUnit.KmH,-    val pressure: PressureUnit = PressureUnit.Hpa,-    val use24Hour: Boolean = false,-)--/** Read [DisplayUnits] from the device's regional preferences. */-@Composable-fun rememberDisplayUnits(): DisplayUnits = DisplayUnits(-    temperature = rememberTempUnit(),-    wind = rememberWindUnit(),-    pressure = rememberPressureUnit(),-    use24Hour = rememberUse24Hour(),-)--/** Everything the forecast page draws for one saved location. */-data class LocationUiState(-    val location: SavedLocation,-    val forecast: ForecastResponse? = null,-    val airQuality: AirQualityCurrent? = null,-    val refreshing: Boolean = false,-    val error: String? = null,-    /** The hour/day the user is inspecting, or null for "now / today". */-    val selected: SelectedDateOrTime? = null,-)--/**- * One row of the locations drawer. [description] ("Last updated 4m ago" / "No data yet")- * is resolved by the binder because it needs both a [android.content.Context] for the- * string and a clock — neither of which belongs in a screen that has to render- * identically every time.- */-data class LocationRow(-    val location: SavedLocation,-    val description: String,-    val weatherCode: Int? = null,-    val isDay: Boolean = true,-)--/** Everything the locations drawer draws. */-data class LocationsUiState(-    val rows: List<LocationRow> = emptyList(),-    val activeLocationId: Long? = null,-    /** True while a device-location fix is being requested. */-    val deviceLocationLoading: Boolean = false,-)--/**- * Callbacks the screens fire. Every method has a no-op default so a preview can render a- * screen without supplying behaviour — [Noop] is the whole implementation a preview needs.- * The signatures match [WeatherViewModel]'s existing methods, which is why the ViewModel- * implements this directly rather than through an adapter.- */-interface WeatherActions {-    fun refreshAll(force: Boolean = false) {}-    fun toggleTime(isoTime: String) {}-    fun toggleDay(isoDate: String) {}-    fun clearSelection() {}-    fun deleteLocation(location: SavedLocation) {}-    fun reorderLocations(ordered: List<SavedLocation>) {}--    companion object {-        val Noop: WeatherActions = object : WeatherActions {}-    }-}+package com.vayunmathur.weather.platform++import androidx.compose.runtime.Composable+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.domain.PressureUnit+import com.vayunmathur.weather.domain.SelectedDateOrTime+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.WindUnit+import com.vayunmathur.weather.network.AirQualityCurrent+import com.vayunmathur.weather.network.ForecastResponse++/**+ * The UI contract between [WeatherViewModel] and the screens.+ *+ * Screens take a state value plus an actions interface rather than the ViewModel itself,+ * so they can be rendered by a `@Preview` — which is what the store listing images are+ * generated from. It lives in `util` rather than `ui` so the dependency runs one way:+ * `ui` depends on `util`, and the ViewModel implements the actions interface.+ */++/**+ * Display units and the 12/24-hour choice, resolved from the device's regional+ * preferences by the binder rather than inside the screens. Hoisting them is what keeps a+ * preview reproducible: the render machine's locale and clock setting no longer leak into+ * the image.+ */+data class DisplayUnits(+    val temperature: TemperatureUnit = TemperatureUnit.Celsius,+    val wind: WindUnit = WindUnit.KmH,+    val pressure: PressureUnit = PressureUnit.Hpa,+    val use24Hour: Boolean = false,+)++/** Read [DisplayUnits] from the device's regional preferences. */+@Composable+fun rememberDisplayUnits(): DisplayUnits = DisplayUnits(+    temperature = rememberTempUnit(),+    wind = rememberWindUnit(),+    pressure = rememberPressureUnit(),+    use24Hour = rememberUse24Hour(),+)++/** Everything the forecast page draws for one saved location. */+data class LocationUiState(+    val location: SavedLocation,+    val forecast: ForecastResponse? = null,+    val airQuality: AirQualityCurrent? = null,+    val refreshing: Boolean = false,+    val error: String? = null,+    /** The hour/day the user is inspecting, or null for "now / today". */+    val selected: SelectedDateOrTime? = null,+)++/**+ * One row of the locations drawer. [description] ("Last updated 4m ago" / "No data yet")+ * is resolved by the binder because it needs both a [android.content.Context] for the+ * string and a clock — neither of which belongs in a screen that has to render+ * identically every time.+ */+data class LocationRow(+    val location: SavedLocation,+    val description: String,+    val weatherCode: Int? = null,+    val isDay: Boolean = true,+)++/** Everything the locations drawer draws. */+data class LocationsUiState(+    val rows: List<LocationRow> = emptyList(),+    val activeLocationId: Long? = null,+    /** True while a device-location fix is being requested. */+    val deviceLocationLoading: Boolean = false,+)++/**+ * Callbacks the screens fire. Every method has a no-op default so a preview can render a+ * screen without supplying behaviour — [Noop] is the whole implementation a preview needs.+ * The signatures match [WeatherViewModel]'s existing methods, which is why the ViewModel+ * implements this directly rather than through an adapter.+ */+interface WeatherActions {+    fun refreshAll(force: Boolean = false) {}+    fun toggleTime(isoTime: String) {}+    fun toggleDay(isoDate: String) {}+    fun clearSelection() {}+    fun deleteLocation(location: SavedLocation) {}+    fun reorderLocations(ordered: List<SavedLocation>) {}++    companion object {+        val Noop: WeatherActions = object : WeatherActions {}+    }+}
weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.ktindex 18f67932e7..0dc73f9912 100644--- a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt+++ b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt@@ -1,248 +1,244 @@-package com.vayunmathur.weather.platform--import android.app.Application-import androidx.lifecycle.AndroidViewModel-import androidx.lifecycle.ViewModel-import androidx.lifecycle.ViewModelProvider-import androidx.lifecycle.viewModelScope-import androidx.glance.appwidget.updateAll-import com.vayunmathur.weather.R-import com.vayunmathur.weather.data.SavedLocation-import com.vayunmathur.weather.data.WeatherRepository-import com.vayunmathur.weather.data.WeatherRefreshWorker-import com.vayunmathur.weather.data.weatherJson-import com.vayunmathur.weather.domain.SelectedDateOrTime-import com.vayunmathur.weather.domain.roundCoord-import com.vayunmathur.weather.widget.glance.WeatherGlanceWidget-import com.vayunmathur.weather.network.AirQualityResponse-import com.vayunmathur.weather.network.ForecastResponse-import com.vayunmathur.weather.network.WeatherApi-import kotlinx.coroutines.async-import kotlinx.coroutines.coroutineScope-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.SharingStarted-import kotlinx.coroutines.flow.StateFlow-import kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.flow.stateIn-import kotlinx.coroutines.flow.update-import kotlinx.coroutines.launch-import kotlinx.coroutines.withTimeoutOrNull--data class ForecastUiState(-    val forecast: ForecastResponse? = null,-    val airQuality: AirQualityResponse? = null,-    val refreshing: Boolean = false,-    val error: String? = null,-    val fetchedAtEpochMs: Long = 0,-)--sealed interface SelectedDateOrTime {-    data class Time(val isoTime: String) : SelectedDateOrTime-    data class Day(val isoDate: String) : SelectedDateOrTime-}--class WeatherViewModel(-    application: Application,-    private val repository: WeatherRepository,-) : AndroidViewModel(application), WeatherActions {--    val savedLocations: StateFlow<List<SavedLocation>?> = repository.locations-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)--    private val _forecasts = MutableStateFlow<Map<Long, ForecastUiState>>(emptyMap())-    val forecasts: StateFlow<Map<Long, ForecastUiState>> = _forecasts.asStateFlow()--    private val inFlight = mutableSetOf<Long>()--    private val _selected = MutableStateFlow<SelectedDateOrTime?>(null)-    val selectedDateOrTime: StateFlow<SelectedDateOrTime?> = _selected.asStateFlow()--    fun selectTime(isoTime: String) { _selected.value = SelectedDateOrTime.Time(isoTime) }--    fun selectDay(isoDate: String) { _selected.value = SelectedDateOrTime.Day(isoDate) }--    override fun clearSelection() { _selected.value = null }--    override fun toggleTime(isoTime: String) {-        val current = _selected.value-        _selected.value = if (current is SelectedDateOrTime.Time && current.isoTime == isoTime) null else SelectedDateOrTime.Time(isoTime)-    }--    override fun toggleDay(isoDate: String) {-        val current = _selected.value-        _selected.value = if (current is SelectedDateOrTime.Day && current.isoDate == isoDate) null else SelectedDateOrTime.Day(isoDate)-    }--    init {-        WeatherRefreshWorker.scheduleHourlyRefresh(application)-    }--    fun ensureForecast(location: SavedLocation, force: Boolean = false) {-        synchronized(inFlight) {-            if (location.id in inFlight) return-            val existing = _forecasts.value[location.id]-            val memStale = existing?.forecast == null ||-                (System.currentTimeMillis() - existing.fetchedAtEpochMs) >= STALE_THRESHOLD_MS-            if (!force && !memStale) return-            inFlight.add(location.id)-        }--        viewModelScope.launch {-            try {-                var haveFreshCache = false-                if (_forecasts.value[location.id]?.forecast == null) {-                    val cache = repository.getCache(roundCoord(location.latitude), roundCoord(location.longitude))-                    if (cache != null) {-                        runCatching { weatherJson.decodeFromString<ForecastResponse>(cache.forecastJson) }-                            .onSuccess { decoded ->-                                val cachedAir = cache.airQualityJson?.let { json ->-                                    runCatching { weatherJson.decodeFromString<AirQualityResponse>(json) }.getOrNull()-                                }-                                _forecasts.update { current ->-                                    current + (location.id to ForecastUiState(-                                        forecast = decoded,-                                        airQuality = cachedAir,-                                        refreshing = false,-                                        fetchedAtEpochMs = cache.fetchedAtEpochMs,-                                    ))-                                }-                                haveFreshCache = (System.currentTimeMillis() - cache.fetchedAtEpochMs) < STALE_THRESHOLD_MS-                            }-                    }-                }--                if (!force && haveFreshCache) return@launch--                val target = if (location.isCurrent) refreshDeviceLocationFix(location) else location--                _forecasts.update { current ->-                    val prev = current[location.id]-                    current + (location.id to (prev?.copy(refreshing = true) ?: ForecastUiState(refreshing = true)))-                }--                data class FetchResult(val forecast: kotlin.Result<ForecastResponse>, val air: AirQualityResponse?)-                val fetched: FetchResult = coroutineScope {-                    val forecastDeferred = async { runCatching { WeatherApi.forecast(target.latitude, target.longitude) } }-                    val airQualityDeferred = async { runCatching { WeatherApi.airQuality(target.latitude, target.longitude) }.getOrNull() }-                    FetchResult(forecastDeferred.await(), airQualityDeferred.await())-                }-                val forecastResult = fetched.forecast-                val airQuality = fetched.air--                forecastResult-                    .onSuccess { fresh ->-                        val now = System.currentTimeMillis()-                        val resolvedAir = airQuality ?: _forecasts.value[location.id]?.airQuality-                        repository.writeForecastCache(target.latitude, target.longitude, fresh, resolvedAir, now)-                        _forecasts.update { current ->-                            current + (location.id to ForecastUiState(-                                forecast = fresh,-                                airQuality = resolvedAir,-                                refreshing = false,-                                error = null,-                                fetchedAtEpochMs = now,-                            ))-                        }-                        runCatching { WeatherGlanceWidget().updateAll(getApplication<Application>()) }-                    }-                    .onFailure { e ->-                        _forecasts.update { current ->-                            val prev = current[location.id]-                            current + (location.id to (prev?.copy(-                                airQuality = airQuality ?: prev.airQuality,-                                refreshing = false,-                                error = e.message ?: "Failed to load forecast",-                            ) ?: ForecastUiState(-                                airQuality = airQuality,-                                refreshing = false,-                                error = e.message,-                            )))-                        }-                    }-            } finally {-                synchronized(inFlight) { inFlight.remove(location.id) }-            }-        }-    }--    override fun refreshAll(force: Boolean) {-        for (location in savedLocations.value.orEmpty()) {-            ensureForecast(location, force)-        }-    }--    override fun deleteLocation(location: SavedLocation) {-        viewModelScope.launch {-            repository.deleteLocation(location)-            _forecasts.update { it - location.id }-        }-    }--    override fun reorderLocations(ordered: List<SavedLocation>) {-        viewModelScope.launch {-            ordered.forEachIndexed { index, loc ->-                if (loc.displayOrder != index) repository.setOrder(loc.id, index)-            }-        }-    }--    fun addLocation(name: String, country: String, latitude: Double, longitude: Double) {-        viewModelScope.launch {-            val existing = repository.getLocations()-            repository.insertLocation(-                SavedLocation(-                    name = name,-                    country = country,-                    latitude = latitude,-                    longitude = longitude,-                    displayOrder = existing.size,-                    isCurrent = false,-                )-            )-        }-    }--    fun setCurrentLocation(name: String, latitude: Double, longitude: Double) {-        viewModelScope.launch {-            val app = getApplication<Application>()-            val defaultName = app.getString(R.string.current_location)-            repository.replaceCurrentDeviceLocation(-                SavedLocation(-                    name = name.ifBlank { defaultName },-                    country = "",-                    latitude = latitude,-                    longitude = longitude,-                    displayOrder = -1,-                    isCurrent = true,-                )-            )-        }-    }--    private suspend fun refreshDeviceLocationFix(location: SavedLocation): SavedLocation {-        val context = getApplication<Application>()-        if (!LocationProvider.hasPermission(context)) return location-        val fix = withTimeoutOrNull(LOCATION_FIX_TIMEOUT_MS) { LocationProvider.currentLocation(context) } ?: return location-        val distance = FloatArray(1)-        android.location.Location.distanceBetween(location.latitude, location.longitude, fix.latitude, fix.longitude, distance)-        if (distance[0] < MIN_LOCATION_MOVE_METERS) return location-        repository.updateCoordinates(location.id, fix.latitude, fix.longitude)-        return location.copy(latitude = fix.latitude, longitude = fix.longitude)-    }--    companion object {-        const val STALE_THRESHOLD_MS = 15 * 60 * 1000L-        private const val LOCATION_FIX_TIMEOUT_MS = 8_000L-        private const val MIN_LOCATION_MOVE_METERS = 500f-    }-}--class WeatherViewModelFactory(-    private val application: Application,-    private val repository: WeatherRepository,-) : ViewModelProvider.Factory {-    @Suppress("UNCHECKED_CAST")-    override fun <T : ViewModel> create(modelClass: Class<T>): T {-        return WeatherViewModel(application, repository) as T-    }-}+package com.vayunmathur.weather.platform++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.ViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import androidx.glance.appwidget.updateAll+import com.vayunmathur.weather.R+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.data.WeatherRepository+import com.vayunmathur.weather.data.WeatherRefreshWorker+import com.vayunmathur.weather.data.weatherJson+import com.vayunmathur.weather.domain.SelectedDateOrTime+import com.vayunmathur.weather.domain.roundCoord+import com.vayunmathur.weather.widget.glance.WeatherGlanceWidget+import com.vayunmathur.weather.network.AirQualityResponse+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.WeatherApi+import kotlinx.coroutines.async+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withTimeoutOrNull++data class ForecastUiState(+    val forecast: ForecastResponse? = null,+    val airQuality: AirQualityResponse? = null,+    val refreshing: Boolean = false,+    val error: String? = null,+    val fetchedAtEpochMs: Long = 0,+)+++class WeatherViewModel(+    application: Application,+    private val repository: WeatherRepository,+) : AndroidViewModel(application), WeatherActions {++    val savedLocations: StateFlow<List<SavedLocation>?> = repository.locations+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)++    private val _forecasts = MutableStateFlow<Map<Long, ForecastUiState>>(emptyMap())+    val forecasts: StateFlow<Map<Long, ForecastUiState>> = _forecasts.asStateFlow()++    private val inFlight = mutableSetOf<Long>()++    private val _selected = MutableStateFlow<SelectedDateOrTime?>(null)+    val selectedDateOrTime: StateFlow<SelectedDateOrTime?> = _selected.asStateFlow()++    fun selectTime(isoTime: String) { _selected.value = SelectedDateOrTime.Time(isoTime) }++    fun selectDay(isoDate: String) { _selected.value = SelectedDateOrTime.Day(isoDate) }++    override fun clearSelection() { _selected.value = null }++    override fun toggleTime(isoTime: String) {+        val current = _selected.value+        _selected.value = if (current is SelectedDateOrTime.Time && current.isoTime == isoTime) null else SelectedDateOrTime.Time(isoTime)+    }++    override fun toggleDay(isoDate: String) {+        val current = _selected.value+        _selected.value = if (current is SelectedDateOrTime.Day && current.isoDate == isoDate) null else SelectedDateOrTime.Day(isoDate)+    }++    init {+        WeatherRefreshWorker.scheduleHourlyRefresh(application)+    }++    fun ensureForecast(location: SavedLocation, force: Boolean = false) {+        synchronized(inFlight) {+            if (location.id in inFlight) return+            val existing = _forecasts.value[location.id]+            val memStale = existing?.forecast == null ||+                (System.currentTimeMillis() - existing.fetchedAtEpochMs) >= STALE_THRESHOLD_MS+            if (!force && !memStale) return+            inFlight.add(location.id)+        }++        viewModelScope.launch {+            try {+                var haveFreshCache = false+                if (_forecasts.value[location.id]?.forecast == null) {+                    val cache = repository.getCache(roundCoord(location.latitude), roundCoord(location.longitude))+                    if (cache != null) {+                        runCatching { weatherJson.decodeFromString<ForecastResponse>(cache.forecastJson) }+                            .onSuccess { decoded ->+                                val cachedAir = cache.airQualityJson?.let { json ->+                                    runCatching { weatherJson.decodeFromString<AirQualityResponse>(json) }.getOrNull()+                                }+                                _forecasts.update { current ->+                                    current + (location.id to ForecastUiState(+                                        forecast = decoded,+                                        airQuality = cachedAir,+                                        refreshing = false,+                                        fetchedAtEpochMs = cache.fetchedAtEpochMs,+                                    ))+                                }+                                haveFreshCache = (System.currentTimeMillis() - cache.fetchedAtEpochMs) < STALE_THRESHOLD_MS+                            }+                    }+                }++                if (!force && haveFreshCache) return@launch++                val target = if (location.isCurrent) refreshDeviceLocationFix(location) else location++                _forecasts.update { current ->+                    val prev = current[location.id]+                    current + (location.id to (prev?.copy(refreshing = true) ?: ForecastUiState(refreshing = true)))+                }++                data class FetchResult(val forecast: kotlin.Result<ForecastResponse>, val air: AirQualityResponse?)+                val fetched: FetchResult = coroutineScope {+                    val forecastDeferred = async { runCatching { WeatherApi.forecast(target.latitude, target.longitude) } }+                    val airQualityDeferred = async { runCatching { WeatherApi.airQuality(target.latitude, target.longitude) }.getOrNull() }+                    FetchResult(forecastDeferred.await(), airQualityDeferred.await())+                }+                val forecastResult = fetched.forecast+                val airQuality = fetched.air++                forecastResult+                    .onSuccess { fresh ->+                        val now = System.currentTimeMillis()+                        val resolvedAir = airQuality ?: _forecasts.value[location.id]?.airQuality+                        repository.writeForecastCache(target.latitude, target.longitude, fresh, resolvedAir, now)+                        _forecasts.update { current ->+                            current + (location.id to ForecastUiState(+                                forecast = fresh,+                                airQuality = resolvedAir,+                                refreshing = false,+                                error = null,+                                fetchedAtEpochMs = now,+                            ))+                        }+                        runCatching { WeatherGlanceWidget().updateAll(getApplication<Application>()) }+                    }+                    .onFailure { e ->+                        _forecasts.update { current ->+                            val prev = current[location.id]+                            current + (location.id to (prev?.copy(+                                airQuality = airQuality ?: prev.airQuality,+                                refreshing = false,+                                error = e.message ?: "Failed to load forecast",+                            ) ?: ForecastUiState(+                                airQuality = airQuality,+                                refreshing = false,+                                error = e.message,+                            )))+                        }+                    }+            } finally {+                synchronized(inFlight) { inFlight.remove(location.id) }+            }+        }+    }++    override fun refreshAll(force: Boolean) {+        for (location in savedLocations.value.orEmpty()) {+            ensureForecast(location, force)+        }+    }++    override fun deleteLocation(location: SavedLocation) {+        viewModelScope.launch {+            repository.deleteLocation(location)+            _forecasts.update { it - location.id }+        }+    }++    override fun reorderLocations(ordered: List<SavedLocation>) {+        viewModelScope.launch {+            ordered.forEachIndexed { index, loc ->+                if (loc.displayOrder != index) repository.setOrder(loc.id, index)+            }+        }+    }++    fun addLocation(name: String, country: String, latitude: Double, longitude: Double) {+        viewModelScope.launch {+            val existing = repository.getLocations()+            repository.insertLocation(+                SavedLocation(+                    name = name,+                    country = country,+                    latitude = latitude,+                    longitude = longitude,+                    displayOrder = existing.size,+                    isCurrent = false,+                )+            )+        }+    }++    fun setCurrentLocation(name: String, latitude: Double, longitude: Double) {+        viewModelScope.launch {+            val app = getApplication<Application>()+            val defaultName = app.getString(R.string.current_location)+            repository.replaceCurrentDeviceLocation(+                SavedLocation(+                    name = name.ifBlank { defaultName },+                    country = "",+                    latitude = latitude,+                    longitude = longitude,+                    displayOrder = -1,+                    isCurrent = true,+                )+            )+        }+    }++    private suspend fun refreshDeviceLocationFix(location: SavedLocation): SavedLocation {+        val context = getApplication<Application>()+        if (!LocationProvider.hasPermission(context)) return location+        val fix = withTimeoutOrNull(LOCATION_FIX_TIMEOUT_MS) { LocationProvider.currentLocation(context) } ?: return location+        val distance = FloatArray(1)+        android.location.Location.distanceBetween(location.latitude, location.longitude, fix.latitude, fix.longitude, distance)+        if (distance[0] < MIN_LOCATION_MOVE_METERS) return location+        repository.updateCoordinates(location.id, fix.latitude, fix.longitude)+        return location.copy(latitude = fix.latitude, longitude = fix.longitude)+    }++    companion object {+        const val STALE_THRESHOLD_MS = 15 * 60 * 1000L+        private const val LOCATION_FIX_TIMEOUT_MS = 8_000L+        private const val MIN_LOCATION_MOVE_METERS = 500f+    }+}++class WeatherViewModelFactory(+    private val application: Application,+    private val repository: WeatherRepository,+) : ViewModelProvider.Factory {+    @Suppress("UNCHECKED_CAST")+    override fun <T : ViewModel> create(modelClass: Class<T>): T {+        return WeatherViewModel(application, repository) as T+    }+}\ No newline at end of file
weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.ktindex 5907e1c0e9..08f6f56554 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt@@ -1,420 +1,420 @@-package com.vayunmathur.weather.ui--import androidx.activity.compose.BackHandler-import androidx.compose.animation.AnimatedVisibility-import androidx.compose.animation.expandVertically-import androidx.compose.animation.fadeIn-import androidx.compose.animation.fadeOut-import androidx.compose.animation.shrinkVertically-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.DrawerState-import com.vayunmathur.library.ui.DrawerValue-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.ModalDrawerSheet-import com.vayunmathur.library.ui.ModalNavigationDrawer-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.PullToRefreshBox-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar-import com.vayunmathur.library.ui.rememberDrawerState-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue-import androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.dp-import androidx.lifecycle.Lifecycle-import androidx.lifecycle.compose.LocalLifecycleOwner-import androidx.lifecycle.repeatOnLifecycle-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.weather.R-import com.vayunmathur.weather.Route-import com.vayunmathur.weather.ui.components.CurrentWeatherCard-import com.vayunmathur.weather.ui.components.DailyCard-import com.vayunmathur.weather.ui.components.HourlyCard-import com.vayunmathur.weather.ui.components.MainSearchBar-import com.vayunmathur.weather.ui.components.MetricGraphSheet-import com.vayunmathur.weather.ui.components.SelectedDateTimeHeader-import com.vayunmathur.weather.ui.components.SummaryCard-import com.vayunmathur.weather.ui.components.WeatherBlocks-import com.vayunmathur.weather.domain.DisplayUnits-import com.vayunmathur.weather.domain.LocationUiState-import com.vayunmathur.weather.domain.SelectedDateOrTime-import com.vayunmathur.weather.domain.WeatherMetric-import com.vayunmathur.weather.domain.formatHourAxisLabel-import com.vayunmathur.weather.domain.metricSeries-import com.vayunmathur.weather.domain.metricValueFormatter-import com.vayunmathur.weather.domain.parseLocalIsoToEpochSec-import com.vayunmathur.weather.domain.resolveConditions-import com.vayunmathur.weather.platform.WeatherActions-import com.vayunmathur.weather.platform.WeatherViewModel-import com.vayunmathur.weather.platform.precipitationNowcast-import com.vayunmathur.weather.platform.rememberDisplayUnits-import kotlinx.coroutines.delay-import kotlinx.coroutines.launch--/** Binds [WeatherViewModel] and the back stack to the stateless [HomeScreen]. */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun HomePage(backStack: NavBackStack<Route>, viewModel: WeatherViewModel) {-    val locations = viewModel.savedLocations.collectAsState().value--    if (locations == null) {-        // Room hasn't answered yet. Hold a plain surface rather than falling-        // through to EmptyHome, which would flash the location chooser on-        // every cold start before the saved rows arrive.-        Scaffold(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh) {}-        return-    }--    if (locations.isEmpty()) {-        EmptyHome(-            viewModel = viewModel,-            onAddLocation = { backStack.add(Route.SearchLocation) },-        )-        return-    }--    var activeLocationId by remember { mutableStateOf(locations.first().id) }-    val activeLocation = locations.firstOrNull { it.id == activeLocationId } ?: locations.first()--    val forecasts by viewModel.forecasts.collectAsState()-    val selected by viewModel.selectedDateOrTime.collectAsState()-    val forecastState = forecasts[activeLocation.id]-    val forecast = forecastState?.forecast--    val lifecycleOwner = LocalLifecycleOwner.current-    LaunchedEffect(activeLocation.id, lifecycleOwner) {-        // Only poll while the app is actually in the foreground; repeatOnLifecycle-        // cancels the loop when the app is backgrounded and restarts it on resume,-        // so we don't hit the network every 60s behind the user's back (the hourly-        // WorkManager job covers background refreshes).-        lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {-            while (true) {-                viewModel.refreshAll()-                delay(60_000)-            }-        }-    }--    // "Rain in ~30 min" needs both the wall clock and the string table, so it is-    // resolved here rather than inside the screen — see WeatherUiContract.-    val context = LocalContext.current-    val nowcast = if (selected == null && forecast != null) {-        precipitationNowcast(context, forecast.minutely15, forecast.utcOffsetSeconds)-    } else {-        null-    }--    val drawerState = rememberDrawerState(DrawerValue.Closed)-    val scope = rememberCoroutineScope()-    val closeDrawer = { scope.launch { drawerState.close() } }--    HomeScreen(-        state = LocationUiState(-            location = activeLocation,-            forecast = forecast,-            airQuality = forecastState?.airQuality?.current,-            refreshing = forecastState?.refreshing == true,-            error = forecastState?.error,-            selected = selected,-        ),-        units = rememberDisplayUnits(),-        actions = viewModel,-        drawerState = drawerState,-        precipitationNowcast = nowcast,-        onOpenMap = { metric, isoTime ->-            backStack.add(-                Route.WeatherMap(-                    latitude = activeLocation.latitude,-                    longitude = activeLocation.longitude,-                    name = activeLocation.name,-                    isoTime = isoTime,-                    metric = metric.name,-                )-            )-        },-        drawerContent = {-            LocationsPage(-                backStack = backStack,-                viewModel = viewModel,-                activeLocation = activeLocation,-                onLocationSelect = { picked ->-                    activeLocationId = picked.id-                    viewModel.clearSelection()-                    closeDrawer()-                },-                onClose = { closeDrawer() },-            )-        },-    )-}--/**- * The forecast page, with no dependency on the ViewModel, the back stack or the clock so it- * can be rendered from a `@Preview` — see `src/screenshotTest`, which is where the store- * listing images come from.- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun HomeScreen(-    state: LocationUiState,-    units: DisplayUnits,-    actions: WeatherActions,-    drawerState: DrawerState = rememberDrawerState(DrawerValue.Closed),-    /** Short-range rain outlook; reads a clock, so the binder resolves it. */-    precipitationNowcast: String? = null,-    /**-     * "Now" for the hourly strip and the sun arc. A parameter rather than a clock read so a-     * preview's fixed sample data can't age out from under it.-     */-    nowEpochSec: Long = System.currentTimeMillis() / 1000,-    onOpenMap: (WeatherMetric, String?) -> Unit = { _, _ -> },-    /** The locations drawer. Empty in a preview, which has no saved-location list. */-    drawerContent: @Composable () -> Unit = {},-) {-    val scope = rememberCoroutineScope()-    BackHandler(enabled = drawerState.isOpen) { scope.launch { drawerState.close() } }--    ModalNavigationDrawer(-        drawerState = drawerState,-        drawerContent = {-            ModalDrawerSheet(-                drawerContainerColor = MaterialTheme.colorScheme.surfaceContainer,-            ) {-                drawerContent()-            }-        },-    ) {-        Scaffold(-            containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,-        ) { paddingValues ->-            ForecastColumn(-                state = state,-                units = units,-                actions = actions,-                drawerState = drawerState,-                paddingValues = paddingValues,-                precipitationNowcast = precipitationNowcast,-                nowEpochSec = nowEpochSec,-                onOpenMap = onOpenMap,-            )-        }-    }-}--@OptIn(ExperimentalMaterial3Api::class)-@Composable-private fun ForecastColumn(-    state: LocationUiState,-    units: DisplayUnits,-    actions: WeatherActions,-    drawerState: DrawerState,-    paddingValues: PaddingValues,-    precipitationNowcast: String?,-    nowEpochSec: Long,-    onOpenMap: (WeatherMetric, String?) -> Unit,-) {-    var graphMetric by remember { mutableStateOf<WeatherMetric?>(null) }--    val forecast = state.forecast-    val selected = state.selected-    val scrollState = rememberScrollState()--    PullToRefreshBox(-        isRefreshing = state.refreshing,-        onRefresh = { actions.refreshAll(force = true) },-        modifier = Modifier.fillMaxSize(),-    ) {-        Column(modifier = Modifier.fillMaxSize().verticalScroll(scrollState)) {-            MainSearchBar(-                paddingValues = paddingValues,-                drawerState = drawerState,-                activeLocation = state.location,-            )--            if (forecast == null) {-                Box(modifier = Modifier.fillMaxSize().padding(top = 64.dp), contentAlignment = Alignment.TopCenter) {-                    val error = state.error-                    if (error != null) {-                        Text(error, color = MaterialTheme.colorScheme.error)-                    } else {-                        CircularProgressIndicator()-                    }-                }-                return@Column-            }--            val current = forecast.current-            val daily = forecast.daily-            val resolved = resolveConditions(forecast, selected)--            var lastSelection by remember { mutableStateOf(selected) }-            LaunchedEffect(selected) { if (selected != null) lastSelection = selected }-            AnimatedVisibility(-                visible = selected != null,-                enter = expandVertically() + fadeIn(),-                exit = shrinkVertically() + fadeOut(),-            ) {-                (selected ?: lastSelection)?.let { sel ->-                    SelectedDateTimeHeader(-                        selection = sel,-                        forecast = forecast,-                        use24Hour = units.use24Hour,-                        onClear = { actions.clearSelection() },-                    )-                }-            }--            if (current != null && resolved != null) {-                CurrentWeatherCard(-                    weatherCode = resolved.weatherCode,-                    isDay = resolved.isDay,-                    temperature = resolved.temperature,-                    apparentTemperature = resolved.apparentTemperature,-                    high = resolved.high,-                    low = resolved.low,-                    tempUnit = units.temperature,-                )-            }-            Column(-                // Include the navigation-bar inset so the last cards (Air quality /-                // Pollen) clear the system nav bar and can scroll fully into view.-                modifier = Modifier.padding(-                    start = 16.dp,-                    end = 16.dp,-                    top = 24.dp,-                    bottom = paddingValues.calculateBottomPadding(),-                ),-                verticalArrangement = Arrangement.spacedBy(14.dp),-            ) {-                if (selected == null) {-                    SummaryCard(forecast = forecast, tempUnit = units.temperature)-                }-                if (forecast.hourly != null) {-                    HourlyCard(-                        hourly = forecast.hourly,-                        tempUnit = units.temperature,-                        utcOffsetSeconds = forecast.utcOffsetSeconds,-                        use24Hour = units.use24Hour,-                        selectedIsoTime = (selected as? SelectedDateOrTime.Time)?.isoTime,-                        onHourSelected = { actions.toggleTime(it) },-                        scrollToIsoDate = (selected as? SelectedDateOrTime.Day)?.isoDate,-                        nowEpochSec = nowEpochSec,-                    )-                }-                if (daily != null) {-                    DailyCard(-                        daily = daily,-                        tempUnit = units.temperature,-                        selectedIsoDate = (selected as? SelectedDateOrTime.Day)?.isoDate,-                        onDaySelected = { actions.toggleDay(it) },-                    )-                }-                if (current != null && resolved != null) {-                    val sunriseEpoch = resolved.sunriseIso?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }-                    val sunsetEpoch = resolved.sunsetIso?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }-                    val moonriseEpoch = resolved.moonriseIso?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }-                    val moonsetEpoch = resolved.moonsetIso?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }-                    WeatherBlocks(-                        current = resolved.blockCurrent,-                        uvIndex = resolved.uvIndexMax,-                        air = state.airQuality,-                        sunriseEpochSec = sunriseEpoch,-                        sunsetEpochSec = sunsetEpoch,-                        precipitationMm = resolved.precipitationSum,-                        precipitationNowcast = precipitationNowcast,-                        daylightDurationSec = resolved.daylightDurationSec,-                        moonPhase = resolved.moonPhase,-                        moonriseEpochSec = moonriseEpoch,-                        moonsetEpochSec = moonsetEpoch,-                        onMetricSelected = { graphMetric = it },-                        tempUnit = units.temperature,-                        windUnit = units.wind,-                        pressureUnit = units.pressure,-                        use24Hour = units.use24Hour,-                        nowEpochSec = nowEpochSec,-                    )-                }-            }-        }--        val gm = graphMetric-        if (gm != null && forecast != null) {-            MetricGraphSheet(-                title = stringResource(gm.title),-                points = metricSeries(forecast, gm, selected),-                valueLabel = metricValueFormatter(gm, units.temperature, units.wind, units.pressure),-                timeLabel = { epoch -> formatHourAxisLabel(epoch, units.use24Hour) },-                onOpenMap = {-                    val iso = when (val s = selected) {-                        is SelectedDateOrTime.Time -> s.isoTime-                        is SelectedDateOrTime.Day -> "${s.isoDate}T00:00"-                        null -> null-                    }-                    onOpenMap(gm, iso)-                    graphMetric = null-                },-                onDismiss = { graphMetric = null },-            )-        }-    }-}--/**- * Shown in place of the forecast when nothing is pinned yet. Stays on the ViewModel: it is- * an empty state, not a listing shot.- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-private fun EmptyHome(viewModel: WeatherViewModel, onAddLocation: () -> Unit) {-    val (onUseCurrent, requesting) = rememberRequestDeviceLocation(viewModel)--    Scaffold(topBar = { TopAppBar(title = { Text(stringResource(R.string.weather_title)) }) }) { padding ->-        Box(modifier = Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {-            Column(horizontalAlignment = Alignment.CenterHorizontally) {-                Text(stringResource(R.string.no_locations_yet), style = MaterialTheme.typography.titleMedium)-                Text(-                    stringResource(R.string.add_a_city_or_use_your_current_location),-                    style = MaterialTheme.typography.bodyMedium,-                    color = MaterialTheme.colorScheme.onSurfaceVariant,-                    modifier = Modifier.padding(horizontal = 32.dp, vertical = 8.dp),-                )-                Button(onClick = onAddLocation) { Text(stringResource(R.string.add_location)) }-                Spacer(Modifier.height(8.dp))-                OutlinedButton(-                    onClick = { onUseCurrent() },-                    enabled = !requesting,-                ) {-                    if (requesting) {-                        CircularProgressIndicator(-                            modifier = Modifier.padding(end = 8.dp),-                            strokeWidth = 2.dp,-                        )-                    }-                    Text(if (requesting) stringResource(R.string.locating) else stringResource(R.string.use_current_location))-                }-            }-        }-    }-}+package com.vayunmathur.weather.ui++import androidx.activity.compose.BackHandler+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.expandVertically+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.shrinkVertically+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.DrawerState+import com.vayunmathur.library.ui.DrawerValue+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.ModalDrawerSheet+import com.vayunmathur.library.ui.ModalNavigationDrawer+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.PullToRefreshBox+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.rememberDrawerState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LocalLifecycleOwner+import androidx.lifecycle.repeatOnLifecycle+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.weather.R+import com.vayunmathur.weather.Route+import com.vayunmathur.weather.ui.components.CurrentWeatherCard+import com.vayunmathur.weather.ui.components.DailyCard+import com.vayunmathur.weather.ui.components.HourlyCard+import com.vayunmathur.weather.ui.components.MainSearchBar+import com.vayunmathur.weather.ui.components.MetricGraphSheet+import com.vayunmathur.weather.ui.components.SelectedDateTimeHeader+import com.vayunmathur.weather.ui.components.SummaryCard+import com.vayunmathur.weather.ui.components.WeatherBlocks+import com.vayunmathur.weather.platform.DisplayUnits+import com.vayunmathur.weather.platform.LocationUiState+import com.vayunmathur.weather.domain.SelectedDateOrTime+import com.vayunmathur.weather.domain.WeatherMetric+import com.vayunmathur.weather.domain.formatHourAxisLabel+import com.vayunmathur.weather.domain.metricSeries+import com.vayunmathur.weather.domain.metricValueFormatter+import com.vayunmathur.weather.domain.parseLocalIsoToEpochSec+import com.vayunmathur.weather.domain.resolveConditions+import com.vayunmathur.weather.platform.WeatherActions+import com.vayunmathur.weather.platform.WeatherViewModel+import com.vayunmathur.weather.platform.precipitationNowcast+import com.vayunmathur.weather.platform.rememberDisplayUnits+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++/** Binds [WeatherViewModel] and the back stack to the stateless [HomeScreen]. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun HomePage(backStack: NavBackStack<Route>, viewModel: WeatherViewModel) {+    val locations = viewModel.savedLocations.collectAsState().value++    if (locations == null) {+        // Room hasn't answered yet. Hold a plain surface rather than falling+        // through to EmptyHome, which would flash the location chooser on+        // every cold start before the saved rows arrive.+        Scaffold(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh) {}+        return+    }++    if (locations.isEmpty()) {+        EmptyHome(+            viewModel = viewModel,+            onAddLocation = { backStack.add(Route.SearchLocation) },+        )+        return+    }++    var activeLocationId by remember { mutableStateOf(locations.first().id) }+    val activeLocation = locations.firstOrNull { it.id == activeLocationId } ?: locations.first()++    val forecasts by viewModel.forecasts.collectAsState()+    val selected by viewModel.selectedDateOrTime.collectAsState()+    val forecastState = forecasts[activeLocation.id]+    val forecast = forecastState?.forecast++    val lifecycleOwner = LocalLifecycleOwner.current+    LaunchedEffect(activeLocation.id, lifecycleOwner) {+        // Only poll while the app is actually in the foreground; repeatOnLifecycle+        // cancels the loop when the app is backgrounded and restarts it on resume,+        // so we don't hit the network every 60s behind the user's back (the hourly+        // WorkManager job covers background refreshes).+        lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {+            while (true) {+                viewModel.refreshAll()+                delay(60_000)+            }+        }+    }++    // "Rain in ~30 min" needs both the wall clock and the string table, so it is+    // resolved here rather than inside the screen — see WeatherUiContract.+    val context = LocalContext.current+    val nowcast = if (selected == null && forecast != null) {+        precipitationNowcast(context, forecast.minutely15, forecast.utcOffsetSeconds)+    } else {+        null+    }++    val drawerState = rememberDrawerState(DrawerValue.Closed)+    val scope = rememberCoroutineScope()+    val closeDrawer = { scope.launch { drawerState.close() } }++    HomeScreen(+        state = LocationUiState(+            location = activeLocation,+            forecast = forecast,+            airQuality = forecastState?.airQuality?.current,+            refreshing = forecastState?.refreshing == true,+            error = forecastState?.error,+            selected = selected,+        ),+        units = rememberDisplayUnits(),+        actions = viewModel,+        drawerState = drawerState,+        precipitationNowcast = nowcast,+        onOpenMap = { metric, isoTime ->+            backStack.add(+                Route.WeatherMap(+                    latitude = activeLocation.latitude,+                    longitude = activeLocation.longitude,+                    name = activeLocation.name,+                    isoTime = isoTime,+                    metric = metric.name,+                )+            )+        },+        drawerContent = {+            LocationsPage(+                backStack = backStack,+                viewModel = viewModel,+                activeLocation = activeLocation,+                onLocationSelect = { picked ->+                    activeLocationId = picked.id+                    viewModel.clearSelection()+                    closeDrawer()+                },+                onClose = { closeDrawer() },+            )+        },+    )+}++/**+ * The forecast page, with no dependency on the ViewModel, the back stack or the clock so it+ * can be rendered from a `@Preview` — see `src/screenshotTest`, which is where the store+ * listing images come from.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun HomeScreen(+    state: LocationUiState,+    units: DisplayUnits,+    actions: WeatherActions,+    drawerState: DrawerState = rememberDrawerState(DrawerValue.Closed),+    /** Short-range rain outlook; reads a clock, so the binder resolves it. */+    precipitationNowcast: String? = null,+    /**+     * "Now" for the hourly strip and the sun arc. A parameter rather than a clock read so a+     * preview's fixed sample data can't age out from under it.+     */+    nowEpochSec: Long = System.currentTimeMillis() / 1000,+    onOpenMap: (WeatherMetric, String?) -> Unit = { _, _ -> },+    /** The locations drawer. Empty in a preview, which has no saved-location list. */+    drawerContent: @Composable () -> Unit = {},+) {+    val scope = rememberCoroutineScope()+    BackHandler(enabled = drawerState.isOpen) { scope.launch { drawerState.close() } }++    ModalNavigationDrawer(+        drawerState = drawerState,+        drawerContent = {+            ModalDrawerSheet(+                drawerContainerColor = MaterialTheme.colorScheme.surfaceContainer,+            ) {+                drawerContent()+            }+        },+    ) {+        Scaffold(+            containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,+        ) { paddingValues ->+            ForecastColumn(+                state = state,+                units = units,+                actions = actions,+                drawerState = drawerState,+                paddingValues = paddingValues,+                precipitationNowcast = precipitationNowcast,+                nowEpochSec = nowEpochSec,+                onOpenMap = onOpenMap,+            )+        }+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun ForecastColumn(+    state: LocationUiState,+    units: DisplayUnits,+    actions: WeatherActions,+    drawerState: DrawerState,+    paddingValues: PaddingValues,+    precipitationNowcast: String?,+    nowEpochSec: Long,+    onOpenMap: (WeatherMetric, String?) -> Unit,+) {+    var graphMetric by remember { mutableStateOf<WeatherMetric?>(null) }++    val forecast = state.forecast+    val selected = state.selected+    val scrollState = rememberScrollState()++    PullToRefreshBox(+        isRefreshing = state.refreshing,+        onRefresh = { actions.refreshAll(force = true) },+        modifier = Modifier.fillMaxSize(),+    ) {+        Column(modifier = Modifier.fillMaxSize().verticalScroll(scrollState)) {+            MainSearchBar(+                paddingValues = paddingValues,+                drawerState = drawerState,+                activeLocation = state.location,+            )++            if (forecast == null) {+                Box(modifier = Modifier.fillMaxSize().padding(top = 64.dp), contentAlignment = Alignment.TopCenter) {+                    val error = state.error+                    if (error != null) {+                        Text(error, color = MaterialTheme.colorScheme.error)+                    } else {+                        CircularProgressIndicator()+                    }+                }+                return@Column+            }++            val current = forecast.current+            val daily = forecast.daily+            val resolved = resolveConditions(forecast, selected)++            var lastSelection by remember { mutableStateOf(selected) }+            LaunchedEffect(selected) { if (selected != null) lastSelection = selected }+            AnimatedVisibility(+                visible = selected != null,+                enter = expandVertically() + fadeIn(),+                exit = shrinkVertically() + fadeOut(),+            ) {+                (selected ?: lastSelection)?.let { sel ->+                    SelectedDateTimeHeader(+                        selection = sel,+                        forecast = forecast,+                        use24Hour = units.use24Hour,+                        onClear = { actions.clearSelection() },+                    )+                }+            }++            if (current != null && resolved != null) {+                CurrentWeatherCard(+                    weatherCode = resolved.weatherCode,+                    isDay = resolved.isDay,+                    temperature = resolved.temperature,+                    apparentTemperature = resolved.apparentTemperature,+                    high = resolved.high,+                    low = resolved.low,+                    tempUnit = units.temperature,+                )+            }+            Column(+                // Include the navigation-bar inset so the last cards (Air quality /+                // Pollen) clear the system nav bar and can scroll fully into view.+                modifier = Modifier.padding(+                    start = 16.dp,+                    end = 16.dp,+                    top = 24.dp,+                    bottom = paddingValues.calculateBottomPadding(),+                ),+                verticalArrangement = Arrangement.spacedBy(14.dp),+            ) {+                if (selected == null) {+                    SummaryCard(forecast = forecast, tempUnit = units.temperature)+                }+                if (forecast.hourly != null) {+                    HourlyCard(+                        hourly = forecast.hourly,+                        tempUnit = units.temperature,+                        utcOffsetSeconds = forecast.utcOffsetSeconds,+                        use24Hour = units.use24Hour,+                        selectedIsoTime = (selected as? SelectedDateOrTime.Time)?.isoTime,+                        onHourSelected = { actions.toggleTime(it) },+                        scrollToIsoDate = (selected as? SelectedDateOrTime.Day)?.isoDate,+                        nowEpochSec = nowEpochSec,+                    )+                }+                if (daily != null) {+                    DailyCard(+                        daily = daily,+                        tempUnit = units.temperature,+                        selectedIsoDate = (selected as? SelectedDateOrTime.Day)?.isoDate,+                        onDaySelected = { actions.toggleDay(it) },+                    )+                }+                if (current != null && resolved != null) {+                    val sunriseEpoch = resolved.sunriseIso?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }+                    val sunsetEpoch = resolved.sunsetIso?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }+                    val moonriseEpoch = resolved.moonriseIso?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }+                    val moonsetEpoch = resolved.moonsetIso?.let { parseLocalIsoToEpochSec(it, forecast.utcOffsetSeconds) }+                    WeatherBlocks(+                        current = resolved.blockCurrent,+                        uvIndex = resolved.uvIndexMax,+                        air = state.airQuality,+                        sunriseEpochSec = sunriseEpoch,+                        sunsetEpochSec = sunsetEpoch,+                        precipitationMm = resolved.precipitationSum,+                        precipitationNowcast = precipitationNowcast,+                        daylightDurationSec = resolved.daylightDurationSec,+                        moonPhase = resolved.moonPhase,+                        moonriseEpochSec = moonriseEpoch,+                        moonsetEpochSec = moonsetEpoch,+                        onMetricSelected = { graphMetric = it },+                        tempUnit = units.temperature,+                        windUnit = units.wind,+                        pressureUnit = units.pressure,+                        use24Hour = units.use24Hour,+                        nowEpochSec = nowEpochSec,+                    )+                }+            }+        }++        val gm = graphMetric+        if (gm != null && forecast != null) {+            MetricGraphSheet(+                title = stringResource(gm.title),+                points = metricSeries(forecast, gm, selected),+                valueLabel = metricValueFormatter(gm, units.temperature, units.wind, units.pressure),+                timeLabel = { epoch -> formatHourAxisLabel(epoch, units.use24Hour) },+                onOpenMap = {+                    val iso = when (val s = selected) {+                        is SelectedDateOrTime.Time -> s.isoTime+                        is SelectedDateOrTime.Day -> "${s.isoDate}T00:00"+                        null -> null+                    }+                    onOpenMap(gm, iso)+                    graphMetric = null+                },+                onDismiss = { graphMetric = null },+            )+        }+    }+}++/**+ * Shown in place of the forecast when nothing is pinned yet. Stays on the ViewModel: it is+ * an empty state, not a listing shot.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun EmptyHome(viewModel: WeatherViewModel, onAddLocation: () -> Unit) {+    val (onUseCurrent, requesting) = rememberRequestDeviceLocation(viewModel)++    Scaffold(topBar = { TopAppBar(title = { Text(stringResource(R.string.weather_title)) }) }) { padding ->+        Box(modifier = Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {+            Column(horizontalAlignment = Alignment.CenterHorizontally) {+                Text(stringResource(R.string.no_locations_yet), style = MaterialTheme.typography.titleMedium)+                Text(+                    stringResource(R.string.add_a_city_or_use_your_current_location),+                    style = MaterialTheme.typography.bodyMedium,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                    modifier = Modifier.padding(horizontal = 32.dp, vertical = 8.dp),+                )+                Button(onClick = onAddLocation) { Text(stringResource(R.string.add_location)) }+                Spacer(Modifier.height(8.dp))+                OutlinedButton(+                    onClick = { onUseCurrent() },+                    enabled = !requesting,+                ) {+                    if (requesting) {+                        CircularProgressIndicator(+                            modifier = Modifier.padding(end = 8.dp),+                            strokeWidth = 2.dp,+                        )+                    }+                    Text(if (requesting) stringResource(R.string.locating) else stringResource(R.string.use_current_location))+                }+            }+        }+    }+}
weather/src/main/java/com/vayunmathur/weather/ui/components/CurrentWeatherCard.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/CurrentWeatherCard.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/CurrentWeatherCard.ktindex 0910945371..513c1743e8 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/CurrentWeatherCard.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/CurrentWeatherCard.kt@@ -17,9 +17,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp-import com.vayunmathur.weather.util.TemperatureUnit-import com.vayunmathur.weather.util.formatTemperatureCompact-import com.vayunmathur.weather.util.weatherConditionForCode+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.formatTemperatureCompact+import com.vayunmathur.weather.domain.weatherConditionForCode import androidx.compose.ui.res.stringResource import com.vayunmathur.weather.R 
weather/src/main/java/com/vayunmathur/weather/ui/components/DailyCard.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/DailyCard.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/DailyCard.ktindex 72092db3e9..222619e7e6 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/DailyCard.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/DailyCard.kt@@ -27,9 +27,9 @@ import androidx.compose.ui.res.stringResource import com.vayunmathur.library.util.localizedDayOfWeekNames import com.vayunmathur.weather.R import com.vayunmathur.weather.network.Daily-import com.vayunmathur.weather.util.TemperatureUnit-import com.vayunmathur.weather.util.formatTemperatureCompact-import com.vayunmathur.weather.util.weatherConditionForCode+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.formatTemperatureCompact+import com.vayunmathur.weather.domain.weatherConditionForCode import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate 
weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.ktindex 08b1910183..39c697fbfe 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.kt@@ -36,11 +36,11 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.res.stringResource import com.vayunmathur.weather.R import com.vayunmathur.weather.network.Hourly-import com.vayunmathur.weather.util.TemperatureUnit-import com.vayunmathur.weather.util.formatStripHour-import com.vayunmathur.weather.util.formatTemperatureCompact-import com.vayunmathur.weather.util.parseLocalIsoToEpochSec-import com.vayunmathur.weather.util.weatherConditionForCode+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.formatStripHour+import com.vayunmathur.weather.domain.formatTemperatureCompact+import com.vayunmathur.weather.domain.parseLocalIsoToEpochSec+import com.vayunmathur.weather.domain.weatherConditionForCode import androidx.compose.ui.unit.sp import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.TimeZone
weather/src/main/java/com/vayunmathur/weather/ui/components/LocationItem.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/LocationItem.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/LocationItem.ktindex 961a207ca5..bb489b0048 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/LocationItem.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/LocationItem.kt@@ -23,8 +23,8 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.vayunmathur.weather.R import com.vayunmathur.weather.data.SavedLocation-import com.vayunmathur.weather.util.WeatherCondition-import com.vayunmathur.weather.util.weatherConditionForCode+import com.vayunmathur.weather.domain.WeatherCondition+import com.vayunmathur.weather.domain.weatherConditionForCode  /**  * Direct port of WeatherMaster's `LocationItem`. Pill or extraLarge
weather/src/main/java/com/vayunmathur/weather/ui/components/MetricGraphSheet.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/MetricGraphSheet.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/MetricGraphSheet.ktindex 5826ec42d4..5a6d15d0ba 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/MetricGraphSheet.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/MetricGraphSheet.kt@@ -41,7 +41,7 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.weather.R-import com.vayunmathur.weather.util.MetricPoint+import com.vayunmathur.weather.domain.MetricPoint import kotlin.math.roundToInt  /**
weather/src/main/java/com/vayunmathur/weather/ui/components/SelectedHeader.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/SelectedHeader.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/SelectedHeader.ktindex 30bd3658cf..5a1f6c3b1d 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/SelectedHeader.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/SelectedHeader.kt@@ -14,9 +14,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.vayunmathur.weather.network.ForecastResponse-import com.vayunmathur.weather.util.SelectedDateOrTime-import com.vayunmathur.weather.util.formatDayMonthLabel-import com.vayunmathur.weather.util.formatSelectedHourLabel+import com.vayunmathur.weather.domain.SelectedDateOrTime+import com.vayunmathur.weather.domain.formatDayMonthLabel+import com.vayunmathur.weather.domain.formatSelectedHourLabel  /**  * Prominent banner shown at the top of the page when the user is inspecting a
weather/src/main/java/com/vayunmathur/weather/ui/components/SummaryCard.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/SummaryCard.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/SummaryCard.ktindex 9692547ff8..379eb3b4d5 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/SummaryCard.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/SummaryCard.kt@@ -16,8 +16,8 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.weather.R import com.vayunmathur.weather.network.ForecastResponse-import com.vayunmathur.weather.util.TemperatureUnit-import com.vayunmathur.weather.util.computeDaySummary+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.platform.computeDaySummary  /**  * Port of WeatherMaster's `SummaryCard`. `Surface(shape = extraLarge,
weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.ktindex 465d1500cd..191ee06382 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherBlocks.kt@@ -26,10 +26,10 @@ import com.vayunmathur.weather.ui.components.blocks.SunBlock import com.vayunmathur.weather.ui.components.blocks.UvIndexBlock import com.vayunmathur.weather.ui.components.blocks.VisibilityBlock import com.vayunmathur.weather.ui.components.blocks.WindBlock-import com.vayunmathur.weather.util.TemperatureUnit-import com.vayunmathur.weather.util.PressureUnit-import com.vayunmathur.weather.util.WeatherMetric-import com.vayunmathur.weather.util.WindUnit+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.PressureUnit+import com.vayunmathur.weather.domain.WeatherMetric+import com.vayunmathur.weather.domain.WindUnit  /**  * Port of WeatherMaster's `WeatherBlocks` grid (simplified): adaptive 140 dp
weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherIconBox.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherIconBox.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherIconBox.ktindex 6a49c51a64..5870d89b92 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherIconBox.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/WeatherIconBox.kt@@ -9,7 +9,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.Icon import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.weather.util.WeatherCondition+import com.vayunmathur.weather.domain.WeatherCondition  /**  * Reusable weather-icon renderer. Same role as WeatherMaster's
weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/HumidityBlock.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/HumidityBlock.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/HumidityBlock.ktindex f6ef5929c2..6ceb9da17a 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/HumidityBlock.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/HumidityBlock.kt@@ -20,8 +20,8 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.vayunmathur.weather.R import com.vayunmathur.weather.network.Current-import com.vayunmathur.weather.util.TemperatureUnit-import com.vayunmathur.weather.util.formatTemperatureCompact+import com.vayunmathur.weather.domain.TemperatureUnit+import com.vayunmathur.weather.domain.formatTemperatureCompact import androidx.compose.ui.res.stringResource  /**
weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/MoonBlock.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/MoonBlock.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/MoonBlock.ktindex a225ba8282..cf7eb5826b 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/MoonBlock.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/MoonBlock.kt@@ -29,7 +29,7 @@ import com.vayunmathur.library.ui.IconKeyboardArrowUp import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface import com.vayunmathur.weather.R-import com.vayunmathur.weather.util.formatClockTime+import com.vayunmathur.weather.domain.formatClockTime import kotlin.math.PI import kotlin.math.abs import kotlin.math.cos
weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PrecipitationBlock.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PrecipitationBlock.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PrecipitationBlock.ktindex b17cbe345d..7ad96e8654 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PrecipitationBlock.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PrecipitationBlock.kt@@ -16,7 +16,7 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.res.stringResource import com.vayunmathur.weather.R-import com.vayunmathur.weather.util.mmToInches+import com.vayunmathur.weather.domain.mmToInches import java.util.Locale  /**
weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PressureBlock.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PressureBlock.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PressureBlock.ktindex 8c6dce6037..4d66fbacc2 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PressureBlock.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/PressureBlock.kt@@ -15,8 +15,8 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.res.stringResource import com.vayunmathur.weather.R import com.vayunmathur.weather.network.Current-import com.vayunmathur.weather.util.PressureUnit-import com.vayunmathur.weather.util.hpaToInHg+import com.vayunmathur.weather.domain.PressureUnit+import com.vayunmathur.weather.domain.hpaToInHg import java.util.Locale  /**
weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/SunBlock.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/SunBlock.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/SunBlock.ktindex 1a768e84c0..ce524939c6 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/SunBlock.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/SunBlock.kt@@ -22,7 +22,7 @@ import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.unit.dp import androidx.compose.ui.res.stringResource import com.vayunmathur.weather.R-import com.vayunmathur.weather.util.formatClockTime+import com.vayunmathur.weather.domain.formatClockTime import kotlin.math.cos import kotlin.math.sin 
weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/VisibilityBlock.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/VisibilityBlock.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/VisibilityBlock.ktindex f64050865f..672a859355 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/VisibilityBlock.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/VisibilityBlock.kt@@ -15,7 +15,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.res.stringResource import com.vayunmathur.weather.R import com.vayunmathur.weather.network.Current-import com.vayunmathur.weather.util.metersToMiles+import com.vayunmathur.weather.domain.metersToMiles import kotlin.math.roundToInt  /**
weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/WindBlock.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/WindBlock.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/WindBlock.ktindex 5d770712c4..b177689883 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/WindBlock.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/blocks/WindBlock.kt@@ -22,9 +22,9 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.vayunmathur.weather.R import com.vayunmathur.weather.network.Current-import com.vayunmathur.weather.util.WindUnit-import com.vayunmathur.weather.util.compassDirection-import com.vayunmathur.weather.util.formatWind+import com.vayunmathur.weather.domain.WindUnit+import com.vayunmathur.weather.domain.compassDirection+import com.vayunmathur.weather.domain.formatWind import androidx.compose.ui.res.stringResource  /**