wevva 0.4.2__tar.gz → 0.4.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. {wevva-0.4.2 → wevva-0.4.3}/PKG-INFO +2 -2
  2. {wevva-0.4.2 → wevva-0.4.3}/pyproject.toml +2 -2
  3. {wevva-0.4.2 → wevva-0.4.3}/wevva/app.py +102 -15
  4. {wevva-0.4.2 → wevva-0.4.3}/wevva/messages.py +10 -0
  5. {wevva-0.4.2 → wevva-0.4.3}/wevva/screens/weather_screen.py +6 -0
  6. wevva-0.4.3/wevva/services/alerts.py +211 -0
  7. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/saved_locations.py +77 -18
  8. wevva-0.4.2/wevva/services/alerts.py +0 -113
  9. {wevva-0.4.2 → wevva-0.4.3}/.gitignore +0 -0
  10. {wevva-0.4.2 → wevva-0.4.3}/LICENSE +0 -0
  11. {wevva-0.4.2 → wevva-0.4.3}/README.md +0 -0
  12. {wevva-0.4.2 → wevva-0.4.3}/wevva/__init__.py +0 -0
  13. {wevva-0.4.2 → wevva-0.4.3}/wevva/__main__.py +0 -0
  14. {wevva-0.4.2 → wevva-0.4.3}/wevva/alerts.py +0 -0
  15. {wevva-0.4.2 → wevva-0.4.3}/wevva/api.py +0 -0
  16. {wevva-0.4.2 → wevva-0.4.3}/wevva/cli.py +0 -0
  17. {wevva-0.4.2 → wevva-0.4.3}/wevva/conditions.py +0 -0
  18. {wevva-0.4.2 → wevva-0.4.3}/wevva/config.py +0 -0
  19. {wevva-0.4.2 → wevva-0.4.3}/wevva/constants.py +0 -0
  20. {wevva-0.4.2 → wevva-0.4.3}/wevva/controller.py +0 -0
  21. {wevva-0.4.2 → wevva-0.4.3}/wevva/location_metadata.py +0 -0
  22. {wevva-0.4.2 → wevva-0.4.3}/wevva/models.py +0 -0
  23. {wevva-0.4.2 → wevva-0.4.3}/wevva/openmeteo.py +0 -0
  24. {wevva-0.4.2 → wevva-0.4.3}/wevva/screens/air_quality_help.py +0 -0
  25. {wevva-0.4.2 → wevva-0.4.3}/wevva/screens/author_screen.py +0 -0
  26. {wevva-0.4.2 → wevva-0.4.3}/wevva/screens/help.py +0 -0
  27. {wevva-0.4.2 → wevva-0.4.3}/wevva/screens/search_screen.py +0 -0
  28. {wevva-0.4.2 → wevva-0.4.3}/wevva/screens/settings_screen.py +0 -0
  29. {wevva-0.4.2 → wevva-0.4.3}/wevva/services/air_quality.py +0 -0
  30. {wevva-0.4.2 → wevva-0.4.3}/wevva/services/geocoding.py +0 -0
  31. {wevva-0.4.2 → wevva-0.4.3}/wevva/services/weather.py +0 -0
  32. {wevva-0.4.2 → wevva-0.4.3}/wevva/utils/__init__.py +0 -0
  33. {wevva-0.4.2 → wevva-0.4.3}/wevva/utils/colors.py +0 -0
  34. {wevva-0.4.2 → wevva-0.4.3}/wevva/utils/country_codes.py +0 -0
  35. {wevva-0.4.2 → wevva-0.4.3}/wevva/utils/formatting.py +0 -0
  36. {wevva-0.4.2 → wevva-0.4.3}/wevva/utils/geo.py +0 -0
  37. {wevva-0.4.2 → wevva-0.4.3}/wevva/utils/visualization.py +0 -0
  38. {wevva-0.4.2 → wevva-0.4.3}/wevva/wevva.tcss +0 -0
  39. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/air_quality.py +0 -0
  40. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/astronomy_info.py +0 -0
  41. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/context_bar.py +0 -0
  42. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/current_conditions.py +0 -0
  43. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/current_detail.py +0 -0
  44. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/daily_forecast.py +0 -0
  45. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/daily_summary.py +0 -0
  46. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/hourly_forecast.py +0 -0
  47. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/location_info.py +0 -0
  48. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/precip_info.py +0 -0
  49. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/search_dialog.py +0 -0
  50. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/search_results.py +0 -0
  51. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/weather_alerts.py +0 -0
  52. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/weather_summary.py +0 -0
  53. {wevva-0.4.2 → wevva-0.4.3}/wevva/widgets/weather_widget.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wevva
