wevva 0.4.2__tar.gz → 0.4.4__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.4}/PKG-INFO +2 -2
  2. {wevva-0.4.2 → wevva-0.4.4}/pyproject.toml +2 -2
  3. {wevva-0.4.2 → wevva-0.4.4}/wevva/app.py +112 -15
  4. {wevva-0.4.2 → wevva-0.4.4}/wevva/messages.py +10 -0
  5. {wevva-0.4.2 → wevva-0.4.4}/wevva/screens/weather_screen.py +6 -0
  6. wevva-0.4.4/wevva/services/alerts.py +255 -0
  7. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/saved_locations.py +77 -18
  8. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/weather_alerts.py +3 -3
  9. wevva-0.4.2/wevva/services/alerts.py +0 -113
  10. {wevva-0.4.2 → wevva-0.4.4}/.gitignore +0 -0
  11. {wevva-0.4.2 → wevva-0.4.4}/LICENSE +0 -0
  12. {wevva-0.4.2 → wevva-0.4.4}/README.md +0 -0
  13. {wevva-0.4.2 → wevva-0.4.4}/wevva/__init__.py +0 -0
  14. {wevva-0.4.2 → wevva-0.4.4}/wevva/__main__.py +0 -0
  15. {wevva-0.4.2 → wevva-0.4.4}/wevva/alerts.py +0 -0
  16. {wevva-0.4.2 → wevva-0.4.4}/wevva/api.py +0 -0
  17. {wevva-0.4.2 → wevva-0.4.4}/wevva/cli.py +0 -0
  18. {wevva-0.4.2 → wevva-0.4.4}/wevva/conditions.py +0 -0
  19. {wevva-0.4.2 → wevva-0.4.4}/wevva/config.py +0 -0
  20. {wevva-0.4.2 → wevva-0.4.4}/wevva/constants.py +0 -0
  21. {wevva-0.4.2 → wevva-0.4.4}/wevva/controller.py +0 -0
  22. {wevva-0.4.2 → wevva-0.4.4}/wevva/location_metadata.py +0 -0
  23. {wevva-0.4.2 → wevva-0.4.4}/wevva/models.py +0 -0
  24. {wevva-0.4.2 → wevva-0.4.4}/wevva/openmeteo.py +0 -0
  25. {wevva-0.4.2 → wevva-0.4.4}/wevva/screens/air_quality_help.py +0 -0
  26. {wevva-0.4.2 → wevva-0.4.4}/wevva/screens/author_screen.py +0 -0
  27. {wevva-0.4.2 → wevva-0.4.4}/wevva/screens/help.py +0 -0
  28. {wevva-0.4.2 → wevva-0.4.4}/wevva/screens/search_screen.py +0 -0
  29. {wevva-0.4.2 → wevva-0.4.4}/wevva/screens/settings_screen.py +0 -0
  30. {wevva-0.4.2 → wevva-0.4.4}/wevva/services/air_quality.py +0 -0
  31. {wevva-0.4.2 → wevva-0.4.4}/wevva/services/geocoding.py +0 -0
  32. {wevva-0.4.2 → wevva-0.4.4}/wevva/services/weather.py +0 -0
  33. {wevva-0.4.2 → wevva-0.4.4}/wevva/utils/__init__.py +0 -0
  34. {wevva-0.4.2 → wevva-0.4.4}/wevva/utils/colors.py +0 -0
  35. {wevva-0.4.2 → wevva-0.4.4}/wevva/utils/country_codes.py +0 -0
  36. {wevva-0.4.2 → wevva-0.4.4}/wevva/utils/formatting.py +0 -0
  37. {wevva-0.4.2 → wevva-0.4.4}/wevva/utils/geo.py +0 -0
  38. {wevva-0.4.2 → wevva-0.4.4}/wevva/utils/visualization.py +0 -0
  39. {wevva-0.4.2 → wevva-0.4.4}/wevva/wevva.tcss +0 -0
  40. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/air_quality.py +0 -0
  41. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/astronomy_info.py +0 -0
  42. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/context_bar.py +0 -0
  43. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/current_conditions.py +0 -0
  44. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/current_detail.py +0 -0
  45. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/daily_forecast.py +0 -0
  46. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/daily_summary.py +0 -0
  47. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/hourly_forecast.py +0 -0
  48. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/location_info.py +0 -0
  49. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/precip_info.py +0 -0
  50. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/search_dialog.py +0 -0
  51. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/search_results.py +0 -0
  52. {wevva-0.4.2 → wevva-0.4.4}/wevva/widgets/weather_summary.py +0 -0
  53. {wevva-0.4.2 → wevva-0.4.4}/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.4
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.4.0
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.4"
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.4.0",
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,19 @@ 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
+ _combine_alerts,
38
+ _get_native_alerts_async_with_status,
39
+ _get_reusable_alerts_async_with_status,
40
+ normalize_country_code,
41
+ )
34
42
  from wevva.services.weather import fetch_weather