3
- Version: 0.4.2
3
+ Version: 0.4.3
4
4
  Summary: Textual TUI for viewing weather via Open-Meteo
5
5
  Author-email: Nick Ferguson <nick.ferguson@ed.ac.uk>
6
6
  License: MIT License
@@ -40,7 +40,7 @@ Requires-Dist: questionary>=2.1.1
40
40
  Requires-Dist: textual>=3.1.0
41
41
  Requires-Dist: typer>=0.21.1
42
42
  Requires-Dist: wcwidth>=0.2.13
43
- Requires-Dist: wevva-warnings==0.3.2
43
+ Requires-Dist: wevva-warnings>=0.3.5
44
44
  Description-Content-Type: text/markdown
45
45
 
46
46
  # wevva
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "wevva"
3
- version = "0.4.2"
3
+ version = "0.4.3"
4
4
  description = "Textual TUI for viewing weather via Open-Meteo"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -23,7 +23,7 @@ dependencies = [
23
23
  "textual>=3.1.0",
24
24
  "typer>=0.21.1",
25
25
  "wcwidth>=0.2.13",
26
- "wevva-warnings==0.3.2",
26
+ "wevva-warnings>=0.3.5",
27
27
  ]
28
28
 
29
29
  [project.scripts]
@@ -1,11 +1,12 @@
1
1
  """Textual TUI for displaying weather forecasts."""
2
2
 
3
3
  import asyncio
4
+ import time
4
5
  from typing import ClassVar
5
6
 
6
7
  from textual.app import App
7
8
 