35
43
  from wevva.widgets.saved_locations import SavedLocationWeatherSummary
36
44
 
37
45
 
46
+ AlertCacheKey = tuple[str | None, str]
47
+
48
+
38
49
  class Wevva(App, inherit_bindings=False):
39
50
  """Minimal textual weather app showing current, next 24h, daily and warnings."""
40
51
 
@@ -43,7 +54,7 @@ class Wevva(App, inherit_bindings=False):
43
54
  BINDINGS: ClassVar[list[tuple[str, str, str]]] = [
44
55
  ('q', 'quit', 'Quit'), # exit the app
45
56
  ('s', 'search', 'Search'), # open place search screen
46
- ('r', 'refresh', 'Refresh'), # fetch latest forecast
57
+ ('r', 'force_refresh', 'Refresh'), # fetch latest forecast and warnings
47
58
  ('l', 'toggle_locations', 'Locations'), # show/hide saved locations
48
59
  ('a', 'save_current_location', 'Save Location'),
49
60
  ('d', 'delete_saved_location', 'Delete Location'),
@@ -51,6 +62,8 @@ class Wevva(App, inherit_bindings=False):
51
62
  ('u', 'settings', 'Settings'), # open settings
52
63
  ]
53
64
 
65
+ ALERT_CACHE_TTL_SECONDS = 15 * 60
66
+
54
67
  def __init__(
55
68
  self,
56
69
  initial_location: LocationMetadata | None = None,
@@ -84,6 +97,8 @@ class Wevva(App, inherit_bindings=False):
84
97
  self._refresh_in_flight = False # debounce concurrent refreshes
85
98
  self._refresh_generation = 0
86
99
  self._alerts_task: asyncio.Task[None] | None = None
100
+ self._alert_cache: dict[AlertCacheKey, tuple[float, tuple[Alert, ...]]] = {}
101
+ self._alert_cache_clock = time.monotonic
87
102
  self._saved_weather_tasks: dict[str, asyncio.Task[None]] = {}
88
103
  self._saved_weather_generation = 0
89
104
  # Emoji rendering toggle (widgets can read via self.app.emoji_enabled)
@@ -112,6 +127,14 @@ class Wevva(App, inherit_bindings=False):
112
127
  # Actions / key bindings
113
128
  # ------------------------------------------------------------
114
129
  async def action_refresh(self) -> None:
130
+ """Programmatically refresh weather, reusing a valid warning result."""
131
+ await self._refresh_weather(force_alert_refresh=False)
132
+
133
+ async def action_force_refresh(self) -> None:
134
+ """Refresh weather and explicitly bypass the warning-result cache."""
135
+ await self._refresh_weather(force_alert_refresh=True)
136
+
137
+ async def _refresh_weather(self, *, force_alert_refresh: bool) -> None:
115
138
  """Fetch via controller and broadcast `WeatherUpdated`."""
116
139
  if self._refresh_in_flight:
117
140
  return
@@ -131,7 +154,7 @@ class Wevva(App, inherit_bindings=False):
131
154
  )
132
155
  # Forward fresh data to the weather screen
133
156
  self.weather_screen.post_message(event)
134
- self._schedule_alert_refresh(refresh_generation)
157
+ self._schedule_alert_refresh(refresh_generation, force_refresh=force_alert_refresh)
135
158
  except Exception as e:
136
159
  # Forward error to the weather screen to surface it
137
160
  self.weather_screen.post_message(WeatherFetchFailed(e))
@@ -415,18 +438,30 @@ class Wevva(App, inherit_bindings=False):
415
438
  self._alerts_task.cancel()
416
439
  self._alerts_task = None
417
440
 
418
- def _schedule_alert_refresh(self, refresh_generation: int) -> None:
419
- """Start a background alert fetch for the current location."""
441
+ def _schedule_alert_refresh(self, refresh_generation: int, *, force_refresh: bool = False) -> None:
442
+ """Use cached reusable alerts and refresh native point-query alerts."""
420
443
  lat = self.location.latitude
421
444
  lon = self.location.longitude
422
445
  if lat is None or lon is None:
423
446
  return
447
+ country_code = normalize_country_code(self.location.country_code)
448
+ warning_language = 'en' if self.warning_language == 'en' else 'auto'
449
+ cache_key = (country_code, warning_language)
450
+ entry = None
451
+ if not force_refresh:
452
+ entry = self._alert_cache.get(cache_key)
453
+ if entry is not None and self._alert_cache_clock() - entry[0] >= self.ALERT_CACHE_TTL_SECONDS:
454
+ del self._alert_cache[cache_key]
455
+ entry = None
424
456
  self._alerts_task = asyncio.create_task(
425
457
  self._fetch_alerts_for_location(
426
458
  lat=lat,
427
459
  lon=lon,
428
- country_code=self.location.country_code,
460
+ country_code=country_code,
461
+ warning_language=warning_language,
462
+ cache_key=cache_key,
429
463
  refresh_generation=refresh_generation,
464
+ cached_candidates=entry[1] if entry is not None else None,
430
465
  )
431
466
  )
432
467
 
@@ -435,24 +470,86 @@ class Wevva(App, inherit_bindings=False):
435
470
  *,
436
471
  lat: float,
437
472
  lon: float,
438
- country_code: str,
473
+ country_code: str | None,
474
+ warning_language: str,
475
+ cache_key: AlertCacheKey,
439
476
  refresh_generation: int,
477
+ cached_candidates: tuple[Alert, ...] | None,
440
478
  ) -> None:
441
- """Fetch alerts in the background and post them if still current."""
479
+ """Fetch reusable/native alerts in the background and post if current."""
480
+ loop = asyncio.get_running_loop()
481
+ provider_names: dict[str, str] = {}
482
+
483
+ def report_progress(event: str, payload: dict[str, object]) -> None:
484
+ """Transfer the warning worker's callback safely to the TUI loop."""
485
+ payload = dict(payload)
486
+ source = payload.get('source')
487
+ provider_name = payload.get('provider_name')
488
+ if isinstance(source, str) and isinstance(provider_name, str) and provider_name:
489
+ provider_names[source] = provider_name
490
+ elif isinstance(source, str) and source in provider_names:
491
+ payload['provider_name'] = provider_names[source]
492
+ loop.call_soon_threadsafe(
493
+ self._post_alert_progress_if_current,
494
+ event,
495
+ payload,
496
+ lat,
497
+ lon,
498
+ refresh_generation,
499
+ )
500
+
501
+ if cached_candidates is None:
502
+ try:
503
+ candidates, completed = await _get_reusable_alerts_async_with_status(
504
+ country_code,
505
+ warning_language,
506
+ progress=report_progress,
507
+ )
508
+ except asyncio.CancelledError:
509
+ raise
510
+ except Exception:
511
+ candidates = []
512
+ completed = False
513
+
514
+ if completed:
515
+ self._alert_cache[cache_key] = self._alert_cache_clock(), tuple(candidates)
516
+ else:
517
+ candidates = list(cached_candidates)
518
+
442
519
  try:
443
- alerts = await get_alerts_async(
520
+ native_alerts, _ = await _get_native_alerts_async_with_status(
444
521
  lat,
445
522
  lon,
446
- country_code or None,
447
- self.warning_language,
523
+ country_code,
524
+ warning_language,
448
525
  )
449
526
  except asyncio.CancelledError:
450
527
  raise
451
528
  except Exception:
452
- alerts = []
529
+ native_alerts = []
453
530
 
454
- if refresh_generation != self._refresh_generation:
455
- return
456
- if self.location.latitude != lat or self.location.longitude != lon:
531
+ if (
532
+ refresh_generation != self._refresh_generation
533
+ or self.location.latitude != lat
534
+ or self.location.longitude != lon
535
+ ):
457
536
  return
537
+ alerts = _combine_alerts(candidates, native_alerts, lat, lon)
458
538
  self.weather_screen.post_message(WeatherAlertsUpdated(alerts=alerts))
539
+
540
+ def _post_alert_progress_if_current(
541
+ self,
542
+ event: str,
543
+ payload: dict[str, object],
544
+ lat: float,
545
+ lon: float,
546
+ refresh_generation: int,
547
+ ) -> None:
548
+ """Post progress only when it still belongs to the active location."""
549
+ if (
550
+ refresh_generation != self._refresh_generation
551
+ or self.location.latitude != lat
552
+ or self.location.longitude != lon
553
+ ):
554
+ return
555
+ 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,255 @@
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
+ deduplicate_alerts,
13
+ get_alerts_for_point,
14
+ get_alerts_for_source,
15
+ get_native_alerts_for_point,
16
+ get_reusable_alerts_for_country,
17
+ match_alerts_to_point,
18
+ )
19
+
20
+ from wevva.utils.country_codes import get_alpha2_by_alpha3
21
+
22
+
23
+ def normalize_country_code(country_code: str | None) -> str | None:
24
+ """Normalize app country codes to the alpha-2 format expected downstream."""
25
+ code = (country_code or '').strip().upper()
26
+ if not code:
27
+ return None
28
+ if len(code) == 2:
29
+ return code
30
+ if len(code) == 3:
31
+ return get_alpha2_by_alpha3(code)
32
+ return None
33
+
34
+
35
+ def _filter_visible_alerts(alerts: list[Alert], *, now: datetime | None = None) -> list[Alert]:
36
+ """Return alerts whose expiry has not passed."""
37
+ now = now or datetime.now(UTC)
38
+ if now.tzinfo is None:
39
+ now = now.replace(tzinfo=UTC)
40
+ else:
41
+ now = now.astimezone(UTC)
42
+
43
+ visible_alerts: list[Alert] = []
44
+ for alert in alerts:
45
+ expires = alert.expires
46
+ if expires is None:
47
+ visible_alerts.append(alert)
48
+ continue
49
+ if expires.tzinfo is None:
50
+ expires = expires.replace(tzinfo=UTC)
51
+ else:
52
+ expires = expires.astimezone(UTC)
53
+ if expires >= now:
54
+ visible_alerts.append(alert)
55
+ return visible_alerts
56
+
57
+
58
+ def _get_alerts_with_status(
59
+ lat: float,
60
+ lon: float,
61
+ country_code: str | None = None,
62
+ warning_language: str = 'auto',
63
+ progress: WarningQueryProgress | None = None,
64
+ ) -> tuple[list[Alert], bool]:
65
+ """Fetch alerts, retaining whether an empty result is a success."""
66
+ normalized_country = normalize_country_code(country_code)
67
+ if normalized_country is None:
68
+ return [], True
69
+ lang = 'en' if warning_language == 'en' else None
70
+ try:
71
+ alerts = get_alerts_for_point(
72
+ lat=lat,
73
+ lon=lon,
74
+ country_code=normalized_country,
75
+ lang=lang,
76
+ active_only=False,
77
+ progress=progress,
78
+ )
79
+ return _filter_visible_alerts(alerts), True
80
+ except UnsupportedCountryError:
81
+ return [], True
82
+ except Exception:
83
+ return [], False
84
+
85
+
86
+ def _get_reusable_alerts_with_status(
87
+ country_code: str | None,
88
+ warning_language: str = 'auto',
89
+ progress: WarningQueryProgress | None = None,
90
+ ) -> tuple[list[Alert], bool]:
91
+ """Fetch reusable country candidates and retain completion status."""
92
+ normalized_country = normalize_country_code(country_code)
93
+ if normalized_country is None:
94
+ return [], True
95
+ lang = 'en' if warning_language == 'en' else None
96
+ try:
97
+ return get_reusable_alerts_for_country(normalized_country, lang=lang, progress=progress), True
98
+ except UnsupportedCountryError:
99
+ return [], True
100
+ except Exception:
101
+ return [], False
102
+
103
+
104
+ def _get_native_alerts_with_status(
105
+ lat: float,
106
+ lon: float,
107
+ country_code: str | None,
108
+ warning_language: str = 'auto',
109
+ ) -> tuple[list[Alert], bool]:
110
+ """Fetch native point-query alerts and retain completion status."""
111
+ normalized_country = normalize_country_code(country_code)
112
+ if normalized_country is None:
113
+ return [], True
114
+ lang = 'en' if warning_language == 'en' else None
115
+ try:
116
+ return get_native_alerts_for_point(
117
+ lat=lat,
118
+ lon=lon,
119
+ country_code=normalized_country,
120
+ lang=lang,
121
+ active_only=False,
122
+ ), True
123
+ except UnsupportedCountryError:
124
+ return [], True
125
+ except Exception:
126
+ return [], False
127
+
128
+
129
+ def _combine_alerts(candidates: list[Alert], native_alerts: list[Alert], lat: float, lon: float) -> list[Alert]:
130
+ """Match reusable candidates, combine native results, and hide expired alerts."""
131
+ local_alerts = match_alerts_to_point(candidates, lat=lat, lon=lon)
132
+ return _filter_visible_alerts(deduplicate_alerts([*local_alerts, *native_alerts]))
133
+
134
+
135
+ def get_alerts(
136
+ lat: float,
137
+ lon: float,
138
+ country_code: str | None = None,
139
+ warning_language: str = 'auto',
140
+ progress: WarningQueryProgress | None = None,
141
+ ) -> list[Alert]:
142
+ """Fetch current or future alerts for one point.
143
+
144
+ ``progress`` receives optional public progress events from
145
+ ``wevva-warnings``. It runs on this function's calling thread and does not
146
+ affect the returned alert list.
147
+ """
148
+ return _get_alerts_with_status(
149
+ lat,
150
+ lon,
151
+ country_code,
152
+ warning_language,
153
+ progress,
154
+ )[0]
155
+
156
+
157
+ async def _get_alerts_async_with_status(
158
+ lat: float,
159
+ lon: float,
160
+ country_code: str | None = None,
161
+ warning_language: str = 'auto',
162
+ progress: WarningQueryProgress | None = None,
163
+ ) -> tuple[list[Alert], bool]:
164
+ """Worker-thread version of :func:`_get_alerts_with_status`."""
165
+ return await asyncio.to_thread(
166
+ _get_alerts_with_status,
167
+ lat,
168
+ lon,
169
+ country_code,
170
+ warning_language,
171
+ progress,
172
+ )
173
+
174
+
175
+ async def _get_reusable_alerts_async_with_status(
176
+ country_code: str | None,
177
+ warning_language: str = 'auto',
178
+ progress: WarningQueryProgress | None = None,
179
+ ) -> tuple[list[Alert], bool]:
180
+ """Worker-thread version of :func:`_get_reusable_alerts_with_status`."""
181
+ return await asyncio.to_thread(
182
+ _get_reusable_alerts_with_status,
183
+ country_code,
184
+ warning_language,
185
+ progress,
186
+ )
187
+
188
+
189
+ async def _get_native_alerts_async_with_status(
190
+ lat: float,
191
+ lon: float,
192
+ country_code: str | None,
193
+ warning_language: str = 'auto',
194
+ ) -> tuple[list[Alert], bool]:
195
+ """Worker-thread version of :func:`_get_native_alerts_with_status`."""
196
+ return await asyncio.to_thread(
197
+ _get_native_alerts_with_status,
198
+ lat,
199
+ lon,
200
+ country_code,
201
+ warning_language,
202
+ )
203
+
204
+
205
+ async def get_alerts_async(
206
+ lat: float,
207
+ lon: float,
208
+ country_code: str | None = None,
209
+ warning_language: str = 'auto',
210
+ progress: WarningQueryProgress | None = None,
211
+ ) -> list[Alert]:
212
+ """Async wrapper for point-based alert lookups.
213
+
214
+ The optional progress callback runs in the worker thread used for the
215
+ blocking warning-provider query.
216
+ """
217
+ return await asyncio.to_thread(
218
+ get_alerts,
219
+ lat,
220
+ lon,
221
+ country_code,
222
+ warning_language,
223
+ progress,
224
+ )
225
+
226
+
227
+ def get_source_alerts(source_id: str, *, active_only: bool = False) -> list[Alert]:
228
+ """Fetch alerts from one registry source, returning ``[]`` on failure."""
229
+ try:
230
+ return get_alerts_for_source(source_id, active_only=active_only)
231
+ except Exception:
232
+ return []
233
+
234
+
235
+ async def get_source_alerts_async(
236
+ source_id: str,
237
+ *,
238
+ active_only: bool = False,
239
+ ) -> list[Alert]:
240
+ """Async wrapper for source-based alert lookups."""
241
+ return await asyncio.to_thread(
242
+ get_source_alerts,
243
+ source_id,
244
+ active_only=active_only,
245
+ )
246
+
247
+
248
+ __all__ = [
249
+ 'Alert',
250
+ 'get_alerts',
251
+ 'get_alerts_async',
252
+ 'get_source_alerts',
253
+ 'get_source_alerts_async',
254
+ 'normalize_country_code',
255
+ ]
@@ -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
@@ -78,6 +78,7 @@ class WeatherAlertsPanel(Container):
78
78
  width: 98;
79
79
  border: round $primary;
80
80
  border-title-color: $primary;
81
+ border-title-style: bold;
81
82
  border-title-align: center;
82
83
  margin-bottom: 1;
83
84
  hatch: right $background-lighten-1;
@@ -131,7 +132,7 @@ class WeatherAlertsPanel(Container):
131
132
  severity_color = alert_severity_color(self.app.theme_variables, alert)
132
133
 
133
134
  alert_count = len(self.alerts)
134
- self.border_title = f'{alert_count} Weather Alert{"s" if alert_count != 1 else ""}'
135
+ self.border_title = f'{alert_count} Severe Weather Alert{"s" if alert_count != 1 else ""}'
135
136
  self.border_subtitle = None
136
137
  self.apply_frame_color(severity_color)
137
138
 
@@ -165,8 +166,7 @@ class WeatherAlertsPanel(Container):
165
166
 
166
167
  if onset is not None and end is not None:
167
168
  line = (
168
- f'[dim italic]Active from[/] [i]{self.fmt_clock(onset)}[/i] '
169
- f'[dim italic]until[/] [i]{self.fmt_clock(end)}[/i]'
169
+ f'[dim italic]Active from[/] [i]{self.fmt_clock(onset)}[/i] [dim italic]until[/] [i]{self.fmt_clock(end)}[/i]'
170
170
  )
171
171
  elif onset is not None:
172
172
  line = f'[dim italic]Active from[/] [i]{self.fmt_clock(onset)}[/i]'
@@ -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