8
- from wevva.alerts import get_alerts_async
9
+ from wevva.alerts import Alert
9
10
  from wevva.config import (
10
11
  add_saved_location,
11
12
  load_preferences,
@@ -23,6 +24,7 @@ from wevva.location_metadata import LocationMetadata
23
24
  from wevva.messages import (
24
25
  PlaceSelected,
25
26
  SavedLocationSelected,
27
+ WeatherAlertsProgress,
26
28
  WeatherAlertsUpdated,
27
29
  WeatherFetchFailed,
28
30
  WeatherUpdated,
@@ -31,10 +33,18 @@ from wevva.screens.help import HelpScreen
31
33
  from wevva.screens.search_screen import SearchScreen
32
34
  from wevva.screens.settings_screen import SettingsScreen
33
35
  from wevva.screens.weather_screen import WeatherScreen
36
+ from wevva.services.alerts import (
37
+ _get_alert_candidates_async_with_status,
38
+ _match_alert_candidates,
39
+ normalize_country_code,
40
+ )
34
41
  from wevva.services.weather import fetch_weather
35
42
  from wevva.widgets.saved_locations import SavedLocationWeatherSummary
36
43
 
37
44
 
45
+ AlertCacheKey = tuple[str | None, str]
46
+
47
+
38
48
  class Wevva(App, inherit_bindings=False):
39
49
  """Minimal textual weather app showing current, next 24h, daily and warnings."""
40
50
 
@@ -43,7 +53,7 @@ class Wevva(App, inherit_bindings=False):
43
53
  BINDINGS: ClassVar[list[tuple[str, str, str]]] = [
44
54
  ('q', 'quit', 'Quit'), # exit the app
45
55
  ('s', 'search', 'Search'), # open place search screen
46
- ('r', 'refresh', 'Refresh'), # fetch latest forecast
56
+ ('r', 'force_refresh', 'Refresh'), # fetch latest forecast and warnings
47
57
  ('l', 'toggle_locations', 'Locations'), # show/hide saved locations
48
58
  ('a', 'save_current_location', 'Save Location'),
49
59
  ('d', 'delete_saved_location', 'Delete Location'),
@@ -51,6 +61,8 @@ class Wevva(App, inherit_bindings=False):
51
61
  ('u', 'settings', 'Settings'), # open settings
52
62
  ]
53
63
 
64
+ ALERT_CACHE_TTL_SECONDS = 15 * 60
65
+
54
66
  def __init__(
55
67
  self,
56
68
  initial_location: LocationMetadata | None = None,
@@ -84,6 +96,8 @@ class Wevva(App, inherit_bindings=False):
84
96
  self._refresh_in_flight = False # debounce concurrent refreshes
85
97
  self._refresh_generation = 0
86
98
  self._alerts_task: asyncio.Task[None] | None = None
99
+ self._alert_cache: dict[AlertCacheKey, tuple[float, tuple[Alert, ...]]] = {}
100
+ self._alert_cache_clock = time.monotonic
87
101
  self._saved_weather_tasks: dict[str, asyncio.Task[None]] = {}
88
102
  self._saved_weather_generation = 0
89
103
  # Emoji rendering toggle (widgets can read via self.app.emoji_enabled)
@@ -112,6 +126,14 @@ class Wevva(App, inherit_bindings=False):
112
126
  # Actions / key bindings
113
127
  # ------------------------------------------------------------
114
128
  async def action_refresh(self) -> None:
129
+ """Programmatically refresh weather, reusing a valid warning result."""
130
+ await self._refresh_weather(force_alert_refresh=False)
131
+
132
+ async def action_force_refresh(self) -> None:
133
+ """Refresh weather and explicitly bypass the warning-result cache."""
134
+ await self._refresh_weather(force_alert_refresh=True)
135
+
136
+ async def _refresh_weather(self, *, force_alert_refresh: bool) -> None:
115
137
  """Fetch via controller and broadcast `WeatherUpdated`."""
116
138
  if self._refresh_in_flight:
117
139
  return
@@ -131,7 +153,7 @@ class Wevva(App, inherit_bindings=False):
131
153
  )
132
154
  # Forward fresh data to the weather screen
133
155
  self.weather_screen.post_message(event)
134
- self._schedule_alert_refresh(refresh_generation)
156
+ self._schedule_alert_refresh(refresh_generation, force_refresh=force_alert_refresh)
135
157
  except Exception as e:
136
158
  # Forward error to the weather screen to surface it
137
159
  self.weather_screen.post_message(WeatherFetchFailed(e))
@@ -415,17 +437,36 @@ class Wevva(App, inherit_bindings=False):
415
437
  self._alerts_task.cancel()
416
438
  self._alerts_task = None
417
439
 
418
- def _schedule_alert_refresh(self, refresh_generation: int) -> None:
419
- """Start a background alert fetch for the current location."""
440
+ def _schedule_alert_refresh(self, refresh_generation: int, *, force_refresh: bool = False) -> None:
441
+ """Use a cached alert result or start a background alert fetch."""
420
442
  lat = self.location.latitude
421
443
  lon = self.location.longitude
422
444
  if lat is None or lon is None:
423
445
  return
446
+ country_code = normalize_country_code(self.location.country_code)
447
+ warning_language = 'en' if self.warning_language == 'en' else 'auto'
448
+ cache_key = (country_code, warning_language)
449
+ if not force_refresh:
450
+ entry = self._alert_cache.get(cache_key)
451
+ if entry is not None and self._alert_cache_clock() - entry[0] >= self.ALERT_CACHE_TTL_SECONDS:
452
+ del self._alert_cache[cache_key]
453
+ entry = None
454
+ if entry is not None:
455
+ if (
456
+ refresh_generation == self._refresh_generation
457
+ and self.location.latitude == lat
458
+ and self.location.longitude == lon
459
+ ):
460
+ alerts = _match_alert_candidates(list(entry[1]), lat, lon)
461
+ self.weather_screen.post_message(WeatherAlertsUpdated(alerts=alerts))
462
+ return
424
463
  self._alerts_task = asyncio.create_task(
425
464
  self._fetch_alerts_for_location(
426
465
  lat=lat,
427
466
  lon=lon,
428
- country_code=self.location.country_code,
467
+ country_code=country_code,
468
+ warning_language=warning_language,
469
+ cache_key=cache_key,
429
470
  refresh_generation=refresh_generation,
430
471
  )
431
472
  )
@@ -435,24 +476,70 @@ class Wevva(App, inherit_bindings=False):
435
476
  *,
436
477
  lat: float,
437
478
  lon: float,
438
- country_code: str,
479
+ country_code: str | None,
480
+ warning_language: str,
481
+ cache_key: AlertCacheKey,
439
482
  refresh_generation: int,
440
483
  ) -> None:
441
484
  """Fetch alerts in the background and post them if still current."""
442
- try:
443
- alerts = await get_alerts_async(
485
+ loop = asyncio.get_running_loop()
486
+ provider_names: dict[str, str] = {}
487
+
488
+ def report_progress(event: str, payload: dict[str, object]) -> None:
489
+ """Transfer the warning worker's callback safely to the TUI loop."""
490
+ payload = dict(payload)
491
+ source = payload.get('source')
492
+ provider_name = payload.get('provider_name')
493
+ if isinstance(source, str) and isinstance(provider_name, str) and provider_name:
494
+ provider_names[source] = provider_name
495
+ elif isinstance(source, str) and source in provider_names:
496
+ payload['provider_name'] = provider_names[source]
497
+ loop.call_soon_threadsafe(
498
+ self._post_alert_progress_if_current,
499
+ event,
500
+ payload,
444
501
  lat,
445
502
  lon,
446
- country_code or None,
447
- self.warning_language,
503
+ refresh_generation,
504
+ )
505
+
506
+ try:
507
+ candidates, completed = await _get_alert_candidates_async_with_status(
508
+ country_code,
509
+ warning_language,
510
+ progress=report_progress,
448
511
  )
449
512
  except asyncio.CancelledError:
450
513
  raise
451
514
  except Exception:
452
- alerts = []
515
+ candidates = []
516
+ completed = False
453
517
 
454
- if refresh_generation != self._refresh_generation:
455
- return
456
- if self.location.latitude != lat or self.location.longitude != lon:
518
+ if completed:
519
+ self._alert_cache[cache_key] = self._alert_cache_clock(), tuple(candidates)
520
+
521
+ if (
522
+ refresh_generation != self._refresh_generation
523
+ or self.location.latitude != lat
524
+ or self.location.longitude != lon
525
+ ):
457
526
  return
527
+ alerts = _match_alert_candidates(candidates, lat, lon)
458
528
  self.weather_screen.post_message(WeatherAlertsUpdated(alerts=alerts))
529
+
530
+ def _post_alert_progress_if_current(
531
+ self,
532
+ event: str,
533
+ payload: dict[str, object],
534
+ lat: float,
535
+ lon: float,
536
+ refresh_generation: int,
537
+ ) -> None:
538
+ """Post progress only when it still belongs to the active location."""
539
+ if (
540
+ refresh_generation != self._refresh_generation
541
+ or self.location.latitude != lat
542
+ or self.location.longitude != lon
543
+ ):
544
+ return
545
+ self.weather_screen.post_message(WeatherAlertsProgress(event=event, payload=payload))
@@ -58,6 +58,16 @@ class WeatherAlertsUpdated(Message):
58
58
  self.alerts = alerts or []
59
59
 
60
60
 
61
+ class WeatherAlertsProgress(Message):
62
+ """Sent while a background warning query is still running."""
63
+
64
+ def __init__(self, *, event: str, payload: dict[str, object]):
65
+ """Create a progress update from the public warning-library callback."""
66
+ super().__init__()
67
+ self.event = event
68
+ self.payload = dict(payload)
69
+
70
+
61
71
  class WeatherAlertSelected(Message):
62
72
  """Sent when the selected alert tab changes."""
63
73
 
@@ -19,6 +19,7 @@ from wevva.messages import (
19
19
  DaySelected,
20
20
  HourHighlighted,
21
21
  WeatherAlertSelected,
22
+ WeatherAlertsProgress,
22
23
  WeatherAlertsUpdated,
23
24
  WeatherUpdated,
24
25
  )
@@ -346,6 +347,10 @@ class WeatherScreen(Screen[None]):
346
347
  """Render alerts that arrive after the main forecast content."""
347
348
  await self.render_alert_panel(event.alerts)
348
349
 
350
+ def on_weather_alerts_progress(self, event: WeatherAlertsProgress) -> None:
351
+ """Forward individual warning work to the saved-locations sidebar."""
352
+ self.saved_locations_sidebar.update_warning_progress(event.event, event.payload)
353
+
349
354
  def on_weather_alert_selected(self, event: WeatherAlertSelected) -> None:
350
355
  """Show full text for the selected alert in the details sidebar."""
351
356
  self.alert_details_sidebar.update_alert(event.alert)
@@ -357,6 +362,7 @@ class WeatherScreen(Screen[None]):
357
362
  async def render_alert_panel(self, alerts: list[Alert]) -> None:
358
363
  """Mount a compact tabbed alert panel, or none when there are no alerts."""
359
364
  await self.weather_warnings.remove_children()
365
+ self.saved_locations_sidebar.clear_warning_progress()
360
366
  if not alerts:
361
367
  self.warnings_row.display = False
362
368
  self.weather_warnings.display = False
@@ -0,0 +1,211 @@
1
+ """Alert service helpers built on top of ``wevva_warnings``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from datetime import UTC, datetime
7
+
8
+ from wevva_warnings import (
9
+ Alert,
10
+ UnsupportedCountryError,
11
+ WarningQueryProgress,
12
+ get_alerts_for_country,
13
+ get_alerts_for_point,
14
+ get_alerts_for_source,
15
+ match_alerts_to_point,
16
+ )
17
+
18
+ from wevva.utils.country_codes import get_alpha2_by_alpha3
19
+
20
+
21
+ def normalize_country_code(country_code: str | None) -> str | None:
22
+ """Normalize app country codes to the alpha-2 format expected downstream."""
23
+ code = (country_code or '').strip().upper()
24
+ if not code:
25
+ return None
26
+ if len(code) == 2:
27
+ return code
28
+ if len(code) == 3:
29
+ return get_alpha2_by_alpha3(code)
30
+ return None
31
+
32
+
33
+ def _filter_visible_alerts(alerts: list[Alert], *, now: datetime | None = None) -> list[Alert]:
34
+ """Return alerts whose expiry has not passed."""
35
+ now = now or datetime.now(UTC)
36
+ if now.tzinfo is None:
37
+ now = now.replace(tzinfo=UTC)
38
+ else:
39
+ now = now.astimezone(UTC)
40
+
41
+ visible_alerts: list[Alert] = []
42
+ for alert in alerts:
43
+ expires = alert.expires
44
+ if expires is None:
45
+ visible_alerts.append(alert)
46
+ continue
47
+ if expires.tzinfo is None:
48
+ expires = expires.replace(tzinfo=UTC)
49
+ else:
50
+ expires = expires.astimezone(UTC)
51
+ if expires >= now:
52
+ visible_alerts.append(alert)
53
+ return visible_alerts
54
+
55
+
56
+ def _get_alerts_with_status(
57
+ lat: float,
58
+ lon: float,
59
+ country_code: str | None = None,
60
+ warning_language: str = 'auto',
61
+ progress: WarningQueryProgress | None = None,
62
+ ) -> tuple[list[Alert], bool]:
63
+ """Fetch alerts, retaining whether an empty result is a success."""
64
+ normalized_country = normalize_country_code(country_code)
65
+ if normalized_country is None:
66
+ return [], True
67
+ lang = 'en' if warning_language == 'en' else None
68
+ try:
69
+ alerts = get_alerts_for_point(
70
+ lat=lat,
71
+ lon=lon,
72
+ country_code=normalized_country,
73
+ lang=lang,
74
+ active_only=False,
75
+ progress=progress,
76
+ )
77
+ return _filter_visible_alerts(alerts), True
78
+ except UnsupportedCountryError:
79
+ return [], True
80
+ except Exception:
81
+ return [], False
82
+
83
+
84
+ def _get_alert_candidates_with_status(
85
+ country_code: str | None,
86
+ warning_language: str = 'auto',
87
+ progress: WarningQueryProgress | None = None,
88
+ ) -> tuple[list[Alert], bool]:
89
+ """Fetch country candidates and retain whether the query completed."""
90
+ normalized_country = normalize_country_code(country_code)
91
+ if normalized_country is None:
92
+ return [], True
93
+ lang = 'en' if warning_language == 'en' else None
94
+ try:
95
+ return get_alerts_for_country(normalized_country, lang=lang, progress=progress), True
96
+ except UnsupportedCountryError:
97
+ return [], True
98
+ except Exception:
99
+ return [], False
100
+
101
+
102
+ def _match_alert_candidates(candidates: list[Alert], lat: float, lon: float) -> list[Alert]:
103
+ """Match cached country candidates locally and hide expired alerts."""
104
+ return _filter_visible_alerts(match_alerts_to_point(candidates, lat=lat, lon=lon))
105
+
106
+
107
+ def get_alerts(
108
+ lat: float,
109
+ lon: float,
110
+ country_code: str | None = None,
111
+ warning_language: str = 'auto',
112
+ progress: WarningQueryProgress | None = None,
113
+ ) -> list[Alert]:
114
+ """Fetch current or future alerts for one point.
115
+
116
+ ``progress`` receives optional public progress events from
117
+ ``wevva-warnings``. It runs on this function's calling thread and does not
118
+ affect the returned alert list.
119
+ """
120
+ return _get_alerts_with_status(
121
+ lat,
122
+ lon,
123
+ country_code,
124
+ warning_language,
125
+ progress,
126
+ )[0]
127
+
128
+
129
+ async def _get_alerts_async_with_status(
130
+ lat: float,
131
+ lon: float,
132
+ country_code: str | None = None,
133
+ warning_language: str = 'auto',
134
+ progress: WarningQueryProgress | None = None,
135
+ ) -> tuple[list[Alert], bool]:
136
+ """Worker-thread version of :func:`_get_alerts_with_status`."""
137
+ return await asyncio.to_thread(
138
+ _get_alerts_with_status,
139
+ lat,
140
+ lon,
141
+ country_code,
142
+ warning_language,
143
+ progress,
144
+ )
145
+
146
+
147
+ async def _get_alert_candidates_async_with_status(
148
+ country_code: str | None,
149
+ warning_language: str = 'auto',
150
+ progress: WarningQueryProgress | None = None,
151
+ ) -> tuple[list[Alert], bool]:
152
+ """Worker-thread version of :func:`_get_alert_candidates_with_status`."""
153
+ return await asyncio.to_thread(
154
+ _get_alert_candidates_with_status,
155
+ country_code,
156
+ warning_language,
157
+ progress,
158
+ )
159
+
160
+
161
+ async def get_alerts_async(
162
+ lat: float,
163
+ lon: float,
164
+ country_code: str | None = None,
165
+ warning_language: str = 'auto',
166
+ progress: WarningQueryProgress | None = None,
167
+ ) -> list[Alert]:
168
+ """Async wrapper for point-based alert lookups.
169
+
170
+ The optional progress callback runs in the worker thread used for the
171
+ blocking warning-provider query.
172
+ """
173
+ return await asyncio.to_thread(
174
+ get_alerts,
175
+ lat,
176
+ lon,
177
+ country_code,
178
+ warning_language,
179
+ progress,
180
+ )
181
+
182
+
183
+ def get_source_alerts(source_id: str, *, active_only: bool = False) -> list[Alert]:
184
+ """Fetch alerts from one registry source, returning ``[]`` on failure."""
185
+ try:
186
+ return get_alerts_for_source(source_id, active_only=active_only)
187
+ except Exception:
188
+ return []
189
+
190
+
191
+ async def get_source_alerts_async(
192
+ source_id: str,
193
+ *,
194
+ active_only: bool = False,
195
+ ) -> list[Alert]:
196
+ """Async wrapper for source-based alert lookups."""
197
+ return await asyncio.to_thread(
198
+ get_source_alerts,
199
+ source_id,
200
+ active_only=active_only,
201
+ )
202
+
203
+
204
+ __all__ = [
205
+ 'Alert',
206
+ 'get_alerts',
207
+ 'get_alerts_async',
208
+ 'get_source_alerts',
209
+ 'get_source_alerts_async',
210
+ 'normalize_country_code',
211
+ ]
@@ -7,7 +7,7 @@ from dataclasses import dataclass
7
7
  from rich.text import Text
8
8
  from textual.app import ComposeResult
9
9
  from textual.containers import Container
10
- from textual.widgets import OptionList
10
+ from textual.widgets import OptionList, ProgressBar
11
11
  from textual.widgets.option_list import Option
12
12
 
13
13
  from wevva.conditions import Condition
@@ -39,31 +39,25 @@ class SavedLocationsSidebar(Container):
39
39
  # margin-bottom: 1;
40
40
  # margin-top: 1;
41
41
  margin: 2 0 2 2;
42
- # border-right: heavy $primary;
42
+ layout: vertical;
43
43
  background: $background;
44
- hatch: right $primary-muted;
45
- border: round $primary;
44
+ hatch: right $background-lighten-1;
46
45
  }
47
46
 
48
47
  SavedLocationsSidebar.hidden {
49
48
  display: none;
50
49
  }
51
50
 
52
- #saved-location-header {
53
- height: 3;
54
- width: 100%;
55
- }
56
-
57
- #saved-location-title {
58
- height: 3;
51
+ #saved-locations-panel {
52
+ height: 1fr;
59
53
  width: 100%;
60
- content-align: center middle;
61
- color: $primary;
62
- text-style: bold;
54
+ margin: 0;
55
+ border: round $primary;
56
+ background: $background;
63
57
  }
64
58
 
65
59
  #saved-location-list {
66
- height: 1fr;
60
+ height: 100%;
67
61
  width: 100%;
68
62
  # border: round $primary-muted;
69
63
  border: none;
@@ -73,18 +67,53 @@ class SavedLocationsSidebar(Container):
73
67
  #saved-location-list > .option-list--separator {
74
68
  color: $primary-muted;
75
69
  }
70
+
71
+ #saved-location-warning-progress {
72
+ layout: vertical;
73
+ width: 100%;
74
+ height: auto;
75
+ padding: 0 1;
76
+ margin: 1 0 0 0;
77
+ border: round $primary;
78
+ background: $background;
79
+ color: $text-muted;
80
+ }
81
+
82
+ #saved-location-warning-progress-bar {
83
+ width: 100%;
84
+ height: 1;
85
+ }
86
+
87
+ #saved-location-warning-progress-bar > Bar {
88
+ width: 1fr;
89
+ }
76
90
  """
77
91
 
78
92
  def __init__(self, *, id: str = 'saved-locations-sidebar') -> None:
79
93
  super().__init__(id=id)
80
- self.border_title = 'Saved Locations'
81
- self.styles.border_title_align = 'left'
82
94
  self._locations: list[LocationMetadata] = []
83
95
  self._location_cache: dict[str, LocationMetadata] = {}
84
96
  self._weather_summaries: dict[str, SavedLocationWeatherSummary] = {}
85
97
 
86
98
  def compose(self) -> ComposeResult:
87
- yield OptionList(id='saved-location-list')
99
+ self.locations_panel = Container(id='saved-locations-panel')
100
+ self.locations_panel.border_title = 'Saved Locations'
101
+ self.locations_panel.styles.border_title_align = 'left'
102
+ with self.locations_panel:
103
+ yield OptionList(id='saved-location-list')
104
+
105
+ self.warning_progress = Container(id='saved-location-warning-progress')
106
+ self.warning_progress.border_title = 'Checking warnings'
107
+ self.warning_progress.styles.border_title_align = 'left'
108
+ self.warning_progress.display = False
109
+ with self.warning_progress:
110
+ self.warning_progress_bar = ProgressBar(
111
+ total=None,
112
+ show_percentage=True,
113
+ show_eta=False,
114
+ id='saved-location-warning-progress-bar',
115
+ )
116
+ yield self.warning_progress_bar
88
117
 
89
118
  @property
90
119
  def locations(self) -> OptionList:
@@ -107,6 +136,36 @@ class SavedLocationsSidebar(Container):
107
136
  """Return the cached summary for one saved location, if any."""
108
137
  return self._weather_summaries.get(location_key(location))
109
138
 
139
+ def update_warning_progress(self, event: str, payload: dict[str, object]) -> None:
140
+ """Show progress only while individual warning work has a known total."""
141
+ details = self._warning_progress_details(event, payload)
142
+ if details is None:
143
+ return
144
+ completed, total = details
145
+ self.warning_progress_bar.update(total=total, progress=completed)
146
+ self.warning_progress.display = True
147
+
148
+ def clear_warning_progress(self) -> None:
149
+ """Hide the transient warning-query progress panel."""
150
+ self.warning_progress_bar.update(total=None, progress=0)
151
+ self.warning_progress.display = False
152
+
153
+ @staticmethod
154
+ def _warning_progress_details(event: str, payload: dict[str, object]) -> tuple[int, int] | None:
155
+ """Return sidebar progress-bar data for individual warning work."""
156
+ total = payload.get('total')
157
+ completed = payload.get('completed')
158
+ phase = payload.get('phase')
159
+ if event not in {'alerts_total', 'alerts_checked'} or not isinstance(total, int) or total <= 0:
160
+ return None
161
+ if phase not in {'documents', 'geometry', 'matching'}:
162
+ return None
163
+
164
+ progress = 0 if event == 'alerts_total' else completed
165
+ if not isinstance(progress, int):
166
+ return None
167
+ return progress, total
168
+
110
169
  def _render_locations(self) -> None:
111
170
  if not self.is_mounted:
112
171
  return
@@ -1,113 +0,0 @@
1
- """Alert service helpers built on top of ``wevva_warnings``."""
2
-
3
- from __future__ import annotations
4
-
5
- import asyncio
6
- from datetime import UTC, datetime
7
-
8
- from wevva_warnings import (
9
- Alert,
10
- UnsupportedCountryError,
11
- get_alerts_for_point,
12
- get_alerts_for_source,
13
- )
14
-
15
- from wevva.utils.country_codes import get_alpha2_by_alpha3
16
-
17
-
18
- def normalize_country_code(country_code: str | None) -> str | None:
19
- """Normalize app country codes to the alpha-2 format expected downstream."""
20
- code = (country_code or '').strip().upper()
21
- if not code:
22
- return None
23
- if len(code) == 2:
24
- return code
25
- if len(code) == 3:
26
- return get_alpha2_by_alpha3(code)
27
- return None
28
-
29
-
30
- def get_alerts(
31
- lat: float,
32
- lon: float,
33
- country_code: str | None = None,
34
- warning_language: str = 'auto',
35
- ) -> list[Alert]:
36
- """Fetch current or future alerts for one point, returning ``[]`` on unsupported input."""
37
- normalized_country = normalize_country_code(country_code)
38
- if normalized_country is None:
39
- return []
40
- lang = 'en' if warning_language == 'en' else None
41
- try:
42
- alerts = get_alerts_for_point(
43
- lat=lat,
44
- lon=lon,
45
- country_code=normalized_country,
46
- lang=lang,
47
- active_only=False,
48
- )
49
- now = datetime.now(UTC)
50
- visible_alerts: list[Alert] = []
51
- for alert in alerts:
52
- expires = alert.expires
53
- if expires is None:
54
- visible_alerts.append(alert)
55
- continue
56
- if expires.tzinfo is None:
57
- expires = expires.replace(tzinfo=UTC)
58
- else:
59
- expires = expires.astimezone(UTC)
60
- if expires >= now:
61
- visible_alerts.append(alert)
62
- return visible_alerts
63
- except UnsupportedCountryError:
64
- return []
65
- except Exception:
66
- return []
67
-
68
-
69
- async def get_alerts_async(
70
- lat: float,
71
- lon: float,
72
- country_code: str | None = None,
73
- warning_language: str = 'auto',
74
- ) -> list[Alert]:
75
- """Async wrapper for point-based alert lookups."""
76
- return await asyncio.to_thread(
77
- get_alerts,
78
- lat,
79
- lon,
80
- country_code,
81
- warning_language,
82
- )
83
-
84
-
85
- def get_source_alerts(source_id: str, *, active_only: bool = False) -> list[Alert]:
86
- """Fetch alerts from one registry source, returning ``[]`` on failure."""
87
- try:
88
- return get_alerts_for_source(source_id, active_only=active_only)
89
- except Exception:
90
- return []
91
-
92
-
93
- async def get_source_alerts_async(
94
- source_id: str,
95
- *,
96
- active_only: bool = False,
97
- ) -> list[Alert]:
98
- """Async wrapper for source-based alert lookups."""
99
- return await asyncio.to_thread(
100
- get_source_alerts,
101
- source_id,
102
- active_only=active_only,
103
- )
104
-
105
-
106
- __all__ = [
107
- 'Alert',
108
- 'get_alerts',
109
- 'get_alerts_async',
110
- 'get_source_alerts',
111
- 'get_source_alerts_async',
112
- 'normalize_country_code',
113
- ]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes